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
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
|
/*-
* ============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.components.impl;
import static org.openecomp.sdc.be.components.attribute.GetOutputUtils.isGetOutputValueForOutput;
import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput;
import static org.openecomp.sdc.be.components.utils.PropertiesUtils.getPropertyCapabilityOfChildInstance;
import com.google.common.collect.Sets;
import fj.data.Either;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.json.JSONArray;
import org.json.JSONObject;
import org.onap.sdc.tosca.datatypes.model.PropertyType;
import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException;
import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
import org.openecomp.sdc.be.components.impl.exceptions.ToscaGetFunctionExceptionSupplier;
import org.openecomp.sdc.be.components.impl.instance.ComponentInstanceChangeOperationOrchestrator;
import org.openecomp.sdc.be.components.impl.utils.DirectivesUtil;
import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceMergeDataBusinessLogic;
import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder;
import org.openecomp.sdc.be.components.utils.PropertiesUtils;
import org.openecomp.sdc.be.components.validation.ComponentValidations;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.datamodel.utils.PropertyValueConstraintValidationUtil;
import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.GetOutputValueDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.GetPolicyValueDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.datatypes.elements.ToscaGetFunctionDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.PropertySource;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.datatypes.tosca.ToscaGetFunctionType;
import org.openecomp.sdc.be.exception.BusinessException;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.impl.ForwardingPathUtils;
import org.openecomp.sdc.be.impl.ServiceFilterUtils;
import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.AttributeDefinition;
import org.openecomp.sdc.be.model.CapabilityDefinition;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.ComponentInstanceAttribute;
import org.openecomp.sdc.be.model.ComponentInstanceInput;
import org.openecomp.sdc.be.model.ComponentInstanceOutput;
import org.openecomp.sdc.be.model.ComponentInstancePropInput;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.ComponentParametersView;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.GroupDefinition;
import org.openecomp.sdc.be.model.InputDefinition;
import org.openecomp.sdc.be.model.InterfaceDefinition;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.OutputDefinition;
import org.openecomp.sdc.be.model.PolicyDefinition;
import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.RelationshipInfo;
import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
import org.openecomp.sdc.be.model.RequirementDefinition;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.ToscaPropertyData;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.jsonjanusgraph.config.ContainerInstanceTypesData;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ForwardingPathOperation;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeFilterOperation;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTemplateOperation;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
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.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.be.model.validation.ToscaFunctionValidator;
import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
import org.openecomp.sdc.common.log.elements.ErrorLogOptionalData;
import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.yaml.snakeyaml.Yaml;
@org.springframework.stereotype.Component
public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
private static final Logger log = Logger.getLogger(ComponentInstanceBusinessLogic.class);
private static final String VF_MODULE = "org.openecomp.groups.VfModule";
private static final String TRY_TO_CREATE_ENTRY_ON_GRAPH = "Try to create entry on graph";
private static final String CLOUD_SPECIFIC_FIXED_KEY_WORD = "cloudtech";
private static final String[][] CLOUD_SPECIFIC_KEY_WORDS = {{"k8s", "azure", "aws"}, /* cloud specific technology */
{"charts", "day0", "configtemplate"} /*cloud specific sub type*/};
private static final String FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE = "Failed to create entry on graph for component instance {}";
private static final String ENTITY_ON_GRAPH_IS_CREATED = "Entity on graph is created.";
private static final String INVALID_COMPONENT_TYPE = "invalid component type";
private static final String FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID = "Failed to retrieve component, component id {}";
private static final String FAILED_TO_LOCK_SERVICE = "Failed to lock service {}";
private static final String CREATE_OR_UPDATE_PROPERTY_VALUE = "CreateOrUpdatePropertyValue";
private static final String FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS = "Failed to copy the component instance to the canvas";
private static final String COPY_COMPONENT_INSTANCE_OK = "Copy component instance OK";
private static final String CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE =
"Cannot attach resource instances to container resource of type {}";
private static final String FAILED_TO_UPDATE_COMPONENT_INSTANCE_CAPABILITY = "Failed to update component instance capability on instance {} in "
+ "container {}";
private static final String SERVICE_PROXY = "serviceProxy";
private static final String ASSOCIATE_RI_TO_RI = "associateRIToRI";
private static final String COMPONENT_ARCHIVED = "Component is archived. Component id: {}";
private static final String RESTRICTED_OPERATION_ON_SERVIVE = "Restricted operation for user: {} on service {}";
private static final String FAILED_TO_LOCK_COMPONENT = "Failed to lock component {}";
private static final String RESTRICTED_OPERATION_ON_COMPONENT = "Restricted operation for user: {} on component {}";
private static final String RESOURCE_INSTANCE = "resource instance";
private static final String SERVICE = "service";
private final ComponentInstanceOperation componentInstanceOperation;
private final ArtifactsBusinessLogic artifactBusinessLogic;
private final ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL;
private final ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator;
private final ForwardingPathOperation forwardingPathOperation;
private final NodeFilterOperation nodeFilterOperation;
private final ToscaFunctionValidator toscaFunctionValidator;
private final PropertyBusinessLogic propertyBusinessLogic;
@Autowired
private CompositionBusinessLogic compositionBusinessLogic;
@Autowired
private ContainerInstanceTypesData containerInstanceTypesData;
@Autowired
public ComponentInstanceBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation,
IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation,
InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
ComponentInstanceOperation componentInstanceOperation, ArtifactsBusinessLogic artifactBusinessLogic,
ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL,
ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator,
ForwardingPathOperation forwardingPathOperation, NodeFilterOperation nodeFilterOperation,
ArtifactsOperations artifactToscaOperation, final ToscaFunctionValidator toscaFunctionValidator,
PropertyBusinessLogic propertyBusinessLogic) {
super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
artifactToscaOperation);
this.componentInstanceOperation = componentInstanceOperation;
this.artifactBusinessLogic = artifactBusinessLogic;
this.compInstMergeDataBL = compInstMergeDataBL;
this.onChangeInstanceOperationOrchestrator = onChangeInstanceOperationOrchestrator;
this.forwardingPathOperation = forwardingPathOperation;
this.nodeFilterOperation = nodeFilterOperation;
this.toscaFunctionValidator = toscaFunctionValidator;
this.propertyBusinessLogic = propertyBusinessLogic;
}
public ComponentInstance createComponentInstance(String containerComponentParam, String containerComponentId, String userId,
ComponentInstance resourceInstance) {
return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, true);
}
public List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId) {
List<ComponentInstanceProperty> resList = new ArrayList<>();
Map<String, List<ComponentInstanceProperty>> ciPropertiesMap = component.getComponentInstancesProperties();
if (ciPropertiesMap != null && !ciPropertiesMap.isEmpty()) {
ciPropertiesMap.forEach((s, ciPropList) -> {
String ciName = "";
Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s)).findAny();
if (ciOp.isPresent()) {
ciName = ciOp.get().getName();
}
if (ciPropList != null && !ciPropList.isEmpty()) {
for (ComponentInstanceProperty prop : ciPropList) {
List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
addCompInstanceProperty(s, ciName, prop, inputsValues, inputId, resList);
}
}
});
}
return resList;
}
public List<ComponentInstanceAttribute> getComponentInstanceAttributesByOutputId(final org.openecomp.sdc.be.model.Component component,
final String outputId) {
final List<ComponentInstanceAttribute> resList = new ArrayList<>();
final Map<String, List<ComponentInstanceAttribute>> componentInstancesAttributes = component.getComponentInstancesAttributes();
if (org.apache.commons.collections4.MapUtils.isNotEmpty(componentInstancesAttributes)) {
componentInstancesAttributes.forEach((s, componentInstanceAttributeList) -> {
String ciName = "";
final Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s))
.findAny();
if (ciOp.isPresent()) {
ciName = ciOp.get().getName();
}
if (componentInstanceAttributeList != null && !componentInstanceAttributeList.isEmpty()) {
for (final ComponentInstanceAttribute compInstanceAttribute : componentInstanceAttributeList) {
List<GetOutputValueDataDefinition> outputValues = compInstanceAttribute.getGetOutputValues();
addCompInstanceAttribute(s, ciName, compInstanceAttribute, outputValues, outputId, resList);
}
}
});
}
return resList;
}
private void addCompInstanceProperty(String s, String ciName, ComponentInstanceProperty prop, List<GetInputValueDataDefinition> inputsValues,
String inputId, List<ComponentInstanceProperty> resList) {
if (inputsValues != null && !inputsValues.isEmpty()) {
for (GetInputValueDataDefinition inputData : inputsValues) {
if (isGetInputValueForInput(inputData, inputId)) {
prop.setComponentInstanceId(s);
prop.setComponentInstanceName(ciName);
resList.add(prop);
break;
}
}
}
}
private void addCompInstanceAttribute(final String s, final String ciName, final ComponentInstanceAttribute attribute,
final List<GetOutputValueDataDefinition> outputsValues, final String outputId,
final List<ComponentInstanceAttribute> resList) {
if (outputsValues != null && !outputsValues.isEmpty()) {
for (final GetOutputValueDataDefinition outputData : outputsValues) {
if (isGetOutputValueForOutput(outputData, outputId)) {
attribute.setComponentInstanceId(s);
attribute.setComponentInstanceName(ciName);
resList.add(attribute);
break;
}
}
}
}
public Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicyId(Component component, PolicyDefinition policy) {
Optional<ComponentInstanceProperty> propertyCandidate = getComponentInstancePropertyByPolicy(component, policy);
if (propertyCandidate.isPresent()) {
ComponentInstanceProperty componentInstanceProperty = propertyCandidate.get();
Optional<GetPolicyValueDataDefinition> getPolicyCandidate = getGetPolicyValueDataDefinition(policy, componentInstanceProperty);
getPolicyCandidate
.ifPresent(getPolicyValue -> updateComponentInstancePropertyAfterUndeclaration(componentInstanceProperty, getPolicyValue, policy));
return Optional.of(componentInstanceProperty);
}
return Optional.empty();
}
private void updateComponentInstancePropertyAfterUndeclaration(ComponentInstanceProperty componentInstanceProperty,
GetPolicyValueDataDefinition getPolicyValue, PolicyDefinition policyDefinition) {
componentInstanceProperty.setValue(getPolicyValue.getOrigPropertyValue());
List<GetPolicyValueDataDefinition> getPolicyValues = componentInstanceProperty.getGetPolicyValues();
if (CollectionUtils.isNotEmpty(getPolicyValues)) {
getPolicyValues.remove(getPolicyValue);
componentInstanceProperty.setGetPolicyValues(getPolicyValues);
policyDefinition.setGetPolicyValues(getPolicyValues);
}
}
private Optional<GetPolicyValueDataDefinition> getGetPolicyValueDataDefinition(PolicyDefinition policy,
ComponentInstanceProperty componentInstanceProperty) {
List<GetPolicyValueDataDefinition> getPolicyValues = policy.getGetPolicyValues();
return getPolicyValues.stream().filter(getPolicyValue -> getPolicyValue.getPropertyName().equals(componentInstanceProperty.getName()))
.findAny();
}
private Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicy(Component component, PolicyDefinition policy) {
Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component.getComponentInstancesProperties();
if (MapUtils.isEmpty(componentInstancesProperties)) {
return Optional.empty();
}
String instanceUniqueId = policy.getInstanceUniqueId();
List<ComponentInstanceProperty> componentInstanceProperties =
componentInstancesProperties.containsKey(instanceUniqueId) ? componentInstancesProperties.get(instanceUniqueId) : new ArrayList<>();
return componentInstanceProperties.stream().filter(property -> property.getName().equals(policy.getName())).findAny();
}
public List<ComponentInstanceInput> getComponentInstanceInputsByInputId(org.openecomp.sdc.be.model.Component component, String inputId) {
List<ComponentInstanceInput> resList = new ArrayList<>();
Map<String, List<ComponentInstanceInput>> ciInputsMap = component.getComponentInstancesInputs();
if (ciInputsMap != null && !ciInputsMap.isEmpty()) {
ciInputsMap.forEach((s, ciPropList) -> {
String ciName = "";
Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s)).findAny();
if (ciOp.isPresent()) {
ciName = ciOp.get().getName();
}
if (ciPropList != null && !ciPropList.isEmpty()) {
for (ComponentInstanceInput prop : ciPropList) {
List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
addCompInstanceInput(s, ciName, prop, inputsValues, inputId, resList);
}
}
});
}
return resList;
}
public List<ComponentInstanceOutput> getComponentInstanceOutputsByOutputId(final org.openecomp.sdc.be.model.Component component,
final String outputId) {
final List<ComponentInstanceOutput> resList = new ArrayList<>();
final Map<String, List<ComponentInstanceOutput>> ciInputsMap = component.getComponentInstancesOutputs();
if (ciInputsMap != null && !ciInputsMap.isEmpty()) {
ciInputsMap.forEach((s, ciPropList) -> {
String ciName = "";
final Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s))
.findAny();
if (ciOp.isPresent()) {
ciName = ciOp.get().getName();
}
if (ciPropList != null && !ciPropList.isEmpty()) {
for (final ComponentInstanceOutput prop : ciPropList) {
final List<GetOutputValueDataDefinition> outputValues = prop.getGetOutputValues();
addCompInstanceOutput(s, ciName, prop, outputValues, outputId, resList);
}
}
});
}
return resList;
}
private void addCompInstanceInput(String s, String ciName, ComponentInstanceInput prop, List<GetInputValueDataDefinition> inputsValues,
String inputId, List<ComponentInstanceInput> resList) {
if (inputsValues != null && !inputsValues.isEmpty()) {
for (GetInputValueDataDefinition inputData : inputsValues) {
if (isGetInputValueForInput(inputData, inputId)) {
prop.setComponentInstanceId(s);
prop.setComponentInstanceName(ciName);
resList.add(prop);
break;
}
}
}
}
private void addCompInstanceOutput(final String s, final String ciName, final ComponentInstanceOutput prop,
final List<GetOutputValueDataDefinition> outputsValues, final String outputId,
final List<ComponentInstanceOutput> resList) {
if (outputsValues != null && !outputsValues.isEmpty()) {
for (final GetOutputValueDataDefinition outputData : outputsValues) {
if (isGetOutputValueForOutput(outputData, outputId)) {
prop.setComponentInstanceId(s);
prop.setComponentInstanceName(ciName);
resList.add(prop);
break;
}
}
}
}
public ComponentInstance createComponentInstance(final String containerComponentParam, final String containerComponentId, final String userId,
final ComponentInstance resourceInstance, final boolean needLock) {
final User user = validateUserExists(userId);
validateUserNotEmpty(user, "Create component instance");
validateJsonBody(resourceInstance, ComponentInstance.class);
final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
final org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
if (ModelConverter.isAtomicComponent(containerComponent)) {
if (log.isDebugEnabled()) {
log.debug(CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE, containerComponent.assetType());
}
throw new ByActionStatusComponentException(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType());
}
validateCanWorkOnComponent(containerComponent, userId);
Component origComponent = null;
if (resourceInstance != null && containerComponentType != null) {
final OriginTypeEnum originType = resourceInstance.getOriginType();
validateInstanceName(resourceInstance);
if (originType == OriginTypeEnum.ServiceProxy) {
origComponent = getOrigComponentForServiceProxy(containerComponent, resourceInstance);
} else if (originType == OriginTypeEnum.ServiceSubstitution) {
origComponent = getOrigComponentForServiceSubstitution(resourceInstance);
} else {
origComponent = getAndValidateOriginComponentOfComponentInstance(containerComponent, resourceInstance);
validateOriginAndResourceInstanceTypes(containerComponent, origComponent, originType);
}
validateResourceInstanceState(containerComponent, origComponent);
overrideFields(origComponent, resourceInstance);
compositionBusinessLogic.validateAndSetDefaultCoordinates(resourceInstance);
}
return createComponent(needLock, containerComponent, origComponent, resourceInstance, user);
}
private Component getOrigComponentForServiceProxy(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance resourceInstance) {
Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName(SERVICE_PROXY, null);
if (isServiceProxyOrigin(serviceProxyOrigin)) {
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
}
Component origComponent = serviceProxyOrigin.left().value();
StorageOperationStatus fillProxyRes = fillInstanceData(resourceInstance, origComponent);
if (isFillProxyRes(fillProxyRes)) {
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes));
}
validateOriginAndResourceInstanceTypes(containerComponent, origComponent, OriginTypeEnum.ServiceProxy);
return origComponent;
}
private Component getOrigComponentForServiceSubstitution(ComponentInstance resourceInstance) {
final Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade
.getToscaFullElement(resourceInstance.getComponentUid());
if (getServiceResult.isRight()) {
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
}
final Component service = getServiceResult.left().value();
final Either<Component, StorageOperationStatus> getServiceDerivedFromTypeResult = toscaOperationFacade
.getLatestByToscaResourceName(service.getDerivedFromGenericType(), service.getModel());
if (getServiceDerivedFromTypeResult.isRight()) {
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
}
Component origComponent = getServiceDerivedFromTypeResult.left().value();
final StorageOperationStatus fillProxyRes = fillInstanceData(resourceInstance, origComponent);
if (isFillProxyRes(fillProxyRes)) {
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes));
}
return origComponent;
}
private ComponentInstance createComponent(boolean needLock, Component containerComponent, Component origComponent,
ComponentInstance resourceInstance, User user) {
boolean failed = false;
try {
lockIfNeed(needLock, containerComponent);
log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
return createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
} catch (ComponentException e) {
failed = true;
throw e;
} finally {
if (needLock) {
unlockComponent(failed, containerComponent);
}
}
}
/**
* Try using either to make a judgment
*
* @param containerComponentParam
* @param containerComponentId
* @param userId
* @param resourceInstance
* @return
*/
public Either<ComponentInstance, ResponseFormat> createRealComponentInstance(String containerComponentParam, String containerComponentId,
String userId, ComponentInstance resourceInstance) {
log.debug("enter createRealComponentInstance");
return createRealComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, true);
}
/**
* Try using either to make a judgment
*
* @param needLock
* @param containerComponentParam
* @param containerComponentId
* @param userId
* @param resourceInstance
* @return
*/
public Either<ComponentInstance, ResponseFormat> createRealComponentInstance(String containerComponentParam, String containerComponentId,
String userId, ComponentInstance resourceInstance,
boolean needLock) {
log.debug("enter createRealComponentInstance");
Component origComponent = null;
User user;
org.openecomp.sdc.be.model.Component containerComponent = null;
ComponentTypeEnum containerComponentType;
try {
user = validateUserExists(userId);
validateUserNotEmpty(user, "Create component instance");
validateJsonBody(resourceInstance, ComponentInstance.class);
containerComponentType = validateComponentType(containerComponentParam);
containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
log.debug("enter createRealComponentInstance,validate user json success");
if (ModelConverter.isAtomicComponent(containerComponent)) {
log.debug(CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE, containerComponent.assetType());
throw new ByActionStatusComponentException(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType());
}
validateCanWorkOnComponent(containerComponent, userId);
log.debug("enter createRealComponentInstance,validateCanWorkOnComponent success");
if (resourceInstance != null && containerComponentType != null) {
log.debug("enter createRealComponentInstance,start create ComponentInstance");
OriginTypeEnum originType = resourceInstance.getOriginType();
validateInstanceName(resourceInstance);
if (originType == OriginTypeEnum.ServiceProxy) {
log.debug("enter createRealComponentInstance,originType equals ServiceProxy");
Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName(SERVICE_PROXY, null);
if (isServiceProxyOrigin(serviceProxyOrigin)) {
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
}
origComponent = serviceProxyOrigin.left().value();
StorageOperationStatus fillProxyRes = fillInstanceData(resourceInstance, origComponent);
if (isFillProxyRes(fillProxyRes)) {
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes));
}
} else {
log.debug("enter createRealComponentInstance,originType is not ServiceProxy");
origComponent = getAndValidateOriginComponentOfComponentInstance(containerComponent, resourceInstance);
}
validateOriginAndResourceInstanceTypes(containerComponent, origComponent, originType);
validateResourceInstanceState(containerComponent, origComponent);
overrideFields(origComponent, resourceInstance);
compositionBusinessLogic.validateAndSetDefaultCoordinates(resourceInstance);
log.debug("enter createRealComponentInstance,final validate success");
}
return createRealComponent(needLock, containerComponent, origComponent, resourceInstance, user);
} catch (ComponentException e) {
log.debug("create Real Component Instance failed");
throw e;
}
}
private Either<ComponentInstance, ResponseFormat> createRealComponent(boolean needLock, Component containerComponent, Component origComponent,
ComponentInstance resourceInstance, User user) {
log.debug("enter createRealComponent");
boolean failed = false;
try {
lockIfNeed(needLock, containerComponent);
log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
return createRealComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
} catch (ComponentException e) {
failed = true;
throw e;
} finally {
if (needLock) {
unlockComponent(failed, containerComponent);
}
}
}
private Either<ComponentInstance, ResponseFormat> createRealComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent,
Component originComponent,
ComponentInstance componentInstance, User user) {
log.debug("enter createRealComponentInstanceOnGraph");
Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade
.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
if (result.isRight()) {
log.debug("enter createRealComponentInstanceOnGraph,result is right");
ActionStatus status = componentsUtils.convertFromStorageResponse(result.right().value());
log.debug(FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE, componentInstance.getName());
return Either.right(componentsUtils.getResponseFormat(status));
}
log.debug(ENTITY_ON_GRAPH_IS_CREATED);
log.debug("enter createRealComponentInstanceOnGraph,Entity on graph is created.");
Component updatedComponent = result.left().value().getLeft();
Map<String, String> existingEnvVersions = new HashMap<>();
// TODO existingEnvVersions ??
addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream()
.filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
if (!updatedInstanceOptional.isPresent()) {
log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
}
log.debug("enter createRealComponentInstanceOnGraph,and final success");
return Either.left(updatedInstanceOptional.get());
}
private void overrideFields(Component origComponent, ComponentInstance resourceInstance) {
resourceInstance.setComponentVersion(origComponent.getVersion());
resourceInstance.setIcon(origComponent.getIcon());
}
private void validateInstanceName(ComponentInstance resourceInstance) {
String resourceInstanceName = resourceInstance.getName();
if (StringUtils.isEmpty(resourceInstanceName)) {
log.debug("ComponentInstance name is empty");
throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
}
if (!ValidationUtils.validateComponentNameLength(resourceInstanceName)) {
log.debug("ComponentInstance name exceeds max length {} ", ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
}
if (!ValidationUtils.validateComponentNamePattern(resourceInstanceName)) {
log.debug("ComponentInstance name {} has invalid format", resourceInstanceName);
throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
}
}
private void validateResourceInstanceState(Component containerComponent, Component origComponent) {
if (origComponent.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
containerComponent.getComponentType().getValue(), origComponent.getLifecycleState().toString());
}
}
private void validateOriginAndResourceInstanceTypes(final Component containerComponent, final Component origComponent,
final OriginTypeEnum originType) {
final ResourceTypeEnum resourceType = getResourceTypeEnumFromOriginComponent(origComponent);
validateOriginType(originType, resourceType);
validateOriginComponentIsValidForContainer(containerComponent, resourceType);
}
private void validateOriginComponentIsValidForContainer(Component containerComponent, ResourceTypeEnum resourceType) {
switch (containerComponent.getComponentType()) {
case SERVICE:
if (!containerInstanceTypesData.isAllowedForServiceComponent(resourceType, containerComponent.getModel())) {
throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
containerComponent.getComponentType().toString(), resourceType.name());
}
break;
case RESOURCE:
final ResourceTypeEnum componentResourceType = ((Resource) containerComponent).getResourceType();
if (!containerInstanceTypesData.isAllowedForResourceComponent(componentResourceType, resourceType)) {
throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
containerComponent.getComponentType().toString(), resourceType.name());
}
break;
default:
throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
}
}
private void validateOriginType(OriginTypeEnum originType, ResourceTypeEnum resourceType) {
ResourceTypeEnum convertedOriginType;
try {
convertedOriginType = ResourceTypeEnum.getTypeIgnoreCase(originType.name());
} catch (Exception e) {
throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
}
if (resourceType != convertedOriginType) {
throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
}
}
private ResourceTypeEnum getResourceTypeEnumFromOriginComponent(final Component origComponent) {
switch (origComponent.getComponentType()) {
case SERVICE:
return ResourceTypeEnum.ServiceProxy;
case RESOURCE:
return ((Resource) origComponent).getResourceType();
default:
throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
}
}
private void lockIfNeed(boolean needLock, Component containerComponent) {
if (needLock) {
lockComponent(containerComponent, "createComponentInstance");
}
}
private boolean isServiceProxyOrigin(Either<Component, StorageOperationStatus> serviceProxyOrigin) {
if (serviceProxyOrigin.isRight()) {
log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
return true;
}
return false;
}
private StorageOperationStatus fillInstanceData(ComponentInstance resourceInstance, Component origComponent) {
final ComponentParametersView filter = new ComponentParametersView(true);
filter.setIgnoreCapabilities(false);
filter.setIgnoreCapabiltyProperties(false);
filter.setIgnoreComponentInstances(false);
filter.setIgnoreRequirements(false);
filter.setIgnoreInterfaces(false);
filter.setIgnoreProperties(false);
filter.setIgnoreAttributes(false);
filter.setIgnoreInputs(false);
Either<Component, StorageOperationStatus> serviceRes = toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter);
if (serviceRes.isRight()) {
return serviceRes.right().value();
}
final Component service = serviceRes.left().value();
final Map<String, List<CapabilityDefinition>> capabilities = service.getCapabilities();
resourceInstance.setCapabilities(capabilities);
final Map<String, List<RequirementDefinition>> req = service.getRequirements();
resourceInstance.setRequirements(req);
final Map<String, InterfaceDefinition> serviceInterfaces = service.getInterfaces();
if (MapUtils.isNotEmpty(serviceInterfaces)) {
serviceInterfaces.forEach(resourceInstance::addInterface);
}
resourceInstance.setProperties(PropertiesUtils.getProperties(service));
resourceInstance.setAttributes(service.getAttributes());
final List<InputDefinition> serviceInputs = service.getInputs();
resourceInstance.setInputs(serviceInputs);
resourceInstance.setSourceModelInvariant(service.getInvariantUUID());
resourceInstance.setSourceModelName(service.getName());
resourceInstance.setSourceModelUuid(service.getUUID());
resourceInstance.setSourceModelUid(service.getUniqueId());
resourceInstance.setComponentUid(origComponent.getUniqueId());
resourceInstance.setComponentVersion(service.getVersion());
switch (resourceInstance.getOriginType()) {
case ServiceProxy:
return fillProxyInstanceData(resourceInstance, origComponent, service);
case ServiceSubstitution:
return fillServiceSubstitutableNodeTypeData(resourceInstance, service);
default:
return StorageOperationStatus.OK;
}
}
private StorageOperationStatus fillProxyInstanceData(final ComponentInstance resourceInstance, final Component origComponent,
final Component service) {
final String name = ValidationUtils.normalizeComponentInstanceName(service.getName()) + ToscaOperationFacade.PROXY_SUFFIX;
final String toscaResourceName = ((Resource) origComponent).getToscaResourceName();
final int lastIndexOf = toscaResourceName.lastIndexOf('.');
if (lastIndexOf != -1) {
final String proxyToscaName = toscaResourceName.substring(0, lastIndexOf + 1) + name;
resourceInstance.setToscaComponentName(proxyToscaName);
}
resourceInstance.setName(name);
resourceInstance.setIsProxy(true);
resourceInstance.setDescription("A Proxy for Service " + service.getName());
return StorageOperationStatus.OK;
}
private StorageOperationStatus fillServiceSubstitutableNodeTypeData(final ComponentInstance resourceInstance, final Component service) {
resourceInstance.setToscaComponentName("org.openecomp.service." + ValidationUtils.convertToSystemName(service.getName()));
resourceInstance.setName(ValidationUtils.normalizeComponentInstanceName(service.getName()));
resourceInstance.setIsProxy(false);
resourceInstance.setDescription("A substitutable node type for service " + service.getName());
return StorageOperationStatus.OK;
}
public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId,
String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null;
ComponentInstance resourceInstance = createAndAssotiateInfo.getNode();
RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate();
User user = validateUserExists(userId);
final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
if (ModelConverter.isAtomicComponent(containerComponent)) {
log.debug(CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE, containerComponent.assetType());
return Either
.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
}
validateCanWorkOnComponent(containerComponent, userId);
boolean failed = false;
try {
lockComponent(containerComponent, "createAndAssociateRIToRI");
log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
Component origComponent = getOriginComponentFromComponentInstance(resourceInstance);
log.debug(ENTITY_ON_GRAPH_IS_CREATED);
ComponentInstance resResourceInfo = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) {
associationInfo.setFromNode(resResourceInfo.getUniqueId());
} else {
associationInfo.setToNode(resResourceInfo.getUniqueId());
}
Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade
.associateResourceInstances(containerComponent, containerComponentId, associationInfo);
if (resultReqCapDef.isLeft()) {
log.debug(ENTITY_ON_GRAPH_IS_CREATED);
RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef);
resultOp = Either.left(resInfo);
return resultOp;
} else {
log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode());
resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(
componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
return resultOp;
}
} catch (ComponentException e) {
failed = true;
throw e;
} finally {
unlockComponent(failed, containerComponent);
}
}
private Component getOriginComponentFromComponentInstance(ComponentInstance componentInstance) {
return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getComponentUid());
}
private Component getInstanceOriginNode(ComponentInstance componentInstance) {
return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getActualComponentUid());
}
private Component getOriginComponentFromComponentInstance(String componentInstanceName, String origComponetId) {
Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(origComponetId);
if (eitherComponent.isRight()) {
log.debug("Failed to get origin component with id {} for component instance {} ", origComponetId, componentInstanceName);
throw new ByActionStatusComponentException(
componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null);
}
return eitherComponent.left().value();
}
private ComponentInstance createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent,
ComponentInstance componentInstance, User user) {
Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade
.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
if (result.isRight()) {
log.debug(FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE, componentInstance.getName());
throw new ByResponseFormatComponentException(componentsUtils
.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "",
null));
}
log.debug(ENTITY_ON_GRAPH_IS_CREATED);
Component updatedComponent = result.left().value().getLeft();
Map<String, String> existingEnvVersions = new HashMap<>();
// TODO existingEnvVersions ??
addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream()
.filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
if (!updatedInstanceOptional.isPresent()) {
log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
}
return updatedInstanceOptional.get();
}
public boolean isCloudSpecificArtifact(String artifact) {
if (artifact.contains(CLOUD_SPECIFIC_FIXED_KEY_WORD)) {
for (int i = 0; i < CLOUD_SPECIFIC_KEY_WORDS.length; i++) {
if (Arrays.stream(CLOUD_SPECIFIC_KEY_WORDS[i]).noneMatch(artifact::contains)) {
return false;
}
}
return true;
} else {
return false;
}
}
/**
* addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's
* artifacts
*
* @param containerComponent
* @param componentInstance
* @param originComponent
* @param user
* @param existingEnvVersions
* @return
*/
protected ActionStatus addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance,
org.openecomp.sdc.be.model.Component originComponent, User user,
Map<String, String> existingEnvVersions) {
log.debug("add artifacts to resource instance");
List<GroupDefinition> filteredGroups = new ArrayList<>();
ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance);
if (ActionStatus.OK != status) {
throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(status, "", null));
}
StorageOperationStatus artStatus;
// generate heat_env if necessary
Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts();
if (MapUtils.isNotEmpty(componentDeploymentArtifacts)) {
Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<>();
Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>();
Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getHeatArtifactDeploymentTimeout()
.getDefaultMinutes();
List<ArtifactDefinition> listOfCloudSpecificArts = new ArrayList<>();
for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) {
String type = artifact.getArtifactType();
if (!type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact);
}
if (type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HELM.getType()) || type
.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()) || type
.equalsIgnoreCase(ArtifactTypeEnum.CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT.getType())) {
artifact.setTimeout(defaultHeatTimeout);
} else {
continue;
}
if (artifact.checkEsIdExist()) {
ArtifactDefinition artifactDefinition = artifactBusinessLogic
.createHeatEnvPlaceHolder(new ArrayList<>(), artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(),
NodeTypeEnum.ResourceInstance, componentInstance.getName(), user, containerComponent, existingEnvVersions);
// put env
finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
if (CollectionUtils.isNotEmpty(originComponent.getGroups())) {
filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
}
if (isCloudSpecificArtifact(artifactDefinition.getArtifactName())) {
listOfCloudSpecificArts.add(artifact);
}
if (CollectionUtils.isNotEmpty(filteredGroups)) {
filteredGroups.stream()
.filter(g -> g.getArtifacts() != null &&
g.getArtifacts().stream().anyMatch(p -> p.equals(artifactDefinition.getGeneratedFromId()))).findFirst()
.ifPresent(g -> fillInstanceArtifactMap(groupInstancesArtifacts, artifactDefinition, g));
}
}
}
groupInstancesArtifacts.forEach((k, v) -> v.addAll(listOfCloudSpecificArts));
filteredGroups.forEach(g -> listOfCloudSpecificArts.forEach(e -> {
g.getArtifactsUuid().add(e.getArtifactUUID());
g.getArtifacts().add(e.getUniqueId());
}));
artStatus = toscaOperationFacade
.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
if (artStatus != StorageOperationStatus.OK) {
log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(),
containerComponent.getUniqueId(), artStatus);
throw new ByResponseFormatComponentException(
componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
}
StorageOperationStatus result = toscaOperationFacade
.addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
if (result != StorageOperationStatus.OK) {
log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId());
throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result)));
}
componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
}
artStatus = toscaOperationFacade
.addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts());
if (artStatus != StorageOperationStatus.OK) {
log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}",
componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
throw new ByResponseFormatComponentException(
componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
}
componentInstance.setArtifacts(originComponent.getArtifacts());
return ActionStatus.OK;
}
private void fillInstanceArtifactMap(Map<String, List<ArtifactDefinition>> groupInstancesArtifacts, ArtifactDefinition artifactDefinition,
GroupDefinition groupInstance) {
List<ArtifactDefinition> artifactsUid;
if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) {
artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId());
} else {
artifactsUid = new ArrayList<>();
}
artifactsUid.add(artifactDefinition);
groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid);
}
private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) {
Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic
.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null);
Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>();
if (getResourceDeploymentArtifacts.isRight()) {
StorageOperationStatus status = getResourceDeploymentArtifacts.right().value();
if (status != StorageOperationStatus.NOT_FOUND) {
log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status);
return componentsUtils.convertFromStorageResponseForResourceInstance(status, true);
}
} else {
deploymentArtifacts = getResourceDeploymentArtifacts.left().value();
}
if (!deploymentArtifacts.isEmpty()) {
Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<>(deploymentArtifacts);
for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) {
if (!artifact.getValue().checkEsIdExist()) {
tempDeploymentArtifacts.remove(artifact.getKey());
}
}
resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts);
}
return ActionStatus.OK;
}
public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId,
String componentInstanceId, String userId,
ComponentInstance componentInstance) {
return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, true);
}
public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(final String containerComponentParam,
final String containerComponentId,
final String componentInstanceId, final String userId,
ComponentInstance componentInstance, boolean needLock) {
validateUserExists(userId);
final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
final Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
validateCanWorkOnComponent(containerComponent, userId);
ComponentTypeEnum instanceType = getComponentType(containerComponentType);
Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade
.validateComponentExists(componentInstance.getComponentUid());
if (validateParentStatus.isRight()) {
log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId);
throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(),
instanceType.getValue().toLowerCase());
}
if (!Boolean.TRUE.equals(validateParentStatus.left().value())) {
throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(),
instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId);
}
if (needLock) {
lockComponent(containerComponent, "updateComponentInstance");
}
Component origComponent;
boolean failed = false;
try {
origComponent = getOriginComponentFromComponentInstance(componentInstance);
componentInstance = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId,
componentInstance);
} catch (ComponentException e) {
failed = true;
throw e;
} finally {
if (needLock) {
unlockComponent(failed, containerComponent);
}
}
return Either.left(componentInstance);
}
// New Multiple Instance Update API
public List<ComponentInstance> updateComponentInstance(String containerComponentParam, Component containerComponent, String containerComponentId,
String userId, List<ComponentInstance> componentInstanceList, boolean needLock) {
boolean failed = false;
try {
validateUserExists(userId);
final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
ComponentParametersView componentFilter = new ComponentParametersView();
componentFilter.disableAll();
componentFilter.setIgnoreUsers(false);
componentFilter.setIgnoreComponentInstances(false);
if (containerComponent == null) {
containerComponent = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter);
}
validateCanWorkOnComponent(containerComponent, userId);
ComponentTypeEnum instanceType = getComponentType(containerComponentType);
for (ComponentInstance componentInstance : componentInstanceList) {
boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId());
if (!validateParent) {
throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(),
instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId);
}
}
if (needLock) {
lockComponent(containerComponent, "updateComponentInstance");
}
List<ComponentInstance> updatedList = new ArrayList<>();
List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances();
List<ComponentInstance> listForUpdate = new ArrayList<>();
if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty()) {
containerComponent.setComponentInstances(componentInstanceList);
} else {
Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator();
while (iterator.hasNext()) {
ComponentInstance origInst = iterator.next();
Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId()))
.findAny();
if (op.isPresent()) {
ComponentInstance updatedCi = op.get();
updatedCi = buildComponentInstance(updatedCi, origInst);
Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName());
if (!Boolean.TRUE.equals(isUniqueName)) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
"Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ",
origInst.getName(), updatedCi.getName());
throw new ByResponseFormatComponentException(componentsUtils
.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
}
listForUpdate.add(updatedCi);
} else {
listForUpdate.add(origInst);
}
}
containerComponent.setComponentInstances(listForUpdate);
Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade
.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter);
if (updateStatus.isRight()) {
CommonUtility
.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ",
containerComponent.getName(), updateStatus.right().value());
throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(
componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
}
for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) {
Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName()))
.findAny();
if (op.isPresent()) {
updatedList.add(updatedInstance);
}
}
}
return updatedList;
} catch (ComponentException e) {
failed = true;
throw e;
} finally {
if (needLock) {
unlockComponent(failed, containerComponent);
}
}
}
private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) {
return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId));
}
private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) {
if (ComponentTypeEnum.PRODUCT == containerComponentType) {
return ComponentTypeEnum.SERVICE_INSTANCE;
} else {
return ComponentTypeEnum.RESOURCE_INSTANCE;
}
}
private ComponentInstance updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType,
org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
ComponentInstance componentInstance) {
Optional<ComponentInstance> componentInstanceOptional;
Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
ComponentInstance oldComponentInstance = null;
boolean isNameChanged = false;
componentInstanceOptional = containerComponent.getComponentInstances().stream()
.filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
if (!componentInstanceOptional.isPresent()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ",
componentInstance.getName(), containerComponent.getName());
throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
}
String oldComponentName;
oldComponentInstance = componentInstanceOptional.get();
oldComponentName = oldComponentInstance.getName();
String newInstanceName = componentInstance.getName();
if (oldComponentName != null && !oldComponentInstance.getName().equals(newInstanceName)) {
isNameChanged = true;
}
Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName);
if (!Boolean.TRUE.equals(isUniqueName)) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
"Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ",
oldComponentInstance.getName(), newInstanceName);
throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(),
componentInstance.getName());
}
if (!DirectivesUtil.isValid(componentInstance.getDirectives())) {
final String directivesStr = componentInstance.getDirectives().stream().collect(Collectors.joining(" , ", " [ ", " ] "));
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
"Failed to update the directives of the component instance {} to {}. Directives data {} is invalid. ", oldComponentInstance.getName(),
newInstanceName, directivesStr);
throw new ByActionStatusComponentException(ActionStatus.DIRECTIVES_INVALID_VALUE, containerComponentType.getValue(),
componentInstance.getName());
}
updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent,
updateComponentInstanceMetadata(oldComponentInstance, componentInstance));
if (updateRes.isRight()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
"Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(),
containerComponent.getName(), updateRes.right().value());
throw new ByResponseFormatComponentException(componentsUtils
.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true),
"", null));
} else {
// region - Update instance Groups
if (isNameChanged) {
Either<StorageOperationStatus, StorageOperationStatus> result = toscaOperationFacade
.cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId);
if (result.isRight()) {
CommonUtility
.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId,
result.right().value());
}
if (containerComponent instanceof Service) {
Either<ComponentInstance, ResponseFormat> renameEither = renameServiceFilter((Service) containerComponent, newInstanceName,
oldComponentInstance.getName());
if (renameEither.isRight()) {
throw new ByResponseFormatComponentException(renameEither.right().value());
}
updateForwardingPathDefinition(containerComponent, componentInstance, oldComponentName);
}
}
// endregion
}
String newInstanceId = updateRes.left().value().getRight();
Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream()
.filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
if (!updatedInstanceOptional.isPresent()) {
log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(),
containerComponent.getName());
throw new ByResponseFormatComponentException(
componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
}
return componentInstanceOptional.get();
}
private void updateForwardingPathDefinition(Component containerComponent, ComponentInstance componentInstance, String oldComponentName) {
Collection<ForwardingPathDataDefinition> forwardingPathDataDefinitions = getForwardingPathDataDefinitions(containerComponent.getUniqueId());
Set<ForwardingPathDataDefinition> updated = new ForwardingPathUtils()
.updateComponentInstanceName(forwardingPathDataDefinitions, oldComponentName, componentInstance.getName());
updated.forEach(fp -> {
Either<ForwardingPathDataDefinition, StorageOperationStatus> resultEither = forwardingPathOperation
.updateForwardingPath(containerComponent.getUniqueId(), fp);
if (resultEither.isRight()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.ERROR, "Failed to rename forwarding path for container {}. error {} ",
containerComponent.getName(), resultEither.right().value());
}
});
}
public Either<ComponentInstance, ResponseFormat> renameServiceFilter(final Service containerComponent, final String newInstanceName,
final String oldInstanceName) {
Map<String, CINodeFilterDataDefinition> renamedNodesFilter = ServiceFilterUtils
.getRenamedNodesFilter(containerComponent, oldInstanceName, newInstanceName);
for (Entry<String, CINodeFilterDataDefinition> entry : renamedNodesFilter.entrySet()) {
Either<CINodeFilterDataDefinition, StorageOperationStatus> renameEither = nodeFilterOperation
.updateNodeFilter(containerComponent.getUniqueId(), entry.getKey(), entry.getValue());
if (renameEither.isRight()) {
return Either.right(componentsUtils.getResponseFormatForResourceInstance(
componentsUtils.convertFromStorageResponse(renameEither.right().value(), ComponentTypeEnum.SERVICE), containerComponent.getName(),
null));
}
}
return Either.left(null);
}
/**
* @param oldPrefix- The normalized old vf name
* @param newNormailzedPrefix- The normalized new vf name
* @param qualifiedGroupInstanceName- old Group Instance Name
**/
// modify group names
private String getNewGroupName(String oldPrefix, String newNormailzedPrefix, String qualifiedGroupInstanceName) {
if (qualifiedGroupInstanceName == null) {
log.info("CANNOT change group name ");
return null;
}
if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName
.startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix))) {
return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix);
}
return qualifiedGroupInstanceName;
}
private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) {
oldComponentInstance.setName(newComponentInstance.getName());
oldComponentInstance.setModificationTime(System.currentTimeMillis());
oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString());
oldComponentInstance.setDirectives(newComponentInstance.getDirectives());
oldComponentInstance.setMaxOccurrences(newComponentInstance.getMaxOccurrences());
oldComponentInstance.setMinOccurrences(newComponentInstance.getMinOccurrences());
oldComponentInstance.setInstanceCount(newComponentInstance.getInstanceCount());
if (oldComponentInstance.getGroupInstances() != null) {
oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(),
ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName())));
}
return oldComponentInstance;
}
public ComponentInstance deleteComponentInstance(final String containerComponentParam, final String containerComponentId,
final String componentInstanceId, String userId) throws BusinessLogicException {
validateUserExists(userId);
final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
final Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
validateCanWorkOnComponent(containerComponent, userId);
boolean failed = false;
final Optional<ComponentInstance> componentInstanceOptional = containerComponent.getComponentInstanceById(componentInstanceId);
if (!componentInstanceOptional.isPresent()) {
throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND));
}
ComponentInstance componentInstance = componentInstanceOptional.get();
try {
if (containerComponent instanceof Service || containerComponent instanceof Resource) {
final Either<String, StorageOperationStatus> deleteServiceFilterEither = nodeFilterOperation
.deleteNodeFilter(containerComponent, componentInstanceId);
if (deleteServiceFilterEither.isRight()) {
final ActionStatus status = componentsUtils
.convertFromStorageResponse(deleteServiceFilterEither.right().value(), containerComponentType);
janusGraphDao.rollback();
throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(status, componentInstanceId));
}
final Either<ComponentInstance, ResponseFormat> resultOp = deleteNodeFiltersFromComponentInstance(containerComponent,
componentInstance, containerComponentType, userId);
if (resultOp.isRight()) {
janusGraphDao.rollback();
throw new ByResponseFormatComponentException(resultOp.right().value());
}
}
lockComponent(containerComponent, "deleteComponentInstance");
final ComponentInstance deletedCompInstance = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
componentInstance = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId, containerComponentType,
deletedCompInstance);
final ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator
.doOnDeleteInstanceOperations(containerComponent, componentInstanceId);
if (ActionStatus.OK != onDeleteOperationsStatus) {
throw new ByActionStatusComponentException(onDeleteOperationsStatus);
}
} catch (final ComponentException e) {
failed = true;
throw e;
} finally {
unlockComponent(failed, containerComponent);
}
return componentInstance;
}
/**
* Try to modify the delete and return two cases
*
* @param containerComponentParam
* @param containerComponentId
* @param componentInstanceId
* @param userId
* @return
*/
public Either<ComponentInstance, ResponseFormat> deleteAbstractComponentInstance(String containerComponentParam, String containerComponentId,
String componentInstanceId, String userId) {
log.debug("enter deleteAbstractComponentInstance");
validateUserExists(userId);
final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
validateCanWorkOnComponent(containerComponent, userId);
boolean failed = false;
ComponentInstance deletedRelatedInst;
try {
if (containerComponent instanceof Service) {
final Optional<ComponentInstance> componentInstanceById = containerComponent.getComponentInstanceById(componentInstanceId);
if (componentInstanceById.isPresent()) {
ComponentInstance componentInstance = componentInstanceById.get();
Either<String, StorageOperationStatus> deleteServiceFilterEither = nodeFilterOperation
.deleteNodeFilter(containerComponent, componentInstanceId);
if (deleteServiceFilterEither.isRight()) {
log.debug("enter deleteAbstractComponentInstance:deleteServiceFilterEither is right, filed");
ActionStatus status = componentsUtils
.convertFromStorageResponse(deleteServiceFilterEither.right().value(), containerComponentType);
janusGraphDao.rollback();
return Either.right(componentsUtils.getResponseFormat(status, componentInstance.getName()));
}
Either<ComponentInstance, ResponseFormat> resultOp = deleteNodeFiltersFromComponentInstance(containerComponent, componentInstance,
ComponentTypeEnum.SERVICE, userId);
if (resultOp.isRight()) {
log.debug("enter deleteAbstractComponentInstance:resultOp is right, filed");
janusGraphDao.rollback();
return resultOp;
}
}
}
log.debug("enter deleteAbstractComponentInstance:");
lockComponent(containerComponent, "deleteComponentInstance");
ComponentInstance deletedCompInstance = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
deletedRelatedInst = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId, containerComponentType,
deletedCompInstance);
ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator
.doOnDeleteInstanceOperations(containerComponent, componentInstanceId);
log.debug("enter deleteAbstractComponentInstance,get onDeleteOperationsStatus:{}", onDeleteOperationsStatus);
if (ActionStatus.OK != onDeleteOperationsStatus) {
throw new ByActionStatusComponentException(onDeleteOperationsStatus);
}
} catch (ComponentException e) {
failed = true;
throw e;
} finally {
unlockComponent(failed, containerComponent);
}
log.debug("enter deleteAbstractComponentInstance,deleted RelatedInst success");
return Either.left(deletedRelatedInst);
}
public Either<ComponentInstance, ResponseFormat> deleteNodeFiltersFromComponentInstance(final Component component,
final ComponentInstance componentInstance,
final ComponentTypeEnum containerComponentType,
final String userId) {
final Set<String> componentFiltersIDsToBeDeleted = getComponentFiltersRelatedToComponentInstance(component.getUniqueId(), componentInstance);
if (!componentFiltersIDsToBeDeleted.isEmpty()) {
final Set<String> ids = component.getComponentInstances().stream().filter(ci -> componentFiltersIDsToBeDeleted.contains(ci.getName()))
.map(ComponentInstance::getUniqueId).collect(Collectors.toSet());
final Either<Set<String>, StorageOperationStatus> deleteComponentNodeFiltersEither = nodeFilterOperation
.deleteNodeFilters(component, ids);
if (deleteComponentNodeFiltersEither.isRight()) {
final ActionStatus status = componentsUtils
.convertFromStorageResponse(deleteComponentNodeFiltersEither.right().value(), containerComponentType);
return Either.right(componentsUtils.getResponseFormat(status, componentInstance.getName()));
}
for (final String id : ids) {
final Optional<ComponentInstance> componentInstanceById = component.getComponentInstanceById(id);
if (!componentInstanceById.isPresent()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
final ComponentInstance componentInstanceToBeUpdated = componentInstanceById.get();
componentInstanceToBeUpdated.setDirectives(Collections.emptyList());
final Either<ComponentInstance, ResponseFormat> componentInstanceResponseFormatEither = updateComponentInstanceMetadata(
containerComponentType.getValue(), component.getUniqueId(), componentInstanceToBeUpdated.getUniqueId(), userId,
componentInstanceToBeUpdated, false);
if (componentInstanceResponseFormatEither.isRight()) {
return componentInstanceResponseFormatEither;
}
}
}
return Either.left(componentInstance);
}
private Set<String> getComponentFiltersRelatedToComponentInstance(String containerComponentId, ComponentInstance componentInstance) {
ComponentParametersView filter = new ComponentParametersView(true);
filter.setIgnoreComponentInstances(false);
Either<Component, StorageOperationStatus> componentFilterOrigin = toscaOperationFacade.getToscaElement(containerComponentId, filter);
final Component component = componentFilterOrigin.left().value();
return ComponentsUtils.getNodesFiltersToBeDeleted(component, componentInstance);
}
ComponentInstance deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId, ComponentTypeEnum containerComponentType,
ComponentInstance componentInstance) {
if (containerComponentType == ComponentTypeEnum.SERVICE) {
List<String> pathIDsToBeDeleted = getForwardingPathsRelatedToComponentInstance(containerComponentId, componentInstance.getName());
if (!pathIDsToBeDeleted.isEmpty()) {
deleteForwardingPaths(containerComponentId, pathIDsToBeDeleted);
}
}
return componentInstance;
}
private void deleteForwardingPaths(String serviceId, List<String> pathIdsToDelete) {
Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
if (storageStatus.isRight()) {
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus.right().value()));
}
Either<Set<String>, StorageOperationStatus> result = forwardingPathOperation
.deleteForwardingPath(storageStatus.left().value(), Sets.newHashSet(pathIdsToDelete));
if (result.isRight()) {
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(result.right().value()));
}
}
private List<String> getForwardingPathsRelatedToComponentInstance(String containerComponentId, String componentInstanceId) {
Collection<ForwardingPathDataDefinition> allPaths = getForwardingPathDataDefinitions(containerComponentId);
List<String> pathIDsToBeDeleted = new ArrayList<>();
allPaths.stream().filter(path -> isPathRelatedToComponent(path, componentInstanceId))
.forEach(path -> pathIDsToBeDeleted.add(path.getUniqueId()));
return pathIDsToBeDeleted;
}
private Collection<ForwardingPathDataDefinition> getForwardingPathDataDefinitions(String containerComponentId) {
ComponentParametersView filter = new ComponentParametersView(true);
filter.setIgnoreServicePath(false);
Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade.getToscaElement(containerComponentId, filter);
return forwardingPathOrigin.left().value().getForwardingPaths().values();
}
private boolean isPathRelatedToComponent(ForwardingPathDataDefinition pathDataDefinition, String componentInstanceId) {
return pathDataDefinition.getPathElements().getListToscaDataDefinition().stream().anyMatch(
elementDataDefinition -> elementDataDefinition.getFromNode().equalsIgnoreCase(componentInstanceId) || elementDataDefinition.getToNode()
.equalsIgnoreCase(componentInstanceId));
}
private ComponentInstance deleteComponentInstance(Component containerComponent, String componentInstanceId,
ComponentTypeEnum containerComponentType) {
Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade
.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
if (deleteRes.isRight()) {
log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId);
ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType);
throw new ByActionStatusComponentException(status, componentInstanceId);
}
log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent);
ComponentInstance deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent);
if (CollectionUtils.isNotEmpty(containerComponent.getInputs())) {
List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream()
.filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
if (CollectionUtils.isNotEmpty(inputsToDelete)) {
StorageOperationStatus deleteInputsRes = toscaOperationFacade
.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, inputsToDelete);
if (deleteInputsRes != StorageOperationStatus.OK) {
log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType),
componentInstanceId);
}
}
}
if (CollectionUtils.isNotEmpty(containerComponent.getOutputs())) {
final List<OutputDefinition> outputsToDelete = containerComponent.getOutputs().stream()
.filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
if (CollectionUtils.isNotEmpty(outputsToDelete)) {
final StorageOperationStatus deleteOutputsRes = toscaOperationFacade
.deleteComponentInstanceOutputsFromTopologyTemplate(containerComponent, outputsToDelete);
if (deleteOutputsRes != StorageOperationStatus.OK) {
log.debug("Failed to delete outputs of the component instance {} from container component. ", componentInstanceId);
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(deleteOutputsRes, containerComponentType),
componentInstanceId);
}
}
}
return deletedInstance;
}
private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) {
ComponentInstance foundInstance = null;
for (ComponentInstance instance : containerComponent.getComponentInstances()) {
if (instance.getUniqueId().equals(componentInstanceId)) {
foundInstance = instance;
containerComponent.getComponentInstances().remove(instance);
break;
}
}
findAndRemoveComponentInstanceRelations(componentInstanceId, containerComponent);
return foundInstance;
}
private void findAndRemoveComponentInstanceRelations(String componentInstanceId, Component containerComponent) {
if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstancesRelations())) {
containerComponent.setComponentInstancesRelations(
containerComponent.getComponentInstancesRelations().stream().filter(r -> isNotBelongingRelation(componentInstanceId, r))
.collect(Collectors.toList()));
}
}
private boolean isNotBelongingRelation(String componentInstanceId, RequirementCapabilityRelDef relation) {
return !relation.getToNode().equals(componentInstanceId) && !relation.getFromNode().equals(componentInstanceId);
}
public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef,
ComponentTypeEnum componentTypeEnum) {
return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, true);
}
public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef,
ComponentTypeEnum componentTypeEnum, boolean needLock) {
validateUserExists(userId);
RequirementCapabilityRelDef requirementCapabilityRelDef;
org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
validateCanWorkOnComponent(containerComponent, userId);
boolean failed = false;
try {
if (needLock) {
lockComponent(containerComponent, ASSOCIATE_RI_TO_RI);
}
requirementCapabilityRelDef = associateRIToRIOnGraph(containerComponent, requirementDef);
} catch (ComponentException e) {
failed = true;
throw e;
} finally {
if (needLock) {
unlockComponent(failed, containerComponent);
}
}
return requirementCapabilityRelDef;
}
public RequirementCapabilityRelDef associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef) {
log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade
.associateResourceInstances(null, containerComponent.getUniqueId(), requirementDef);
if (result.isLeft()) {
log.debug(ENTITY_ON_GRAPH_IS_CREATED);
return result.left().value();
} else {
log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
String fromNameOrId = "";
String toNameOrId = "";
Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
toNameOrId = requirementDef.getFromNode();
fromNameOrId = requirementDef.getFromNode();
if (fromResult.isLeft()) {
fromNameOrId = fromResult.left().value().getName();
}
if (toResult.isLeft()) {
toNameOrId = toResult.left().value().getName();
}
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true),
fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement());
}
}
/**
* @param componentId
* @param userId
* @param requirementDefList
* @param componentTypeEnum
* @return
*/
public List<RequirementCapabilityRelDef> batchDissociateRIFromRI(String componentId, String userId,
List<RequirementCapabilityRelDef> requirementDefList,
ComponentTypeEnum componentTypeEnum) {
validateUserExists(userId);
org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
validateCanWorkOnComponent(containerComponent, userId);
boolean failed = false;
List<RequirementCapabilityRelDef> delOkResult = new ArrayList<>();
try {
lockComponent(containerComponent, ASSOCIATE_RI_TO_RI);
for (RequirementCapabilityRelDef requirementDef : requirementDefList) {
RequirementCapabilityRelDef requirementCapabilityRelDef = dissociateRIFromRI(componentId, userId, requirementDef,
containerComponent.getComponentType());
delOkResult.add(requirementCapabilityRelDef);
}
} catch (ComponentException e) {
failed = true;
throw e;
} finally {
unlockComponent(failed, containerComponent);
}
return delOkResult;
}
public RequirementCapabilityRelDef dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef,
ComponentTypeEnum componentTypeEnum) {
validateUserExists(userId);
org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
validateCanWorkOnComponent(containerComponent, userId);
boolean failed = false;
try {
lockComponent(containerComponent, ASSOCIATE_RI_TO_RI);
log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade
.dissociateResourceInstances(componentId, requirementDef);
if (result.isLeft()) {
log.debug(ENTITY_ON_GRAPH_IS_CREATED);
return result.left().value();
} else {
log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
String fromNameOrId = "";
String toNameOrId = "";
Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent,
requirementDef.getFromNode());
Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
toNameOrId = requirementDef.getFromNode();
fromNameOrId = requirementDef.getFromNode();
if (fromResult.isLeft()) {
fromNameOrId = fromResult.left().value().getName();
}
if (toResult.isLeft()) {
toNameOrId = toResult.left().value().getName();
}
throw new ByActionStatusComponentException(
componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId,
requirementDef.getRelationships().get(0).getRelation().getRequirement());
}
} catch (ComponentException e) {
failed = true;
throw e;
} finally {
unlockComponent(failed, containerComponent);
}
}
/**
* Allows to get relation contained in specified component according to received Id
*
* @param componentId
* @param relationId
* @param userId
* @param componentTypeEnum
* @return
*/
public Either<RequirementCapabilityRelDef, ResponseFormat> getRelationById(String componentId, String relationId, String userId,
ComponentTypeEnum componentTypeEnum) {
Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
try {
org.openecomp.sdc.be.model.Component containerComponent = null;
RequirementCapabilityRelDef foundRelation = null;
validateUserExists(userId);
containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
List<RequirementCapabilityRelDef> requirementCapabilityRelations = containerComponent.getComponentInstancesRelations();
foundRelation = findRelation(relationId, requirementCapabilityRelations);
if (foundRelation == null) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId);
log.debug("Relation with id {} was not found on the component", relationId, componentId);
resultOp = Either.right(responseFormat);
}
if (resultOp == null) {
resultOp = setRelatedCapability(foundRelation, containerComponent);
}
if (resultOp.isLeft()) {
resultOp = setRelatedRequirement(foundRelation, containerComponent);
}
} catch (Exception e) {
log.error("The exception {} occured upon get relation {} of the component {} ", e, relationId, componentId);
resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
return resultOp;
}
private RequirementCapabilityRelDef findRelation(String relationId, List<RequirementCapabilityRelDef> requirementCapabilityRelations) {
for (RequirementCapabilityRelDef relationship : requirementCapabilityRelations) {
if (relationship.getRelationships().stream().anyMatch(r -> r.getRelation().getId().equals(relationId))) {
return relationship;
}
}
return null;
}
private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedRequirement(RequirementCapabilityRelDef foundRelation,
Component containerComponent) {
Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
String instanceId = foundRelation.getFromNode();
Optional<RequirementDefinition> foundRequirement;
Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId))
.findFirst();
if (!instance.isPresent()) {
ResponseFormat responseFormat = componentsUtils
.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance",
containerComponent.getComponentType().getValue(), containerComponent.getName());
log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
result = Either.right(responseFormat);
}
if (result == null && instance.isPresent()) {
for (List<RequirementDefinition> requirements : instance.get().getRequirements().values()) {
foundRequirement = requirements.stream()
.filter(r -> isBelongingCalcRequirement(relationshipInfo, r, containerComponent.getLifecycleState())).findFirst();
if (foundRequirement.isPresent()) {
foundRelation.resolveSingleRelationship().setRequirement(foundRequirement.get());
result = Either.left(foundRelation);
}
}
}
if (result == null) {
Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade
.getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, this::isBelongingFullRequirement);
if (getfulfilledRequirementRes.isRight()) {
ResponseFormat responseFormat = componentsUtils
.getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), instanceId,
containerComponent.getUniqueId());
log.debug("Requirement {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId,
containerComponent.getUniqueId());
result = Either.right(responseFormat);
} else {
foundRelation.resolveSingleRelationship().setRequirement(getfulfilledRequirementRes.left().value());
}
}
if (result == null) {
result = Either.left(foundRelation);
}
return result;
}
private boolean isBelongingFullRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) {
return req.getName().equals(relationshipInfo.getRequirement()) && req.getUniqueId().equals(relationshipInfo.getRequirementUid()) && req
.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
}
private boolean isBelongingCalcRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req, LifecycleStateEnum state) {
return nameMatches(relationshipInfo.getRequirement(), req.getName(), req.getPreviousName(), state) && req.getUniqueId()
.equals(relationshipInfo.getRequirementUid()) && req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
}
private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedCapability(RequirementCapabilityRelDef foundRelation,
Component containerComponent) {
Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
String instanceId = foundRelation.getToNode();
Optional<CapabilityDefinition> foundCapability;
Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId))
.findFirst();
if (!instance.isPresent()) {
ResponseFormat responseFormat = componentsUtils
.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance",
containerComponent.getComponentType().getValue(), containerComponent.getName());
log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
result = Either.right(responseFormat);
}
if (result == null && instance.isPresent()) {
for (List<CapabilityDefinition> capabilities : instance.get().getCapabilities().values()) {
foundCapability = capabilities.stream()
.filter(c -> isBelongingCalcCapability(relationshipInfo, c, containerComponent.getLifecycleState())).findFirst();
if (foundCapability.isPresent()) {
foundRelation.resolveSingleRelationship().setCapability(foundCapability.get());
result = Either.left(foundRelation);
}
}
}
if (result == null) {
Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade
.getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, this::isBelongingFullCapability);
if (getfulfilledRequirementRes.isRight()) {
ResponseFormat responseFormat = componentsUtils
.getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), instanceId,
containerComponent.getUniqueId());
log.debug("Capability {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId,
containerComponent.getUniqueId());
result = Either.right(responseFormat);
} else {
foundRelation.resolveSingleRelationship().setCapability(getfulfilledRequirementRes.left().value());
}
}
if (result == null) {
result = Either.left(foundRelation);
}
return result;
}
private boolean isBelongingFullCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) {
return cap.getName().equals(relationshipInfo.getCapability()) && cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) && cap
.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
}
private boolean isBelongingCalcCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap, LifecycleStateEnum state) {
return nameMatches(relationshipInfo.getCapability(), cap.getName(), cap.getPreviousName(), state) && cap.getUniqueId()
.equals(relationshipInfo.getCapabilityUid()) && cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
}
private boolean nameMatches(String nameFromRelationship, String currName, String previousName, LifecycleStateEnum state) {
return state == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT ? currName.equals(nameFromRelationship)
: previousName != null && previousName.equals(nameFromRelationship);
}
private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation
.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
Either<ComponentInstanceProperty, ResponseFormat> result;
if (eitherAttribute.isLeft()) {
log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid());
ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
result = Either.left(instanceAttribute);
} else {
log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId);
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
}
return result;
}
private Either<ComponentInstanceProperty, ResponseFormat> createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
Either<ComponentInstanceProperty, ResponseFormat> result;
Wrapper<Integer> indexCounterWrapper = new Wrapper<>();
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper);
if (!errorWrapper.isEmpty()) {
result = Either.right(errorWrapper.getInnerElement());
} else {
Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation
.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
if (eitherAttribute.isLeft()) {
log.debug("Attribute value was added to resource instance {}", resourceInstanceId);
ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
result = Either.left(instanceAttribute);
} else {
log.debug("Failed to add attribute value {} to resource instance {}", attribute, resourceInstanceId);
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
}
}
return result;
}
/**
* Create Or Updates Attribute Instance
*
* @param componentTypeEnum
* @param componentId
* @param resourceInstanceId
* @param attribute
* @param userId
* @return
*/
public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId,
String resourceInstanceId,
ComponentInstanceProperty attribute, String userId) {
Either<ComponentInstanceProperty, ResponseFormat> result = null;
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
validateUserExists(userId);
if (errorWrapper.isEmpty()) {
validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper);
}
if (errorWrapper.isEmpty()) {
validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper);
}
if (errorWrapper.isEmpty()) {
validateComponentLock(componentId, componentTypeEnum, errorWrapper);
}
try {
if (errorWrapper.isEmpty()) {
final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid());
if (isCreate) {
result = createAttributeValue(attribute, resourceInstanceId);
} else {
result = updateAttributeValue(attribute, resourceInstanceId);
}
} else {
result = Either.right(errorWrapper.getInnerElement());
}
return result;
} finally {
if (result == null || result.isRight()) {
janusGraphDao.rollback();
} else {
janusGraphDao.commit();
}
// unlock resource
graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
}
}
public Either<List<ComponentInstanceProperty>, ResponseFormat> createOrUpdatePropertiesValues(ComponentTypeEnum componentTypeEnum,
String componentId, String resourceInstanceId,
List<ComponentInstanceProperty> properties,
String userId) {
Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
/*-------------------------------Validations---------------------------------*/
validateUserExists(userId);
if (componentTypeEnum == null) {
BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
return resultOp;
}
Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
if (getResourceResult.isRight()) {
log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResourceResult.right().value(), componentTypeEnum);
return Either.right(componentsUtils.getResponseFormat(actionStatus, componentId));
}
Component containerComponent = getResourceResult.left().value();
if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
if (Boolean.TRUE.equals(containerComponent.isArchived())) {
log.info(COMPONENT_ARCHIVED, componentId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, containerComponent.getName()));
}
log.info(RESTRICTED_OPERATION_ON_SERVIVE, userId, componentId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
if (resourceInstanceStatus.isRight()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
resourceInstanceId, RESOURCE_INSTANCE, SERVICE, componentId));
}
ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
// Validate instance property against it's constrains
Either<Boolean, ResponseFormat> constraintValidatorResponse = validatePropertyValueConstraint(properties, componentId);
if (constraintValidatorResponse.isRight()) {
log.error("Failed validation value and constraint of property: {}", constraintValidatorResponse.right().value());
return Either.right(constraintValidatorResponse.right().value());
}
// lock resource
StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
if (lockStatus != StorageOperationStatus.OK) {
log.debug(FAILED_TO_LOCK_SERVICE, componentId);
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
}
List<ComponentInstanceProperty> updatedProperties = new ArrayList<>();
try {
for (ComponentInstanceProperty property : properties) {
validateMandatoryFields(property);
validatePropertyExistsOnComponent(property, containerComponent, foundResourceInstance);
validatePropertyConstraintsNotChanged(properties, foundResourceInstance);
String propertyParentUniqueId = property.getParentUniqueId();
if (property.isToscaFunction()) {
toscaFunctionValidator.validate(property, containerComponent);
property.setValue(property.getToscaFunction().getValue());
}
if (CollectionUtils.isNotEmpty(property.getSubPropertyToscaFunctions())) {
ToscaPropertyType type = ToscaPropertyType.isValidType(property.getType());
if (ToscaPropertyType.LIST.equals(type)) {
final JSONArray jsonArray = property.getValue() == null ? new JSONArray() : new JSONArray(property.getValue());
property.getSubPropertyToscaFunctions().stream().forEach(subToscaFunction -> {
addE(jsonArray, subToscaFunction.getSubPropertyPath(), subToscaFunction.getToscaFunction().getValue());
});
property.setValue(jsonArray.toString());
} else {
final JSONObject jObject = property.getValue() == null ? new JSONObject() : new JSONObject(property.getValue());
property.getSubPropertyToscaFunctions().stream().forEach(subToscaFunction -> {
addE(jObject, subToscaFunction.getSubPropertyPath(), subToscaFunction.getToscaFunction().getValue());
});
property.setValue(jObject.toString());
}
}
Either<String, ResponseFormat> updatedPropertyValue = updatePropertyObjectValue(property, containerComponent.getModel());
if (updatedPropertyValue.isRight()) {
log.error("Failed to update property object value of property: {}",
property);
throw new ByResponseFormatComponentException(updatedPropertyValue.right().value());
}
Optional<CapabilityDefinition>
capPropDefinition = getPropertyCapabilityOfChildInstance(propertyParentUniqueId, foundResourceInstance.getCapabilities());
if (capPropDefinition.isPresent()) {
updatedPropertyValue
.bimap(updatedValue -> updateCapabilityPropFromUpdateInstProp(property, updatedValue,
containerComponent, foundResourceInstance, capPropDefinition.get().getType(),
capPropDefinition.get().getName()), Either::right);
} else {
updatedPropertyValue.bimap(
updatedValue -> updatePropertyOnContainerComponent(property, updatedValue, containerComponent, foundResourceInstance),
Either::right
);
updatedProperties.add(property);
}
}
Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
if (updateContainerRes.isRight()) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
return resultOp;
}
resultOp = Either.left(updatedProperties);
return resultOp;
} catch (final ComponentException e) {
return Either.right(e.getResponseFormat());
} finally {
if (resultOp == null || resultOp.isRight()) {
janusGraphDao.rollback();
} else {
janusGraphDao.commit();
}
// unlock resource
graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
}
}
private void addE(JSONArray jsonArray, List<String> path, String value) {
Object objectForPath = jsonArray.opt(Integer.parseInt(path.get(0)));
if (objectForPath == null) {
if (path.size() > 1) {
if (StringUtils.isNumeric(path.get(1))) {
objectForPath = new JSONArray();
} else {
objectForPath = new JSONObject();
}
jsonArray.put(Integer.parseInt(path.get(0)), objectForPath);
}
}
if (path.size() == 1) {
Object valueAsObject = new Yaml().loadAs(value, Object.class);
jsonArray.put(Integer.parseInt(path.get(0)), valueAsObject);
} else {
if (objectForPath instanceof JSONObject) {
addE((JSONObject) objectForPath, path.subList(1, path.size()), value);
} else {
addE((JSONArray) objectForPath, path.subList(1, path.size()), value);
}
}
}
private void addE(JSONObject jsonObject, List<String> path, String value) {
Object objectForPath = null;
if (jsonObject.has(path.get(0))) {
objectForPath = jsonObject.get(path.get(0));
} else {
if (path.size() > 1 && StringUtils.isNumeric(path.get(1))) {
objectForPath = new JSONArray();
} else {
objectForPath = new JSONObject();
}
jsonObject.put(path.get(0), objectForPath);
}
if (path.size() == 1) {
Object valueAsObject = new Yaml().loadAs(value, Object.class);
jsonObject.put(path.get(0), valueAsObject);
} else {
if (objectForPath instanceof JSONObject) {
addE((JSONObject) objectForPath, path.subList(1, path.size()), value);
} else {
addE((JSONArray) objectForPath, path.subList(1, path.size()), value);
}
}
}
private void setJsonObjectForSubProperty(final JSONObject jObject, final List<String> path, String value) {
if (path.size() == 1) {
Object valueAsObject = new Yaml().loadAs(value, Object.class);
jObject.put(path.get(0), valueAsObject);
} else {
if (!jObject.has(path.get(0))) {
jObject.put(path.get(0), new JSONObject());
}
final JSONObject jsonObject = jObject.getJSONObject(path.get(0));
setJsonObjectForSubProperty(jsonObject, path.subList(1, path.size()), value);
}
}
public Either<List<ComponentInstanceAttribute>, ResponseFormat> createOrUpdateAttributeValues(final ComponentTypeEnum componentTypeEnum,
final String componentId,
final String resourceInstanceId,
final List<ComponentInstanceAttribute> attributes,
final String userId) {
Either<List<ComponentInstanceAttribute>, ResponseFormat> resultOp = null;
/*-------------------------------Validations---------------------------------*/
validateUserExists(userId);
if (componentTypeEnum == null) {
BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
return resultOp;
}
final Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade
.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
if (getResourceResult.isRight()) {
log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
final ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResourceResult.right().value(), componentTypeEnum);
return Either.right(componentsUtils.getResponseFormat(actionStatus, componentId));
}
final Component containerComponent = getResourceResult.left().value();
if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
if (Boolean.TRUE.equals(containerComponent.isArchived())) {
log.info(COMPONENT_ARCHIVED, componentId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, containerComponent.getName()));
}
log.info(RESTRICTED_OPERATION_ON_SERVIVE, userId, componentId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
final Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
resourceInstanceId);
if (resourceInstanceStatus.isRight()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
resourceInstanceId, RESOURCE_INSTANCE, SERVICE, componentId));
}
final ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
// Validate instance attributes against it's constraints
List<PropertyDefinition> attributesToValidate = new ArrayList<>();
attributes.forEach((componentInstanceAttribute) -> {
PropertyDefinition propertyDefinition = new PropertyDefinition();
propertyDefinition.setValue(componentInstanceAttribute.getValue());
propertyDefinition.setType(componentInstanceAttribute.getType());
propertyDefinition.setName(componentInstanceAttribute.getName());
propertyDefinition.setUniqueId(componentInstanceAttribute.getUniqueId());
attributesToValidate.add(propertyDefinition);
});
Either<Boolean, ResponseFormat> constraintValidatorResponse = validatePropertyValueConstraint(attributesToValidate, componentId);
if (constraintValidatorResponse.isRight()) {
log.error("Failed validation value and constraint of attribute: {}", constraintValidatorResponse.right().value());
return Either.right(constraintValidatorResponse.right().value());
}
// lock resource
final StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
if (lockStatus != StorageOperationStatus.OK) {
log.debug(FAILED_TO_LOCK_SERVICE, componentId);
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
}
final List<ComponentInstanceAttribute> updatedProperties = new ArrayList<>();
try {
for (final ComponentInstanceAttribute attribute : attributes) {
final ComponentInstanceAttribute componentInstanceProperty = validateAttributeExistsOnComponent(attribute, containerComponent,
foundResourceInstance);
final Either<String, ResponseFormat> updatedPropertyValue = updateAttributeObjectValue(attribute);
if (updatedPropertyValue.isRight()) {
log.error("Failed to update attribute object value of attribute: {}", attribute);
throw new ByResponseFormatComponentException(updatedPropertyValue.right().value());
}
updatedPropertyValue.bimap(
updatedValue -> {
componentInstanceProperty.setValue(updatedValue);
return updateAttributeOnContainerComponent(attribute, updatedValue,
containerComponent, foundResourceInstance);
}, Either::right);
updatedProperties.add(componentInstanceProperty);
}
final Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
if (updateContainerRes.isRight()) {
final ActionStatus actionStatus = componentsUtils
.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
return resultOp;
}
resultOp = Either.left(updatedProperties);
return resultOp;
} catch (final ComponentException e) {
return Either.right(e.getResponseFormat());
} finally {
if (resultOp == null || resultOp.isRight()) {
janusGraphDao.rollback();
} else {
janusGraphDao.commit();
}
// unlock resource
graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
}
}
private void validateMandatoryFields(PropertyDataDefinition property) {
if (StringUtils.isEmpty(property.getName())) {
throw new ByActionStatusComponentException(ActionStatus.MISSING_PROPERTY_NAME);
}
}
private void validatePropertyExistsOnComponent(ComponentInstanceProperty property, Component containerComponent,
ComponentInstance foundResourceInstance) {
List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties()
.get(foundResourceInstance.getUniqueId());
final boolean hasProperty = instanceProperties.stream().anyMatch(p -> p.getName().equals(property.getName()));
if (!hasProperty) {
throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, property.getName());
}
}
private ComponentInstanceAttribute validateAttributeExistsOnComponent(final ComponentInstanceAttribute attribute,
final Component containerComponent,
final ComponentInstance foundResourceInstance) {
final List<ComponentInstanceAttribute> instanceProperties =
containerComponent.getComponentInstancesAttributes().get(foundResourceInstance.getUniqueId());
final Optional<ComponentInstanceAttribute> instanceAttribute =
instanceProperties.stream().filter(p -> p.getName().equals(attribute.getName())).findAny();
if (!instanceAttribute.isPresent()) {
throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, attribute.getName());
}
return instanceAttribute.get();
}
private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property,
String newValue, Component containerComponent,
ComponentInstance foundResourceInstance,
String capabilityType, String capabilityName) {
String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent,
foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
if (actionStatus != null) {
return actionStatus;
}
return componentsUtils.getResponseFormat(ActionStatus.OK);
}
private ResponseFormat updateCapabilityPropFromUpdateInstProp(ComponentInstanceProperty property,
String newValue, Component containerComponent,
ComponentInstance foundResourceInstance,
String capabilityType, String capabilityName) {
String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
Either<Component, StorageOperationStatus> getComponentRes =
toscaOperationFacade.getToscaFullElement(foundResourceInstance.getComponentUid());
if (getComponentRes.isRight()) {
return componentsUtils.getResponseFormat(getComponentRes.right().value());
}
ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent,
foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
if (actionStatus != null) {
return actionStatus;
}
return componentsUtils.getResponseFormat(ActionStatus.OK);
}
private ResponseFormat updateCapPropOnContainerComponent(ComponentInstanceProperty property, String newValue,
Component containerComponent,
ComponentInstance foundResourceInstance,
String capabilityType, String capabilityName,
String componentInstanceUniqueId) {
Map<String, List<CapabilityDefinition>> capabilities =
Optional.ofNullable(foundResourceInstance.getCapabilities()).orElse(Collections.emptyMap());
List<CapabilityDefinition> capPerType =
Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList());
Optional<CapabilityDefinition> cap =
capPerType.stream().filter(c -> c.getName().equals(capabilityName)).findAny();
if (cap.isPresent()) {
List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
if (capProperties != null) {
Optional<ComponentInstanceProperty> instanceProperty =
capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
StorageOperationStatus status;
if (instanceProperty.isPresent()) {
String capKey = ModelConverter
.buildCapabilityPropertyKey(foundResourceInstance.getOriginType().isAtomicType(), capabilityType, capabilityName,
componentInstanceUniqueId, cap.get());
instanceProperty.get().setValue(newValue);
List<String> path = new ArrayList<>();
path.add(componentInstanceUniqueId);
path.add(capKey);
instanceProperty.get().setPath(path);
status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent,
componentInstanceUniqueId, capKey, instanceProperty.get());
if (status != StorageOperationStatus.OK) {
ActionStatus actionStatus =
componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
}
foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
}
}
}
return null;
}
private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty instanceProperty, String newValue,
Component containerComponent, ComponentInstance foundResourceInstance) {
StorageOperationStatus status;
instanceProperty.setValue(newValue);
status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), instanceProperty);
if (status != StorageOperationStatus.OK) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
}
foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
return componentsUtils.getResponseFormat(ActionStatus.OK);
}
private ResponseFormat updateAttributeOnContainerComponent(final ComponentInstanceAttribute instanceAttribute,
final String newValue,
final Component containerComponent,
final ComponentInstance foundResourceInstance) {
instanceAttribute.setValue(newValue);
final StorageOperationStatus status =
toscaOperationFacade.updateComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), instanceAttribute);
if (status != StorageOperationStatus.OK) {
final ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
}
foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
return componentsUtils.getResponseFormat(ActionStatus.OK);
}
private <T extends PropertyDefinition> Either<String, ResponseFormat> validatePropertyObjectValue(T property, String newValue, boolean isInput) {
final Map<String, DataTypeDefinition> allDataTypes = componentsUtils.getAllDataTypes(applicationDataTypeCache, property.getModel());
String propertyType = property.getType();
String innerType = getInnerType(property);
// Specific Update Logic
Either<Object, Boolean> isValid = propertyOperation
.validateAndUpdatePropertyValue(property.getType(), newValue, true, innerType, allDataTypes);
if (isValid.isRight()) {
if (!Boolean.TRUE.equals(isValid.right().value())) {
log.error("Invalid value {} of property {} ", newValue, property.getName());
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
} else {
Object object = isValid.left().value();
if (object != null) {
newValue = object.toString();
}
}
if (validateAndUpdateRules(property, isInput, allDataTypes, innerType, propertyType)) {
return Either.right(componentsUtils.getResponseFormat(componentsUtils
.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
}
return Either.left(newValue);
}
private <T extends PropertyDefinition> boolean validateAndUpdateRules(T property, boolean isInput, Map<String, DataTypeDefinition> allDataTypes,
String innerType, String propertyType) {
if (!isInput) {
ImmutablePair<String, Boolean> pair = propertyOperation
.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
if (pair.getRight() != null && !pair.getRight()) {
BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
return true;
}
}
return false;
}
private <T extends PropertyDefinition> Either<String, ResponseFormat> updatePropertyObjectValue(T property, final String model) {
final Map<String, DataTypeDefinition> allDataTypes = componentsUtils.getAllDataTypes(applicationDataTypeCache, model);
String innerType = null;
String propertyType = property.getType();
ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
SchemaDefinition schema = property.getSchema();
if (schema == null) {
log.debug("Schema doesn't exists for property of type {}", type);
return Either
.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
}
PropertyDataDefinition propDef = schema.getProperty();
if (propDef == null) {
log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
return Either
.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
}
innerType = propDef.getType();
}
// Specific Update Logic
String newValue = property.getValue();
if (property.hasToscaFunction() || CollectionUtils.isNotEmpty(property.getSubPropertyToscaFunctions())) {
return Either.left(newValue);
}
Either<Object, Boolean> isValid = propertyOperation
.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
if (isValid.isRight()) {
if (!Boolean.TRUE.equals(isValid.right().value())) {
log.debug("validate and update property value has failed with value: {}", property.getValue());
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
}
} else {
Object object = isValid.left().value();
if (object != null) {
newValue = object.toString();
}
}
ImmutablePair<String, Boolean> pair = propertyOperation
.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
if (pair.getRight() != null && Boolean.FALSE.equals(pair.getRight())) {
BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
}
return Either.left(newValue);
}
private <T extends AttributeDefinition> Either<String, ResponseFormat> updateAttributeObjectValue(final T attribute) {
String innerType = null;
final String attributeType = attribute.getType();
final ToscaPropertyType type = ToscaPropertyType.isValidType(attributeType);
log.debug("The type of the attribute {} is {}", attribute.getUniqueId(), attributeType);
if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
final SchemaDefinition def = attribute.getSchema();
if (def == null) {
log.debug("Schema doesn't exists for attribute of type {}", type);
return Either
.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
}
PropertyDataDefinition propDef = def.getProperty();
if (propDef == null) {
log.debug("Property in Schema Definition inside attribute of type {} doesn't exist", type);
return Either
.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
}
innerType = propDef.getType();
}
// Specific Update Logic
String newValue = attribute.getValue();
final var isValid = attributeOperation.validateAndUpdateAttributeValue(attribute, innerType,
componentsUtils.getAllDataTypes(applicationDataTypeCache, attribute.getModel()));
if (isValid.isRight()) {
final Boolean res = isValid.right().value();
if (!Boolean.TRUE.equals(res)) {
log.debug("validate and update attribute value has failed with value: {}", newValue);
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
}
} else {
final Object object = isValid.left().value();
if (object != null) {
newValue = object.toString();
}
}
return Either.left(newValue);
}
private <T extends PropertyDefinition> void validateToscaGetFunction(T property, Component parentComponent) {
final ToscaGetFunctionDataDefinition toscaGetFunction = (ToscaGetFunctionDataDefinition) property.getToscaFunction();
validateGetToscaFunctionAttributes(toscaGetFunction);
validateGetPropertySource(toscaGetFunction.getFunctionType(), toscaGetFunction.getPropertySource());
if (toscaGetFunction.getFunctionType() == ToscaGetFunctionType.GET_INPUT) {
validateGetFunction(property, parentComponent.getInputs(), parentComponent.getModel());
return;
}
if (toscaGetFunction.getFunctionType() == ToscaGetFunctionType.GET_PROPERTY) {
if (toscaGetFunction.getPropertySource() == PropertySource.SELF) {
validateGetFunction(property, parentComponent.getProperties(), parentComponent.getModel());
} else if (toscaGetFunction.getPropertySource() == PropertySource.INSTANCE) {
final ComponentInstance componentInstance =
parentComponent.getComponentInstanceById(toscaGetFunction.getSourceUniqueId())
.orElseThrow(ToscaGetFunctionExceptionSupplier.instanceNotFound(toscaGetFunction.getSourceName()));
validateGetFunction(property, componentInstance.getProperties(), parentComponent.getModel());
}
return;
}
if (toscaGetFunction.getFunctionType() == ToscaGetFunctionType.GET_ATTRIBUTE) {
if (toscaGetFunction.getPropertySource() == PropertySource.SELF) {
validateGetFunction(property, parentComponent.getAttributes(), parentComponent.getModel());
} else if (toscaGetFunction.getPropertySource() == PropertySource.INSTANCE) {
final ComponentInstance componentInstance =
parentComponent.getComponentInstanceById(toscaGetFunction.getSourceUniqueId())
.orElseThrow(ToscaGetFunctionExceptionSupplier.instanceNotFound(toscaGetFunction.getSourceName()));
validateGetFunction(property, componentInstance.getAttributes(), parentComponent.getModel());
}
return;
}
throw ToscaGetFunctionExceptionSupplier.functionNotSupported(toscaGetFunction.getFunctionType()).get();
}
private <T extends PropertyDefinition> void validateGetFunction(final T property,
final List<? extends ToscaPropertyData> parentProperties,
final String model) {
final ToscaGetFunctionDataDefinition toscaGetFunction = (ToscaGetFunctionDataDefinition) property.getToscaFunction();
if (CollectionUtils.isEmpty(parentProperties)) {
throw ToscaGetFunctionExceptionSupplier
.propertyNotFoundOnTarget(toscaGetFunction.getPropertyName(), toscaGetFunction.getPropertySource(),
toscaGetFunction.getFunctionType()
).get();
}
final String getFunctionPropertyUniqueId = toscaGetFunction.getPropertyUniqueId();
ToscaPropertyData referredProperty = parentProperties.stream()
.filter(property1 -> getFunctionPropertyUniqueId.equals(property1.getUniqueId()))
.findFirst()
.orElseThrow(ToscaGetFunctionExceptionSupplier
.propertyNotFoundOnTarget(toscaGetFunction.getPropertyName(), toscaGetFunction.getPropertySource()
, toscaGetFunction.getFunctionType())
);
if (toscaGetFunction.isSubProperty()) {
referredProperty = findSubProperty(referredProperty, toscaGetFunction, model);
}
if (!property.getType().equals(referredProperty.getType()) && !"list".equalsIgnoreCase(referredProperty.getType())) {
throw ToscaGetFunctionExceptionSupplier
.propertyTypeDiverge(toscaGetFunction.getType(), referredProperty.getType(), property.getType()).get();
}
if (PropertyType.typeHasSchema(referredProperty.getType()) && !referredProperty.getSchemaType().equals(property.getType()) && !referredProperty.getSchemaType().equals(property.getSchemaType())) {
throw ToscaGetFunctionExceptionSupplier
.propertySchemaDiverge(toscaGetFunction.getType(), referredProperty.getSchemaType(), property.getSchemaType()).get();
}
}
private ToscaPropertyData findSubProperty(final ToscaPropertyData referredProperty,
final ToscaGetFunctionDataDefinition toscaGetFunction,
final String model) {
final Map<String, DataTypeDefinition> dataTypeMap = loadDataTypes(model);
final List<String> propertyPathFromSource = toscaGetFunction.getPropertyPathFromSource();
DataTypeDefinition dataType = dataTypeMap.get(referredProperty.getType());
if (dataType == null) {
throw ToscaGetFunctionExceptionSupplier
.propertyDataTypeNotFound(propertyPathFromSource.get(0), referredProperty.getType(), toscaGetFunction.getFunctionType()).get();
}
ToscaPropertyData foundProperty = referredProperty;
for (int i = 1; i < propertyPathFromSource.size(); i++) {
final String currentPropertyName = propertyPathFromSource.get(i);
foundProperty = dataType.getProperties().stream()
.filter(propertyDefinition -> currentPropertyName.equals(propertyDefinition.getName())).findFirst()
.orElseThrow(
ToscaGetFunctionExceptionSupplier
.propertyNotFoundOnTarget(propertyPathFromSource.subList(0, i), toscaGetFunction.getPropertySource(),
toscaGetFunction.getFunctionType())
);
dataType = dataTypeMap.get(foundProperty.getType());
if (dataType == null) {
throw ToscaGetFunctionExceptionSupplier
.propertyDataTypeNotFound(propertyPathFromSource.subList(0, i), foundProperty.getType(),
toscaGetFunction.getFunctionType()).get();
}
}
return foundProperty;
}
private Map<String, DataTypeDefinition> loadDataTypes(String model) {
final Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypeEither =
applicationDataTypeCache.getAll(model);
if (dataTypeEither.isRight()) {
throw ToscaGetFunctionExceptionSupplier.couldNotLoadDataTypes(model).get();
}
return dataTypeEither.left().value();
}
private void validateGetPropertySource(final ToscaGetFunctionType functionType, final PropertySource propertySource) {
if (functionType == ToscaGetFunctionType.GET_INPUT && propertySource != PropertySource.SELF) {
throw ToscaGetFunctionExceptionSupplier
.targetSourceNotSupported(functionType, propertySource).get();
}
if (functionType == ToscaGetFunctionType.GET_PROPERTY && !List.of(PropertySource.SELF, PropertySource.INSTANCE).contains(propertySource)) {
throw ToscaGetFunctionExceptionSupplier
.targetSourceNotSupported(functionType, propertySource).get();
}
}
private void validateGetToscaFunctionAttributes(final ToscaGetFunctionDataDefinition toscaGetFunction) {
if (toscaGetFunction.getFunctionType() == null) {
throw ToscaGetFunctionExceptionSupplier.targetFunctionTypeNotFound().get();
}
if (toscaGetFunction.getPropertySource() == null) {
throw ToscaGetFunctionExceptionSupplier.targetPropertySourceNotFound(toscaGetFunction.getFunctionType()).get();
}
if (CollectionUtils.isEmpty(toscaGetFunction.getPropertyPathFromSource())) {
throw ToscaGetFunctionExceptionSupplier
.targetSourcePathNotFound(toscaGetFunction.getFunctionType()).get();
}
if (StringUtils.isEmpty(toscaGetFunction.getSourceName()) || StringUtils.isBlank(toscaGetFunction.getSourceName())) {
throw ToscaGetFunctionExceptionSupplier.sourceNameNotFound(toscaGetFunction.getPropertySource()).get();
}
if (StringUtils.isEmpty(toscaGetFunction.getSourceUniqueId()) || StringUtils.isBlank(toscaGetFunction.getSourceUniqueId())) {
throw ToscaGetFunctionExceptionSupplier.sourceIdNotFound(toscaGetFunction.getPropertySource()).get();
}
if (StringUtils.isEmpty(toscaGetFunction.getPropertyName()) || StringUtils.isBlank(toscaGetFunction.getPropertyName())) {
throw ToscaGetFunctionExceptionSupplier.propertyNameNotFound(toscaGetFunction.getPropertySource()).get();
}
if (StringUtils.isEmpty(toscaGetFunction.getPropertyUniqueId()) || StringUtils.isBlank(toscaGetFunction.getPropertyUniqueId())) {
throw ToscaGetFunctionExceptionSupplier.propertyIdNotFound(toscaGetFunction.getPropertySource()).get();
}
}
private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent,
ComponentInstance foundResourceInstance) {
StorageOperationStatus status;
input.setValue(newValue);
status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
if (status != StorageOperationStatus.OK) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
}
foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
return componentsUtils.getResponseFormat(ActionStatus.OK);
}
public Either<List<ComponentInstanceInput>, ResponseFormat> createOrUpdateInstanceInputValues(ComponentTypeEnum componentTypeEnum,
String componentId, String resourceInstanceId,
List<ComponentInstanceInput> inputs,
String userId) {
Either<List<ComponentInstanceInput>, ResponseFormat> resultOp = null;
validateUserExists(userId);
if (componentTypeEnum == null) {
BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
return resultOp;
}
Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
if (getResourceResult.isRight()) {
log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResourceResult.right().value(), componentTypeEnum);
return Either.right(componentsUtils.getResponseFormat(actionStatus, componentId));
}
Component containerComponent = getResourceResult.left().value();
if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
if (Boolean.TRUE.equals(containerComponent.isArchived())) {
log.info(COMPONENT_ARCHIVED, componentId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, containerComponent.getName()));
}
log.info(RESTRICTED_OPERATION_ON_SERVIVE, userId, componentId);
resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
return resultOp;
}
Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
if (resourceInstanceStatus.isRight()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
resourceInstanceId, RESOURCE_INSTANCE, SERVICE, componentId));
}
ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
// lock resource
StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
if (lockStatus != StorageOperationStatus.OK) {
log.debug(FAILED_TO_LOCK_SERVICE, componentId);
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
}
List<ComponentInstanceInput> updatedInputs = new ArrayList<>();
try {
for (ComponentInstanceInput input : inputs) {
validateMandatoryFields(input);
ComponentInstanceInput componentInstanceInput = validateInputExistsOnComponent(input, containerComponent, foundResourceInstance);
Either<String, ResponseFormat> validatedInputValue = validatePropertyObjectValue(componentInstanceInput, input.getValue(), true);
if (validatedInputValue.isRight()) {
throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT, input.getName());
}
updateInputOnContainerComponent(componentInstanceInput, validatedInputValue.left().value(), containerComponent,
foundResourceInstance);
updatedInputs.add(componentInstanceInput);
}
Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
if (updateContainerRes.isRight()) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
return resultOp;
}
resultOp = Either.left(updatedInputs);
return resultOp;
} finally {
if (resultOp == null || resultOp.isRight()) {
janusGraphDao.rollback();
} else {
janusGraphDao.commit();
}
// unlock resource
graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
}
}
private ComponentInstanceInput validateInputExistsOnComponent(ComponentInstanceInput input, Component containerComponent,
ComponentInstance foundResourceInstance) {
List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(foundResourceInstance.getUniqueId());
Optional<ComponentInstanceInput> instanceInput = instanceProperties.stream().filter(p -> p.getName().equals(input.getName())).findAny();
if (!instanceInput.isPresent()) {
throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, input.getName());
}
return instanceInput.get();
}
public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum,
String componentId, String resourceInstanceId,
String groupInstanceId,
ComponentInstanceProperty property,
String userId) {
Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
validateUserExists(userId);
if (componentTypeEnum == null) {
BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
return resultOp;
}
if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
log.info("Restricted operation for user: {} on service: {}", userId, componentId);
resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
return resultOp;
}
// lock resource
StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
if (lockStatus != StorageOperationStatus.OK) {
log.debug(FAILED_TO_LOCK_SERVICE, componentId);
resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
return resultOp;
}
try {
String propertyValueUid = property.getValueUniqueUid();
if (propertyValueUid == null) {
Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation
.increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
if (counterRes.isRight()) {
log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property);
StorageOperationStatus status = counterRes.right().value();
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
}
Integer index = counterRes.left().value();
Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation
.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
if (result.isLeft()) {
log.trace("Property value was added to resource instance {}", resourceInstanceId);
ComponentInstanceProperty instanceProperty = result.left().value();
resultOp = Either.left(instanceProperty);
} else {
log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId);
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
}
} else {
Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation
.updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
if (result.isLeft()) {
log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
ComponentInstanceProperty instanceProperty = result.left().value();
resultOp = Either.left(instanceProperty);
} else {
log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId);
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
}
}
if (resultOp.isLeft()) {
StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId);
if (updateCustomizationUUID != StorageOperationStatus.OK) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID);
resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
}
}
return resultOp;
} finally {
if (resultOp == null || resultOp.isRight()) {
janusGraphDao.rollback();
} else {
janusGraphDao.commit();
}
// unlock resource
graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
}
}
public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId,
String resourceInstanceId, String propertyValueId, String userId) {
validateUserExists(userId);
Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
if (componentTypeEnum == null) {
BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
return resultOp;
}
if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) {
log.info("Restricted operation for user {} on service {}", userId, serviceId);
resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
return resultOp;
}
// lock resource
StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType());
if (lockStatus != StorageOperationStatus.OK) {
log.debug(FAILED_TO_LOCK_SERVICE, serviceId);
resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
return resultOp;
}
try {
Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation
.removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
if (result.isLeft()) {
log.debug("Property value {} was removed from graph.", propertyValueId);
ComponentInstanceProperty instanceProperty = result.left().value();
resultOp = Either.left(instanceProperty);
return resultOp;
} else {
log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId);
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
return resultOp;
}
} finally {
if (resultOp == null || resultOp.isRight()) {
janusGraphDao.rollback();
} else {
janusGraphDao.commit();
}
// unlock resource
graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType());
}
}
private Component getAndValidateOriginComponentOfComponentInstance(Component containerComponent, ComponentInstance componentInstance) {
ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponent.getComponentType());
Component component;
Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
if (getComponentRes.isRight()) {
log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(),
componentInstance.getName());
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType);
throw new ByActionStatusComponentException(actionStatus, Constants.EMPTY_STRING);
}
component = getComponentRes.left().value();
LifecycleStateEnum resourceCurrState = component.getLifecycleState();
if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
ActionStatus actionStatus = ActionStatus.CONTAINER_CANNOT_CONTAIN_COMPONENT_IN_STATE;
throw new ByActionStatusComponentException(actionStatus, containerComponent.getComponentType().toString(), resourceCurrState.toString());
}
if (Boolean.TRUE.equals(component.isArchived())) {
ActionStatus actionStatus = ActionStatus.COMPONENT_IS_ARCHIVED;
throw new ByActionStatusComponentException(actionStatus, component.getName());
}
final Map<String, InterfaceDefinition> componentInterfaces = component.getInterfaces();
if (MapUtils.isNotEmpty(componentInterfaces)) {
componentInterfaces.forEach(componentInstance::addInterface);
}
return component;
}
public Either<Set<String>, ResponseFormat> forwardingPathOnVersionChange(String containerComponentParam,
String containerComponentId,
String componentInstanceId,
ComponentInstance newComponentInstance) {
Either<Set<String>, ResponseFormat> resultOp;
final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
ComponentParametersView componentParametersView = getComponentParametersViewForForwardingPath();
//Fetch Component
Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
//Fetch current component instance
Either<ComponentInstance, StorageOperationStatus> eitherResourceInstance =
getResourceInstanceById(containerComponent, componentInstanceId);
if (eitherResourceInstance.isRight()) {
resultOp = Either.right(componentsUtils.getResponseFormat(
ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
return resultOp;
}
ComponentInstance currentResourceInstance = eitherResourceInstance.left().value();
//Check whether new componentInstance exists
String resourceId = newComponentInstance.getComponentUid();
Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
if (componentExistsRes.isRight()) {
log.debug("Failed to find resource {}", resourceId);
resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse
(componentExistsRes.right().value()), resourceId));
return resultOp;
} else if (!Boolean.TRUE.equals(componentExistsRes.left().value())) {
log.debug("The resource {} not found ", resourceId);
resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
return resultOp;
}
//Fetch component using new component instance uid
Component updatedContainerComponent = getOriginComponentFromComponentInstance(newComponentInstance);
Set<String> toDeleteForwardingPaths = getForwardingPaths(containerComponent,
currentResourceInstance, updatedContainerComponent);
resultOp = Either.left(toDeleteForwardingPaths);
return resultOp;
}
private Set<String> getForwardingPaths(Component containerComponent, ComponentInstance currentResourceInstance,
Component updatedContainerComponent) {
DataForMergeHolder dataForMergeHolder = new DataForMergeHolder();
dataForMergeHolder.setOrigComponentInstId(currentResourceInstance.getName());
Service service = (Service) containerComponent;
ForwardingPathUtils forwardingPathUtils = new ForwardingPathUtils();
return forwardingPathUtils.
getForwardingPathsToBeDeletedOnVersionChange(service, dataForMergeHolder, updatedContainerComponent);
}
private ComponentParametersView getComponentParametersViewForForwardingPath() {
ComponentParametersView componentParametersView = new ComponentParametersView();
componentParametersView.setIgnoreCapabiltyProperties(false);
componentParametersView.setIgnoreServicePath(false);
return componentParametersView;
}
public ComponentInstance changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId,
String userId, ComponentInstance newComponentInstance) {
User user = validateUserExists(userId);
final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
ComponentParametersView componentParametersView = new ComponentParametersView();
componentParametersView.setIgnoreCapabiltyProperties(false);
org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType,
componentParametersView);
validateCanWorkOnComponent(containerComponent, userId);
Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId);
if (resourceInstanceStatus.isRight()) {
throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId,
containerComponentId);
}
ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
return changeInstanceVersion(containerComponent, currentResourceInstance, newComponentInstance, user, containerComponentType);
}
public ComponentInstance changeInstanceVersion(org.openecomp.sdc.be.model.Component containerComponent,
ComponentInstance currentResourceInstance,
ComponentInstance newComponentInstance,
User user,
final ComponentTypeEnum containerComponentType) {
boolean failed = false;
Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus;
try {
lockComponent(containerComponent, "changeComponentInstanceVersion");
String containerComponentId = containerComponent.getUniqueId();
String componentInstanceId = currentResourceInstance.getUniqueId();
if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) {
return currentResourceInstance;
}
String resourceId = newComponentInstance.getComponentUid();
Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade
.validateComponentExists(resourceId);
if (componentExistsRes.isRight()) {
StorageOperationStatus errorStatus = componentExistsRes.right().value();
log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId, errorStatus);
throw new ByActionStatusComponentException(
componentsUtils.convertFromStorageResponse(errorStatus), resourceId);
} else if (!Boolean.TRUE.equals(componentExistsRes.left().value())) {
log.debug("The resource {} not found ", resourceId);
throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, resourceId);
}
Component eitherOriginComponent = getInstanceOriginNode(currentResourceInstance);
DataForMergeHolder dataHolder = compInstMergeDataBL
.saveAllDataBeforeDeleting(containerComponent, currentResourceInstance, eitherOriginComponent);
ComponentInstance resResourceInfo = deleteComponentInstance(containerComponent, componentInstanceId,
containerComponentType);
if (resResourceInfo == null) {
log.error("Calling `deleteComponentInstance` for the resource {} returned a null", resourceId);
throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, resourceId);
} else {
Component origComponent = null;
OriginTypeEnum originType = currentResourceInstance.getOriginType();
newComponentInstance.setOriginType(originType);
if (originType == OriginTypeEnum.ServiceProxy) {
Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade
.getLatestByName(SERVICE_PROXY, null);
if (isServiceProxyOrigin(serviceProxyOrigin)) {
throw new ByActionStatusComponentException(
componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
}
origComponent = serviceProxyOrigin.left().value();
StorageOperationStatus fillProxyRes = fillInstanceData(newComponentInstance, origComponent);
if (isFillProxyRes(fillProxyRes)) {
throw new ByActionStatusComponentException(
componentsUtils.convertFromStorageResponse(fillProxyRes));
}
} else if (originType == OriginTypeEnum.ServiceSubstitution) {
final Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade
.getToscaFullElement(newComponentInstance.getComponentUid());
if (getServiceResult.isRight()) {
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
}
final Component service = getServiceResult.left().value();
final Either<Component, StorageOperationStatus> getServiceDerivedFromTypeResult = toscaOperationFacade
.getLatestByToscaResourceName(service.getDerivedFromGenericType(), service.getModel());
if (getServiceDerivedFromTypeResult.isRight()) {
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
}
origComponent = getServiceDerivedFromTypeResult.left().value();
final StorageOperationStatus fillProxyRes = fillInstanceData(newComponentInstance, origComponent);
if (isFillProxyRes(fillProxyRes)) {
throw new ByActionStatusComponentException(
componentsUtils.convertFromStorageResponse(fillProxyRes));
}
} else {
origComponent = getOriginComponentFromComponentInstance(newComponentInstance);
newComponentInstance.setName(resResourceInfo.getName());
final Map<String, InterfaceDefinition> componentInterfaces = origComponent.getInterfaces();
if (MapUtils.isNotEmpty(componentInterfaces)) {
componentInterfaces.forEach(newComponentInstance::addInterface);
}
}
newComponentInstance.setInvariantName(resResourceInfo.getInvariantName());
newComponentInstance.setPosX(resResourceInfo.getPosX());
newComponentInstance.setPosY(resResourceInfo.getPosY());
newComponentInstance.setDescription(resResourceInfo.getDescription());
newComponentInstance.setInstanceCount(resResourceInfo.getInstanceCount());
newComponentInstance.setMaxOccurrences(resResourceInfo.getMaxOccurrences());
newComponentInstance.setMinOccurrences(resResourceInfo.getMinOccurrences());
newComponentInstance.setDirectives(resResourceInfo.getDirectives());
checkForExternalReqAndCapabilities(origComponent, resResourceInfo);
ComponentInstance updatedComponentInstance =
createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user);
dataHolder.setCurrInstanceNode(origComponent);
compInstMergeDataBL
.mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId, newComponentInstance.getUniqueId());
ActionStatus postChangeVersionResult = onChangeInstanceOperationOrchestrator
.doPostChangeVersionOperations(containerComponent, currentResourceInstance, newComponentInstance);
if (postChangeVersionResult != ActionStatus.OK) {
throw new ByActionStatusComponentException(postChangeVersionResult);
}
ComponentParametersView filter = new ComponentParametersView(true);
filter.setIgnoreComponentInstances(false);
Either<Component, StorageOperationStatus> updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter);
if (updatedComponentRes.isRight()) {
StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value();
ActionStatus actionStatus = componentsUtils
.convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType());
log.debug("Component with id {} was not found", containerComponentId);
throw new ByActionStatusComponentException(actionStatus, Constants.EMPTY_STRING);
}
maintainNodeFilters(currentResourceInstance, newComponentInstance, containerComponentId);
resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(),
updatedComponentInstance.getUniqueId());
if (resourceInstanceStatus.isRight()) {
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse
(resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId());
}
return resourceInstanceStatus.left().value();
}
} catch (ComponentException e) {
failed = true;
throw e;
} finally {
unlockComponent(failed, containerComponent);
}
}
private void maintainNodeFilters(
ComponentInstance currentResourceInstance,
ComponentInstance newComponentInstance,
String containerComponentId) {
CINodeFilterDataDefinition filterToMaintain = currentResourceInstance.getNodeFilter();
if (null != filterToMaintain) {
nodeFilterOperation.addNodeFilterData(
containerComponentId.toLowerCase(),
newComponentInstance.getUniqueId(),
filterToMaintain);
}
}
private void checkForExternalReqAndCapabilities(Component component, ComponentInstance resResourceInfo) {
if (MapUtils.isNotEmpty(component.getRequirements())) {
component.getRequirements().entrySet().forEach(requirementsMap -> {
if (MapUtils.isNotEmpty(resResourceInfo.getRequirements()) &&
resResourceInfo.getRequirements().containsKey(requirementsMap.getKey())) {
List<RequirementDefinition> resourceReqList = resResourceInfo.getRequirements().get(requirementsMap.getKey());
for (RequirementDefinition requirements : requirementsMap.getValue()) {
String requirementName = requirements.getName();
resourceReqList.forEach(requirementDefinition -> {
if (requirementName.equals(requirementDefinition.getName()) && requirementDefinition.isExternal()) {
requirements.setExternal(requirementDefinition.isExternal());
}
});
}
}
});
}
if (MapUtils.isNotEmpty(component.getCapabilities())) {
component.getCapabilities().entrySet().forEach(capabilityMap -> {
if (MapUtils.isNotEmpty(resResourceInfo.getCapabilities()) && resResourceInfo.getCapabilities().containsKey(capabilityMap.getKey())) {
List<CapabilityDefinition> resourceCapList = resResourceInfo.getCapabilities().get(capabilityMap.getKey());
capabilityMap.getValue().forEach(capabilities -> {
String capabilityName = capabilities.getName();
for (CapabilityDefinition capDef : resourceCapList) {
if (capabilityName.equals(capDef.getName()) && capDef.isExternal()) {
capabilities.setExternal(capDef.isExternal());
}
}
});
}
});
}
}
private boolean isFillProxyRes(StorageOperationStatus fillProxyRes) {
if (fillProxyRes != StorageOperationStatus.OK) {
log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
return true;
}
return false;
}
// US831698
public List<ComponentInstanceProperty> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId,
String componentInstanceUniqueId, String userId) {
Component containerComponent = null;
boolean failed = false;
try {
validateUserExists(userId);
validateComponentType(containerComponentTypeParam);
Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
if (validateContainerComponentExists.isRight()) {
throw new ByActionStatusComponentException(
componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()));
}
containerComponent = validateContainerComponentExists.left().value();
Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
componentInstanceUniqueId);
if (resourceInstanceStatus.isRight()) {
throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId,
containerComponentId);
}
List<ComponentInstanceProperty> instanceProperties = new ArrayList<>();
if (MapUtils.isNotEmpty(containerComponent.getComponentInstancesProperties())) {
instanceProperties = containerComponent.getComponentInstancesProperties()
.get(componentInstanceUniqueId);
}
return instanceProperties;
} catch (ComponentException e) {
failed = true;
throw e;
} finally {
unlockComponent(failed, containerComponent);
}
}
public List<ComponentInstanceAttribute> getComponentInstanceAttributesById(final String containerComponentTypeParam,
final String containerComponentId,
final String componentInstanceUniqueId,
final String userId) {
Component containerComponent = null;
boolean failed = false;
try {
validateUserExists(userId);
validateComponentType(containerComponentTypeParam);
final Either<Component, StorageOperationStatus> validateContainerComponentExists =
toscaOperationFacade.getToscaElement(containerComponentId);
if (validateContainerComponentExists.isRight()) {
throw new ByActionStatusComponentException(
componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()));
}
containerComponent = validateContainerComponentExists.left().value();
if (getResourceInstanceById(containerComponent, componentInstanceUniqueId).isRight()) {
throw new ByActionStatusComponentException(
ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId);
}
final Map<String, List<ComponentInstanceAttribute>> componentInstancesAttributes = containerComponent.getComponentInstancesAttributes();
return componentInstancesAttributes == null ? new ArrayList<>()
: componentInstancesAttributes.getOrDefault(componentInstanceUniqueId, new ArrayList<>());
} catch (final ComponentException e) {
failed = true;
throw e;
} finally {
unlockComponent(failed, containerComponent);
}
}
protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType,
Wrapper<Integer> instaceCounterWrapper,
Wrapper<ResponseFormat> errorWrapper) {
Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation
.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true);
if (counterRes.isRight()) {
log.debug("increase And Get {} failed resource instance {}", counterType, resourceInstanceId);
StorageOperationStatus status = counterRes.right().value();
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
} else {
instaceCounterWrapper.setInnerElement(counterRes.left().value());
}
}
/**
* updates componentInstance modificationTime
*
* @param componentInstance
* @param componentInstanceType
* @param modificationTime
* @param inTransaction
* @return
*/
public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(
ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
Either<ComponentInstanceData, ResponseFormat> result;
Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation
.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
inTransaction);
if (updateComponentInstanceRes.isRight()) {
log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(),
updateComponentInstanceRes.right().value());
result = Either
.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
} else {
result = Either.left(updateComponentInstanceRes.left().value());
}
return result;
}
public Either<ComponentInstance, ResponseFormat> deleteServiceProxy() {
// TODO Add implementation
return Either.left(new ComponentInstance());
}
public Either<ComponentInstance, ResponseFormat> createServiceProxy() {
// TODO Add implementation
return Either.left(new ComponentInstance());
}
public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion() {
// TODO Add implementation
return Either.left(new ComponentInstance());
}
private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance,
String newInstanceName) {
return ComponentValidations.validateNameIsUniqueInComponent(oldComponentInstance.getName(), newInstanceName, containerComponent);
}
private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(final Component containerComponent, final String instanceId) {
final List<ComponentInstance> instances = containerComponent.getComponentInstances();
if (CollectionUtils.isEmpty(instances)) {
return Either.right(StorageOperationStatus.NOT_FOUND);
}
final Optional<ComponentInstance> foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
if (foundInstance.isEmpty()) {
return Either.right(StorageOperationStatus.NOT_FOUND);
}
return Either.left(foundInstance.get());
}
private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) {
Long creationDate = origInstanceForUpdate.getCreationTime();
Long modificationTime = System.currentTimeMillis();
resourceInstanceForUpdate.setCreationTime(creationDate);
resourceInstanceForUpdate.setModificationTime(modificationTime);
resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID());
if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) {
resourceInstanceForUpdate.setName(origInstanceForUpdate.getName());
}
resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName()));
if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon())) {
resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon());
}
if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion())) {
resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion());
}
if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName())) {
resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName());
}
if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName())) {
resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName());
}
if (resourceInstanceForUpdate.getOriginType() == null) {
resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType());
}
if (resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy) {
resourceInstanceForUpdate.setIsProxy(true);
}
if (resourceInstanceForUpdate.getSourceModelInvariant() == null) {
resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant());
}
if (resourceInstanceForUpdate.getSourceModelName() == null) {
resourceInstanceForUpdate.setSourceModelName(origInstanceForUpdate.getSourceModelName());
}
if (resourceInstanceForUpdate.getSourceModelUuid() == null) {
resourceInstanceForUpdate.setSourceModelUuid(origInstanceForUpdate.getSourceModelUuid());
}
if (resourceInstanceForUpdate.getSourceModelUid() == null) {
resourceInstanceForUpdate.setSourceModelUid(origInstanceForUpdate.getSourceModelUid());
}
if (resourceInstanceForUpdate.getCreatedFrom() == null) {
resourceInstanceForUpdate.setCreatedFrom(origInstanceForUpdate.getCreatedFrom());
}
return resourceInstanceForUpdate;
}
/**
* Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
*
* @param containerComponentType
* @param containerComponentId
* @param componentInstanceUniqueId
* @param capabilityType
* @param capabilityName
* @param userId
* @param ownerId
* @return
*/
public List<ComponentInstanceProperty> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId,
String componentInstanceUniqueId, String capabilityType,
String capabilityName, String ownerId, String userId) {
Component containerComponent = null;
List<ComponentInstanceProperty> resultOp = null;
try {
validateUserExists(userId);
validateComponentType(containerComponentType);
containerComponent = toscaOperationFacade.getToscaFullElement(containerComponentId).left().on(this::componentException);
ComponentInstance resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId).left()
.on(this::componentInstanceException);
resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, ownerId,
resourceInstanceStatus.getCapabilities());
} catch (StorageException | ComponentException e) {
unlockRollbackWithException(containerComponent, e);
} catch (Exception e) {
unlockRollbackWithException(containerComponent, new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR));
}
unlockWithCommit(containerComponent);
return resultOp;
}
private List<ComponentInstanceProperty> findCapabilityOfInstance(String componentId, String instanceId, String capabilityType,
String capabilityName, String ownerId,
Map<String, List<CapabilityDefinition>> instanceCapabilities) {
CapabilityDefinition foundCapability;
if (MapUtils.isNotEmpty(instanceCapabilities)) {
List<CapabilityDefinition> capabilitiesPerType = instanceCapabilities.get(capabilityType);
if (capabilitiesPerType != null) {
Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream()
.filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst();
if (capabilityOpt.isPresent()) {
foundCapability = capabilityOpt.get();
return foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties();
}
}
}
return fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName, ownerId);
}
private List<ComponentInstanceProperty> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType,
String capabilityName, String ownerId) {
try {
return toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId)
.left().on(this::componentInstancePropertyListException);
} catch (Exception e) {
log.debug("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId,
capabilityName, e);
throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
}
}
public Either<RequirementDefinition, ResponseFormat> updateInstanceRequirement(ComponentTypeEnum componentTypeEnum, String containerComponentId,
String componentInstanceUniqueId,
RequirementDefinition requirementDef, String userId) {
Either<RequirementDefinition, ResponseFormat> resultOp = null;
validateUserExists(userId);
if (componentTypeEnum == null) {
BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceRequirement", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
}
Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
if (getResourceResult.isRight()) {
log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
Component containerComponent = getResourceResult.left().value();
if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
log.info(RESTRICTED_OPERATION_ON_COMPONENT, userId, containerComponentId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
componentInstanceUniqueId);
if (resourceInstanceStatus.isRight()) {
return Either.right(componentsUtils
.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
}
// lock resource
StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
if (lockStatus != StorageOperationStatus.OK) {
log.debug(FAILED_TO_LOCK_COMPONENT, containerComponentId);
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
}
try {
StorageOperationStatus updateRequirementStatus = toscaOperationFacade
.updateComponentInstanceRequirement(containerComponentId, componentInstanceUniqueId, requirementDef);
if (updateRequirementStatus != StorageOperationStatus.OK) {
log.debug("Failed to update component instance requirement on instance {} in container {}", componentInstanceUniqueId,
containerComponentId);
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateRequirementStatus)));
}
Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
if (updateContainerRes.isRight()) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
return resultOp;
}
resultOp = Either.left(requirementDef);
return resultOp;
} finally {
if (resultOp == null || resultOp.isRight()) {
janusGraphDao.rollback();
} else {
janusGraphDao.commit();
}
// unlock resource
graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
}
}
public Either<CapabilityDefinition, ResponseFormat> updateInstanceCapability(final ComponentTypeEnum containerComponentType,
final String containerComponentId,
final String componentInstanceUniqueId,
final CapabilityDefinition capabilityDefinition,
final String userId) {
if (containerComponentType == null) {
BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapability", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
}
validateUserExists(userId);
final Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
if (getResourceResult.isRight()) {
log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND, containerComponentId));
}
final Component containerComponent = getResourceResult.left().value();
if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
log.info(RESTRICTED_OPERATION_ON_COMPONENT, userId, containerComponentId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
final Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus =
getResourceInstanceById(containerComponent, componentInstanceUniqueId);
if (resourceInstanceStatus.isRight()) {
return Either.right(componentsUtils
.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
}
// lock resource
final StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, containerComponentType.getNodeType());
if (lockStatus != StorageOperationStatus.OK) {
log.debug(FAILED_TO_LOCK_COMPONENT, containerComponentId);
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
}
var success = false;
try {
final CapabilityDataDefinition updatedCapabilityDefinition = toscaOperationFacade
.updateComponentInstanceCapability(containerComponentId, componentInstanceUniqueId, capabilityDefinition);
final Either<Component, StorageOperationStatus> updateContainerEither = toscaOperationFacade
.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
if (updateContainerEither.isRight()) {
var actionStatus = componentsUtils.convertFromStorageResponse(updateContainerEither.right().value(), containerComponentType);
return Either.right(componentsUtils.getResponseFormat(actionStatus));
}
success = true;
return Either.left(new CapabilityDefinition(updatedCapabilityDefinition));
} catch (final BusinessException e) {
log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, NodeTemplateOperation.class.getName(), (ErrorLogOptionalData) null,
FAILED_TO_UPDATE_COMPONENT_INSTANCE_CAPABILITY, componentInstanceUniqueId, containerComponentId);
throw e;
} catch (final Exception e) {
log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, NodeTemplateOperation.class.getName(), (ErrorLogOptionalData) null,
FAILED_TO_UPDATE_COMPONENT_INSTANCE_CAPABILITY, componentInstanceUniqueId, containerComponentId);
throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
} finally {
if (success) {
janusGraphDao.commit();
} else {
janusGraphDao.rollback();
}
// unlock resource
graphLockOperation.unlockComponent(containerComponentId, containerComponentType.getNodeType());
}
}
public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum,
String containerComponentId,
String componentInstanceUniqueId,
String capabilityType, String capabilityName,
List<ComponentInstanceProperty> properties,
String userId) {
Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
validateUserExists(userId);
if (componentTypeEnum == null) {
BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
}
Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
if (getResourceResult.isRight()) {
log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
Component containerComponent = getResourceResult.left().value();
if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
log.info(RESTRICTED_OPERATION_ON_COMPONENT, userId, containerComponentId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
componentInstanceUniqueId);
if (resourceInstanceStatus.isRight()) {
return Either.right(componentsUtils
.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
}
ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
// lock resource
StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
if (lockStatus != StorageOperationStatus.OK) {
log.debug(FAILED_TO_LOCK_COMPONENT, containerComponentId);
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
}
try {
for (ComponentInstanceProperty property : properties) {
Either<String, ResponseFormat> newPropertyValueEither = validatePropertyObjectValue(property, property.getValue(), false);
newPropertyValueEither.bimap(
updatedValue -> updateCapabilityPropertyOnContainerComponent(property, updatedValue, containerComponent, foundResourceInstance,
capabilityType, capabilityName), Either::right);
}
Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
if (updateContainerRes.isRight()) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
return resultOp;
}
resultOp = Either.left(properties);
return resultOp;
} finally {
if (resultOp == null || resultOp.isRight()) {
janusGraphDao.rollback();
} else {
janusGraphDao.commit();
}
// unlock resource
graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
}
}
public Either<Map<String, ComponentInstance>, ResponseFormat> copyComponentInstance(ComponentInstance inputComponentInstance,
String containerComponentId, String componentInstanceId,
String userId) {
Map<String, ComponentInstance> resultMap = new HashMap<>();
Either<Component, StorageOperationStatus> getOrigComponent = toscaOperationFacade.getToscaElement(containerComponentId);
if (getOrigComponent.isRight()) {
log.error("Failed to get the original component information");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
}
Component origComponent = getOrigComponent.left().value();
try {
lockComponent(origComponent, "copyComponentInstance");
} catch (ComponentException e) {
log.error("destComponentInstance's data is {}", origComponent.toString());
return Either.right(componentsUtils
.getResponseFormat(ActionStatus.USER_DEFINED, "Failed to lock component destComponentInstance's data is {}",
origComponent.toString()));
}
boolean failed = false;
ComponentInstance actionResponse = null;
try {
actionResponse = createComponentInstance("services", containerComponentId, userId, inputComponentInstance, false);
} catch (ComponentException e) {
failed = true;
// on failure of the create instance unlock the resource and rollback the transaction.
return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
} finally {
// on failure of the create instance unlock the resource and rollback the transaction.
if (null == actionResponse) {
log.error(FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS);
unlockComponent(failed, origComponent);
}
}
Either<String, ResponseFormat> resultOp = null;
try {
ComponentInstance destComponentInstance = actionResponse;
log.debug("destComponentInstance's data is {}", destComponentInstance);
resultOp = deepCopyComponentInstance(origComponent, containerComponentId, componentInstanceId, destComponentInstance, userId);
resultMap.put("componentInstance", destComponentInstance);
} finally {
// unlock resource
if (resultOp == null || resultOp.isRight()) {
unlockComponent(true, origComponent);
janusGraphDao.rollback();
log.error("Failed to deep copy component instance");
} else {
unlockComponent(false, origComponent);
janusGraphDao.commit();
log.debug("Success trasaction commit");
}
}
if (resultOp == null || resultOp.isRight()) {
return Either
.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, "Failed to deep copy the component instance to the canvas"));
} else {
return Either.left(resultMap);
}
}
private Either<String, ResponseFormat> deepCopyComponentInstance(Component sourceComponent, String containerComponentId,
String sourceComponentInstanceId, ComponentInstance destComponentInstance,
String userId) {
Either<Component, StorageOperationStatus> getDestComponent = toscaOperationFacade.getToscaElement(containerComponentId);
if (getDestComponent.isRight()) {
log.error("Failed to get the dest component information");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
}
Component destComponent = getDestComponent.left().value();
Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs = copyComponentInstanceWithPropertiesAndInputs(sourceComponent,
destComponent, sourceComponentInstanceId, destComponentInstance);
if (copyComponentInstanceWithPropertiesAndInputs.isRight()) {
log.error("Failed to copy component instance with properties and inputs as part of deep copy");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED,
"Failed to copy the component instance with properties and inputs as part of deep copy"));
}
Either<String, ResponseFormat> copyComponentInstanceWithAttributes = copyComponentInstanceWithAttributes(sourceComponent, destComponent,
sourceComponentInstanceId, destComponentInstance, userId);
if (copyComponentInstanceWithAttributes.isRight()) {
log.error("Failed to copy component instance with attributes as part of deep copy");
return Either.right(componentsUtils
.getResponseFormat(ActionStatus.USER_DEFINED, "Failed to copy the component instance with attributes as part of deep copy"));
}
return Either.left(COPY_COMPONENT_INSTANCE_OK);
}
private Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs(Component sourceComponent, Component destComponent,
String sourceComponentInstanceId,
ComponentInstance destComponentInstance) {
log.debug("start to copy ComponentInstance with properties and inputs");
List<ComponentInstanceProperty> sourcePropList = null;
if (sourceComponent.getComponentInstancesProperties() != null
&& sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId) != null) {
sourcePropList = sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId);
log.debug("sourcePropList");
}
List<ComponentInstanceProperty> destPropList = null;
String destComponentInstanceId = destComponentInstance.getUniqueId();
log.debug("destComponentInstanceId: {}", destComponentInstance.getUniqueId());
if (destComponent.getComponentInstancesProperties() != null
&& destComponent.getComponentInstancesProperties().get(destComponentInstanceId) != null) {
destPropList = destComponent.getComponentInstancesProperties().get(destComponentInstanceId);
log.debug("destPropList {}");
}
List<ComponentInstancePropInput> componentInstancePropInputList = new ArrayList<>();
if (null != destPropList && null != sourcePropList) {
log.debug("start to set property and attribute");
for (ComponentInstanceProperty destProp : destPropList) {
String destPropertyName = destProp.getName();
for (ComponentInstanceProperty sourceProp : sourcePropList) {
if (!destPropertyName.equals(sourceProp.getName())) {
continue;
}
log.debug("now set property");
final List<GetInputValueDataDefinition> getInputValues = sourceProp.getGetInputValues();
if (getInputValues == null && !StringUtils.isEmpty(sourceProp.getValue()) && (destProp.getValue() == null || !destProp.getValue()
.equals(sourceProp.getValue()))) {
log.debug("Now starting to copy the property {} in value {}", destPropertyName, sourceProp.getValue());
destProp.setValue(sourceProp.getValue());
Either<String, ResponseFormat> updatePropertyValueEither = updateComponentInstanceProperty(destComponent.getUniqueId(),
destComponentInstanceId, destProp);
if (updatePropertyValueEither.isRight()) {
log.error("Failed to copy the property {}", destPropertyName);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
"Failed to paste component instance to the canvas, property copy"));
}
break;
}
log.debug("Now start to update inputs");
if (getInputValues != null) {
if (getInputValues.isEmpty()) {
log.debug("property is return from input, set by man");
break;
}
log.debug("Now starting to copy the {} property", destPropertyName);
Either<String, ResponseFormat> getSourceInputDefaultValue = getInputListDefaultValue(sourceComponent,
getInputValues.get(0).getInputId());
if (getSourceInputDefaultValue.isRight()) {
return Either.right(getSourceInputDefaultValue.right().value());
}
componentInstancePropInputList.add(new ComponentInstancePropInput(destProp));
}
}
}
}
return Either.left(COPY_COMPONENT_INSTANCE_OK);
}
private Either<String, ResponseFormat> copyComponentInstanceWithAttributes(Component sourceComponent, Component destComponent,
String sourceComponentInstanceId,
ComponentInstance destComponentInstance, String userId) {
String destComponentInstanceId = destComponentInstance.getUniqueId();
log.info("start to copy component instance with attributes");
List<ComponentInstanceAttribute> sourceAttributeList = null;
if (sourceComponent.getComponentInstancesAttributes() != null
&& sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId) != null) {
sourceAttributeList = sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId);
log.info("sourceAttributes {}");
}
List<ComponentInstanceAttribute> destAttributeList = null;
if (destComponent.getComponentInstancesAttributes() != null
&& destComponent.getComponentInstancesAttributes().get(destComponentInstanceId) != null) {
destAttributeList = destComponent.getComponentInstancesAttributes().get(destComponentInstanceId);
log.info("destAttributeList {}");
}
if (null != sourceAttributeList && null != destAttributeList) {
log.info("set attribute");
for (ComponentInstanceAttribute sourceAttribute : sourceAttributeList) {
String sourceAttributeName = sourceAttribute.getName();
for (ComponentInstanceAttribute destAttribute : destAttributeList) {
if (sourceAttributeName.equals(destAttribute.getName())) {
log.debug("Start to copy the attribute exists {}", sourceAttributeName);
sourceAttribute.setUniqueId(
UniqueIdBuilder.buildResourceInstanceUniqueId("attribute", destComponentInstanceId.split("\\.")[1], sourceAttributeName));
Either<ComponentInstanceAttribute, ResponseFormat> updateAttributeValueEither = createOrUpdateAttributeValueForCopyPaste(
ComponentTypeEnum.SERVICE, destComponent.getUniqueId(), destComponentInstanceId, sourceAttribute, userId);
if (updateAttributeValueEither.isRight()) {
log.error("Failed to copy the attribute");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
"Failed to paste component instance to the canvas, attribute copy"));
}
break;
}
}
}
}
return Either.left(COPY_COMPONENT_INSTANCE_OK);
}
private Either<ComponentInstanceAttribute, ResponseFormat> createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum componentTypeEnum,
String componentId, String resourceInstanceId,
ComponentInstanceAttribute attribute,
String userId) {
Either<ComponentInstanceAttribute, ResponseFormat> resultOp = null;
validateUserExists(userId);
if (componentTypeEnum == null) {
BeEcompErrorManager.getInstance()
.logInvalidInputError("createOrUpdateAttributeValueForCopyPaste", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
return resultOp;
}
Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
if (getResourceResult.isRight()) {
log.info("Failed to retrieve component id {}", componentId);
resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
return resultOp;
}
Component containerComponent = getResourceResult.left().value();
Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
if (resourceInstanceStatus.isRight()) {
resultOp = Either
.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
return resultOp;
}
ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
String propertyType = attribute.getType();
ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
log.info("The type of attribute id{},is {} ", attribute.getUniqueId(), propertyType);
if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
SchemaDefinition def = attribute.getSchema();
if (def == null) {
log.info("Schema doesn't exists for attribute of type {}", type);
return Either
.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
}
PropertyDataDefinition propDef = def.getProperty();
if (propDef == null) {
log.info("Attribute in Schema Definition inside attribute of type {} doesn't exist", type);
return Either
.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
}
}
List<ComponentInstanceAttribute> instanceAttributes = containerComponent.getComponentInstancesAttributes().get(resourceInstanceId);
Optional<ComponentInstanceAttribute> instanceAttribute = instanceAttributes.stream()
.filter(p -> p.getUniqueId().equals(attribute.getUniqueId())).findAny();
StorageOperationStatus status;
if (instanceAttribute.isPresent()) {
log.info("updateComponentInstanceAttribute");
status = toscaOperationFacade.updateComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
} else {
log.info("addComponentInstanceAttribute");
status = toscaOperationFacade.addComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
}
if (status != StorageOperationStatus.OK) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
return resultOp;
}
List<String> path = new ArrayList<>();
path.add(foundResourceInstance.getUniqueId());
attribute.setPath(path);
foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
if (updateContainerRes.isRight()) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
return resultOp;
}
resultOp = Either.left(attribute);
return resultOp;
}
private Either<String, ResponseFormat> updateComponentInstanceProperty(String containerComponentId, String componentInstanceId,
ComponentInstanceProperty property) {
Either<String, ResponseFormat> resultOp;
Either<Component, StorageOperationStatus> getComponent = toscaOperationFacade.getToscaElement(containerComponentId);
if (getComponent.isRight()) {
log.error("Failed to get the component information");
return Either.right(componentsUtils
.getResponseFormatForResourceInstanceProperty(ActionStatus.INVALID_CONTENT_PARAM, "Failed to get the component information"));
}
Component containerComponent = getComponent.left().value();
StorageOperationStatus status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
if (status != StorageOperationStatus.OK) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
return resultOp;
}
Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
if (updateContainerRes.isRight()) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
return resultOp;
}
return Either.left("Update OK");
}
private Either<String, ResponseFormat> getInputListDefaultValue(Component component, String inputId) {
List<InputDefinition> inputList = component.getInputs();
for (InputDefinition input : inputList) {
if (input.getUniqueId().equals(inputId)) {
if (input.getDefaultValue() == null) {
log.debug("The input's default value is null");
return Either.left(null);
}
return Either.left(input.getDefaultValue());
}
}
log.error("The input's default value with id {} is not found", inputId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, "Failed to paste component instance to the canvas"));
}
/**
* Method to delete selected nodes and edges on composition page
*
* @param containerComponentType
* @param componentId
* @param componentInstanceIdList
* @param userId
* @return
*/
public Map<String, List<String>> batchDeleteComponentInstance(String containerComponentType, String componentId,
List<String> componentInstanceIdList, String userId) {
List<String> deleteErrorIds = new ArrayList<>();
Map<String, List<String>> deleteErrorMap = new HashMap<>();
validateUserExists(userId);
org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId,
ComponentTypeEnum.findByParamName(containerComponentType), null);
boolean failed = false;
try {
lockComponent(containerComponent, "batchDeleteComponentInstance");
for (String eachInstanceId : componentInstanceIdList) {
Either<ComponentInstance, ResponseFormat> actionResponse = batchDeleteComponentInstance(containerComponent, containerComponentType,
eachInstanceId);
log.debug("batchDeleteResourceInstances actionResponse is {}", actionResponse);
if (actionResponse.isRight()) {
log.error("Failed to delete ComponentInstance [{}]", eachInstanceId);
deleteErrorIds.add(eachInstanceId);
}
}
//sending the ids of the error nodes that were not deleted to UI
deleteErrorMap.put("deleteFailedIds", deleteErrorIds);
return deleteErrorMap;
} catch (ComponentException e) {
failed = true;
throw e;
} finally {
unlockComponent(failed, containerComponent);
}
}
private Either<ComponentInstance, ResponseFormat> batchDeleteComponentInstance(Component containerComponent, String containerComponentType,
String componentInstanceId) {
ComponentInstance resultOp;
final ComponentTypeEnum containerComponentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
try {
resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentTypeEnum);
log.info("Successfully deleted instance with id {}", componentInstanceId);
return Either.left(resultOp);
} catch (ComponentException e) {
log.error("Failed to deleteComponentInstance with instanceId[{}]", componentInstanceId);
return Either.right(new ResponseFormat());
}
}
private void validatePropertyConstraintsNotChanged(List<ComponentInstanceProperty> newProperties, ComponentInstance originalResourceInstance) {
for (ComponentInstanceProperty newProperty : newProperties) {
Optional<PropertyDefinition> originalProperty = originalResourceInstance.getProperties().stream()
.filter(prop -> prop.getUniqueId().equals(newProperty.getUniqueId())).findAny();
if (originalProperty.isPresent()) {
List<PropertyConstraint> originalConstraints = originalProperty.get().getConstraints();
List<PropertyConstraint> newConstraints = newProperty.getConstraints();
if (!Objects.equals(originalConstraints, newConstraints)) {
throw new ByActionStatusComponentException(ActionStatus.CANNOT_CHANGE_CONSTRAINTS);
}
} else {
throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, newProperty.getUniqueId());
}
}
}
private Either<Boolean, ResponseFormat> validatePropertyValueConstraint(List<? extends PropertyDefinition> properties, final String componentId) {
try {
String propertyModel = propertyBusinessLogic.getComponentModelByComponentId(componentId);
PropertyValueConstraintValidationUtil propertyValueConstraintValidationUtil = new PropertyValueConstraintValidationUtil();
return propertyValueConstraintValidationUtil.validatePropertyConstraints(properties, applicationDataTypeCache, propertyModel);
} catch (BusinessLogicException e) {
return Either.right(e.getResponseFormat());
}
}
public void validateUser(final String userId) {
final User user = userValidations.validateUserExists(userId);
userValidations.validateUserRole(user, Arrays.asList(Role.DESIGNER, Role.ADMIN));
}
public void setCompositionBusinessLogic(CompositionBusinessLogic compositionBusinessLogic) {
this.compositionBusinessLogic = compositionBusinessLogic;
}
public void setContainerInstanceTypesData(ContainerInstanceTypesData containerInstanceTypesData) {
this.containerInstanceTypesData = containerInstanceTypesData;
}
}
|