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
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
|
/*-
* ============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 com.google.common.annotations.VisibleForTesting;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import fj.data.Either;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.elasticsearch.common.Strings;
import org.openecomp.sdc.be.components.ArtifactsResolver;
import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.config.validation.DeploymentArtifactHeatConfiguration;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.heat.HeatParameterType;
import org.openecomp.sdc.be.model.jsontitan.operations.InterfaceOperation;
import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation;
import org.openecomp.sdc.be.components.utils.InterfaceOperationUtils;
import org.openecomp.sdc.be.model.operations.api.*;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
import org.openecomp.sdc.be.resources.data.ESArtifactData;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
import org.openecomp.sdc.be.servlets.RepresentationUtils;
import org.openecomp.sdc.be.tosca.CsarUtils;
import org.openecomp.sdc.be.tosca.ToscaError;
import org.openecomp.sdc.be.tosca.ToscaExportHandler;
import org.openecomp.sdc.be.tosca.ToscaRepresentation;
import org.openecomp.sdc.be.user.IUserBusinessLogic;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.be.user.UserBusinessLogic;
import org.openecomp.sdc.be.utils.TypeUtils;
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.log.wrappers.Logger;
import org.openecomp.sdc.common.util.GeneralUtility;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.common.util.YamlToObjectConverter;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.xml.sax.*;
import org.yaml.snakeyaml.Yaml;
import javax.servlet.http.HttpServletRequest;
import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.Map.Entry;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
@org.springframework.stereotype.Component("artifactBusinessLogic")
public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private static final String RESOURCE_INSTANCE = "resource instance";
private static final String ARTIFACT_TYPE_OTHER = "OTHER";
private static final String ARTIFACT_DESCRIPTION = "artifact description";
private static final String ARTIFACT_LABEL = "artifact label";
private static final String ARTIFACT_URL = "artifact url";
private static final String ARTIFACT_NAME = "artifact name";
private static final String ARTIFACT_PAYLOAD = "artifact payload";
private static final String ARTIFACT_PLACEHOLDER_TYPE = "type";
private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
public static final String HEAT_ENV_NAME = "heatEnv";
public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
public static final String HEAT_ENV_SUFFIX = "env";
private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
private static final Logger log = Logger.getLogger(ArtifactsBusinessLogic.class);
public static final String FAILED_UPDATE_GROUPS = "Failed to update groups of the component {}. ";
public static final String FAILED_UPDATE_ARTIFACT = "Failed to delete or update the artifact {}. Parent uniqueId is {}";
public static final String FAILED_SAVE_ARTIFACT = "Failed to save the artifact.";
public static final String UPDATE_ARTIFACT_LOCK = "Update Artifact - lock ";
public static final String FAILED_DOWNLOAD_ARTIFACT = "Download artifact {} failed";
public static final String FAILED_UPLOAD_ARTIFACT_TO_COMPONENT = "Failed to upload artifact to component with type {} and uuid {}. Status is {}. ";
public static final String FAILED_UPLOAD_ARTIFACT_TO_INSTANCE = "Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ";
public static final String FAILED_FETCH_COMPONENT = "Could not fetch component with type {} and uuid {}. Status is {}. ";
public static final String NULL_PARAMETER = "One of the function parameteres is null";
public static final String COMPONENT_INSTANCE_NOT_FOUND = "Component instance {} was not found for component {}";
public static final String ROLLBACK = "all changes rollback";
public static final String COMMIT = "all changes committed";
public static final String ARTIFACT_SAVED = "Artifact saved into ES - {}";
public static final String UPDATE_ARTIFACT = "Update Artifact";
public static final String FOUND_DEPLOYMENT_ARTIFACT = "Found deployment artifact {}";
private Gson gson = new GsonBuilder().setPrettyPrinting().create();
@javax.annotation.Resource
private IInterfaceLifecycleOperation interfaceLifecycleOperation;
@javax.annotation.Resource
private IUserAdminOperation userOperaton;
@javax.annotation.Resource
private IElementOperation elementOperation;
@javax.annotation.Resource
private ResourceBusinessLogic resourceBusinessLogic;
@javax.annotation.Resource
private ServiceBusinessLogic serviceBusinessLogic;
@javax.annotation.Resource
private UserBusinessLogic userAdminManager;
@javax.annotation.Resource
private IHeatParametersOperation heatParametersOperation;
@Autowired
private ArtifactCassandraDao artifactCassandraDao;
@Autowired
private ToscaExportHandler toscaExportUtils;
@Autowired
private CsarUtils csarUtils;
@Autowired
private LifecycleBusinessLogic lifecycleBusinessLogic;
@Autowired
private IUserBusinessLogic userBusinessLogic;
@Autowired
private NodeTemplateOperation nodeTemplateOperation;
@Autowired
private ArtifactsResolver artifactsResolver;
public enum ArtifactOperationEnum {
CREATE, UPDATE, DELETE, DOWNLOAD, LINK;
public static boolean isCreateOrLink(ArtifactOperationEnum operation) {
return operation == CREATE || operation == LINK;
}
}
public class ArtifactOperationInfo {
private ArtifactOperationEnum artifactOperationEnum;
private boolean isExternalApi;
private boolean ignoreLifecycleState;
public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) {
this.artifactOperationEnum = artifactOperationEnum;
this.isExternalApi = isExternalApi;
this.ignoreLifecycleState = ignoreLifecycleState;
}
public boolean isExternalApi() {
return isExternalApi;
}
public boolean ignoreLifecycleState() {
return ignoreLifecycleState;
}
public ArtifactOperationEnum getArtifactOperationEnum() {
return artifactOperationEnum;
}
}
// new flow US556184
public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
String origMd5, String originData, String interfaceUuid, String operationUuid, String parentId, String containerComponentType) {
return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceUuid, operationUuid, parentId, containerComponentType, true, false);
}
public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
String origMd5, String originData, String interfaceUuid, String operationUuid, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) {
// step 1 - detect auditing type
AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
// step 2 - check header
if (userId == null) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId);
handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null);
return Either.right(responseFormat);
}
// step 3 - check user existence
Either<User, ResponseFormat> userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction);
if (userResult.isRight()) {
return Either.right(userResult.right().value());
}
// step 4 - check user's role
User user = userResult.left().value();
Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation);
if (validateUserRole.isRight()) {
return Either.right(validateUserRole.right().value());
}
// steps 5 - 6 - 7
// 5. check service/resource existence
// 6. check service/resource check out
// 7. user is owner of checkout state
org.openecomp.sdc.be.model.Component component = null;
String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, auditingAction, user, artifactId, componentType, containerComponentType);
if (validateComponent.isRight()) {
return Either.right(validateComponent.right().value());
}
component = validateComponent.left().value();
Either<Boolean, ResponseFormat> validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation);
if (validateWorkOnResource.isRight()) {
return Either.right(validateWorkOnResource.right().value());
}
// step 8
return validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceUuid, operationUuid, user, component,
shouldLock, inTransaction, true);
}
/**
* This Method validates only the Artifact and does not validate user / role / component ect...<br>
* For regular usage use <br>
* {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)}
*
* @return
*/
public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId,
ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceUuid, String operationName, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
Component parent = component;
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, auditingAction, user, component, parent, errorWrapper, shouldLock, inTransaction);
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
if (errorWrapper.isEmpty()) {
// step 10
result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceUuid, operationName, auditingAction, user, parent, shouldLock, inTransaction, needUpdateGroup);
}
else {
result = Either.right(errorWrapper.getInnerElement());
}
return result;
}
private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user,
Component component, Component parent, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) {
ArtifactDefinition validatedArtifactInfo = artifactInfo;
if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE || operation
.getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) {
Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component);
if (validateArtifact.isRight()) {
ResponseFormat responseFormat = validateArtifact.right().value();
handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
errorWrapper.setInnerElement(validateArtifact.right().value());
}
else if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) {
validatedArtifactInfo = validateArtifact.left().value();
handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, errorWrapper, shouldLock, inTransaction);
}
}
return validatedArtifactInfo;
}
private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition,
ResponseFormat> validateArtifact, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) {
ArtifactDefinition validatedArtifact = validateArtifact.left().value();
if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())
&& ComponentTypeEnum.SERVICE == component.getComponentType()) {
ComponentInstance componentInstance = component.getComponentInstances()
.stream()
.filter(p -> p.getUniqueId().equals(componentId))
.findAny()
.get();
Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts();
ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values()
.stream()
.filter(p -> p.getUniqueId()
.equals(validatedArtifact.getUniqueId()))
.findAny()
.get();
Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance
.getName(), user, componentId, shouldLock, inTransaction);
if (eitherGenerated.isRight()) {
errorWrapper.setInnerElement(eitherGenerated.right().value());
}
}
}
private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) {
boolean needGenerate;
needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component
.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType()
.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV
.getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo)));
return needGenerate;
}
private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) {
return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo
.getArtifactType()
.equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum());
}
public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest,
boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) {
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB);
if (generated.isRight()) {
return generated;
}
byte[] decodedPayload = artifactDefinition.getPayloadData();
artifactDefinition.setEsId(artifactDefinition.getUniqueId());
artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload));
return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition
.getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null,
shouldLock, inTransaction);
}
private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) {
log.debug("tosca artifact generation");
if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) {
Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest);
if (generated.isRight()) {
log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right()
.value());
return Either.right(generated.right().value());
}
byte[] value = generated.left().value();
artifactInfo.setPayload(value);
}
else {
Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
if (exportComponent.isRight()) {
log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right()
.value());
ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(status);
return Either.right(responseFormat);
}
log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
String payload = exportComponent.left().value().getMainYaml();
artifactInfo.setPayloadData(payload);
}
return Either.left(Either.left(artifactInfo));
}
private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
switch (operation.getArtifactOperationEnum()) {
case DOWNLOAD:
if (artifactGenerationRequired(parent, artifactInfo)) {
return generateNotSavedArtifact(parent, artifactInfo);
}
return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent);
case DELETE:
return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction);
case UPDATE:
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = null;
ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)
&& (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
result = handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
if (needUpdateGroup && result.isLeft()) {
Either<ArtifactDefinition, Operation> updateResult = result.left().value();
ActionStatus error = updateGroupInstance(artifactInfo, updateResult.left()
.value(), parent, componentType, componentId);
if (error != ActionStatus.OK) {
result = Either.right(componentsUtils.getResponseFormat(error));
}
}
}
else {
if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) {
result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction, needUpdateGroup);
}
}
if (result == null) {
result = handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
if (needUpdateGroup && result.isLeft()) {
Either<ArtifactDefinition, Operation> updateResult = result.left().value();
ActionStatus error = updateGroupForHeat(artifactInfo, updateResult.left()
.value(), parent, componentType);
if (error != ActionStatus.OK) {
result = Either.right(componentsUtils.getResponseFormat(error));
}
}
}
return result;
case CREATE:
return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
case LINK:
return handleLink(componentId, artifactInfo, auditingAction, user, componentType, parent, shouldLock, inTransaction);
}
return null;
}
private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType) {
List<GroupDefinition> groups = parent.getGroups();
if (groups != null && !groups.isEmpty()) {
List<GroupDataDefinition> groupToUpdate = groups.stream()
.filter(g -> g.getArtifacts() != null && g.getArtifacts()
.contains(artifactInfo
.getUniqueId()))
.collect(Collectors.toList());
if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
groupToUpdate.forEach(g -> {
g.getArtifacts().remove(artifactInfo.getUniqueId());
g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID());
g.getArtifacts().add(artAfterUpdate.getUniqueId());
g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
});
Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
if (status.isRight()) {
log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
return componentsUtils.convertFromStorageResponse(status.right().value());
}
}
}
return ActionStatus.OK;
}
private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent, ComponentTypeEnum componentType) {
List<GroupDefinition> groups = parent.getGroups();
if (groups != null && !groups.isEmpty()) {
List<GroupDataDefinition> groupToUpdate = groups.stream()
.filter(g -> g.getArtifacts() != null && g.getArtifacts()
.contains(artifactInfoHeat
.getUniqueId()))
.collect(Collectors.toList());
if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
groupToUpdate.forEach(g -> {
g.getArtifacts().remove(artifactInfoHeat.getUniqueId());
g.getArtifactsUuid().remove(artifactInfoHeat.getArtifactUUID());
g.getArtifacts().remove(artifactInfoHeatE.getUniqueId());
g.getArtifacts().add(artHeatAfterUpdate.getUniqueId());
g.getArtifactsUuid().add(artHeatAfterUpdate.getArtifactUUID());
g.getArtifacts().add(artHEAfterUpdate.getUniqueId());
});
Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
if (status.isRight()) {
log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
return componentsUtils.convertFromStorageResponse(status.right().value());
}
}
}
return ActionStatus.OK;
}
private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType, String parentId) {
List<GroupInstance> updatedGroupInstances = new ArrayList<>();
List<GroupInstance> groupInstances = null;
Optional<ComponentInstance> componentInstOp = parent.getComponentInstances()
.stream()
.filter(ci -> ci.getUniqueId().equals(parentId))
.findFirst();
if (componentInstOp.isPresent()) {
groupInstances = componentInstOp.get().getGroupInstances();
}
if (CollectionUtils.isNotEmpty(groupInstances)) {
boolean isUpdated = false;
for (GroupInstance groupInstance : groupInstances) {
isUpdated = false;
if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
.contains(artifactInfo
.getUniqueId())) {
groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId());
groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId());
isUpdated = true;
}
if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
.contains(artifactInfo
.getArtifactUUID())) {
groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID());
groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID());
isUpdated = true;
}
if (isUpdated) {
updatedGroupInstances.add(groupInstance);
}
}
}
Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, parentId, updatedGroupInstances);
if (status.isRight()) {
log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
return componentsUtils.convertFromStorageResponse(status.right().value());
}
return ActionStatus.OK;
}
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(Component parent, ArtifactDefinition artifactInfo) {
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
result = generateToscaArtifact(parent, artifactInfo, false, false);
}
else {
String heatArtifactId = artifactInfo.getGeneratedFromId();
Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
if (heatRes.isRight()) {
log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo
.getUniqueId());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes
.right()
.value()), "");
return Either.right(responseFormat);
}
String generatedPayload = generateHeatEnvPayload(heatRes.left().value());
artifactInfo.setPayloadData(generatedPayload);
result = Either.left(Either.left(artifactInfo));
}
return result;
}
private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, boolean needToUpdateGroup) {
convertParentType(componentType);
String parentId = parent.getUniqueId();
Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo
.getGeneratedFromId());
ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value();
if (origMd5 != null) {
Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
if (validateMd5.isRight()) {
ResponseFormat responseFormat = validateMd5.right().value();
handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
return Either.right(responseFormat);
}
if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
if (payloadEither.isRight()) {
ResponseFormat responseFormat = payloadEither.right().value();
handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
return Either.right(responseFormat);
}
}
else { // duplicate
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
return Either.right(responseFormat);
}
}
// lock resource
if (shouldLock) {
Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK);
if (lockComponent.isRight()) {
handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
.value(), componentType, null);
return Either.right(lockComponent.right().value());
}
}
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
try {
resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, needToUpdateGroup);
return resultOp;
}
finally {
// unlock resource
if (resultOp == null || resultOp.isRight()) {
log.debug(ROLLBACK);
if (!inTransaction) {
titanDao.rollback();
}
}
else {
log.debug(COMMIT);
if (!inTransaction) {
titanDao.commit();
}
}
if (shouldLock) {
graphLockOperation.unlockComponent(parent.getUniqueId(), parent.getComponentType().getNodeType());
}
}
}
public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
if (artifactGenerationRequired(component, csarArtifact)) {
Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false);
if (generated.isRight()) {
log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right()
.value());
return Either.right(generated.right().value());
}
return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left()
.value()));
}
return downloadArtifact(csarArtifact);
}
public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
// perform all validation in common flow
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DOWNLOAD), artifactId, null, null, null, null,
null, parentId, containerComponentType);
if (result.isRight()) {
return Either.right(result.right().value());
}
ArtifactDefinition artifactDefinition;
Either<ArtifactDefinition, Operation> insideValue = result.left().value();
if (insideValue.isLeft()) {
artifactDefinition = insideValue.left().value();
}
else {
artifactDefinition = insideValue.right().value().getImplementationArtifact();
}
// for tosca artifacts and heat env on VF level generated on download without saving
if (artifactDefinition.getPayloadData() != null) {
return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition
.getPayloadData()));
}
return downloadArtifact(artifactDefinition);
}
public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
// step 1
// detect auditing type
Map<String, ArtifactDefinition> resMap = null;
Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null;
new Wrapper<>();
// step 2
// check header
if (userId == null) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
resultOp = Either.right(responseFormat);
return resultOp;
}
// step 3
// check user existence
// step 4
// check user's role
validateUserExists(userId, "get artifacts", false);
// steps 5 - 6 - 7
// 5. check service/resource existence
// 6. check service/resource check out
// 7. user is owner of checkout state
org.openecomp.sdc.be.model.Component component = null;
String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
ComponentParametersView componentFilter = new ComponentParametersView();
componentFilter.disableAll();
componentFilter.setIgnoreArtifacts(false);
if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
componentFilter.setIgnoreComponentInstances(false);
}
Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum
.findByParamName(containerComponentType), componentFilter);
if (validateComponent.isRight()) {
resultOp = Either.right(validateComponent.right().value());
return resultOp;
}
component = validateComponent.left().value();
Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, UPDATE_ARTIFACT_LOCK);
if (lockComponent.isRight()) {
resultOp = Either.right(lockComponent.right().value());
return resultOp;
}
try {
ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
if (groupType == null) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
resultOp = Either.right(responseFormat);
return resultOp;
}
if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId);
if (list != null && !list.isEmpty()) {
resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a));
}
else {
resMap = new HashMap<>();
}
resultOp = Either.left(resMap);
return resultOp;
}
else {
Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType
.getNodeType(), groupType, componentId);
if (artifactsMapStatus.isRight()) {
if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
resultOp = Either.right(responseFormat);
}
else {
resMap = new HashMap<>();
resultOp = Either.left(resMap);
}
}
else {
resMap = artifactsMapStatus.left().value();
resultOp = Either.left(resMap);
}
return resultOp;
}
}
finally {
// unlock resource
if (resultOp == null || resultOp.isRight()) {
log.debug(ROLLBACK);
titanDao.rollback();
}
else {
log.debug(COMMIT);
titanDao.commit();
}
componentType = component.getComponentType();
NodeTypeEnum nodeType = componentType.getNodeType();
graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
}
}
private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, Component component) {
// step 9
// check artifact existence
Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component
.getUniqueId());
if (artifactResult.isRight()) {
if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
log.debug("addArtifact - artifact {} not found", artifactId);
return Either.right(responseFormat);
}
else {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult
.right()
.value()));
log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right()
.value());
return Either.right(responseFormat);
}
}
// step 9.1
// check artifact belong to component
boolean found = false;
switch (componentType) {
case RESOURCE:
case SERVICE:
found = checkArtifactInComponent(component, artifactId);
break;
case RESOURCE_INSTANCE:
found = checkArtifactInResourceInstance(component, componentId, artifactId);
break;
default:
}
if (!found) {
String componentName = componentType.name().toLowerCase();
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName);
log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId);
return Either.right(responseFormat);
}
return Either.left(artifactResult.left().value());
}
private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
String artifactId = null;
// step 11
Either<byte[], ResponseFormat> payloadEither = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
if (payloadEither.isRight()) {
return Either.right(payloadEither.right().value());
}
byte[] decodedPayload = payloadEither.left().value();
convertParentType(componentType);
if (shouldLock) {
Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
if (lockComponent.isRight()) {
handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
.value(), componentType, null);
return Either.right(lockComponent.right().value());
}
}
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
try {
resultOp = createArtifact(parent, componentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
return resultOp;
}
finally {
if (shouldLock) {
unlockComponent(resultOp, parent, inTransaction);
}
}
}
private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleLink(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
Component parent, boolean shouldLock, boolean inTransaction) {
if (shouldLock) {
Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
if (lockComponent.isRight()) {
handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
.value(), componentType, null);
return Either.right(lockComponent.right().value());
}
}
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
try {
resultOp = createAndLinkArtifact(parent, componentId, artifactInfo, user, componentType, auditingAction);
return resultOp;
}
finally {
if (shouldLock) {
unlockComponent(resultOp, parent, inTransaction);
}
}
}
private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
convertParentType(componentType);
// lock resource
if (shouldLock) {
Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK);
if (lockComponent.isRight()) {
handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
.value(), componentType, null);
return Either.right(lockComponent.right().value());
}
}
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
try {
resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName);
return resultOp;
}
finally {
if (shouldLock) {
unlockComponent(resultOp, parent, inTransaction);
}
}
}
private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user,
ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
if (payloadEither.isRight()) {
return Either.right(payloadEither.right().value());
}
byte[] decodedPayload = payloadEither.left().value();
return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
}
private Either<byte[], ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
Component parent, String origMd5, String originData, String interfaceType, String operationName) {
// Md5 validations
Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
if (validateMd5.isRight()) {
ResponseFormat responseFormat = validateMd5.right().value();
handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
return Either.right(responseFormat);
}
// step 11
Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent);
if (validateResult.isRight()) {
ResponseFormat responseFormat = validateResult.right().value();
handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
return Either.right(validateResult.right().value());
}
Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
if (payloadEither.isRight()) {
ResponseFormat responseFormat = payloadEither.right().value();
handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
log.debug("Error during handle payload");
return Either.right(responseFormat);
}
// validate heat parameters. this part must be after the parameters are
// extracted in "handlePayload"
Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo
.getArtifactType());
if (validateAndConvertHeatParamers.isRight()) {
ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
log.debug("Error during handle payload");
return Either.right(responseFormat);
}
return payloadEither;
}
public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat,
ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
if (componentsUtils.isExternalApiEvent(auditingActionEnum)) {
return;
}
if (user == null) {
user = new User();
user.setUserId("UNKNOWN");
}
handleInternalAuditEvent(auditingActionEnum, component, componentId, user, artifactDefinition, prevArtifactUuid, currentArtifactUuid, responseFormat, componentTypeEnum, resourceInstanceName);
}
private void handleInternalAuditEvent(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat, ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
switch (componentTypeEnum) {
case RESOURCE:
Resource resource = (Resource) component;
if (resource == null) {
// In that case, component ID should be instead of name
resource = new Resource();
resource.setName(componentId);
}
componentsUtils.auditResource(responseFormat, user, resource, resource.getName(), auditingActionEnum,
ResourceVersionInfo.newBuilder()
.artifactUuid(prevArtifactUuid)
.build(), currentArtifactUuid, artifactDefinition);
break;
case SERVICE:
Service service = (Service) component;
if (service == null) {
// In that case, component ID should be instead of name
service = new Service();
service.setName(componentId);
}
componentsUtils.auditComponent(responseFormat, user, service, auditingActionEnum, new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()),
ResourceVersionInfo.newBuilder()
.artifactUuid(prevArtifactUuid)
.build(),
ResourceVersionInfo.newBuilder()
.artifactUuid(currentArtifactUuid)
.build(),
null, artifactDefinition, null);
break;
case RESOURCE_INSTANCE:
if (resourceInstanceName == null) {
resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
}
componentsUtils.auditComponent(responseFormat, user, component, auditingActionEnum,
new ResourceCommonInfo(resourceInstanceName, ComponentTypeEnum.RESOURCE_INSTANCE.getValue()),
ResourceVersionInfo.newBuilder()
.artifactUuid(prevArtifactUuid)
.build(),
ResourceVersionInfo.newBuilder()
.artifactUuid(currentArtifactUuid)
.build(),
null, artifactDefinition, null);
break;
default:
break;
}
}
private String getResourceInstanceNameFromComponent(Component component, String componentId) {
ComponentInstance resourceInstance = component.getComponentInstances()
.stream()
.filter(p -> p.getUniqueId().equals(componentId))
.findFirst()
.orElse(null);
String resourceInstanceName = null;
if (resourceInstance != null) {
resourceInstanceName = resourceInstance.getName();
}
return resourceInstanceName;
}
private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
StringBuilder sb = new StringBuilder();
if (artifactDefinition != null) {
sb.append(artifactDefinition.getArtifactGroupType().getType())
.append(",")
.append("'")
.append(artifactDefinition.getArtifactLabel())
.append("'")
.append(",")
.append(artifactDefinition.getArtifactType())
.append(",")
.append(artifactDefinition.getArtifactName())
.append(",")
.append(artifactDefinition.getTimeout())
.append(",")
.append(artifactDefinition.getEsId());
sb.append(",");
if (artifactDefinition.getArtifactVersion() != null) {
sb.append(artifactDefinition.getArtifactVersion());
}
else {
sb.append(" ");
}
sb.append(",");
if (artifactDefinition.getArtifactUUID() != null) {
sb.append(artifactDefinition.getArtifactUUID());
}
else {
sb.append(" ");
}
}
return sb.toString();
}
private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) {
if (origMd5 != null) {
String encodeBase64Str = GeneralUtility.calculateMD5Base64EncodedByString(originData);
if (!encodeBase64Str.equals(origMd5)) {
log.debug("The calculated md5 is different then the received one");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
}
}
else {
if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && payload != null && payload.length != 0) {
log.debug("Missing md5 header during artifact create");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
}
// Update metadata
if (payload != null && payload.length != 0) {
log.debug("Cannot have payload while md5 header is missing");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
}
return Either.left(true);
}
private Either<ArtifactDefinition, ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
ComponentTypeEnum componentType, Component parentComponent) {
Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId);
if (artifactById.isRight()) {
return Either.right(artifactById.right().value());
}
ArtifactDefinition currentArtifactInfo = artifactById.left().value();
ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo);
Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent);
if (validateInformationalArtifactRes.isRight()) {
return Either.right(validateInformationalArtifactRes.right().value());
}
Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo);
if (validateAndSetArtifactname.isRight()) {
return Either.right(validateAndSetArtifactname.right().value());
}
if (operationName != null && interfaceName != null) {
operationName = operationName.toLowerCase();
interfaceName = interfaceName.toLowerCase();
}
Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactInfo, operationName, componentType);
if (logicalNameStatus.isRight()) {
return Either.right(logicalNameStatus.right().value());
}
// This is a patch to block possibility of updating service api fields
// through other artifacts flow
ArtifactGroupTypeEnum artifactGroupType = operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL;
if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, artifactGroupType);
}
else {
checkCreateFields(user, artifactInfo, artifactGroupType);
}
composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName);
if (currentArtifactInfo != null) {
artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
}
// artifactGroupType is not allowed to be updated
if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
if (validateGroupType.isRight()) {
return Either.right(validateGroupType.right().value());
}
}
NodeTypeEnum parentType = convertParentType(componentType);
boolean isCreate = ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum());
if (isDeploymentArtifact(artifactInfo)) {
Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, isCreate, artifactInfo, currentArtifactInfo, parentType);
if (deploymentValidationResult.isRight()) {
return Either.right(deploymentValidationResult.right().value());
}
}
else {
artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
}
Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
if (descriptionResult.isRight()) {
return Either.right(descriptionResult.right().value());
}
if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType()
.equals(ArtifactGroupTypeEnum.SERVICE_API)) {
Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
if (validateServiceApiType.isRight()) {
return Either.right(validateServiceApiType.right().value());
}
// Change of type is not allowed and should be ignored
artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
if (validateUrl.isRight()) {
return Either.right(validateUrl.right().value());
}
Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo);
if (validateUpdate.isRight()) {
log.debug("serviceApi first update cnnot be without payload.");
return Either.right(validateUpdate.right().value());
}
}
else {
Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
if (validateArtifactType.isRight()) {
return Either.right(validateArtifactType.right().value());
}
if (artifactInfo.getApiUrl() != null) {
artifactInfo.setApiUrl(null);
log.error("Artifact URL cannot be set through this API - ignoring");
}
if (artifactInfo.getServiceApi() != null && artifactInfo.getServiceApi()) {
artifactInfo.setServiceApi(false);
log.error("Artifact service API flag cannot be changed - ignoring");
}
}
return Either.left(artifactInfo);
}
private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) {
if (operation.getArtifactOperationEnum().equals(ArtifactOperationEnum.UPDATE)) {
artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType());
artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType());
artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel());
}
}
private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) {
Either<ArtifactDefinition, ResponseFormat> result = null;
ArtifactDefinition foundArtifact = null;
if (StringUtils.isNotEmpty(artifactId)) {
foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId);
}
if (foundArtifact != null && ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
log.debug("Artifact {} already exist", artifactId);
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel()));
}
if (foundArtifact == null && !ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId);
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
}
if (result == null) {
result = Either.left(foundArtifact);
}
return result;
}
private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) {
ArtifactDefinition foundArtifact;
if (parentComponent.getUniqueId().equals(parentId)) {
foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId);
}
else {
ComponentInstance instance = findComponentInstance(parentId, parentComponent);
foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId);
}
return foundArtifact;
}
private Either<Boolean, ResponseFormat> validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) {
ComponentTypeEnum parentComponentType = parentComponent.getComponentType();
ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
Either<Boolean, ResponseFormat> validationResult = Either.left(true);
ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
if (artifactType == null) {
validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
.getArtifactType()));
}
else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) {
String artifactTypeName = artifactType.getType();
ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType();
Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager()
.getConfiguration()
.getResourceInformationalArtifacts();
Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet();
if (!validArtifactTypes.contains(artifactTypeName)) {
validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
}
else {
List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName)
.getValidForResourceTypes();
if (!validResourceType.contains(parentResourceType.name())) {
validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
}
}
}
return validationResult;
}
private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
return NodeTypeEnum.Resource;
}
else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
return NodeTypeEnum.ResourceInstance;
}
else {
return NodeTypeEnum.Service;
}
}
public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, Component parent,
boolean shouldLock, boolean inTransaction) {
NodeTypeEnum parentType = convertParentType(componentType);
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = null;
ArtifactDefinition foundArtifact = null;
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getContainerRes = null;
org.openecomp.sdc.be.model.Component fetchedContainerComponent = null;
boolean isDuplicated = false;
String esId = null;
Either<Boolean, StorageOperationStatus> needCloneRes = null;
try {
if (shouldLock) {
Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: ");
if (lockComponent.isRight()) {
handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
.value(), componentType, null);
resultOp = Either.right(lockComponent.right().value());
}
}
if (resultOp == null) {
log.debug("Going to fetch the container component {}. ", parent.getUniqueId());
getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId());
if (getContainerRes.isRight()) {
log.debug("Failed to fetch the container component {}. ", parentId);
responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes
.right()
.value()), artifactId);
handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
resultOp = Either.right(responseFormat);
}
}
if (resultOp == null) {
fetchedContainerComponent = getContainerRes.left().value();
log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId());
getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType);
if (getArtifactRes.isRight()) {
log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent
.getUniqueId());
responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right()
.value(), artifactId);
handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
resultOp = Either.right(responseFormat);
}
else {
foundArtifact = getArtifactRes.left().value().getLeft();
esId = foundArtifact.getEsId();
}
}
if (resultOp == null && StringUtils.isNotEmpty(esId)) {
needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent
.getComponentType()));
if (needCloneRes.isRight()) {
log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId);
responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes
.right()
.value()), foundArtifact.getArtifactDisplayName());
handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
resultOp = Either.right(responseFormat);
}
}
boolean isNeedToDeleteArtifactFromDB = true;
if (resultOp == null) {
if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
String instanceId = parentId;
Either<Boolean, ActionStatus> isOnlyResourceInstanceArtifact = isArtifactOnlyResourceInstanceArtifact(foundArtifact, fetchedContainerComponent, instanceId);
if (isOnlyResourceInstanceArtifact.isRight()) {
log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId);
responseFormat = componentsUtils.getResponseFormatByArtifactId(isOnlyResourceInstanceArtifact.right()
.value(), foundArtifact
.getArtifactDisplayName());
handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
return Either.right(responseFormat);
}
isNeedToDeleteArtifactFromDB = isOnlyResourceInstanceArtifact.left().value();
}
Either<ArtifactDataDefinition, StorageOperationStatus> updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes
.left()
.value());
if (updatedArtifactRes.isRight()) {
log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId);
responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes
.right()
.value()), foundArtifact.getArtifactDisplayName());
handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
resultOp = Either.right(responseFormat);
}
else {
isDuplicated = updatedArtifactRes.left().value().getDuplicated();
}
}
if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated) && isNeedToDeleteArtifactFromDB) {
log.debug("Going to delete the artifact {} from the database. ", artifactId);
CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId);
if (cassandraStatus != CassandraOperationStatus.OK) {
log.debug("Failed to delete the artifact {} from the database. ", artifactId);
responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(componentsUtils.convertToStorageOperationStatus(cassandraStatus)), foundArtifact
.getArtifactDisplayName());
handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
resultOp = Either.right(responseFormat);
}
}
if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes
.left()
.value()
.getRight()
.getGroupInstances());
if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, parentId, updatedGroupInstances);
if (status.isRight()) {
log.debug(FAILED_UPDATE_GROUPS, fetchedContainerComponent.getUniqueId());
responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
.right()
.value()), foundArtifact.getArtifactDisplayName());
handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
resultOp = Either.right(responseFormat);
}
}
}
if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
if (status != StorageOperationStatus.OK) {
log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId);
responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact
.getArtifactDisplayName());
handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
resultOp = Either.right(responseFormat);
}
}
if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent
.getGroups());
if (CollectionUtils.isNotEmpty(updatedGroups)) {
Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, updatedGroups);
if (status.isRight()) {
log.debug(FAILED_UPDATE_GROUPS, fetchedContainerComponent.getUniqueId());
responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
.right()
.value()), foundArtifact.getArtifactDisplayName());
handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
resultOp = Either.right(responseFormat);
}
}
}
if (resultOp == null) {
resultOp = Either.left(Either.left(foundArtifact));
handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null);
}
return resultOp;
}
finally {
if (shouldLock) {
unlockComponent(resultOp, parent, inTransaction);
}
}
}
private Either<Boolean, ActionStatus> isArtifactOnlyResourceInstanceArtifact(ArtifactDefinition foundArtifact, Component parent, String instanceId) {
Either<Boolean, ActionStatus> result = Either.left(true);
ComponentInstance foundInstance = null;
Optional<ComponentInstance> componentInstanceOpt = parent.getComponentInstances()
.stream()
.filter(i -> i.getUniqueId().equals(instanceId))
.findFirst();
if (!componentInstanceOpt.isPresent()) {
result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
}
else {
foundInstance = componentInstanceOpt.get();
String componentUid = foundInstance.getComponentUid();
Either<Component, StorageOperationStatus> getContainerRes = toscaOperationFacade.getToscaElement(componentUid);
if (getContainerRes.isRight()) {
log.debug("Failed to fetch the container component {}. ", componentUid);
return Either.right(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()));
}
Component origComponent = getContainerRes.left().value();
Map<String, ArtifactDefinition> deploymentArtifacts = origComponent.getDeploymentArtifacts();
if (deploymentArtifacts != null && !deploymentArtifacts.isEmpty()) {
Optional<String> op = deploymentArtifacts.keySet()
.stream()
.filter(a -> a.equals(foundArtifact.getArtifactLabel()))
.findAny();
if (op.isPresent()) {
return Either.left(false);
}
}
Map<String, ArtifactDefinition> artifacts = origComponent.getArtifacts();
if (artifacts != null && !artifacts.isEmpty()) {
Optional<String> op = artifacts.keySet()
.stream()
.filter(a -> a.equals(foundArtifact.getArtifactLabel()))
.findAny();
if (op.isPresent()) {
return Either.left(false);
}
}
}
return result;
}
private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) {
List<GroupDataDefinition> updatedGroups = new ArrayList<>();
boolean isUpdated = false;
if (groups != null) {
for (GroupDefinition group : groups) {
isUpdated = false;
if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) {
group.getArtifacts().remove(artifactId);
isUpdated = true;
}
if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid()
.contains(foundArtifact.getArtifactUUID())) {
group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID());
isUpdated = true;
}
if (isUpdated) {
updatedGroups.add(group);
}
}
}
return updatedGroups;
}
private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
List<GroupInstance> updatedGroupInstances = new ArrayList<>();
if (CollectionUtils.isNotEmpty(groupInstances)) {
boolean isUpdated = false;
for (GroupInstance groupInstance : groupInstances) {
isUpdated = false;
if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
.contains(artifactId)) {
groupInstance.getGroupInstanceArtifacts().remove(artifactId);
isUpdated = true;
}
if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
.contains(foundArtifact
.getArtifactUUID())) {
groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
isUpdated = true;
}
if (isUpdated) {
updatedGroupInstances.add(groupInstance);
}
}
}
return updatedGroupInstances;
}
private Either<ArtifactDataDefinition, StorageOperationStatus> deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
Either<ArtifactDataDefinition, StorageOperationStatus> result;
boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi();
String componentId = component.getUniqueId();
String instanceId = componentId.equals(parentId) ? null : parentId;
if (isMandatory) {
log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId);
resetMandatoryArtifactFields(foundArtifact);
result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true, true);
}
else if (cloneIsNeeded) {
log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId);
result = artifactToscaOperation.deleteArtifactWithCloningOnGraph(componentId, foundArtifact, parentType, instanceId, false);
}
else {
log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false);
}
return result;
}
private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) {
Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null;
Map<String, ArtifactDefinition> artifacts = new HashMap<>();
ComponentInstance foundInstance = null;
if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) {
Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances()
.stream()
.filter(i -> i.getUniqueId()
.equals(parentId))
.findFirst();
if (!componentInstanceOpt.isPresent()) {
result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
}
else {
foundInstance = componentInstanceOpt.get();
fetchArtifactsFromInstance(artifactId, artifacts, foundInstance);
}
}
else {
fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts);
}
if (result == null) {
if (artifacts.containsKey(artifactId)) {
result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance));
}
else {
result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND);
}
}
return result;
}
private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) {
Map<String, ArtifactDefinition> currArtifacts;
if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
currArtifacts = component.getDeploymentArtifacts()
.values()
.stream()
.collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
if (MapUtils.isNotEmpty(currArtifacts)) {
artifacts.putAll(currArtifacts);
}
}
if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
currArtifacts = component.getArtifacts()
.values()
.stream()
.collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
if (MapUtils.isNotEmpty(currArtifacts)) {
artifacts.putAll(currArtifacts);
}
}
if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
currArtifacts = component.getToscaArtifacts()
.values()
.stream()
.collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
if (MapUtils.isNotEmpty(currArtifacts)) {
artifacts.putAll(currArtifacts);
}
}
}
private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) {
Map<String, ArtifactDefinition> currArtifacts;
if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) {
currArtifacts = instance.getDeploymentArtifacts()
.values()
.stream()
.collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
if (MapUtils.isNotEmpty(currArtifacts)) {
artifacts.putAll(currArtifacts);
}
}
if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) {
currArtifacts = instance.getArtifacts()
.values()
.stream()
.collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
if (MapUtils.isNotEmpty(currArtifacts)) {
artifacts.putAll(currArtifacts);
}
}
}
private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) {
if (fetchedArtifact != null) {
log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId());
fetchedArtifact.setEsId(null);
fetchedArtifact.setArtifactName(null);
fetchedArtifact.setDescription(null);
fetchedArtifact.setApiUrl(null);
fetchedArtifact.setArtifactChecksum(null);
nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
fetchedArtifact.setArtifactUUID(null);
long time = System.currentTimeMillis();
fetchedArtifact.setPayloadUpdateDate(time);
fetchedArtifact.setHeatParameters(null);
fetchedArtifact.setHeatParamsUpdateDate(null);
}
}
private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) {
StorageOperationStatus error = StorageOperationStatus.OK;
if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
log.debug("Need to re-generate customization UUID for instance {}", instanceId);
error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId);
}
return error;
}
private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType,
Component parent) {
Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent
.getUniqueId());
if (artifactById.isRight()) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus);
ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, "");
handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
return Either.right(responseFormat);
}
ArtifactDefinition artifactDefinition = artifactById.left().value();
if (artifactDefinition == null) {
log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
return Either.right(responseFormat);
}
Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
return Either.left(insideEither);
}
private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, String operationName,
ComponentTypeEnum componentType) {
String artifactLabel = artifactInfo.getArtifactLabel();
if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel()
.isEmpty())) {
BeEcompErrorManager.getInstance()
.logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
log.debug("missing artifact logical name for component {}", componentId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
}
if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && !artifactInfo.getMandatory()) {
if (operationName != null) {
if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
log.debug("artifact label cannot be set {}", artifactLabel);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
}
else {
artifactLabel = operationName;
}
}
String displayName = artifactInfo.getArtifactDisplayName();
if (displayName == null || displayName.isEmpty()) {
displayName = artifactLabel;
}
displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
artifactInfo.setArtifactDisplayName(displayName);
if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
log.debug("Invalid format form Artifact label : {}", artifactLabel);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
if (artifactLabel.isEmpty()) {
log.debug("missing normalized artifact logical name for component {}", componentId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
}
if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String
.valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
}
if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) {
log.debug("Non unique Artifact label : {}", artifactLabel);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
}
}
artifactInfo.setArtifactLabel(artifactLabel);
return Either.left(ActionStatus.OK);
}
private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) {
boolean isUnique = true;
Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts;
if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
}
else {
artifacts = artifactToscaOperation.getArtifacts(componentId);
}
if (artifacts.isLeft()) {
for (String label : artifacts.left().value().keySet()) {
if (label.equals(artifactLabel)) {
isUnique = false;
break;
}
}
}
if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
.getAllInterfacesOfResource(componentId, true, true);
if (allInterfacesOfResource.isLeft()) {
for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
for (Operation operation : interace.getOperationsMap().values()) {
if (operation.getImplementation() != null && operation.getImplementation()
.getArtifactLabel()
.equals(artifactLabel)) {
isUnique = false;
break;
}
}
}
}
}
return isUnique;
}
boolean validateArtifactNameUniqueness(String componentId, Component parentComponent, ArtifactDefinition artifactInfo,
ComponentTypeEnum componentType) {
Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = getArtifacts(componentType,
parentComponent, componentId, artifactInfo.getArtifactGroupType());
String artifactName = artifactInfo.getArtifactName();
if (artifacts.isLeft() && Objects.nonNull(artifacts.left().value())){
if (artifacts.left().value().values().stream()
.anyMatch(ad -> artifactName.equals(ad.getArtifactName())
//check whether it is the same artifact we hold (by label)
&& !artifactInfo.getArtifactLabel().equals(ad.getArtifactLabel()))){
return false;
}
}
if (ComponentTypeEnum.RESOURCE.equals(componentType)) {
return isUniqueArtifactNameInResourceInterfaces(componentId, artifactName, artifactInfo.getArtifactLabel());
}
return true;
}
private boolean isUniqueArtifactNameInResourceInterfaces(String componentId, String artifactName, String artifactLabel) {
Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
.getAllInterfacesOfResource(componentId, true, true);
if (allInterfacesOfResource.isLeft() && Objects.nonNull(allInterfacesOfResource)){
return !allInterfacesOfResource.left().value()
.values()
.stream().map(InterfaceDefinition :: getOperationsMap)
.flatMap(map -> map.values().stream())
.map(OperationDataDefinition::getImplementation)
.filter(Objects::nonNull)
.anyMatch(add -> artifactName.equals(add.getArtifactName())
&& !artifactLabel.equals(add.getArtifactLabel()));
}
return true;
}
private boolean isUniqueLabelInResourceInterfaces(String componentId, String artifactLabel) {
Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
.getAllInterfacesOfResource(componentId, true, true);
if (allInterfacesOfResource.isLeft()){
return !allInterfacesOfResource.left().value()
.values()
.stream().map(InterfaceDefinition :: getOperationsMap)
.flatMap(map -> map.values().stream())
.map(OperationDataDefinition::getImplementation)
.filter(Objects::nonNull)
.anyMatch(add -> artifactLabel.equals(add.getArtifactLabel()));
}
return true;
}
private Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(ComponentTypeEnum componentType, Component parentComponent,
String componentId, ArtifactGroupTypeEnum artifactGroupType) {
Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsResponse;
if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
artifactsResponse = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
}
else {
artifactsResponse = artifactToscaOperation.getArtifacts(componentId);
}
if (artifactsResponse.isRight() && artifactsResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
log.debug("failed to retrieve artifacts for {} ", componentId);
return Either.right(artifactsResponse.right().value());
}
return Either.left(artifactsResponse.left().value().entrySet()
.stream()
.filter(x -> artifactGroupType.equals(x.getValue().getArtifactGroupType()))
.collect(Collectors.toMap(Entry::getKey, Entry::getValue)));
}
private List<String> getListOfArtifactName(Map<String, ArtifactDefinition> artifacts) {
return artifacts.entrySet()
.stream()
.map(x -> x.getValue().getArtifactName())
.collect(Collectors.toList());
}
// ***************************************************************
private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createAndLinkArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, User user,
ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum) {
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
Either<ArtifactDefinition, Operation> insideEither = null;
ComponentInstance foundInstance = findComponentInstance(parentId, parent);
String instanceId = null;
String instanceName = null;
if (foundInstance != null) {
instanceId = foundInstance.getUniqueId();
instanceName = foundInstance.getName();
}
boolean isLeft = false;
String artifactUniqueId = null;
StorageOperationStatus error = null;
// information/deployment/api aritfacts
log.trace("Try to create entry on graph");
NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
.getUniqueId(), nodeType, true, instanceId);
isLeft = result.isLeft();
if (isLeft) {
artifactUniqueId = result.left().value().getUniqueId();
result.left().value();
insideEither = Either.left(result.left().value());
resultOp = Either.left(insideEither);
error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
if (error != StorageOperationStatus.OK) {
isLeft = false;
}
}
if (isLeft) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
return resultOp;
}
else {
log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
.getArtifactDisplayName());
handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
resultOp = Either.right(responseFormat);
return resultOp;
}
}
private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user,
ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
Either<ArtifactDefinition, Operation> insideEither = null;
ComponentInstance foundInstance = findComponentInstance(parentId, parent);
String instanceId = null;
String instanceName = null;
if (foundInstance != null) {
if (foundInstance.isArtifactExists(artifactInfo.getArtifactGroupType(), artifactInfo.getArtifactLabel())) {
log.debug("Failed to create artifact, already exists");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactInfo
.getArtifactLabel());
handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactInfo.getUniqueId(), responseFormat, componentTypeEnum, foundInstance
.getName());
resultOp = Either.right(responseFormat);
return resultOp;
}
instanceId = foundInstance.getUniqueId();
instanceName = foundInstance.getName();
}
if (artifactData == null) {
BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
log.debug("Failed to create artifact object for ES.");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null);
resultOp = Either.right(responseFormat);
return resultOp;
}
// set on graph object id of artifact in ES!
artifactInfo.setEsId(artifactData.getId());
boolean isLeft = false;
String artifactUniqueId = null;
StorageOperationStatus error = null;
if (interfaceType != null && operationName != null) {
// lifecycle artifact
Operation operation = convertToOperation(artifactInfo, operationName);
Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
isLeft = result.isLeft();
if (isLeft) {
artifactUniqueId = result.left().value().getImplementation().getUniqueId();
result.left().value().getImplementation();
insideEither = Either.right(result.left().value());
resultOp = Either.left(insideEither);
}
else {
error = result.right().value();
}
}
else {
// information/deployment/api aritfacts
log.trace("Try to create entry on graph");
NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
.getUniqueId(), nodeType, true, instanceId);
isLeft = result.isLeft();
if (isLeft) {
artifactUniqueId = result.left().value().getUniqueId();
artifactData.setId(result.left().value().getEsId());
insideEither = Either.left(result.left().value());
resultOp = Either.left(insideEither);
error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
if (error != StorageOperationStatus.OK) {
isLeft = false;
}
}
else {
error = result.right().value();
}
}
if (isLeft) {
boolean res = saveArtifacts(artifactData, parentId);
if (res) {
log.debug(ARTIFACT_SAVED, artifactUniqueId);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
return resultOp;
}
else {
BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
log.debug(FAILED_SAVE_ARTIFACT);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
resultOp = Either.right(responseFormat);
return resultOp;
}
}
else {
log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
.getArtifactDisplayName());
handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
resultOp = Either.right(responseFormat);
return resultOp;
}
}
private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) {
ComponentInstance foundInstance = null;
if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
foundInstance = containerComponent.getComponentInstances()
.stream()
.filter(i -> i.getUniqueId().equals(componentInstanceId))
.findFirst()
.orElse(null);
}
return foundInstance;
}
private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
Either<Boolean, ResponseFormat> result = Either.left(true);
Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
validateArtifactTypeExists(responseWrapper, artifactInfo);
ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
if (responseWrapper.isEmpty()) {
validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts);
}
// Common code for all types
// not allowed to change artifactType
if (responseWrapper.isEmpty() && !isCreate) {
Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact);
if (validateServiceApiType.isRight()) {
responseWrapper.setInnerElement(validateServiceApiType.right().value());
}
}
if (responseWrapper.isEmpty()) {
if (parentType.equals(NodeTypeEnum.Resource)) {
Resource resource = (Resource) parentComponent;
ResourceTypeEnum resourceType = resource.getResourceType();
ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
if (config == null) {
responseWrapper.setInnerElement(ResponseFormatManager.getInstance()
.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
.getArtifactType()));
}
else {
List<String> myList = config.getValidForResourceTypes();
Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList);
if (either.isRight()) {
responseWrapper.setInnerElement(either.right().value());
}
}
}
validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType);
}
if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) {
String artifactName = artifactInfo.getArtifactName();
if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) {
validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType);
}
}
if (responseWrapper.isEmpty()) {
switch (artifactType) {
case HEAT:
case HEAT_VOL:
case HEAT_NET:
result = validateHeatDeploymentArtifact(isCreate, artifactInfo, currentArtifact);
break;
case HEAT_ENV:
result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, artifactInfo, parentType);
artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
break;
case DCAE_INVENTORY_TOSCA:
case DCAE_INVENTORY_JSON:
case DCAE_INVENTORY_POLICY:
// Validation is done in handle payload.
case DCAE_INVENTORY_DOC:
case DCAE_INVENTORY_BLUEPRINT:
case DCAE_INVENTORY_EVENT:
// No specific validation
default:
artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
break;
}
}
if (!responseWrapper.isEmpty()) {
result = Either.right(responseWrapper.getInnerElement());
}
return result;
}
private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
ResponseFormat responseFormat = ResponseFormatManager.getInstance()
.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
.getArtifactType());
responseWrapper.setInnerElement(responseFormat);
log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
}
}
private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null;
if (parentType.equals(NodeTypeEnum.Resource)) {
resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
.getConfiguration()
.getResourceDeploymentArtifacts();
}
else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
.getConfiguration()
.getResourceInstanceDeploymentArtifacts();
}
else {
resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
.getConfiguration()
.getServiceDeploymentArtifacts();
}
return resourceDeploymentArtifacts;
}
public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) {
ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
if (artifactType == null) {
ResponseFormat responseFormat = ResponseFormatManager.getInstance()
.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
.getArtifactType());
responseWrapper.setInnerElement(responseFormat);
log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
}
}
private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
ArtifactTypeConfig retConfig = null;
String fileType = artifactType.getType();
if (parentType.equals(NodeTypeEnum.Resource)) {
retConfig = ConfigurationManager.getConfigurationManager()
.getConfiguration()
.getResourceDeploymentArtifacts()
.get(fileType);
}
else if (parentType.equals(NodeTypeEnum.Service)) {
retConfig = ConfigurationManager.getConfigurationManager()
.getConfiguration()
.getServiceDeploymentArtifacts()
.get(fileType);
}
else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
retConfig = ConfigurationManager.getConfigurationManager()
.getConfiguration()
.getResourceInstanceDeploymentArtifacts()
.get(fileType);
}
return retConfig;
}
private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
// extract heat parameters
if (artifactInfo.getPayloadData() != null) {
String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo
.getArtifactType());
if (heatParameters.isRight() && (!heatParameters.right()
.value()
.equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) {
log.info("failed to parse heat parameters ");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
.getArtifactType());
return Either.right(responseFormat);
}
else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
artifactInfo.setListHeatParameters(heatParameters.left().value());
}
}
return Either.left(true);
}
// Valid extension
public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
String fileType = artifactType.getType();
List<String> acceptedTypes = null;
ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) {
log.debug("parent type of artifact can be either resource or service");
responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
return;
}
if (deploymentAcceptedTypes == null) {
log.debug("parent type of artifact can be either resource or service");
responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
.getArtifactType()));
return;
}
else {
acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes();
}
/*
* No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
*/
String artifactName = artifactInfo.getArtifactName();
String fileExtension = GeneralUtility.getFilenameExtension(artifactName);
// Pavel - File extension validation is case-insensitive - Ella,
// 21/02/2016
if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) {
log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType);
responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType));
return;
}
}
private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<>();
Wrapper<byte[]> payloadWrapper = new Wrapper<>();
if (errorWrapper.isEmpty()) {
validateValidYaml(errorWrapper, artifactInfo);
}
if (errorWrapper.isEmpty()) {
// Validate Heat Exist
validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent
.getComponentType());
}
if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement());
}
if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
}
// init Response
Either<Boolean, ResponseFormat> eitherResponse;
if (errorWrapper.isEmpty()) {
eitherResponse = Either.left(true);
}
else {
eitherResponse = Either.right(errorWrapper.getInnerElement());
}
return eitherResponse;
}
public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) {
if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) {
Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition);
if (fillArtifactPayload.isRight()) {
errorWrapper.setInnerElement(fillArtifactPayload.right().value());
log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
}
}
else {
payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
}
}
public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) {
Either<Boolean, ResponseFormat> result = Either.left(true);
Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD
.getEsId());
if (eitherArtifactData.isLeft()) {
byte[] data = eitherArtifactData.left().value().getDataAsArray();
data = Base64.encodeBase64(data);
payloadWrapper.setInnerElement(data);
}
else {
StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData
.right()
.value());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
result = Either.right(responseFormat);
}
return result;
}
@SuppressWarnings("unchecked")
private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData()));
Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
if (eitherHeatEnvProperties.isRight()) {
ResponseFormat responseFormat = ResponseFormatManager.getInstance()
.getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
errorWrapper.setInnerElement(responseFormat);
log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
}
else if (eitherHeatProperties.isRight()) {
ResponseFormat responseFormat = ResponseFormatManager.getInstance()
.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
.getArtifactName(), heatArtifact.getArtifactName());
errorWrapper.setInnerElement(responseFormat);
log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact
.getArtifactName());
}
else {
Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet();
Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet();
heatEnvPropertiesKeys.removeAll(heatPropertiesKeys);
if (!heatEnvPropertiesKeys.isEmpty()) {
ResponseFormat responseFormat = ResponseFormatManager.getInstance()
.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
.getArtifactName(), heatArtifact.getArtifactName());
errorWrapper.setInnerElement(responseFormat);
}
}
}
private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) {
YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData());
if (!isYamlValid) {
ResponseFormat responseFormat = ResponseFormatManager.getInstance()
.getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo
.getArtifactType());
errorWrapper.setInnerElement(responseFormat);
log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName());
}
}
private boolean isValidXml(byte[] xmlToParse) {
boolean isXmlValid = true;
try {
XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
setFeatures(reader);
reader.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
}
catch (ParserConfigurationException | IOException | SAXException e) {
log.debug("Xml is invalid : {}", e.getMessage(), e);
isXmlValid = false;
}
return isXmlValid;
}
private void setFeatures(XMLReader reader) throws SAXNotSupportedException {
try {
reader.setFeature("http://apache.org/xml/features/validation/schema", false);
reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
}
catch (SAXNotRecognizedException e) {
log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e);
}
}
private boolean isValidJson(byte[] jsonToParse) {
String parsed = new String(jsonToParse);
try {
gson.fromJson(parsed, Object.class);
}
catch (Exception e) {
log.debug("Json is invalid : {}", e.getMessage(), e);
return false;
}
return true;
}
private void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) {
boolean artifactNameFound = false;
Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null)
.iterator();
while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
artifactNameFound = artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName());
}
if (artifactNameFound) {
String parentName = parentComponent.getName();
ResponseFormat responseFormat = ResponseFormatManager.getInstance()
.getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType
.name(), parentName, artifactName);
errorWrapper.setInnerElement(responseFormat);
log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
}
}
private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType,
ComponentTypeEnum componentType) {
Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType);
if (res.isRight()) {
ResponseFormat responseFormat;
if (res.right().value() == StorageOperationStatus.NOT_FOUND) {
responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
}
else {
responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
}
errorWrapper.setInnerElement(responseFormat);
return;
}
ArtifactDefinition heatArtifact = res.left().value();
heatArtifactMDWrapper.setInnerElement(heatArtifact);
}
private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
// timeout > 0 for HEAT artifacts
Integer timeout = artifactInfo.getTimeout();
if (timeout == null) {
Integer defaultTimeout = isCreate ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout();
artifactInfo.setTimeout(defaultTimeout);
// HEAT artifact but timeout is invalid
}
else if (timeout < 1) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT));
}
// US649856 - Allow several HEAT files on Resource
log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel());
return Either.left(true);
}
private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) {
String listToString = (typeList != null) ? typeList.toString() : "";
ResponseFormat responseFormat = ResponseFormatManager.getInstance()
.getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo
.getArtifactName(), listToString, resourceType.getValue());
Either<Boolean, ResponseFormat> either = Either.right(responseFormat);
String resourceTypeName = resourceType.name();
if (typeList != null && typeList.contains(resourceTypeName)) {
either = Either.left(true);
}
return either;
}
private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) {
if (artifactInfo.getHeatParameters() != null) {
for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) {
String parameterType = heatParam.getType();
HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
if (heatParameterType == null) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam
.getType());
return Either.right(responseFormat);
}
StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
if (validateAndUpdateProperty != StorageOperationStatus.OK) {
log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam
.getType(), heatParam.getName());
return Either.right(responseFormat);
}
}
}
return Either.left(artifactInfo);
}
public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
if (parentComponent.getDeploymentArtifacts() != null) {
if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) {
Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null);
if (getRI.isRight()) {
return deploymentArtifacts;
}
ComponentInstance ri = getRI.left().value();
if (ri.getDeploymentArtifacts() != null) {
deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
}
}
else if (parentComponent.getDeploymentArtifacts() != null) {
deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
}
}
return deploymentArtifacts;
}
private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) {
// on create if null add informational to current
if (artifactInfo.getArtifactGroupType() == null) {
artifactInfo.setArtifactGroupType(type);
}
if (artifactInfo.getUniqueId() != null) {
log.error("artifact uniqid cannot be set ignoring");
}
artifactInfo.setUniqueId(null);
if (artifactInfo.getArtifactRef() != null) {
log.error("artifact ref cannot be set ignoring");
}
artifactInfo.setArtifactRef(null);
if (artifactInfo.getArtifactRepository() != null) {
log.error("artifact repository cannot be set ignoring");
}
artifactInfo.setArtifactRepository(null);
if (artifactInfo.getUserIdCreator() != null) {
log.error("creator uuid cannot be set ignoring");
}
artifactInfo.setArtifactCreator(user.getUserId());
if (artifactInfo.getUserIdLastUpdater() != null) {
log.error("userId of last updater cannot be set ignoring");
}
artifactInfo.setUserIdLastUpdater(user.getUserId());
if (artifactInfo.getCreatorFullName() != null) {
log.error("creator Full name cannot be set ignoring");
}
String fullName = user.getFirstName() + " " + user.getLastName();
artifactInfo.setUpdaterFullName(fullName);
if (artifactInfo.getUpdaterFullName() != null) {
log.error("updater Full name cannot be set ignoring");
}
artifactInfo.setUpdaterFullName(fullName);
if (artifactInfo.getCreationDate() != null) {
log.error("Creation Date cannot be set ignoring");
}
long time = System.currentTimeMillis();
artifactInfo.setCreationDate(time);
if (artifactInfo.getLastUpdateDate() != null) {
log.error("Last Update Date cannot be set ignoring");
}
artifactInfo.setLastUpdateDate(time);
if (artifactInfo.getEsId() != null) {
log.error("es id cannot be set ignoring");
}
artifactInfo.setEsId(null);
}
private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
String id = artifactId;
if (artifactId == null || artifactId.isEmpty()) {
String uniqueId = null;
if (interfaceName != null && operationName != null) {
uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo
.getArtifactLabel());
}
else {
uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
}
artifactInfo.setUniqueId(uniqueId);
artifactInfo.setEsId(uniqueId);
id = uniqueId;
}
else {
artifactInfo.setUniqueId(artifactId);
artifactInfo.setEsId(artifactId);
}
return id;
}
private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
if (Strings.isNullOrEmpty(artifactInfo.getArtifactType())) {
BeEcompErrorManager.getInstance()
.logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
}
boolean artifactTypeExist = false;
Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null;
ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
allArtifactTypes = getDeploymentArtifactTypes(parentType);
}
else {
allArtifactTypes = elementOperation.getAllArtifactTypes();
}
if (allArtifactTypes.isRight()) {
BeEcompErrorManager.getInstance()
.logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes
.right()
.value()
.name());
log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right()
.value());
return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId));
}
for (ArtifactType type : allArtifactTypes.left().value()) {
if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) {
artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
artifactTypeExist = true;
break;
}
}
if (!artifactTypeExist) {
BeEcompErrorManager.getInstance()
.logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo
.getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
.getArtifactType()));
}
return Either.left(ActionStatus.OK);
}
private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(NodeTypeEnum parentType) {
Map<String, ArtifactTypeConfig> deploymentArtifacts ;
List<ArtifactType> artifactTypes = new ArrayList<>();
if (parentType.equals(NodeTypeEnum.Service)) {
deploymentArtifacts = ConfigurationManager.getConfigurationManager()
.getConfiguration()
.getServiceDeploymentArtifacts();
}
else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
deploymentArtifacts = ConfigurationManager.getConfigurationManager()
.getConfiguration()
.getResourceInstanceDeploymentArtifacts();
}
else {
deploymentArtifacts = ConfigurationManager.getConfigurationManager()
.getConfiguration()
.getResourceDeploymentArtifacts();
}
if (deploymentArtifacts != null) {
for (String artifactType : deploymentArtifacts.keySet()) {
ArtifactType artifactT = new ArtifactType();
artifactT.setName(artifactType);
artifactTypes.add(artifactT);
}
return Either.left(artifactTypes);
}
else {
return Either.right(ActionStatus.GENERAL_ERROR);
}
}
private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
}
return Either.left(true);
}
private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) {
if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
}
String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName());
if (normalizeFileName == null || normalizeFileName.isEmpty()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
}
artifactInfo.setArtifactName(normalizeFileName);
if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
}
return Either.left(true);
}
private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
log.info("artifact type is missing operation ignored");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
}
if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
log.info("artifact type cannot be changed operation ignored");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
return Either.left(true);
}
private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
if (artifactInfo.getArtifactGroupType() == null) {
artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
}
else if (!currentArtifact.getArtifactGroupType()
.getType()
.equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
log.info("artifact group type cannot be changed. operation failed");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
return Either.left(artifactInfo);
}
private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
// on update if null add informational to current
if (currentArtifact.getArtifactGroupType() == null && type != null) {
currentArtifact.setArtifactGroupType(type);
}
if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
log.error("artifact uniqid cannot be set ignoring");
}
artifactInfo.setUniqueId(currentArtifact.getUniqueId());
if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef()
.equals(artifactInfo.getArtifactRef())) {
log.error("artifact ref cannot be set ignoring");
}
artifactInfo.setArtifactRef(currentArtifact.getArtifactRef());
if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository()
.equals(artifactInfo.getArtifactRepository())) {
log.error("artifact repository cannot be set ignoring");
}
artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository());
if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator()
.equals(artifactInfo.getUserIdCreator())) {
log.error("creator uuid cannot be set ignoring");
}
artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator());
if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator()
.equals(artifactInfo.getArtifactCreator())) {
log.error("artifact creator cannot be set ignoring");
}
artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator());
if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater()
.equals(artifactInfo.getUserIdLastUpdater())) {
log.error("userId of last updater cannot be set ignoring");
}
artifactInfo.setUserIdLastUpdater(user.getUserId());
if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName()
.equals(artifactInfo.getCreatorFullName())) {
log.error("creator Full name cannot be set ignoring");
}
artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName());
if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName()
.equals(artifactInfo.getUpdaterFullName())) {
log.error("updater Full name cannot be set ignoring");
}
String fullName = user.getFirstName() + " " + user.getLastName();
artifactInfo.setUpdaterFullName(fullName);
if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate()
.equals(artifactInfo.getCreationDate())) {
log.error("Creation Date cannot be set ignoring");
}
artifactInfo.setCreationDate(currentArtifact.getCreationDate());
if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate()
.equals(artifactInfo.getLastUpdateDate())) {
log.error("Last Update Date cannot be set ignoring");
}
long time = System.currentTimeMillis();
artifactInfo.setLastUpdateDate(time);
if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
log.error("es id cannot be set ignoring");
}
artifactInfo.setEsId(currentArtifact.getUniqueId());
if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName()
.equals(artifactInfo.getArtifactDisplayName())) {
log.error(" Artifact Display Name cannot be set ignoring");
}
artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName());
if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi()
.equals(artifactInfo.getServiceApi())) {
log.debug("serviceApi cannot be set. ignoring.");
}
artifactInfo.setServiceApi(currentArtifact.getServiceApi());
if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType()
.equals(artifactInfo.getArtifactGroupType())) {
log.debug("artifact group cannot be set. ignoring.");
}
artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID()
.isEmpty() && !currentArtifact.getArtifactUUID()
.equals(artifactInfo.getArtifactUUID())) {
log.debug("artifact UUID cannot be set. ignoring.");
}
artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo
.getHeatParameters()
.isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
}
}
private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
for (HeatParameterDefinition parameter : heatParameters) {
HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
if (currentParam != null) {
if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName());
parameter.setName(currentParam.getName());
}
if (parameter.getDefaultValue() != null && !parameter.getDefaultValue()
.equalsIgnoreCase(currentParam.getDefaultValue())) {
log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue());
parameter.setDefaultValue(currentParam.getDefaultValue());
}
if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) {
log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType());
parameter.setType(currentParam.getType());
}
if (parameter.getDescription() != null && !parameter.getDescription()
.equalsIgnoreCase(currentParam.getDescription())) {
log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription());
parameter.setDescription(currentParam.getDescription());
}
// check and set current value
if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
parameter.setCurrentValue(currentParam.getDefaultValue());
}
}
}
}
private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>();
for (HeatParameterDefinition param : currentParameters) {
currentParamsMap.put(param.getUniqueId(), param);
}
return currentParamsMap;
}
private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) {
if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) {
log.debug("Artifact url cannot be empty.");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
}
artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
}
if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
}
return Either.left(true);
}
private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) {
if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) {
log.debug("Artifact description cannot be empty.");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION));
}
String description = artifactInfo.getDescription();
description = ValidationUtils.removeNoneUtf8Chars(description);
description = ValidationUtils.normaliseWhitespace(description);
description = ValidationUtils.stripOctets(description);
description = ValidationUtils.removeHtmlTagsOnly(description);
if (!ValidationUtils.validateIsEnglish(description)) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String
.valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
}
artifactInfo.setDescription(description);
return Either.left(true);
}
private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload,
ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationUuid) {
ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
String prevArtifactId = null;
String currArtifactId = artifactId;
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
Either<ArtifactDefinition, Operation> insideEither = null;
log.trace("Try to update entry on graph");
String artifactUniqueId = null;
ArtifactDefinition artifactDefinition = artifactInfo;
StorageOperationStatus error;
boolean isLeft;
if (interfaceType == null || operationUuid == null) {
log.debug("Entity on graph is updated. Update artifact in ES");
boolean res = true;
// Changing previous and current artifactId for auditing
prevArtifactId = currArtifactId;
currArtifactId = artifactDefinition.getUniqueId();
if (decodedPayload == null) {
if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
.getEsId());
if (artifactFromCassandra.isRight()) {
log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
.value());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
resultOp = Either.right(responseFormat);
return resultOp;
}
// clone data to new artifact
artifactData.setData(artifactFromCassandra.left().value().getData());
artifactData.setId(artifactFromCassandra.left().value().getId());
}
} else {
if (artifactDefinition.getEsId() == null) {
artifactDefinition.setEsId(artifactDefinition.getUniqueId());
artifactData.setId(artifactDefinition.getUniqueId());
}
}
NodeTypeEnum convertParentType = convertParentType(componentType);
Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArtifactOnResource(artifactInfo, parent
.getUniqueId(), artifactId, convertParentType, parentId);
isLeft = result.isLeft();
if (isLeft) {
artifactUniqueId = result.left().value().getUniqueId();
artifactDefinition = result.left().value();
String artifactType = artifactInfo.getArtifactType();
if (NodeTypeEnum.Resource == convertParentType
&& (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType)
|| ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType)
|| ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))
&& !artifactUniqueId.equals(artifactId)) {
// need to update the generated id in heat env
Map<String, ArtifactDefinition> deploymentArtifacts = parent.getDeploymentArtifacts();
Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet()
.stream()
.filter(a -> a.getValue()
.getGeneratedFromId() != null && a
.getValue()
.getGeneratedFromId()
.equals(artifactId))
.findFirst();
if (findFirst.isPresent()) {
ArtifactDefinition artifactEnvInfo = findFirst.get().getValue();
artifactEnvInfo.setArtifactChecksum(null);
artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId);
}
}
error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
insideEither = Either.left(result.left().value());
resultOp = Either.left(insideEither);
if (error != StorageOperationStatus.OK) {
isLeft = false;
}
} else {
error = result.right().value();
}
if (isLeft) {
// create new entry in ES
res = true;
if (artifactData.getData() != null) {
if (!artifactDefinition.getDuplicated() || artifactData.getId() == null) {
artifactData.setId(artifactDefinition.getEsId());
}
res = saveArtifacts(artifactData, parentId);
}
}
if (res) {
log.debug(ARTIFACT_SAVED, artifactUniqueId);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
} else {
BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT);
log.debug(FAILED_SAVE_ARTIFACT);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
resultOp = Either.right(responseFormat);
}
} else {
return updateArtifactsFlowForInterfaceOperations(parent, parentId, artifactId, artifactInfo, user,
decodedPayload, componentType, auditingAction, interfaceType, operationUuid, artifactData, prevArtifactId,
currArtifactId, artifactDefinition);
}
return resultOp;
}
private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactsFlowForInterfaceOperations(
Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user,
byte[] decodedPayload, ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType,
String operationUuid, ESArtifactData artifactData, String prevArtifactId, String currArtifactId,
ArtifactDefinition artifactDefinition) {
StorageOperationStatus error;
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
if (decodedPayload == null) {
if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
.getEsId());
if (artifactFromCassandra.isRight()) {
log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
.value());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
resultOp = Either.right(responseFormat);
return resultOp;
}
// clone data to new artifact
artifactData.setData(artifactFromCassandra.left().value().getData());
artifactData.setId(artifactFromCassandra.left().value().getId());
} else {
// todo if not exist(first time)
}
} else {
if (artifactDefinition.getEsId() == null) {
artifactDefinition.setEsId(artifactDefinition.getUniqueId());
artifactData.setId(artifactDefinition.getUniqueId());
}
}
NodeTypeEnum convertParentType = convertParentType(componentType);
// fetch the resource from storage
Either<Component, StorageOperationStatus> componentStorageOperationStatusEither =
toscaOperationFacade.getToscaElement(parentId);
if (componentStorageOperationStatusEither.isRight()) {
StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value();
log.debug("Failed to fetch resource information by resource id, error {}", errorStatus);
return Either.right(componentsUtils
.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
}
Component storedComponent = componentStorageOperationStatusEither.left().value();
Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils
.getInterfaceDefinitionFromComponentByInterfaceType(storedComponent, interfaceType);
if(!optionalInterface.isPresent()) {
log.debug("Failed to get resource interface for resource Id {}", parentId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceType));
}
//fetch the operation from storage
InterfaceDefinition gotInterface = optionalInterface.get();
Map<String, Operation> operationsMap = gotInterface.getOperationsMap();
Optional<Operation> optionalOperation = operationsMap.values()
.stream()
.filter(o -> o.getUniqueId().equals(operationUuid))
.findFirst();
if (!optionalOperation.isPresent()) {
log.debug("Failed to get resource interface operation for resource Id {} " +
" and operationId {}", parentId, operationUuid);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(
ActionStatus.INTERFACE_OPERATION_NOT_FOUND, parentId);
handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId,
currArtifactId, responseFormat, componentType, null);
return Either.right(responseFormat);
}
Operation operation = optionalOperation.get();
ArtifactDefinition implementationArtifact = operation.getImplementationArtifact();
implementationArtifact.setArtifactName(artifactInfo.getArtifactName());
implementationArtifact.setDescription(artifactInfo.getDescription());
implementationArtifact.setArtifactType(artifactInfo.getArtifactType());
implementationArtifact.setArtifactLabel(artifactInfo.getUniqueId());
implementationArtifact.setEsId(artifactInfo.getEsId());
operation.setImplementation(implementationArtifact);
gotInterface.setOperationsMap(operationsMap);
Either<List<InterfaceDefinition>, StorageOperationStatus> interfaceDefinitionStorageOperationStatusEither =
interfaceOperation.updateInterfaces(storedComponent.getUniqueId(), Collections.singletonList(gotInterface));
if (interfaceDefinitionStorageOperationStatusEither.isRight()){
StorageOperationStatus storageOperationStatus = interfaceDefinitionStorageOperationStatusEither.right().value();
ActionStatus actionStatus =
componentsUtils.convertFromStorageResponseForDataType(storageOperationStatus);
return Either.right(componentsUtils.getResponseFormat(actionStatus));
}
String uniqueId = implementationArtifact.getUniqueId();
artifactData.setId(uniqueId);
CassandraOperationStatus cassandraOperationStatus = artifactCassandraDao.saveArtifact(artifactData);
if(cassandraOperationStatus != CassandraOperationStatus.OK){
log.debug("Failed to persist operation {} artifact, error is {}",operation.getName(),cassandraOperationStatus);
StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(cassandraOperationStatus);
ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
}
return Either.left(Either.left(implementationArtifact));
}
private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) {
log.trace("Starting payload handling");
byte[] payload = artifactInfo.getPayloadData();
byte[] decodedPayload = null;
if (payload != null && payload.length != 0) {
// the generated artifacts were already decoded by the handler
decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
if (decodedPayload.length == 0) {
log.debug("Failed to decode the payload.");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
return Either.right(responseFormat);
}
String checkSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload);
artifactInfo.setArtifactChecksum(checkSum);
log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum);
// Specific payload validations of different types
Either<Boolean, ResponseFormat> isValidPayload = Either.left(true);
if (isDeploymentArtifact(artifactInfo)) {
log.trace("Starting deployment artifacts payload validation");
String artifactType = artifactInfo.getArtifactType();
if (ArtifactTypeEnum.HEAT.getType()
.equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType()
.equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET
.getType()
.equalsIgnoreCase(artifactType)
|| ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
isValidPayload = validateDeploymentHeatPayload(decodedPayload, artifactType);
if (isValidPayload.isLeft()) {
isValidPayload = extractHeatParameters(artifactInfo);
}
}
else if (ArtifactTypeEnum.YANG_XML.getType()
.equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VNF_CATALOG.getType()
.equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VF_LICENSE
.getType()
.equalsIgnoreCase(artifactType)
|| ArtifactTypeEnum.VENDOR_LICENSE.getType()
.equalsIgnoreCase(artifactType) || ArtifactTypeEnum.MODEL_INVENTORY_PROFILE
.getType()
.equalsIgnoreCase(artifactType)
|| ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()
.equalsIgnoreCase(artifactType) || ArtifactTypeEnum.UCPE_LAYER_2_CONFIGURATION
.getType()
.equalsIgnoreCase(artifactType)) {
isValidPayload = validateXmlPayload(decodedPayload, artifactType);
}
else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType()
.equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA
.getType()
.equalsIgnoreCase(artifactType)
|| ArtifactTypeEnum.VES_EVENTS.getType()
.equalsIgnoreCase(artifactType) || ArtifactTypeEnum.LIFECYCLE_OPERATIONS
.getType()
.equalsIgnoreCase(artifactType)) {
String artifactFileName = artifactInfo.getArtifactName();
String fileExtension = GeneralUtility.getFilenameExtension(artifactFileName).toLowerCase();
switch (fileExtension) {
case "xml":
isValidPayload = validateXmlPayload(decodedPayload, artifactType);
break;
case "json":
isValidPayload = validateJsonPayload(decodedPayload, artifactType);
break;
case "yml":
case "yaml":
isValidPayload = validateYmlPayload(decodedPayload, artifactType);
break;
default:
break;
}
}
}
if (isValidPayload.isRight()) {
ResponseFormat responseFormat = isValidPayload.right().value();
return Either.right(responseFormat);
}
} // null/empty payload is normal if called from metadata update ONLY.
// The validation of whether this is metadata/payload update case is
// currently done separately
else {
if (!isArtifactMetadataUpdate) {
log.debug("In artifact: {} Payload is missing.",artifactInfo.getArtifactName());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
return Either.right(responseFormat);
}
}
log.trace("Ended payload handling");
return Either.left(decodedPayload);
}
private Either<Boolean, ResponseFormat> validateDeploymentHeatPayload(byte[] decodedPayload, String artifactType) {
// Basic YAML validation
YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
log.debug("Invalid YAML format");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
return Either.right(responseFormat);
}
if (!ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
// HEAT specific YAML validation
DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(decodedPayload, DeploymentArtifactHeatConfiguration.class);
if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null) {
log.debug("HEAT doesn't contain required \"heat_template_version\" section.");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactType);
return Either.right(responseFormat);
}
}
return Either.left(true);
}
private Either<Boolean, ResponseFormat> validateYmlPayload(byte[] decodedPayload, String artifactType) {
Either<Boolean, ResponseFormat> res = Either.left(true);
YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
log.debug("Invalid YAML format");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
res = Either.right(responseFormat);
}
return res;
}
private Either<Boolean, ResponseFormat> validateXmlPayload(byte[] payload, String artifactType) {
boolean isXmlValid = isValidXml(payload);
if (!isXmlValid) {
ResponseFormat responseFormat = ResponseFormatManager.getInstance()
.getResponseFormat(ActionStatus.INVALID_XML, artifactType);
log.debug("Invalid XML content");
return Either.right(responseFormat);
}
return Either.left(true);
}
private Either<Boolean, ResponseFormat> validateJsonPayload(byte[] payload, String type) {
boolean isJsonValid = isValidJson(payload);
if (!isJsonValid) {
ResponseFormat responseFormat = ResponseFormatManager.getInstance()
.getResponseFormat(ActionStatus.INVALID_JSON, type);
log.debug("Invalid JSON content");
return Either.right(responseFormat);
}
return Either.left(true);
}
public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String userUserId, String artifactId,
boolean inTransaction) {
User user = new User();
user.setUserId(userUserId);
Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata);
if (parent.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent
.right()
.value()));
return Either.right(responseFormat);
}
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent
.left()
.value(),
false, inTransaction);
if (handleDelete.isRight()) {
return Either.right(handleDelete.right().value());
}
Either<ArtifactDefinition, Operation> result = handleDelete.left().value();
return Either.left(result.right().value());
}
private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) {
Operation op = new Operation();
long time = System.currentTimeMillis();
op.setCreationDate(time);
String artifactName = artifactInfo.getArtifactName();
artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
op.setImplementation(artifactInfo);
op.setLastUpdateDate(time);
return op;
}
private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) {
String newArtifactName = operationName + "_" + artifactName;
log.trace("converting artifact name {} to {}", artifactName, newArtifactName);
return newArtifactName;
}
// download by MSO
public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) {
// General validation
if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) {
log.debug(NULL_PARAMETER);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
// Normalizing artifact name
artifactName = ValidationUtils.normalizeFileName(artifactName);
// Resource validation
Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion);
if (validateResourceNameAndVersion.isRight()) {
return Either.right(validateResourceNameAndVersion.right().value());
}
Resource resource = validateResourceNameAndVersion.left().value();
String resourceId = resource.getUniqueId();
// Service validation
Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
if (validateServiceNameAndVersion.isRight()) {
return Either.right(validateServiceNameAndVersion.right().value());
}
Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
if (artifacts == null || artifacts.isEmpty()) {
log.debug("Deployment artifacts of resource {} are not found", resourceId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
}
ArtifactDefinition deploymentArtifact = null;
for (ArtifactDefinition artifactDefinition : artifacts.values()) {
if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName()
.equals(artifactName)) {
log.debug(FOUND_DEPLOYMENT_ARTIFACT, artifactName);
deploymentArtifact = artifactDefinition;
break;
}
}
if (deploymentArtifact == null) {
log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
}
// Downloading the artifact
Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact);
if (downloadArtifactEither.isRight()) {
log.debug(FAILED_DOWNLOAD_ARTIFACT, artifactName);
return Either.right(downloadArtifactEither.right().value());
}
log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
return Either.left(downloadArtifactEither.left().value().getRight());
}
// download by MSO
public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) {
// General validation
if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) {
log.debug(NULL_PARAMETER);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
// Normalizing artifact name
artifactName = ValidationUtils.normalizeFileName(artifactName);
// Service validation
Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
if (validateServiceNameAndVersion.isRight()) {
return Either.right(validateServiceNameAndVersion.right().value());
}
Service service = validateServiceNameAndVersion.left().value();
// ResourceInstance validation
Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName);
if (validateResourceInstance.isRight()) {
return Either.right(validateResourceInstance.right().value());
}
ComponentInstance resourceInstance = validateResourceInstance.left().value();
Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
final String finalArtifactName = artifactName;
Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
boolean hasDeploymentArtifacts = artifacts != null && artifacts.values()
.stream()
.anyMatch(filterArtifactByName);
ArtifactDefinition deployableArtifact;
if (!hasDeploymentArtifacts) {
log.debug("Deployment artifact with name {} not found", artifactName);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
}
log.debug(FOUND_DEPLOYMENT_ARTIFACT, artifactName);
deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get();
// Downloading the artifact
Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact);
if (downloadArtifactEither.isRight()) {
log.debug(FAILED_DOWNLOAD_ARTIFACT, artifactName);
return Either.right(downloadArtifactEither.right().value());
}
log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
return Either.left(downloadArtifactEither.left().value().getRight());
}
private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) {
List<ComponentInstance> riList = service.getComponentInstances();
for (ComponentInstance ri : riList) {
if (ri.getNormalizedName().equals(resourceInstanceName)) {
return Either.left(ri);
}
}
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName));
}
private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) {
Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
if (serviceListBySystemName.isRight()) {
log.debug("Couldn't fetch any service with name {}", serviceName);
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName
.right()
.value(), ComponentTypeEnum.SERVICE), serviceName));
}
List<Service> serviceList = serviceListBySystemName.left().value();
if (serviceList == null || serviceList.isEmpty()) {
log.debug("Couldn't fetch any service with name {}", serviceName);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName));
}
Service foundService = null;
for (Service service : serviceList) {
if (service.getVersion().equals(serviceVersion)) {
log.trace("Found service with version {}", serviceVersion);
foundService = service;
break;
}
}
if (foundService == null) {
log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE
.getValue(), serviceVersion));
}
return Either.left(foundService);
}
private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
if (resourceListBySystemName.isRight()) {
log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName
.right()
.value()), resourceName));
}
return Either.left(resourceListBySystemName.left().value());
}
public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
// Validation
log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName);
if (serviceName == null || serviceVersion == null || artifactName == null) {
log.debug(NULL_PARAMETER);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
// Normalizing artifact name
final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
// Service validation
Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
if (validateServiceNameAndVersion.isRight()) {
return Either.right(validateServiceNameAndVersion.right().value());
}
String serviceId = validateServiceNameAndVersion.left().value().getUniqueId();
// Looking for deployment or tosca artifacts
Service service = validateServiceNameAndVersion.left().value();
if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) {
log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
}
Optional<ArtifactDefinition> foundArtifactOptl = null;
if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
// filters artifact by name
.filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
}
if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) {
foundArtifactOptl = service.getToscaArtifacts().values().stream()
// filters TOSCA artifact by name
.filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
}
if (!foundArtifactOptl.isPresent()) {
log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
}
log.debug(FOUND_DEPLOYMENT_ARTIFACT, normalizedArtifactName);
// Downloading the artifact
Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl
.get());
if (downloadArtifactEither.isRight()) {
log.debug(FAILED_DOWNLOAD_ARTIFACT, normalizedArtifactName);
return Either.right(downloadArtifactEither.right().value());
}
log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
return Either.left(downloadArtifactEither.left().value().getRight());
}
public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) {
log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId);
if (artifactById.isRight()) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus);
return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, ""));
}
ArtifactDefinition artifactDefinition = artifactById.left().value();
if (artifactDefinition == null) {
log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
}
return downloadArtifact(artifactDefinition);
}
private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) {
boolean found = false;
Map<String, ArtifactDefinition> artifactsS = component.getArtifacts();
if (artifactsS != null) {
for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) {
if (entry.getValue().getUniqueId().equals(artifactId)) {
found = true;
break;
}
}
}
Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts();
if (!found && deploymentArtifactsS != null) {
for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) {
if (entry.getValue().getUniqueId().equals(artifactId)) {
found = true;
break;
}
}
}
Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts();
if (!found && toscaArtifactsS != null) {
for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) {
if (entry.getValue().getUniqueId().equals(artifactId)) {
found = true;
break;
}
}
}
Map<String, InterfaceDefinition> interfaces = component.getInterfaces();
if (!found && interfaces != null) {
for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
Map<String, Operation> operations = entry.getValue().getOperationsMap();
for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
if (entryOp.getValue().getImplementation() != null && entryOp.getValue()
.getImplementation()
.getUniqueId()
.equals(artifactId)) {
found = true;
break;
}
}
}
}
switch (component.getComponentType()) {
case RESOURCE:
break;
case SERVICE:
Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts();
if (!found && apiArtifacts != null) {
for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) {
if (entry.getValue().getUniqueId().equals(artifactId)) {
found = true;
break;
}
}
}
break;
default:
}
return found;
}
private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
boolean found = false;
List<ComponentInstance> resourceInstances = component.getComponentInstances();
ComponentInstance resourceInstance = null;
for (ComponentInstance ri : resourceInstances) {
if (ri.getUniqueId().equals(resourceInstanceId)) {
resourceInstance = ri;
break;
}
}
if (resourceInstance != null) {
Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
if (artifacts != null) {
for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
if (entry.getValue().getUniqueId().equals(artifactId)) {
found = true;
break;
}
}
}
if (!found) {
artifacts = resourceInstance.getArtifacts();
if (artifacts != null) {
for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
if (entry.getValue().getUniqueId().equals(artifactId)) {
found = true;
break;
}
}
}
}
}
return found;
}
private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
String containerComponentType) {
ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
componentForAudit.getNodeType();
Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade
.getToscaFullElement(componentId);
if (componentResult.isRight()) {
ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
log.debug("Service not found, serviceId {}", componentId);
handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
return Either.right(responseFormat);
}
return Either.left(componentResult.left().value());
}
private Either<Boolean, ResponseFormat> validateWorkOnComponent(Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation) {
if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD && !operation.ignoreLifecycleState()) {
Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
if (canWork.isRight()) {
String uniqueId = component.getUniqueId();
log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId);
handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right()
.value(), component
.getComponentType(), null);
return Either.right(canWork.right().value());
}
}
return Either.left(true);
}
private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD) {
String role = user.getRole();
if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role);
handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
return Either.right(responseFormat);
}
}
return Either.left(true);
}
private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
User user;
try{
user = validateUserExists(userId, auditingAction.getName(), inTransaction);
} catch(ComponentException e){
user = new User();
user.setUserId(userId);
ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat() :
componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
throw e;
}
return Either.left(user);
}
protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
AuditingActionEnum auditingAction = null;
switch (operation.getArtifactOperationEnum()) {
case CREATE:
auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
break;
case UPDATE:
auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
break;
case DELETE:
auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
break;
case DOWNLOAD:
auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD;
break;
default:
break;
}
return auditingAction;
}
private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition) {
String esArtifactId = artifactDefinition.getEsId();
Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
if (artifactfromES.isRight()) {
CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
log.debug("Error when getting artifact from ES, error: {}", actionStatus);
ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition
.getArtifactDisplayName());
return Either.right(responseFormat);
}
ESArtifactData esArtifactData = artifactfromES.left().value();
byte[] data = esArtifactData.getDataAsArray();
if (data == null) {
log.debug("Artifact data from ES is null");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName()));
}
String artifactName = artifactDefinition.getArtifactName();
log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName);
return Either.left(new ImmutablePair<String, byte[]>(artifactName, data));
}
public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) {
return new ESArtifactData(artifactInfo.getEsId(), artifactPayload);
}
private boolean saveArtifacts(ESArtifactData artifactData, String resourceId) {
CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) {
log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId);
}
else {
log.info("Failed to save artifact {}.", artifactData.getId());
return false;
}
return true;
}
private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) {
return auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE);
}
private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) {
return ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType());
}
public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction);
if (user.isRight()) {
ResponseFormat responseFormat;
if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
log.debug("create artifact placeholder - not authorized user, userId {}", userUserId);
responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
}
else {
log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId);
responseFormat = componentsUtils.getResponseFormat(user.right().value());
}
return Either.right(responseFormat);
}
ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user
.left()
.value(), groupType);
return Either.left(artifactDefinition);
}
public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) {
ArtifactDefinition artifactInfo = new ArtifactDefinition();
String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
artifactInfo.setArtifactDisplayName(artifactName);
artifactInfo.setArtifactLabel(logicalName.toLowerCase());
artifactInfo.setArtifactType(artifactType);
artifactInfo.setDescription(artifactDescription);
artifactInfo.setArtifactGroupType(groupType);
nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
return artifactInfo;
}
private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
String uniqueId = null;
if (resourceId != null) {
uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel()
.toLowerCase());
artifactInfo.setUniqueId(uniqueId);
}
artifactInfo.setUserIdCreator(user.getUserId());
String fullName = user.getFullName();
artifactInfo.setUpdaterFullName(fullName);
long time = System.currentTimeMillis();
artifactInfo.setCreatorFullName(fullName);
artifactInfo.setCreationDate(time);
artifactInfo.setLastUpdateDate(time);
artifactInfo.setUserIdLastUpdater(user.getUserId());
artifactInfo.setMandatory(true);
}
public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, ArtifactGroupTypeEnum groupType, String instanceId) {
return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
}
public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) {
return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId);
}
private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
byte[] payload = payloadStr.getBytes();
ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
return Either.left(artifactData);
}
/**
* @param artifactDefinition
* @return
*/
public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
String instanceId, boolean shouldLock, boolean inTransaction) {
String payload = generateHeatEnvPayload(artifactDefinition);
String prevUUID = artifactDefinition.getArtifactUUID();
ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
.left()
.bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
}
public Either<ArtifactDefinition, ResponseFormat> forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
boolean shouldLock, boolean inTransaction, String instanceId) {
String payload = generateHeatEnvPayload(artifactDefinition);
String prevUUID = artifactDefinition.getArtifactUUID();
ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
return forceGenerateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
.left()
.bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
}
private Either<ArtifactDefinition, ResponseFormat> updateArtifactOnGroupInstance(ComponentTypeEnum componentType, Component component, String instanceId, String prevUUID, ArtifactDefinition clonedBeforeGenerate, ArtifactDefinition updatedArtDef) {
if (prevUUID == null || !prevUUID.equals(updatedArtDef.getArtifactUUID())) {
List<ComponentInstance> componentInstances = component.getComponentInstances();
if (componentInstances != null) {
Optional<ComponentInstance> findFirst = componentInstances.stream()
.filter(ci -> ci.getUniqueId()
.equals(instanceId))
.findFirst();
if (findFirst.isPresent()) {
ComponentInstance relevantInst = findFirst.get();
List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst
.getGroupInstances());
if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
updatedGroupInstances.forEach(gi -> {
gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId());
gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID());
});
Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, instanceId, updatedGroupInstances);
if (status.isRight()) {
log.debug(FAILED_UPDATE_GROUPS, component.getUniqueId());
ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils
.convertFromStorageResponse(status.right()
.value()), clonedBeforeGenerate.getArtifactDisplayName());
return Either.right(responseFormat);
}
}
}
}
}
return Either.left(updatedArtDef);
}
private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
StringBuilder sb = new StringBuilder();
sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
sb.append("parameters:\n");
if (heatParameters != null) {
heatParameters.sort(Comparator.comparing(e -> e.getName()));
List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
String heatValue = heatParameterDefinition.getCurrentValue();
if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
heatValue = heatParameterDefinition.getDefaultValue();
if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
empltyHeatValues.add(heatParameterDefinition);
continue;
}
}
HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
if (type != null) {
switch (type) {
case BOOLEAN:
sb.append(" ")
.append(heatParameterDefinition.getName())
.append(":")
.append(" ")
.append(Boolean.parseBoolean(heatValue))
.append("\n");
break;
case NUMBER:
sb.append(" ")
.append(heatParameterDefinition.getName())
.append(":")
.append(" ")
.append(new BigDecimal(heatValue).toPlainString())
.append("\n");
break;
case COMMA_DELIMITED_LIST:
case JSON:
sb.append(" ")
.append(heatParameterDefinition.getName())
.append(":")
.append(" ")
.append(heatValue)
.append("\n");
break;
default:
String value = heatValue;
boolean starts = value.startsWith("\"");
boolean ends = value.endsWith("\"");
if (!(starts && ends)) {
starts = value.startsWith("'");
ends = value.endsWith("'");
if (!(starts && ends)) {
value = "\"" + value + "\"";
}
}
sb.append(" ")
.append(heatParameterDefinition.getName())
.append(":")
.append(" ")
.append(value);
sb.append("\n");
break;
}
}
}
if (!empltyHeatValues.isEmpty()) {
empltyHeatValues.sort(Comparator.comparing(e -> e.getName()));
empltyHeatValues.forEach(hv -> {
sb.append(" ").append(hv.getName()).append(":");
HeatParameterType type = HeatParameterType.isValidType(hv.getType());
if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv
.getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
sb.append(" \"\"").append("\n");
}
else {
sb.append(" ").append("\n");
}
});
}
}
sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
// DE265919 fix
return sb.toString().replaceAll("\\\\n", "\n");
}
/**
* @param artifactDefinition
* @param payload
* @return
*/
public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, () -> artifactDefinition
.getHeatParamsUpdateDate(),
() -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
}
public Either<ArtifactDefinition, ResponseFormat> forceGenerateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, System::currentTimeMillis,
() -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
}
protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
boolean shouldLock, boolean inTransaction, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition
.getEsId());
if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition
.getPayloadUpdateDate() <= payloadUpdateDateGen.get()) {
log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
ESArtifactData artifactData = null;
if (artifactDataRes.isLeft()) {
artifactData = artifactDataRes.left().value();
}
else {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
return Either.right(artifactDataRes.right().value());
}
String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(artifactData.getDataAsArray());
String oldCheckSum;
String esArtifactId = artifactDefinition.getEsId();
Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
ESArtifactData esArtifactData;
if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
log.debug("Try to fetch artifact from cassandra with id : {}", esArtifactId);
artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
if (artifactfromES.isRight()) {
CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
log.debug("Error when getting artifact from ES, error: {} esid : {}", actionStatus, esArtifactId);
return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
}
esArtifactData = artifactfromES.left().value();
oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(esArtifactData.getDataAsArray());
}
else {
oldCheckSum = artifactDefinition.getArtifactChecksum();
}
Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
if (shouldLock) {
Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
if (lockComponent.isRight()) {
handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition
.getUniqueId(), lockComponent.right().value(), component.getComponentType(), null);
return Either.right(lockComponent.right().value());
}
}
try {
if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component
.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
.getArtifactType(), artifactDefinition.getEsId());
if (updateArifactDefinitionStatus.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
.right()
.value()), artifactDefinition.getArtifactDisplayName());
log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
return Either.right(responseFormat);
}
}
else {
oldCheckSum = artifactDefinition.getArtifactChecksum();
artifactDefinition.setArtifactChecksum(newCheckSum);
artifactDefinition.setEsId(artifactDefinition.getUniqueId());
log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
.getArtifactType(), artifactDefinition.getEsId());
updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component
.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
log.trace("Update Payload ", artifactDefinition.getEsId());
}
if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
artifactDefinition = updateArifactDefinitionStatus.left().value();
artifactData.setId(artifactDefinition.getUniqueId());
CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
if (!inTransaction) {
titanDao.commit();
}
log.debug("Artifact Saved In ES {}", artifactData.getId());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
}
else {
if (!inTransaction) {
titanDao.rollback();
}
log.info("Failed to save artifact {}.", artifactData.getId());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
return Either.right(responseFormat);
}
}
else {
ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
.right()
.value()), artifactDefinition.getArtifactDisplayName());
log.debug("Failed To update artifact {}", artifactData.getId());
handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
return Either.right(responseFormat);
}
}
finally {
if (shouldLock) {
graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType()
.getNodeType());
}
}
}
return Either.left(artifactDefinition);
}
public Map<String, Object> buildJsonForUpdateArtifact(ArtifactDefinition artifactDef, ArtifactGroupTypeEnum artifactGroupType, List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
return this.buildJsonForUpdateArtifact(artifactDef.getUniqueId(), artifactDef.getArtifactName(), artifactDef.getArtifactType(), artifactGroupType, artifactDef
.getArtifactLabel(), artifactDef.getArtifactDisplayName(),
artifactDef.getDescription(), artifactDef.getPayloadData(), updatedRequiredArtifacts, artifactDef.getListHeatParameters());
}
public Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContent,
List<ArtifactTemplateInfo> updatedRequiredArtifacts, List<HeatParameterDefinition> heatParameters) {
Map<String, Object> json = new HashMap<>();
if (artifactId != null && !artifactId.isEmpty()) {
json.put(Constants.ARTIFACT_ID, artifactId);
}
json.put(Constants.ARTIFACT_NAME, artifactName);
json.put(Constants.ARTIFACT_TYPE, artifactType);
json.put(Constants.ARTIFACT_DESCRIPTION, description);
if (artifactContent != null) {
log.debug("payload is encoded. perform decode");
String encodedPayload = Base64.encodeBase64String(artifactContent);
json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
}
json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
json.put(Constants.ARTIFACT_LABEL, label);
json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
: updatedRequiredArtifacts.stream()
.filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e
.getType()
.equals(ArtifactTypeEnum.HEAT_NESTED.getType()))
.map(e -> e.getFileName())
.collect(Collectors.toList()));
json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>()
: heatParameters);
return json;
}
public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateResourceInstanceArtifactNoContent(String resourceId, Component containerComponent, User user, Map<String, Object> json, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo) {
String jsonStr = gson.toJson(json);
ArtifactDefinition artifactDefinitionFromJson = artifactInfo == null ? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class) : artifactInfo;
String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactUniqueId,
artifactDefinitionFromJson, null, jsonStr, null, null, user, containerComponent, false, false, true);
if (uploadArtifactToService.isRight()) {
return Either.right(uploadArtifactToService.right().value());
}
return Either.left(uploadArtifactToService.left().value());
}
private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
convertParentType(componentType);
String parentId = parent.getUniqueId();
ArtifactDefinition currArtifact = artifactInfo;
if (origMd5 != null) {
Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
if (validateMd5.isRight()) {
ResponseFormat responseFormat = validateMd5.right().value();
handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
return Either.right(responseFormat);
}
if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance);
if (deploymentValidationResult.isRight()) {
ResponseFormat responseFormat = deploymentValidationResult.right().value();
handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
return Either.right(responseFormat);
}
Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
if (payloadEither.isRight()) {
ResponseFormat responseFormat = payloadEither.right().value();
handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
return Either.right(responseFormat);
}
}
else { // duplicate
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
return Either.right(responseFormat);
}
}
// lock resource
if (shouldLock) {
Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK);
if (lockComponent.isRight()) {
handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
.value(), componentType, null);
return Either.right(lockComponent.right().value());
}
}
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
try {
resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, origMd5);
return resultOp;
}
finally {
// unlock resource
if (resultOp == null || resultOp.isRight()) {
log.debug(ROLLBACK);
if (!inTransaction) {
titanDao.rollback();
}
}
else {
log.debug(COMMIT);
if (!inTransaction) {
titanDao.commit();
}
}
if (shouldLock) {
componentType = parent.getComponentType();
}
NodeTypeEnum nodeType = componentType.getNodeType();
graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
}
}
private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
ComponentTypeEnum componentType, String origMd5) {
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
Either<ArtifactDefinition, Operation> insideEither = null;
Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
if (getRI.isRight()) {
return Either.right(getRI.right().value());
}
ComponentInstance ri = getRI.left().value();
Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
if (getArtifactRes.isRight()) {
return Either.right(getArtifactRes.right().value());
}
ArtifactDefinition currArtifact = getArtifactRes.left().value();
if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType()
.equals(ArtifactTypeEnum.HEAT_VOL
.getType()) || currArtifact
.getArtifactType()
.equals(ArtifactTypeEnum.HEAT_NET.getType())) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
.getName());
return Either.right(responseFormat);
}
List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
new ArrayList<HeatParameterDefinition>();
// upload
if (origMd5 != null) {
Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri
.getName(), currentHeatEnvParams,
updatedHeatEnvParams, currArtifact.getArtifactName());
if (uploadParamsValidationResult.isRight()) {
ResponseFormat responseFormat = uploadParamsValidationResult.right().value();
handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
.getName());
return Either.right(responseFormat);
}
artifactInfo.setListHeatParameters(updatedHeatEnvParams);
}
Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV
.getType());
if (validateAndConvertHeatParamers.isRight()) {
ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
.getName());
return Either.right(responseFormat);
}
if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
// fill reduced heat env parameters List for updating
replaceCurrHeatValueWithUpdatedValue(currentHeatEnvParams, updatedHeatEnvParams);
currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
currArtifact.setListHeatParameters(currentHeatEnvParams);
Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArtifactOnResource(currArtifact, parent
.getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
if (updateArifactRes.isRight()) {
log.debug("Failed to update artifact on graph - {}", artifactId);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes
.right()
.value()));
handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
.getName());
return Either.right(responseFormat);
}
StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
if (error != StorageOperationStatus.OK) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
.getName());
return Either.right(responseFormat);
}
error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left()
.value()
.getUniqueId(), parent.getUniqueId());
if (error != StorageOperationStatus.OK) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
.getName());
return Either.right(responseFormat);
}
}
insideEither = Either.left(currArtifact);
resultOp = Either.left(insideEither);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri
.getName());
return resultOp;
}
private void replaceCurrHeatValueWithUpdatedValue(List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams) {
for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
String paramName = heatEnvParam.getName();
for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
String updatedParamValue = heatEnvParam.getCurrentValue();
currHeatParam.setCurrentValue(updatedParamValue);
}
}
}
}
private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, boolean needToUpdateGroup) {
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
Either<ArtifactDefinition, Operation> insideEither = null;
String currentHeatId = currHeatArtifact.getUniqueId();
String esArtifactId = currHeatArtifact.getEsId();
Either<ESArtifactData, CassandraOperationStatus> artifactFromES = artifactCassandraDao.getArtifact(esArtifactId);
if (artifactFromES.isRight()) {
CassandraOperationStatus resourceUploadStatus = artifactFromES.right().value();
StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
log.debug("Error when getting artifact from ES, error: {}", actionStatus);
return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName()));
}
ESArtifactData esArtifactData = artifactFromES.left().value();
ArtifactDefinition updatedHeatArt = currHeatArtifact;
List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams
.isEmpty()) {
String paramName;
for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
paramName = heatEnvParam.getName();
for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
String updatedParamValue = heatEnvParam.getCurrentValue();
if (updatedParamValue == null) {
updatedParamValue = heatEnvParam.getDefaultValue();
}
HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
if (!paramType.getValidator().isValid(updatedParamValue, null)) {
ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV
.getType(), paramType.getType(), paramName);
handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, "");
return Either.right(responseFormat);
}
currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
newHeatEnvParams.add(currHeatParam);
break;
}
}
}
if (!newHeatEnvParams.isEmpty()) {
currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArtifactOnResource(currHeatArtifact, parent
.getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId);
if (operationStatus.isRight()) {
log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus
.right()
.value()));
return Either.right(responseFormat);
}
updatedHeatArt = operationStatus.left().value();
boolean res = true;
if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null) {
esArtifactData.setId(updatedHeatArt.getEsId());
}
res = saveArtifacts(esArtifactData, parent.getUniqueId());
if (res) {
log.debug(ARTIFACT_SAVED, updatedHeatArt.getUniqueId());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
.getUniqueId(), responseFormat, componentType, null);
}
else {
BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT);
log.debug(FAILED_SAVE_ARTIFACT);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
.getUniqueId(), responseFormat, componentType, null);
resultOp = Either.right(responseFormat);
}
insideEither = Either.left(updatedHeatArt);
}
}
Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact;
if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
artifactEnvInfo.setArtifactChecksum(null);
updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt
.getUniqueId(), componentType.getNodeType(), componentId);
}
else {
updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType
.getNodeType());
}
if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) {
ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact
.left()
.value(), parent, componentType);
if (result != ActionStatus.OK) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(result);
return Either.right(responseFormat);
}
}
if (updatedHeatEnvParams.isEmpty()) {
return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, user, currHeatArtifact, artifactId, componentType);
}
resultOp = Either.left(insideEither);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
return resultOp;
}
private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, currHeatArtifact.getArtifactName());
handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
return Either.right(responseFormat);
}
private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
StorageOperationStatus error = StorageOperationStatus.OK;
log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
List<GroupInstance> groupsInstances = ri.getGroupInstances();
List<String> groupInstancesId = null;
if (groupsInstances != null && !groupsInstances.isEmpty()) {
groupInstancesId = groupsInstances.stream()
.filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts()
.contains(artifactId))
.map(GroupInstanceDataDefinition::getUniqueId)
.collect(Collectors.toList());
}
if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
}
return error;
}
public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
.getArtifactName(), currArtifactName);
handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
return Either.right(responseFormat);
}
for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
String paramName = uploadedHeatParam.getName();
boolean isExistsInHeat = false;
for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
isExistsInHeat = true;
uploadedHeatParam.setType(currHeatParam.getType());
uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
break;
}
}
if (!isExistsInHeat) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
return Either.right(responseFormat);
}
}
return Either.left(updatedHeatEnvParams);
}
private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
ResponseFormat responseFormat = null;
List<ComponentInstance> ris = component.getComponentInstances();
for (ComponentInstance ri : ris) {
if (riID.equals(ri.getUniqueId())) {
return Either.left(ri);
}
}
responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
log.debug("Resource Instance not found, resourceInstanceId {}", riID);
handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
return Either.right(responseFormat);
}
private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
ResponseFormat responseFormat = null;
Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
for (ArtifactDefinition artifact : rtifactsMap.values()) {
if (artifactId.equals(artifact.getUniqueId())) {
return Either.left(artifact);
}
}
responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri
.getName());
return Either.right(responseFormat);
}
public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
ArtifactDefinition ret;
if (eitherArtifact.isLeft()) {
ret = eitherArtifact.left().value();
}
else {
ret = eitherArtifact.right().value().getImplementationArtifact();
}
return ret;
}
/**
* downloads artifact of component by UUIDs
*
* @param componentType
* @param componentUuid
* @param artifactUUID
* @param resourceCommonInfo
* @return
*/
public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<byte[], ResponseFormat> result;
byte[] downloadedArtifact = null;
Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
if (errorWrapper.isEmpty() && component != null) {
resourceCommonInfo.setResourceName(component.getName());
downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName());
}
if (errorWrapper.isEmpty()) {
result = Either.left(downloadedArtifact);
}
else {
result = Either.right(errorWrapper.getInnerElement());
}
return result;
}
/**
* downloads an artifact of resource instance of component by UUIDs
*
* @param componentType
* @param componentUuid
* @param resourceInstanceName
* @param artifactUUID
* @return
*/
public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<byte[], ResponseFormat> result;
byte[] downloadedArtifact = null;
ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
if (errorWrapper.isEmpty()) {
downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance
.getName());
}
if (errorWrapper.isEmpty()) {
result = Either.left(downloadedArtifact);
}
else {
result = Either.right(errorWrapper.getInnerElement());
}
return result;
}
/**
* uploads an artifact to a component by UUID
*
* @param data
* @param request
* @param componentType
* @param componentUuid
* @param resourceCommonInfo
* @param operation
* @return
*/
public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
Component component = null;
String componentId = null;
ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
String origMd5 = request.getHeader(Constants.MD5_HEADER);
String userId = request.getHeader(Constants.USER_ID_HEADER);
Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
if (getComponentRes.isRight()) {
StorageOperationStatus status = getComponentRes.right().value();
log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
}
if (errorWrapper.isEmpty()) {
componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
if (!getComponentRes.left()
.value()
.getMetadataDataDefinition()
.getState()
.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
if (component != null) {
componentId = component.getUniqueId();
componentName = component.getName();
}
}
resourceCommonInfo.setResourceName(componentName);
}
if (errorWrapper.isEmpty()) {
actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
if (actionResult.isRight()) {
log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
.right()
.value());
return Either.right(actionResult.right().value());
}
return Either.left(actionResult.left().value().left().value());
}
return Either.right(errorWrapper.getInnerElement());
}
/**
* upload an artifact to a resource instance by UUID
*
* @param data
* @param request
* @param componentType
* @param componentUuid
* @param resourceInstanceName
* @param operation
* @return
*/
public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
ArtifactOperationInfo operation) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
ArtifactDefinition uploadArtifact = null;
Component component = null;
String componentInstanceId;
String componentId;
String origMd5 = request.getHeader(Constants.MD5_HEADER);
String userId = request.getHeader(Constants.USER_ID_HEADER);
ImmutablePair<Component, ComponentInstance> componentRiPair = null;
Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
if (getComponentRes.isRight()) {
StorageOperationStatus status = getComponentRes.right().value();
log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName));
}
if (errorWrapper.isEmpty() && !getComponentRes.left()
.value()
.getMetadataDataDefinition()
.getState()
.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
component = checkoutParentComponent(componentType, getComponentRes.left()
.value()
.getMetadataDataDefinition()
.getUniqueId(), userId, errorWrapper);
}
if (errorWrapper.isEmpty()) {
if (component == null) {
componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
}
else {
componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
}
}
if (errorWrapper.isEmpty()) {
componentInstanceId = componentRiPair.getRight().getUniqueId();
componentId = componentRiPair.getLeft().getUniqueId();
ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
.findParamByType(componentType));
if (actionResult.isRight()) {
log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult
.right()
.value());
errorWrapper.setInnerElement(actionResult.right().value());
}
}
if (errorWrapper.isEmpty()) {
uploadArtifact = actionResult.left().value().left().value();
uploadArtifactResult = Either.left(uploadArtifact);
}
else {
uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
}
return uploadArtifactResult;
}
/**
* updates an artifact on a component by UUID
*
* @param data
* @param request
* @param componentType
* @param componentUuid
* @param artifactUUID
* @param operation
* @return
*/
public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
ResourceCommonInfo resourceCommonInfo, ArtifactOperationInfo operation) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
ArtifactDefinition updateArtifact = null;
Component component = null;
String componentId = null;
String artifactId = null;
ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
String origMd5 = request.getHeader(Constants.MD5_HEADER);
String userId = request.getHeader(Constants.USER_ID_HEADER);
Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
if (getComponentRes.isRight()) {
StorageOperationStatus status = getComponentRes.right().value();
log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
}
if (errorWrapper.isEmpty()) {
componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
if (!getComponentRes.left()
.value()
.getMetadataDataDefinition()
.getState()
.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
if (component != null) {
componentId = component.getUniqueId();
componentName = component.getName();
}
}
resourceCommonInfo.setResourceName(componentName);
}
if (errorWrapper.isEmpty()) {
artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
}
if (errorWrapper.isEmpty()) {
actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
if (actionResult.isRight()) {
log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
.right()
.value());
errorWrapper.setInnerElement(actionResult.right().value());
}
}
if (errorWrapper.isEmpty()) {
updateArtifact = actionResult.left().value().left().value();
updateArtifactResult = Either.left(updateArtifact);
}
else {
updateArtifactResult = Either.right(errorWrapper.getInnerElement());
}
return updateArtifactResult;
}
/**
* updates an artifact on a resource instance by UUID
*
* @param data
* @param request
* @param componentType
* @param componentUuid
* @param resourceInstanceName
* @param artifactUUID
* @param operation TODO
* @return
*/
public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
ArtifactOperationInfo operation) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
ArtifactDefinition updateArtifact = null;
Component component = null;
String componentInstanceId = null;
String componentId = null;
String artifactId = null;
String origMd5 = request.getHeader(Constants.MD5_HEADER);
String userId = request.getHeader(Constants.USER_ID_HEADER);
ImmutablePair<Component, ComponentInstance> componentRiPair = null;
Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
if (getComponentRes.isRight()) {
StorageOperationStatus status = getComponentRes.right().value();
log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
}
if (errorWrapper.isEmpty() && !getComponentRes.left()
.value()
.getMetadataDataDefinition()
.getState()
.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
component = checkoutParentComponent(componentType, getComponentRes.left()
.value()
.getMetadataDataDefinition()
.getUniqueId(), userId, errorWrapper);
}
if (errorWrapper.isEmpty()) {
if (component == null) {
componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
}
else {
componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
}
}
if (errorWrapper.isEmpty()) {
componentInstanceId = componentRiPair.getRight().getUniqueId();
componentId = componentRiPair.getLeft().getUniqueId();
artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
}
if (errorWrapper.isEmpty()) {
ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
.findParamByType(componentType));
if (actionResult.isRight()) {
log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult
.right()
.value());
errorWrapper.setInnerElement(actionResult.right().value());
}
}
if (errorWrapper.isEmpty()) {
updateArtifact = actionResult.left().value().left().value();
updateArtifactResult = Either.left(updateArtifact);
}
else {
updateArtifactResult = Either.right(errorWrapper.getInnerElement());
}
return updateArtifactResult;
}
/**
* updates an artifact on a component by UUID
*
* @param data
* @param request
* @param componentType
* @param componentUuid
* @param artifactUUID
* @param operation
* @return
*/
public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnInterfaceOperationByResourceUUID(
String data, HttpServletRequest request, ComponentTypeEnum componentType,
String componentUuid, String interfaceUUID, String operationUUID, String artifactUUID,
ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
ArtifactDefinition updateArtifact = null;
String componentId = null;
ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
String origMd5 = request.getHeader(Constants.MD5_HEADER);
String userId = request.getHeader(Constants.USER_ID_HEADER);
Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
if (getComponentRes.isRight()) {
StorageOperationStatus status = getComponentRes.right().value();
log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
}
if (errorWrapper.isEmpty()) {
componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
if (!getComponentRes.left()
.value()
.getMetadataDataDefinition()
.getState()
.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
Component component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
if (component != null) {
componentId = component.getUniqueId();
componentName = component.getName();
}
}
resourceCommonInfo.setResourceName(componentName);
}
if (errorWrapper.isEmpty()) {
Either<String, ResponseFormat> interfaceName = fetchInterfaceName(componentId, interfaceUUID);
if (interfaceName.isRight()) {
errorWrapper.setInnerElement(interfaceName.right().value());
}
if (errorWrapper.isEmpty()) {
actionResult = handleArtifactRequest(componentId, userId, componentType, operation,
artifactUUID, artifactInfo, origMd5, data, interfaceName.left().value(),
operationUUID, null, null);
if (actionResult.isRight()) {
log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
.right()
.value());
errorWrapper.setInnerElement(actionResult.right().value());
}
}
}
if (errorWrapper.isEmpty()) {
updateArtifact = actionResult.left().value().left().value();
updateArtifactResult = Either.left(updateArtifact);
}
else {
updateArtifactResult = Either.right(errorWrapper.getInnerElement());
}
return updateArtifactResult;
}
private Either<String, ResponseFormat> fetchInterfaceName(String componentId, String interfaceUUID) {
Either<Component, StorageOperationStatus> componentStorageOperationStatusEither = toscaOperationFacade.getToscaElement(componentId);
if (componentStorageOperationStatusEither.isRight()) {
StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value();
log.debug("Failed to fetch component information by component id, error {}", errorStatus);
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
}
Component storedComponent = componentStorageOperationStatusEither.left().value();
Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils
.getInterfaceDefinitionFromComponentByInterfaceId(storedComponent, interfaceUUID);
if(!optionalInterface.isPresent()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceUUID));
}
return Either.left(optionalInterface.get().getType());
}
/**
* deletes an artifact on a component by UUID
*
* @param request
* @param componentType
* @param componentUuid
* @param artifactUUID
* @param resourceCommonInfo
* @param operation TODO
* @return
*/
public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo,
ArtifactOperationInfo operation) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
ArtifactDefinition deleteArtifact = null;
Component component = null;
String componentId = null;
String artifactId = null;
String origMd5 = request.getHeader(Constants.MD5_HEADER);
String userId = request.getHeader(Constants.USER_ID_HEADER);
Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
if (getComponentRes.isRight()) {
StorageOperationStatus status = getComponentRes.right().value();
log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
}
if (errorWrapper.isEmpty()) {
componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
if (!getComponentRes.left()
.value()
.getMetadataDataDefinition()
.getState()
.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
if (component != null) {
componentId = component.getUniqueId();
componentName = component.getName();
}
}
resourceCommonInfo.setResourceName(componentName);
}
if (errorWrapper.isEmpty()) {
artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
}
if (errorWrapper.isEmpty()) {
actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
if (actionResult.isRight()) {
log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
.right()
.value());
errorWrapper.setInnerElement(actionResult.right().value());
}
}
if (errorWrapper.isEmpty()) {
deleteArtifact = actionResult.left().value().left().value();
deleteArtifactResult = Either.left(deleteArtifact);
}
else {
deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
}
return deleteArtifactResult;
}
/**
* deletes an artifact from a resource instance by UUID
*
* @param request
* @param componentType
* @param componentUuid
* @param resourceInstanceName
* @param artifactUUID
* @param operation TODO
* @return
*/
public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
ArtifactOperationInfo operation) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
ArtifactDefinition deleteArtifact = null;
Component component = null;
String componentInstanceId = null;
String componentId = null;
String artifactId = null;
String origMd5 = request.getHeader(Constants.MD5_HEADER);
String userId = request.getHeader(Constants.USER_ID_HEADER);
ImmutablePair<Component, ComponentInstance> componentRiPair = null;
Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
if (getComponentRes.isRight()) {
StorageOperationStatus status = getComponentRes.right().value();
log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
}
if (errorWrapper.isEmpty() && !getComponentRes.left()
.value()
.getMetadataDataDefinition()
.getState()
.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
component = checkoutParentComponent(componentType, getComponentRes.left()
.value()
.getMetadataDataDefinition()
.getUniqueId(), userId, errorWrapper);
}
if (errorWrapper.isEmpty()) {
if (component == null) {
componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
}
else {
componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
}
}
if (errorWrapper.isEmpty()) {
componentInstanceId = componentRiPair.getRight().getUniqueId();
componentId = componentRiPair.getLeft().getUniqueId();
artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
}
if (errorWrapper.isEmpty()) {
actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum
.findParamByType(componentType));
if (actionResult.isRight()) {
log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult
.right()
.value());
errorWrapper.setInnerElement(actionResult.right().value());
}
}
if (errorWrapper.isEmpty()) {
deleteArtifact = actionResult.left().value().left().value();
deleteArtifactResult = Either.left(deleteArtifact);
}
else {
deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
}
return deleteArtifactResult;
}
private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) {
String artifactId = null;
ArtifactDefinition foundArtifact = null;
if (instance.getDeploymentArtifacts() != null) {
foundArtifact = instance.getDeploymentArtifacts()
.values()
.stream()
.filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
.equals(artifactUUID))
.findFirst()
.orElse(null);
}
if (foundArtifact == null && instance.getArtifacts() != null) {
foundArtifact = instance.getArtifacts()
.values()
.stream()
.filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
.equals(artifactUUID))
.findFirst()
.orElse(null);
}
if (foundArtifact == null) {
log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
}
else {
artifactId = foundArtifact.getUniqueId();
}
return artifactId;
}
@SuppressWarnings("unchecked")
public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition heatArtifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
Map<String, String> existingEnvVersions) {
Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
.getConfiguration()
.getDeploymentResourceInstanceArtifacts();
if (deploymentResourceArtifacts == null) {
log.debug("no deployment artifacts are configured for generated artifacts");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
if (placeHolderData == null) {
log.debug("no env type {} are configured for generated artifacts", envType);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
String envLabel = (heatArtifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user
.getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
if (createArtifactPlaceHolder.isRight()) {
return Either.right(createArtifactPlaceHolder.right().value());
}
ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
artifactHeatEnv.setGeneratedFromId(heatArtifact.getUniqueId());
artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
artifactHeatEnv.setTimeout(0);
buildHeatEnvFileName(heatArtifact, artifactHeatEnv, placeHolderData);
// rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
ArtifactDefinition heatEnvPlaceholder;
// Evg : for resource instance artifact will be added later as block with other env artifacts from BL
if (parentType != NodeTypeEnum.ResourceInstance) {
Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component
.getUniqueId(), parentType, parentId);
if (addHeatEnvArtifact.isRight()) {
log.debug("failed to create heat env artifact on resource instance");
return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact
.right()
.value(), false), "", null));
}
heatEnvPlaceholder = createArtifactPlaceHolder.left().value();
}
else {
heatEnvPlaceholder = artifactHeatEnv;
artifactToscaOperation.generateUUID(heatEnvPlaceholder, heatEnvPlaceholder.getArtifactVersion());
setHeatCurrentValuesOnHeatEnvDefaultValues(heatArtifact, heatEnvPlaceholder);
}
ComponentTypeEnum componentType = component.getComponentType();
if (parentType == NodeTypeEnum.ResourceInstance) {
componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
}
componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.ARTIFACT_UPLOAD,
new ResourceCommonInfo(parentName, componentType.getValue()),
ResourceVersionInfo.newBuilder().build(),
ResourceVersionInfo.newBuilder().artifactUuid(heatEnvPlaceholder.getUniqueId()).build(),
null, heatEnvPlaceholder, null);
return Either.left(heatEnvPlaceholder);
}
private void setHeatCurrentValuesOnHeatEnvDefaultValues(ArtifactDefinition artifact, ArtifactDefinition artifactDefinition) {
if (artifact.getListHeatParameters() == null) {
return;
}
List<HeatParameterDefinition> heatEnvParameters = new ArrayList<>();
for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
heatEnvParameter.setCurrentValue(null);
heatEnvParameters.add(heatEnvParameter);
}
artifactDefinition.setListHeatParameters(heatEnvParameters);
}
private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
String name = heatArtifact.getArtifactName();
String fileName;
if (name == null) {
name = heatArtifact.getArtifactLabel();
fileName = name + "." + envExtension;
}
else {
fileName = name.replaceAll("." + heatExtension, "." + envExtension);
}
heatEnvArtifact.setArtifactName(fileName);
}
private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
if (null != existingEnvVersions) {
String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
if (null != prevVersion) {
heatEnvArtifact.setArtifactVersion(prevVersion);
}
}
}
/**
* Handles Artifacts Request For Inner Component
*
* @param artifactsToHandle
* @param component
* @param user
* @param vfcsNewCreatedArtifacts
* @param operation
* @param shouldLock
* @param inTransaction
* @return
*/
public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null;
ComponentTypeEnum componentType = component.getComponentType();
List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult;
String originData;
String origMd5;
try {
for (ArtifactDefinition artifact : artifactsToHandle) {
originData = buildJsonStringForCsarVfcArtifact(artifact);
origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(originData);
actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact
.getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
if (actionResult.isRight()) {
log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component
.getName(), actionResult.right().value());
errorWrapper.setInnerElement(actionResult.right().value());
if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
}
break;
}
uploadedArtifacts.add(actionResult.left().value().left().value());
}
if (errorWrapper.isEmpty()) {
handleArtifactsResult = Either.left(uploadedArtifacts);
}
else {
handleArtifactsResult = Either.right(errorWrapper.getInnerElement());
}
}
catch (Exception e) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
handleArtifactsResult = Either.right(responseFormat);
log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e);
}
return handleArtifactsResult;
}
private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
ComponentInstance componentInstance = null;
String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
if (errorWrapper.isEmpty()) {
componentInstance = component.getComponentInstances()
.stream()
.filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
.equals(normalizedName))
.findFirst()
.orElse(null);
if (componentInstance == null) {
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component
.getComponentType()
.getValue(), component.getName()));
log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
}
}
return componentInstance;
}
private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
ComponentInstance componentInstance = component.getComponentInstances()
.stream()
.filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
.equals(normalizedName))
.findFirst()
.orElse(null);
if (componentInstance == null) {
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component
.getComponentType()
.getValue(), component.getName()));
log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
}
else {
relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
}
return relatedComponentComponentInstancePair;
}
private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
ComponentInstance componentInstance;
ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
if (errorWrapper.isEmpty()) {
componentInstance = component.getComponentInstances()
.stream()
.filter(ci -> ci.getNormalizedName().equals(resourceInstanceName))
.findFirst()
.orElse(null);
if (componentInstance == null) {
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component
.getComponentType()
.getValue(), component.getName()));
log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
}
else {
relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
}
}
return relatedComponentComponentInstancePair;
}
private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) {
byte[] downloadedArtifact = null;
Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
List<ArtifactDefinition> artifactsList = null;
ArtifactDefinition deploymentArtifact = null;
if (artifacts != null && !artifacts.isEmpty()) {
artifactsList = artifacts.values()
.stream()
.filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID()
.equals(artifactUUID))
.collect(Collectors.toList());
}
if (artifactsList == null || artifactsList.isEmpty()) {
log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
}
if (errorWrapper.isEmpty()) {
deploymentArtifact = artifactsList.get(0);
downloadArtifactEither = downloadArtifact(deploymentArtifact);
if (downloadArtifactEither.isRight()) {
log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
errorWrapper.setInnerElement(downloadArtifactEither.right().value());
}
}
if (errorWrapper.isEmpty()) {
log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
downloadedArtifact = downloadArtifactEither.left().value().getRight();
}
return downloadedArtifact;
}
private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
Component component = null;
Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
if (getComponentRes.isRight()) {
StorageOperationStatus status = getComponentRes.right().value();
log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
}
else {
component = getComponentRes.left().value();
}
return component;
}
private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
Component component = null;
Either<List<Component>, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null);
if (getComponentRes.isRight()) {
StorageOperationStatus status = getComponentRes.right().value();
log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
}
else {
List<Component> value = getComponentRes.left().value();
if (value.isEmpty()) {
log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid);
ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status));
}
else {
component = value.get(0);
}
}
return component;
}
private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) {
String artifactId = null;
ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
StorageOperationStatus storageStatus;
ArtifactDefinition latestArtifact = null;
List<ArtifactDefinition> artifacts = null;
Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
if (getArtifactsRes.isRight()) {
storageStatus = getArtifactsRes.right().value();
log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType, parentId, storageStatus);
if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) {
actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
}
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
}
if (errorWrapper.isEmpty()) {
artifacts = getArtifactsRes.left()
.value()
.values()
.stream()
.filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID()
.equals(artifactUUID))
.collect(Collectors.toList());
if (artifacts == null || artifacts.isEmpty()) {
log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
}
}
if (errorWrapper.isEmpty()) {
latestArtifact = artifacts.stream().max((a1, a2) -> {
int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
if (compareRes == 0) {
compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2
.getLastUpdateDate());
}
return compareRes;
}).get();
if (latestArtifact == null) {
log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
}
}
if (errorWrapper.isEmpty()) {
artifactId = latestArtifact.getUniqueId();
}
return artifactId;
}
private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) {
Component component = null;
Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false);
if (getUserRes.isRight()) {
log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes
.right()
.value());
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value()));
}
if (errorWrapper.isEmpty()) {
User modifier = getUserRes.left().value();
LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
if (checkoutRes.isRight()) {
log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType
.getNodeType(), parentId, checkoutRes.right().value().getStatus());
errorWrapper.setInnerElement(checkoutRes.right().value());
}
else {
component = checkoutRes.left().value();
}
}
return component;
}
private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
Map<String, Object> json = new HashMap<>();
String artifactName = artifact.getArtifactName();
json.put(Constants.ARTIFACT_NAME, artifactName);
json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
return gson.toJson(json);
}
@VisibleForTesting
void setNodeTemplateOperation(NodeTemplateOperation nodeTemplateOperation) {
this.nodeTemplateOperation = nodeTemplateOperation;
}
}
|