aboutsummaryrefslogtreecommitdiffstats
path: root/app-c/appc/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/ProviderAdapterImpl.java
blob: b1bba091834640f248f818f46e926c9950a785e9 (plain)
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
/*-
 * ============LICENSE_START=======================================================
 * openECOMP : APP-C
 * ================================================================================
 * 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.appc.adapter.iaas.impl;

import com.woorea.openstack.base.client.OpenStackBaseException;
import com.woorea.openstack.heat.Heat;
import org.glassfish.grizzly.http.util.HttpStatus;
import org.openecomp.appc.Constants;
import org.openecomp.appc.adapter.iaas.ProviderAdapter;
import org.openecomp.appc.adapter.openstack.heat.SnapshotResource;
import org.openecomp.appc.adapter.openstack.heat.StackResource;
import org.openecomp.appc.adapter.openstack.heat.model.CreateSnapshotParams;
import org.openecomp.appc.adapter.openstack.heat.model.Snapshot;
import org.openecomp.appc.configuration.Configuration;
import org.openecomp.appc.configuration.ConfigurationFactory;
import org.openecomp.appc.exceptions.APPCException;
import org.openecomp.appc.exceptions.UnknownProviderException;
import org.openecomp.appc.i18n.Msg;
import org.openecomp.appc.pool.Pool;
import org.openecomp.appc.pool.PoolExtensionException;
import org.openecomp.appc.util.StructuredPropertyHelper;
import org.openecomp.appc.util.StructuredPropertyHelper.Node;
import com.att.cdp.exceptions.*;
import com.att.cdp.openstack.OpenStackContext;
import com.att.cdp.openstack.connectors.HeatConnector;
import com.att.cdp.openstack.util.ExceptionMapper;
import com.att.cdp.pal.util.StringHelper;
import com.att.cdp.zones.*;
import com.att.cdp.zones.model.Image;
import com.att.cdp.zones.model.Server;
import com.att.cdp.zones.model.ServerBootSource;
import com.att.cdp.zones.model.Stack;
import com.att.cdp.zones.model.Server.Status;
import com.att.cdp.zones.spi.AbstractService;
import com.att.cdp.zones.spi.RequestState;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.att.eelf.i18n.EELFResourceManager;
import org.openecomp.sdnc.sli.SvcLogicContext;
import org.slf4j.MDC;

import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;

import java.io.IOException;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 * This class implements the {@link ProviderAdapter} interface. This interface defines the behaviors that our service
 * provides.
 */
@SuppressWarnings("javadoc")
public class ProviderAdapterImpl implements ProviderAdapter {

    /**
     * The name of the adapter
     */
    @SuppressWarnings("nls")
    private static final String ADAPTER_NAME = "Appc IaaS Adapter";

    /**
     * The username and password to use for dynamically created connections
     */
    private static String DEFAULT_USER;
    private static String DEFAULT_PASS;

    /**
     * The constant used to define the adapter name in the mapped diagnostic context
     */
    @SuppressWarnings("nls")
    private static final String MDC_ADAPTER = "adapter";

    /**
     * The constant used to define the service name in the mapped diagnostic context
     */
    @SuppressWarnings("nls")
    static final String MDC_SERVICE = "service";

    /**
     * The constant for the status code for a failed outcome
     */
    @SuppressWarnings("nls")
    private static final String OUTCOME_FAILURE = "failure";

    /**
     * The constant for the status code for a successful outcome
     */
    @SuppressWarnings("nls")
    private static final String OUTCOME_SUCCESS = "success";

    /**
     * A constant for the property token "provider" used in the structured property specifications
     */
    @SuppressWarnings("nls")
    private static final String PROPERTY_PROVIDER = "provider";

    /**
     * A constant for the property token "identity" used in the structured property specifications
     */
    @SuppressWarnings("nls")
    private static final String PROPERTY_PROVIDER_IDENTITY = "identity";

    /**
     * A constant for the property token "tenant" used in the structured property specifications
     */
    @SuppressWarnings("nls")
    private static final String PROPERTY_PROVIDER_TENANT = "tenant";

    /**
     * A constant for the property token "tenant name" used in the structured property specifications
     */
    @SuppressWarnings("nls")
    private static final String PROPERTY_PROVIDER_TENANT_NAME = "name";

    /**
     * A constant for the property token "password" used in the structured property specifications
     */
    @SuppressWarnings("nls")
    private static final String PROPERTY_PROVIDER_TENANT_PASSWORD = "password"; // NOSONAR

    /**
     * A constant for the property token "userid" used in the structured property specifications
     */
    @SuppressWarnings("nls")
    private static final String PROPERTY_PROVIDER_TENANT_USERID = "userid";

    /**
     * A constant for the property token "type" used in the structured property specifications
     */
    @SuppressWarnings("nls")
    private static final String PROPERTY_PROVIDER_TYPE = "type";

    /**
     * The name of the service to evacuate a server
     */
    @SuppressWarnings("nls")
    private static final String EVACUATE_SERVICE = "evacuateServer";

    /**
     * The name of the service to migrate a server
     */
    @SuppressWarnings("nls")
    private static final String MIGRATE_SERVICE = "migrateServer";

    /**
     * The name of the service to rebuild a server
     */
    @SuppressWarnings("nls")
    private static final String REBUILD_SERVICE = "rebuildServer";

    /**
     * The name of the service to restart a server
     */
    @SuppressWarnings("nls")
    private static final String RESTART_SERVICE = "restartServer";

    /**
	 * The name of the service to check status of  a server
	 */
	@SuppressWarnings("nls")
    private static final String VMSTATUSCHECK_SERVICE = "vmStatuschecker";


    /**
     * The name of the service to restart a server
     */
    @SuppressWarnings("nls")
    private static final String SNAPSHOT_SERVICE = "createSnapshot";

    /**
     * The name of the service to terminate a stack
     */
    @SuppressWarnings("nls")
    private static final String TERMINATE_STACK = "terminateStack";

    /**
     * The name of the service to snapshot a stack
     */
    @SuppressWarnings("nls")
    private static final String SNAPSHOT_STACK = "snapshotStack";

    /**
     * The name of a service to start a server
     */
    @SuppressWarnings("nls")
    private static final String START_SERVICE = "startServer";

    /**
     * The name of the service to stop a server
     */
    @SuppressWarnings("nls")
    private static final String STOP_SERVICE = "stopServer";

    /**
     * The name of the service to stop a server
     */
    @SuppressWarnings("nls")
    private static final String TERMINATE_SERVICE = "terminateServer";

    /**
     * The name of the service to lookup a server
     */
    @SuppressWarnings("nls")
    private static final String LOOKUP_SERVICE = "lookupServer";

    /**
     * The logger to be used
     */
    private static final EELFLogger logger = EELFManager.getInstance().getLogger(ProviderAdapterImpl.class);

    private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    /**
     * The constant for a left parenthesis
     */
    private static final char LPAREN = '(';

    /**
     * The constant for a new line control code
     */
    private static final char NL = '\n';

    /**
     * The constant for a single quote
     */
    private static final char QUOTE = '\'';

    /**
     * The constant for a right parenthesis
     */
    private static final char RPAREN = ')';

    /**
     * The constant for a space
     */
    private static final char SPACE = ' ';

    /**
     * A reference to the adapter configuration object.
     */
    private Configuration configuration;

    /**
     * A cache of providers that are predefined.
     */
    private Map<String /* provider name */, ProviderCache> providerCache;

    /**
     * A list of valid initial VM statuses for a migrate operations
     */
    private static final Collection<Status> migratableStatuses = Arrays.asList(Status.READY, Status.RUNNING, Status.SUSPENDED);

    /**
     * This default constructor is used as a work around because the activator wasnt getting called
     */
    @SuppressWarnings("all")
    public ProviderAdapterImpl() {
        initialize();

    }

    /**
     * This constructor is used primarily in the test cases to bypass initialization of the adapter for isolated,
     * disconnected testing
     *
     * @param initialize
     *            True if the adapter is to be initialized, can false if not
     */
    @SuppressWarnings("all")
    public ProviderAdapterImpl(boolean initialize) {
        configuration = ConfigurationFactory.getConfiguration();
        if (initialize) {
            initialize();
        }
    }

    /**
     * @param props
     *            not used
     */
    public ProviderAdapterImpl(@SuppressWarnings("unused") Properties props) {
        initialize();

    }

    /**
     * Returns the symbolic name of the adapter
     *
     * @return The adapter name
     * @see org.openecomp.appc.adapter.iaas.ProviderAdapter#getAdapterName()
     */
    @Override
    public String getAdapterName() {
        return configuration.getProperty(Constants.PROPERTY_ADAPTER_NAME);
    }

    @SuppressWarnings("nls")
    @Override
    public Image createSnapshot(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
        Image snapshot = null;
        RequestContext rc = new RequestContext(ctx);
        rc.isAlive();
        MDC.put(MDC_ADAPTER, ADAPTER_NAME);
        MDC.put(MDC_SERVICE, SNAPSHOT_SERVICE);
        MDC.put(MDC_SERVICE_NAME, "App-C IaaS Adapter:Snapshot");
        String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
        logger.info(Msg.SNAPSHOTING_SERVER, appName);
        String msg;

        try {
            validateParametersExist(rc, params, ProviderAdapter.PROPERTY_INSTANCE_URL,
                ProviderAdapter.PROPERTY_PROVIDER_NAME);
            String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
            debugParameters(params);
            debugContext(ctx);

            VMURL vm = VMURL.parseURL(vm_url);
            if (validateVM(rc, appName, vm_url, vm)) return null;

            IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
            String identStr = (ident == null) ? null : ident.toString();

            Context context = null;
            try {
                context = getContext(rc, vm_url, identStr);
                if (context != null) {
                    Server server = lookupServer(rc, context, vm.getServerId());
                    logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString());

                    if (hasImageAccess(rc, context)) {
                        snapshot = createSnapshot(rc, server);
                        doSuccess(rc);
                    } else {
                        msg = EELFResourceManager.format(Msg.REBUILD_SERVER_FAILED, server.getName(), server.getId(),
                            "Accessing Image Service Failed");
                        logger.error(msg);
                        doFailure(rc, HttpStatus.FORBIDDEN_403, msg);
                    }
                    context.close();
                }
            } catch (ResourceNotFoundException e) {
                msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url);
                logger.error(msg);
                doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
            } catch (Throwable t) {
                msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(),
                    SNAPSHOT_SERVICE, vm_url, context == null ? "Unknown" : context.getTenantName());
                logger.error(msg, t);
                doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
            }
        } catch (RequestFailedException e) {
            doFailure(rc, e.getStatus(), e.getMessage());
        }
        return snapshot;
    }

    private boolean validateVM(RequestContext rc, String appName, String vm_url, VMURL vm)
                    throws RequestFailedException {
        String msg;
        if (vm == null) {
            msg = EELFResourceManager.format(Msg.INVALID_SELF_LINK_URL, appName, vm_url);
            logger.error(msg);
            doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
            return true;
        }
        validateVMURL(vm);
        return false;
    }

    private Image createSnapshot(RequestContext rc, Server server) throws ZoneException, RequestFailedException {
        Context context = server.getContext();
        Provider provider = context.getProvider();
        ImageService service = context.getImageService(); // Already checked access by this point

        String snapshotName = generateSnapshotName(server.getName());

        logger.info(String.format("Creating snapshot of server %s (%s) with name %s", server.getName(), server.getId(),
            snapshotName));

        // Request Snapshot
        String msg;
        while (rc.attempt()) {
            try {
                server.createSnapshot(snapshotName);
                break;
            } catch (ContextConnectionException e) {
                msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
                    context.getTenant().getName(), context.getTenant().getId(), e.getMessage(),
                    Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
                    Integer.toString(rc.getRetryLimit()));
                logger.error(msg, e);
                rc.delay();
            }
        }
        if (rc.isFailed()) {
            msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
            logger.error(msg);
            throw new RequestFailedException("Stop Server", msg, HttpStatus.BAD_GATEWAY_502, server);
        }
        rc.reset();

        // Locate snapshot image
        Image snapshot = null;
        while (rc.attempt()) {
            try {
                snapshot = service.getImageByName(snapshotName);
                if (snapshot != null) {
                    break;
                }
            } catch (ContextConnectionException e) {
                msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
                    context.getTenant().getName(), context.getTenant().getId(), e.getMessage(),
                    Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
                    Integer.toString(rc.getRetryLimit()));
                logger.error(msg, e);
                rc.delay();
            }
        }
        if (rc.isFailed()) {
            msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
            logger.error(msg);
            throw new RequestFailedException("Stop Server", msg, HttpStatus.BAD_GATEWAY_502, server);
        }
        rc.reset();

        // Wait for it to be ready
        waitForStateChange(rc, snapshot, Image.Status.ACTIVE);

        return snapshot;
    }

    private String generateSnapshotName(String server) {
        SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT);
        return String.format("Snapshot of %s at %s", server, df.format(new Date()));
    }

    /**
     * @see org.openecomp.appc.adapter.iaas.ProviderAdapter#evacuateServer(java.util.Map, org.openecomp.sdnc.sli.SvcLogicContext)
     */
    @SuppressWarnings("nls")
    @Override
    public Server evacuateServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
        Server server = null;
        RequestContext rc = new RequestContext(ctx);
        rc.isAlive();
        MDC.put(MDC_ADAPTER, ADAPTER_NAME);
        MDC.put(MDC_SERVICE, EVACUATE_SERVICE);
        MDC.put(MDC_SERVICE_NAME, "App-C IaaS Adapter:Evacuate");
        String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
        logger.info(Msg.EVACUATING_SERVER, appName);
        String msg;

        try {
            validateParametersExist(rc, params, ProviderAdapter.PROPERTY_INSTANCE_URL,
                ProviderAdapter.PROPERTY_PROVIDER_NAME);
            String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
            String providerName = params.get(ProviderAdapter.PROPERTY_PROVIDER_NAME);
            debugParameters(params);
            debugContext(ctx);

            VMURL vm = VMURL.parseURL(vm_url);
            if (validateVM(rc, appName, vm_url, vm)) return null;

            Context context = null;
            try {
                context = getContext(rc, vm_url, providerName);
                if (context != null) {
                    server = lookupServer(rc, context, vm.getServerId());
                    logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString());
                    evacuateServer(rc, server);
                    server.refreshStatus();
                    context.close();
                    doSuccess(rc);
                }
            } catch (ResourceNotFoundException e) {
                msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url);
                logger.error(msg);
                doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
            } catch (Throwable t) {
                msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(),
                    EVACUATE_SERVICE, vm_url, context == null ? "Unknown" : context.getTenantName());
                logger.error(msg, t);
                doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
            }
        } catch (RequestFailedException e) {
            doFailure(rc, e.getStatus(), e.getMessage());
        }

        return server;
    }

    /**
     * @see org.openecomp.appc.adapter.iaas.ProviderAdapter#migrateServer(java.util.Map, org.openecomp.sdnc.sli.SvcLogicContext)
     */
    @SuppressWarnings("nls")
    @Override
    public Server migrateServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
        Server server = null;
        RequestContext rc = new RequestContext(ctx);
        rc.isAlive();
        MDC.put(MDC_ADAPTER, ADAPTER_NAME);
        MDC.put(MDC_SERVICE, MIGRATE_SERVICE);
        MDC.put(MDC_SERVICE_NAME, "App-C IaaS Adapter:Migrate");
        String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
        logger.info(Msg.MIGRATING_SERVER, appName);
        String msg;

        try {
            validateParametersExist(rc, params, ProviderAdapter.PROPERTY_INSTANCE_URL,
                ProviderAdapter.PROPERTY_PROVIDER_NAME);
            String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
            debugParameters(params);
            debugContext(ctx);

            VMURL vm = VMURL.parseURL(vm_url);
            if (validateVM(rc, appName, vm_url, vm)) return null;

            IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
            String identStr = (ident == null) ? null : ident.toString();

            Context context = null;
            try {
                context = getContext(rc, vm_url, identStr);
                if (context != null) {
                    server = lookupServer(rc, context, vm.getServerId());
                    logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString());
                    migrateServer(rc, server);
                    server.refreshStatus();
                    context.close();
                    doSuccess(rc);
                }
            } catch (ResourceNotFoundException e) {
                msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url);
                logger.error(msg);
                doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
            } catch (Throwable t) {
                msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(),
                    MIGRATE_SERVICE, vm_url, context == null ? "Unknown" : context.getTenantName());
                logger.error(msg, t);
                doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
            }
        } catch (RequestFailedException e) {
            doFailure(rc, e.getStatus(), e.getMessage());
        }

        return server;
    }

    private void evacuateServer(RequestContext rc, @SuppressWarnings("unused") Server server) throws ZoneException, RequestFailedException {
        doFailure(rc, HttpStatus.NOT_IMPLEMENTED_501, "The operation 'EVACUATE' is not yet implemented");
    }

    private void migrateServer(RequestContext rc, Server server) throws ZoneException, RequestFailedException {
        String msg;
        Context ctx = server.getContext();
        ComputeService service = ctx.getComputeService();

        // Init status will equal final status
        Status initialStatus = server.getStatus();

        if (initialStatus == null) {
            throw new ZoneException("Failed to determine server's starting status");
        }

        // We can only migrate certain statuses
        if (!migratableStatuses.contains(initialStatus)) {
            throw new ZoneException(String.format("Cannot migrate server that is in %s state. Must be in one of [%s]",
                initialStatus, migratableStatuses));
        }

        boolean inConfirmPhase = false;
        try {
            while (rc.attempt()) {
                try {
                    if (!inConfirmPhase) {
                        // Initial migrate request
                        service.migrateServer(server.getId());
                        // Wait for change to verify resize
                        waitForStateChange(rc, server, Status.READY);
                        inConfirmPhase = true;
                    }

                    // Verify resize
                    service.processResize(server);
                    // Wait for complete. will go back to init status
                    waitForStateChange(rc, server, initialStatus);
                    logger.info("Completed migrate request successfully");
                    return;
                } catch (ContextConnectionException e) {
                    msg = getConnectionExceptionMessage(rc, ctx, e);
                    logger.error(msg, e);
                    rc.delay();
                }
            }
        } catch (ZoneException e) {
            String phase = inConfirmPhase ? "VERIFY MIGRATE" : "REQUEST MIGRATE";
            msg = EELFResourceManager.format(Msg.MIGRATE_SERVER_FAILED, server.getName(), server.getId(), phase,
                e.getMessage());
            generateEvent(rc, false, msg);
            logger.error(msg, e);
            throw new RequestFailedException("Migrate Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
        }

    }

    /**
     * @see org.openecomp.appc.adapter.iaas.ProviderAdapter#rebuildServer(java.util.Map, org.openecomp.sdnc.sli.SvcLogicContext)
     */
    @SuppressWarnings("nls")
    @Override
    public Server rebuildServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
        Server server = null;
        RequestContext rc = new RequestContext(ctx);
        rc.isAlive();
        MDC.put(MDC_ADAPTER, ADAPTER_NAME);
        MDC.put(MDC_SERVICE, REBUILD_SERVICE);
        MDC.put(MDC_SERVICE_NAME, "App-C IaaS Adapter:Rebuild");
        String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
        logger.info(Msg.REBUILDING_SERVER, appName);
        String msg;

        try {
            validateParametersExist(rc, params, ProviderAdapter.PROPERTY_INSTANCE_URL,
                ProviderAdapter.PROPERTY_PROVIDER_NAME);
            String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
            debugParameters(params);
            debugContext(ctx);

            VMURL vm = VMURL.parseURL(vm_url);
            if (validateVM(rc, appName, vm_url, vm)) return null;

            IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
            String identStr = (ident == null) ? null : ident.toString();

            Context context = null;
            try {
                context = getContext(rc, vm_url, identStr);
                if (context != null) {
                    server = lookupServer(rc, context, vm.getServerId());
                    logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString());

                    // Manually checking image service until new PAL release
                    if (hasImageAccess(rc, context)) {
                        rebuildServer(rc, server);
                        doSuccess(rc);
                    } else {
                        msg = EELFResourceManager.format(Msg.REBUILD_SERVER_FAILED, server.getName(), server.getId(),
                            "Accessing Image Service Failed");
                        logger.error(msg);
                        doFailure(rc, HttpStatus.FORBIDDEN_403, msg);
                    }
                    context.close();
                }
            } catch (ResourceNotFoundException e) {
                msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url);
                logger.error(msg);
                doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
            } catch (Throwable t) {
                msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(),
                    STOP_SERVICE, vm_url, context == null ? "Unknown" : context.getTenantName());
                logger.error(msg, t);
                doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
            }
        } catch (RequestFailedException e) {
            doFailure(rc, e.getStatus(), e.getMessage());
        }

        return server;
    }

    /**
     * This method is used to restart an existing virtual machine given the fully qualified URL of the machine.
     * <p>
     * The fully qualified URL contains enough information to locate the appropriate server. The URL is of the form
     * <pre>
     *  [scheme]://[host[:port]] / [path] / [tenant_id] / servers / [vm_id]
     * </pre> Where the various parts of the URL can be parsed and extracted and used to locate the appropriate service
     * in the provider service catalog. This then allows us to open a context using the CDP abstraction, obtain the
     * server by its UUID, and then perform the restart.
     * </p>
     *
     * @throws UnknownProviderException
     *             If the provider cannot be found
     * @throws IllegalArgumentException
     *             if the expected argument(s) are not defined or are invalid
     * @see org.openecomp.appc.adapter.iaas.ProviderAdapter#restartServer(java.util.Map, org.openecomp.sdnc.sli.SvcLogicContext)
     */
    @SuppressWarnings("nls")
    @Override
    public Server restartServer(Map<String, String> params, SvcLogicContext ctx)
        throws UnknownProviderException, IllegalArgumentException {
        Server server = null;
        RequestContext rc = new RequestContext(ctx);
        rc.isAlive();
        MDC.put(MDC_ADAPTER, ADAPTER_NAME);
        MDC.put(MDC_SERVICE, RESTART_SERVICE);
        MDC.put(MDC_SERVICE_NAME, "App-C IaaS Adapter:Restart");
        String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
        logger.info(Msg.RESTARTING_SERVER, appName);

        try {
            validateParametersExist(rc, params, ProviderAdapter.PROPERTY_INSTANCE_URL,
                ProviderAdapter.PROPERTY_PROVIDER_NAME);
            debugParameters(params);
            debugContext(ctx);
            String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);

            VMURL vm = VMURL.parseURL(vm_url);
            if (validateVM(rc, appName, vm_url, vm)) return null;

            IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
            String identStr = (ident == null) ? null : ident.toString();

            Context context = null;
            try {
                context = getContext(rc, vm_url, identStr);
                if (context != null) {
                    server = lookupServer(rc, context, vm.getServerId());
                    logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString());
                    restartServer(rc, server);
                    context.close();
                    doSuccess(rc);
                }
            } catch (ResourceNotFoundException e) {
                String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url);
                logger.error(msg);
                doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
            } catch (Throwable t) {
                String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(),
                    RESTART_SERVICE, vm_url, context == null ? "Unknown" : context.getTenantName());
                logger.error(msg, t);
                doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
            }
        } catch (RequestFailedException e) {
            doFailure(rc, e.getStatus(), e.getMessage());
        }

        return server;
    }

    /* *********************************************************************************/
	/* DEVEN PANCHAL: This method is used to check the status of the VM               */
	/**********************************************************************************/
    public Server vmStatuschecker(Map<String, String> params, SvcLogicContext ctx) throws UnknownProviderException, IllegalArgumentException {
       Server server = null;
       RequestContext rc = new RequestContext(ctx);
       rc.isAlive();
       MDC.put(MDC_ADAPTER, ADAPTER_NAME);
       MDC.put(MDC_SERVICE, VMSTATUSCHECK_SERVICE);
       MDC.put(MDC_SERVICE_NAME, "App-C IaaS Adapter: vmstatuscheck");
       String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);

       try {
           validateParametersExist(rc, params, ProviderAdapter.PROPERTY_INSTANCE_URL,
               ProviderAdapter.PROPERTY_PROVIDER_NAME);
           debugParameters(params);
           debugContext(ctx);
           String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);

           VMURL vm = VMURL.parseURL(vm_url);
           if (validateVM(rc, appName, vm_url, vm)) return null;

           IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
           String identStr = (ident == null) ? null : ident.toString();

           Context context = null;
           try {
               context = getContext(rc, vm_url, identStr);
               if (context != null) {
                   server = lookupServer(rc, context, vm.getServerId());
                   logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString());

                   String statusvm;
                   switch (server.getStatus()) {
                   case DELETED:
                   	statusvm = "deleted";
                       break;

                   case RUNNING:
                   	statusvm = "running";
                       break;

                   case ERROR:
                   	statusvm = "error";
                   	break;

                   case READY:
                   	statusvm = "ready";
                       break;

                   case PAUSED:
                   	statusvm = "paused";
                       break;

                   case SUSPENDED:
                   	statusvm = "suspended";
                       break;

                   case PENDING:
                   	statusvm = "pending";
                       break;

                   default:
                   	statusvm = "default-unknown state-should never occur";
                       break;
               }


                   String statusofVM = statusvm;
                   context.close();
                   SvcLogicContext svcLogic = rc.getSvcLogicContext();
                   svcLogic.setStatus(OUTCOME_SUCCESS);
                   svcLogic.setAttribute("org.openecomp.statusofvm", statusofVM);
                   svcLogic.setAttribute(Constants.STATUS_OF_VM, statusofVM);
                   svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_CODE, Integer.toString(HttpStatus.OK_200.getStatusCode()));
               }
           } catch (ResourceNotFoundException e) {
               String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url);
               logger.error(msg);
               doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
           } catch (Throwable t) {
               String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(),
                   RESTART_SERVICE, vm_url, context == null ? "Unknown" : context.getTenantName());
               logger.error(msg, t);
               doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
           }
       } catch (RequestFailedException e) {
           doFailure(rc, e.getStatus(), e.getMessage());
       }

       return server;
   }

   /* *********************************************************************************/


    /**
     * @see org.openecomp.appc.adapter.iaas.ProviderAdapter#startServer(java.util.Map, org.openecomp.sdnc.sli.SvcLogicContext)
     */
    @SuppressWarnings("nls")
    @Override
    public Server startServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
        Server server = null;
        RequestContext rc = new RequestContext(ctx);
        rc.isAlive();
        MDC.put(MDC_ADAPTER, ADAPTER_NAME);
        MDC.put(MDC_SERVICE, START_SERVICE);
        String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
        logger.info(Msg.RESTARTING_SERVER, appName);

        try {
            validateParametersExist(rc, params, ProviderAdapter.PROPERTY_INSTANCE_URL,
                ProviderAdapter.PROPERTY_PROVIDER_NAME);
            debugParameters(params);
            debugContext(ctx);
            String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
            String providerName = params.get(ProviderAdapter.PROPERTY_PROVIDER_NAME);

            VMURL vm = VMURL.parseURL(vm_url);
            if (validateVM(rc, appName, vm_url, vm)) return null;

            Context context = null;
            try {
                context = getContext(rc, vm_url, providerName);
                if (context != null) {
                    server = lookupServer(rc, context, vm.getServerId());
                    logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString());
                    stopServer(rc, server);
                    server.refreshStatus();
                    context.close();
                    doSuccess(rc);
                }
            } catch (ResourceNotFoundException e) {
                String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url);
                logger.error(msg);
                doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
            } catch (Throwable t) {
                String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(),
                    START_SERVICE, vm_url, context == null ? "Unknown" : context.getTenantName());
                logger.error(msg, t);
                doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
            }
        } catch (RequestFailedException e) {
            doFailure(rc, e.getStatus(), e.getMessage());
        }

        return server;
    }

    /**
     * @see org.openecomp.appc.adapter.iaas.ProviderAdapter#stopServer(java.util.Map, org.openecomp.sdnc.sli.SvcLogicContext)
     */
    @SuppressWarnings("nls")
    @Override
    public Server stopServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
        Server server = null;
        RequestContext rc = new RequestContext(ctx);
        rc.isAlive();
        MDC.put(MDC_ADAPTER, ADAPTER_NAME);
        MDC.put(MDC_SERVICE, STOP_SERVICE);
        String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
        logger.info(Msg.STOPPING_SERVER, appName);

        try {
            validateParametersExist(rc, params, ProviderAdapter.PROPERTY_INSTANCE_URL,
                ProviderAdapter.PROPERTY_PROVIDER_NAME);
            debugParameters(params);
            debugContext(ctx);
            String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
            ctx.setAttribute("STOP_STATUS", "SUCCESS");

            VMURL vm = VMURL.parseURL(vm_url);
            if (validateVM(rc, appName, vm_url, vm)) return null;

            IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
            String identStr = (ident == null) ? null : ident.toString();

            Context context = null;
            try {
                context = getContext(rc, vm_url, identStr);
                if (context != null) {
                    server = lookupServer(rc, context, vm.getServerId());
                    logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString());
                    if (server.getStatus().equals(Status.PENDING)) {
                        throw new RequestFailedException("Server is in pending Status");
                    }
                    stopServer(rc, server);
                    server.refreshStatus();
                    if (server.getStatus().equals(Status.ERROR)) {
                        throw new RequestFailedException("Server is in ERROR state after operation");
                    }
                    context.close();
                    doSuccess(rc);
                }else{
                    ctx.setAttribute("STOP_STATUS", "SERVER_NOT_FOUND");
                }
            } catch (ResourceNotFoundException e) {
                String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url);
                ctx.setAttribute("STOP_STATUS", "SERVER_NOT_FOUND");
                logger.error(msg);
                doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
            } catch (Throwable t) {
                String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(),
                    STOP_SERVICE, vm_url, context == null ? "Unknown" : context.getTenantName());
                logger.error(msg, t);
                ctx.setAttribute("STOP_STATUS", "ERROR");
                doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
            }
        } catch (RequestFailedException e) {
            logger.error(EELFResourceManager.format(Msg.STOP_SERVER_FAILED, appName, "n/a", "n/a", e.getMessage()));
            ctx.setAttribute("STOP_STATUS", "ERROR");
            doFailure(rc, e.getStatus(), e.getMessage());
        }

        return server;
    }

    /**
     * This method is used to validate that the parameters contain all required property names, and that the values are
     * non-null and non-empty strings. We are still not ensured that the value is valid, but at least it exists.
     *
     * @param ctx
     *            The request context object that manages the request
     * @param parameters
     *            The parameters to be checked
     * @param propertyNames
     *            The list of property names that are required to be present.
     * @throws RequestFailedException
     *             If the parameters are not valid
     */
    @SuppressWarnings({
        "nls", "static-method"
    })
    private void validateParametersExist(@SuppressWarnings("unused") RequestContext ctx, Map<String, String> parameters, String... propertyNames)
        throws RequestFailedException {
        boolean success = true;
        StringBuilder msg = new StringBuilder(EELFResourceManager.format(Msg.MISSING_REQUIRED_PROPERTIES, MDC.get(MDC_SERVICE)));
        msg.append(NL);
        for (String propertyName : propertyNames) {
            String value = parameters.get(propertyName);
            if (value == null || value.trim().length() == 0) {
                success = false;
                msg.append(QUOTE);
                msg.append(propertyName);
                msg.append(QUOTE);
                msg.append(SPACE);
            }
        }

        if (!success) {
            logger.error(msg.toString());
            throw new RequestFailedException("Check Parameters", msg.toString(), HttpStatus.BAD_REQUEST_400, (Server)null);
        }
    }

    /**
     * This method is used to create a diagnostic dump of the context for the log
     *
     * @param context
     *            The context to be dumped
     */
    @SuppressWarnings({
        "nls", "static-method"
    })
    private void debugContext(SvcLogicContext context) {
        Set<String> keys = context.getAttributeKeySet();
        StringBuilder builder = new StringBuilder();

        builder.append("Service Logic Context: Status ");
        builder.append(LPAREN);
        builder.append(context.getStatus());
        builder.append(RPAREN);
        builder.append(", Attribute count ");
        builder.append(LPAREN);
        builder.append(keys == null ? "none" : Integer.toString(keys.size()));
        builder.append(RPAREN);
        if (keys != null && !keys.isEmpty()) {
            builder.append(NL);
            for (String key : keys) {
                String value = context.getAttribute(key);
                builder.append("Attribute ");
                builder.append(LPAREN);
                builder.append(key);
                builder.append(RPAREN);
                builder.append(", value ");
                builder.append(LPAREN);
                builder.append(value == null ? "" : value);
                builder.append(RPAREN);
                builder.append(NL);
            }
        }

        logger.debug(builder.toString());
    }

    void validateVMURL(VMURL vm) throws RequestFailedException {
        String name = "vm-id";
        if (vm == null) {
            throw new RequestFailedException(String.format("The value %s cannot be null.", name));
        }

        // Check that its a good uri
        // This will probably never get hit bc of an earlier check while parsing
        // the string to a VMURL
        try {
            //noinspection ResultOfMethodCallIgnored
            URI.create(vm.toString());
        } catch (Exception e) {
            throw new RequestFailedException(
                String.format("The value %s is not well formed [%s].", name, vm.toString()));
        }

        // Check the tenant and vmid segments
        String patternRegex = "([0-9a-f]{8}(-)?[0-9a-f]{4}(-)?[0-9a-f]{4}(-)?[0-9a-f]{4}(-)?[0-9a-f]{12})";
        Pattern pattern = Pattern.compile(patternRegex, Pattern.CASE_INSENSITIVE);

        if (!pattern.matcher(vm.getTenantId()).matches()) {
            throw new RequestFailedException(
                String.format("The value %s has an invalid tenantId [%s].", name, vm.getTenantId()));
        }
        if (!pattern.matcher(vm.getServerId()).matches()) {
            throw new RequestFailedException(
                String.format("The value %s has an invalid serverId [%s].", name, vm.getServerId()));
        }
    }

    @SuppressWarnings("unused")
    private void validateIdentityURL(IdentityURL id) throws RequestFailedException {
        String name = "identity-url";
        if (id == null) {
            throw new RequestFailedException(String.format("The value %s cannot be null.", name));
        }

        // Check that its a good uri
        // This will probably never get hit bc of an earlier check while parsing
        // the string to a VMURL
        try {
            //noinspection ResultOfMethodCallIgnored
            URI.create(id.toString());
        } catch (Exception e) {
            throw new RequestFailedException(
                String.format("The value %s is not well formed [%s].", name, id.toString()));
        }
    }

    /**
     * This method is used to dump the value of the parameters to the log for debugging purposes.
     *
     * @param parameters
     *            The parameters to be printed to the log
     */
    @SuppressWarnings("static-method")
    private void debugParameters(Map<String, String> parameters) {
        for (String key : parameters.keySet()) {
            logger.debug(Msg.PROPERTY_VALUE, key, parameters.get(key));
        }
    }

    /**
     * @param rc
     *            The request context that manages the state and recovery of the request for the life of its processing.
     * @param code
     * @param message
     */
    @SuppressWarnings("static-method")
    private void doFailure(RequestContext rc, HttpStatus code, String message) {
        try {
            doFailure(rc, code, message, null);
        } catch (APPCException ignored) {/* never happens */}
    }


    private void doFailure(RequestContext rc, HttpStatus code, String message, Throwable cause) throws APPCException {
        SvcLogicContext svcLogic = rc.getSvcLogicContext();
        String msg = (message == null) ? code.getReasonPhrase() : message;
        if (msg.contains("\n")) {
            msg = msg.substring(0, msg.indexOf("\n"));
        }
        String status;
        try {
            status = Integer.toString(code.getStatusCode());
        } catch (Exception e) {
            status = "500";
        }
        svcLogic.setStatus(OUTCOME_FAILURE);
        svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_CODE, status);
        svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg);
        svcLogic.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, msg);

        if (null != cause) throw new APPCException(cause);
    }

    /**
     * @param rc
     *            The request context that manages the state and recovery of the request for the life of its processing.
     */
    @SuppressWarnings("static-method")
    private void doSuccess(RequestContext rc) {
        SvcLogicContext svcLogic = rc.getSvcLogicContext();
        svcLogic.setStatus(OUTCOME_SUCCESS);
        svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_CODE, Integer.toString(HttpStatus.OK_200.getStatusCode()));
    }

    /**
     * Generates the event indicating what happened
     *
     * @param rc
     *            The request context that manages the state and recovery of the request for the life of its processing.
     * @param success
     *            True if the event represents a successful outcome
     * @param msg
     *            The detailed message
     */
    private void generateEvent(@SuppressWarnings("unused") RequestContext rc, @SuppressWarnings("unused") boolean success, @SuppressWarnings("unused") String msg) {
        // indication to the DG to generate the event?
    }

    /**
     * This method is a general helper method used to locate a server given its fully-qualified self-link URL on a
     * supported provider, regardless of region(s), and to return an opened context that can be used to access that
     * server.
     *
     * @param rc
     *            The request context that wraps and manages the state of the request
     * @param selfLinkURL
     *            The fully-qualified self-link URL of the server
     * @param providerName
     *            The name of the provider to be searched
     * @return The context that can be used to access the server, or null if not found.
     */
    @SuppressWarnings("nls")
    private Context getContext(RequestContext rc, String selfLinkURL, String providerName) {
        VMURL vm = VMURL.parseURL(selfLinkURL);
        IdentityURL ident = IdentityURL.parseURL(providerName);
        String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);

        if (vm == null) {
            String msg = EELFResourceManager.format(Msg.INVALID_SELF_LINK_URL, appName, selfLinkURL);
            logger.error(msg);
            doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
            return null;
        }

        /*
         * Get the cache of tenants and contexts for the named provider, if one exists
         */
        ProviderCache cache = providerCache.get(providerName);

        /*
         * If one doesn't exist, try and create it. If we have enough information to create it successfully, add it to
         * the cache and continue, otherwise fail the request.
         */
        if (cache == null) {
            if (ident != null) {
                cache = createProviderCache(vm, ident);
            }
            if (cache != null) {
                providerCache.put(cache.getProviderName(), cache);
            } else {
                String msg =
                    EELFResourceManager.format(Msg.UNKNOWN_PROVIDER, providerName, providerCache.keySet().toString());
                logger.error(msg);
                doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
                return null;
            }
        }

        if (providerName == null) {
            logger
                .debug(String.format("Using the default provider cache [%s] since no valid identity url was passed in.",
                    cache.getIdentityURL()));
        }

        // get the tenant cache for the vm
        String identityURL = cache.getIdentityURL();
         TenantCache tenantCache = cache.getTenant(vm.getTenantId());

        if(tenantCache == null){
            //no tenantCache matching tenant, add tenant to the provider cache
                tenantCache = cache.addTenant(vm.getTenantId(),null,DEFAULT_USER, DEFAULT_PASS);

                if(tenantCache == null){
                    //tenant not found
                    String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, selfLinkURL);
                    logger.error(msg);
                    doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
                    return null;
                }
        }

        //reserve the context
        String tenantName = tenantCache.getTenantName();
        String tenantId = tenantCache.getTenantId();
        String region = tenantCache.determineRegion(vm);

        if (region != null) {
            Pool<Context> pool = tenantCache.getPools().get(region);

            while (rc.attempt()) {
                try {
                    Context context = pool.reserve();

                    /*
                     * Insert logic here to test the context for connectivity because we may have gotten one from
                     * the pool that was previously created.
                     */
                    if (context.isStale()) {
                        context.relogin();
                    }
                    return context;
                } catch (PoolExtensionException e) {
                    String msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, providerName, identityURL,
                        tenantName, tenantId, e.getMessage(), Long.toString(rc.getRetryDelay()),
                        Integer.toString(rc.getAttempts()), Integer.toString(rc.getRetryLimit()));
                    logger.error(msg, e);
                    rc.delay();
                } catch (Exception e) {
                    String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e,
                        e.getClass().getSimpleName(), "find", selfLinkURL, tenantCache.getTenantName());

                    logger.error(msg, e);
                    doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
                    return null;
                }
            }

            String msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, providerName, identityURL);
            logger.error(msg);
            doFailure(rc, HttpStatus.BAD_GATEWAY_502, msg);
            return null;
        }


        String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, selfLinkURL);
        logger.error(msg);
        doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
        return null;
    }

    /**
     * initialize the provider adapter by building the context cache
     */
    private void initialize() {
        configuration = ConfigurationFactory.getConfiguration();

        /*
         * Initialize the provider cache for all defined providers. The definition of the providers uses a structured
         * property set, where the names form a hierarchical name space (dotted notation, such as one.two.three). Each
         * name in the name space can also be serialized by appending a sequence number. All nodes at the same level
         * with the same serial number are grouped together in the namespace hierarchy. This allows a hierarchical
         * multi-valued property to be defined, which can then be used to setup the provider and tenant caches.
         * <p>
         * For example, the following definitions show how the namespace hierarchy is defined for two providers, with
         * two tenants on the first provider and a single tenant for the second provider. <pre>
         * provider1.type=OpenStackProvider1
         * provider1.name=OpenStackProviderName1
         * provider1.identity=http://192.168.1.2:5000/v2.0
         * provider1.tenant1.name=MY-TENANT-NAME
         * provider1.tenant1.userid=userid
         * provider1.tenant1.password=userid@123
         * provider1.tenant2.name=MY-TENANT-NAME
         * provider1.tenant2.userid=userid
         * provider1.tenant2.password=userid@123
         * provider2.type=OpenStackProvider2
         * provider2.name=OpenStackProviderName2
         * provider2.identity=http://192.168.1.2:5000/v2.0
         * provider2.tenant1.name=MY-TENANT-NAME
         * provider2.tenant1.userid=userid
         * provider2.tenant1.password=userid@123
         * </pre>
         * </p>
         */
        providerCache = new HashMap<>();
        Properties properties = configuration.getProperties();
        List<Node> providers = StructuredPropertyHelper.getStructuredProperties(properties, PROPERTY_PROVIDER);

        for (Node provider : providers) {
            ProviderCache cache = new ProviderCache();
            List<Node> providerNodes = provider.getChildren();
            for (Node node : providerNodes) {
                if (node.getName().equals(PROPERTY_PROVIDER_TYPE)) {
                    cache.setProviderType(node.getValue());
                } else if (node.getName().equals(PROPERTY_PROVIDER_IDENTITY)) {
                    cache.setIdentityURL(node.getValue());
                    cache.setProviderName(node.getValue());
                } else if (node.getName().startsWith(PROPERTY_PROVIDER_TENANT)) {
                    String tenantName = null;
                    String userId = null;
                    String password = null;
                    for (Node node2 : node.getChildren()) {
                        switch (node2.getName()) {
                            case PROPERTY_PROVIDER_TENANT_NAME:
                                tenantName = node2.getValue();
                                break;
                            case PROPERTY_PROVIDER_TENANT_USERID:
                                userId = node2.getValue();
                                DEFAULT_USER = node2.getValue();
                                break;
                            case PROPERTY_PROVIDER_TENANT_PASSWORD:
                                password = node2.getValue();
                                DEFAULT_PASS = node2.getValue();
                                break;
                        }
                    }

                    cache.addTenant(null, tenantName, userId, password);
                }
            }

            /*
             * Add the provider to the set of providers cached
             */
            if (cache.getIdentityURL() != null && cache.getProviderType() != null) {
                providerCache.put(null, cache);
                providerCache.put(cache.getIdentityURL(), cache);
            }

            /*
             * Now, initialize the cache for the loaded provider
             */
            cache.initialize();
        }
    }

    /**
     * This method is called to rebuild the provided server.
     * <p>
     * If the server was booted from a volume, then the request is failed immediately and no action is taken. Rebuilding
     * a VM from a bootable volume, where the bootable volume itself is not rebuilt, serves no purpose.
     * </p>
     *
     * @param rc
     *            The request context that manages the state and recovery of the request for the life of its processing.
     * @param server
     * @throws ZoneException
     * @throws RequestFailedException
     */
    @SuppressWarnings("nls")
    private void rebuildServer(RequestContext rc, Server server) throws ZoneException, RequestFailedException {

        ServerBootSource builtFrom = server.getBootSource();
        String msg;

        // Throw exception for non image/snap boot source
        if (ServerBootSource.VOLUME.equals(builtFrom)) {
            msg = String.format("Rebuilding is currently not supported for servers built from bootable volumes [%s]",
                server.getId());
            generateEvent(rc, false, msg);
            logger.error(msg);
            throw new RequestFailedException("Rebuild Server", msg, HttpStatus.FORBIDDEN_403, server);
        }
        /*
         * Pending is a bit of a special case. If we find the server is in a pending state, then the provider is in the
         * process of changing state of the server. So, lets try to wait a little bit and see if the state settles down
         * to one we can deal with. If not, then we have to fail the request.
         */
        Context context = server.getContext();
        Provider provider = context.getProvider();
        ComputeService service = context.getComputeService();
        if (server.getStatus().equals(Status.PENDING)) {
            waitForStateChange(rc, server, Status.READY, Status.RUNNING, Status.ERROR, Status.SUSPENDED, Status.PAUSED);
        }

        /*
         * Get the image to use. This is determined by the presence or absence of snapshot images. If any snapshots
         * exist, then the latest snapshot is used, otherwise the image used to construct the VM is used.
         */
        List<Image> snapshots = server.getSnapshots();
        String imageToUse;
        if (snapshots != null && !snapshots.isEmpty()) {
            imageToUse = snapshots.get(0).getId();
        } else {
            imageToUse = server.getImage();
            ImageService imageService = server.getContext().getImageService();
            try {
                while (rc.attempt()) {
                    try {
                        /*
                         * We are just trying to make sure that the image exists. We arent interested in the details at
                         * this point.
                         */
                        imageService.getImage(imageToUse);
                        break;
                    } catch (ContextConnectionException e) {
                        msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(),
                            imageService.getURL(), context.getTenant().getName(), context.getTenant().getId(),
                            e.getMessage(), Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
                            Integer.toString(rc.getRetryLimit()));
                        logger.error(msg, e);
                        rc.delay();
                    }
                }
            } catch (ZoneException e) {
                msg = EELFResourceManager.format(Msg.IMAGE_NOT_FOUND, imageToUse, "rebuild");
                generateEvent(rc, false, msg);
                logger.error(msg);
                throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
            }
        }
        if (rc.isFailed()) {
            msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
            logger.error(msg);
            throw new RequestFailedException("Rebuild Server", msg, HttpStatus.BAD_GATEWAY_502, server);
        }
        rc.reset();

        /*
         * We determine what to do based on the current state of the server
         */
        switch (server.getStatus()) {
            case DELETED:
                // Nothing to do, the server is gone
                msg = EELFResourceManager.format(Msg.SERVER_DELETED, server.getName(), server.getId(),
                    server.getTenantId(), "rebuilt");
                generateEvent(rc, false, msg);
                logger.error(msg);
                throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);

            case RUNNING:
                // Attempt to stop the server, then rebuild it
                stopServer(rc, server);
                rebuildServer(rc, server, imageToUse);
                startServer(rc, server);
                generateEvent(rc, true, OUTCOME_SUCCESS);
                break;

            case ERROR:
                msg = EELFResourceManager.format(Msg.SERVER_ERROR_STATE, server.getName(), server.getId(),
                    server.getTenantId(), "rebuild");
                generateEvent(rc, false, msg);
                logger.error(msg);
                throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);

            case READY:
                // Attempt to rebuild the server
                rebuildServer(rc, server, imageToUse);
                startServer(rc, server);
                generateEvent(rc, true, OUTCOME_SUCCESS);
                break;

            case PAUSED:
                // if paused, un-pause it, stop it, and rebuild it
                unpauseServer(rc, server);
                stopServer(rc, server);
                rebuildServer(rc, server, imageToUse);
                startServer(rc, server);
                generateEvent(rc, true, OUTCOME_SUCCESS);
                break;

            case SUSPENDED:
                // Attempt to resume the suspended server, stop it, and rebuild it
                resumeServer(rc, server);
                stopServer(rc, server);
                rebuildServer(rc, server, imageToUse);
                startServer(rc, server);
                generateEvent(rc, true, OUTCOME_SUCCESS);
                break;

            default:
                // Hmmm, unknown status, should never occur
                msg = EELFResourceManager.format(Msg.UNKNOWN_SERVER_STATE, server.getName(), server.getId(),
                    server.getTenantId(), server.getStatus().name());
                generateEvent(rc, false, msg);
                logger.error(msg);
                throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
        }
    }

    /**
     * This method handles the case of restarting a server once we have found the server and have obtained the abstract
     * representation of the server via the context (i.e., the "Server" object from the CDP-Zones abstraction).
     *
     * @param rc
     *            The request context that manages the state and recovery of the request for the life of its processing.
     * @param server
     *            The server object representing the server we want to operate on
     * @throws ZoneException
     */
    @SuppressWarnings("nls")
    private void restartServer(RequestContext rc, Server server) throws ZoneException, RequestFailedException {
        /*
         * Pending is a bit of a special case. If we find the server is in a pending state, then the provider is in the
         * process of changing state of the server. So, lets try to wait a little bit and see if the state settles down
         * to one we can deal with. If not, then we have to fail the request.
         */
        String msg;
        if (server.getStatus().equals(Status.PENDING)) {
            waitForStateChange(rc, server, Status.READY, Status.RUNNING, Status.ERROR, Status.SUSPENDED, Status.PAUSED);
        }

        /*
         * We determine what to do based on the current state of the server
         */
        switch (server.getStatus()) {
            case DELETED:
                // Nothing to do, the server is gone
                msg = EELFResourceManager.format(Msg.SERVER_DELETED, server.getName(), server.getId(),
                    server.getTenantId(), "restarted");
                generateEvent(rc, false, msg);
                logger.error(msg);
                break;

            case RUNNING:
                // Attempt to stop and start the server
                stopServer(rc, server);
                startServer(rc, server);
                generateEvent(rc, true, OUTCOME_SUCCESS);
                break;

            case ERROR:
                msg = EELFResourceManager.format(Msg.SERVER_ERROR_STATE, server.getName(), server.getId(),
                    server.getTenantId(), "rebuild");
                generateEvent(rc, false, msg);
                logger.error(msg);
                throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);

            case READY:
                // Attempt to start the server
                startServer(rc, server);
                generateEvent(rc, true, OUTCOME_SUCCESS);
                break;

            case PAUSED:
                // if paused, un-pause it
                unpauseServer(rc, server);
                generateEvent(rc, true, OUTCOME_SUCCESS);
                break;

            case SUSPENDED:
                // Attempt to resume the suspended server
                resumeServer(rc, server);
                generateEvent(rc, true, OUTCOME_SUCCESS);
                break;

            default:
                // Hmmm, unknown status, should never occur
                msg = EELFResourceManager.format(Msg.UNKNOWN_SERVER_STATE, server.getName(), server.getId(),
                    server.getTenantId(), server.getStatus().name());
                generateEvent(rc, false, msg);
                logger.error(msg);
                break;
        }

    }

    /**
     * Resume a suspended server and wait for it to enter a running state
     *
     * @param rc
     *            The request context that manages the state and recovery of the request for the life of its processing.
     * @param server
     *            The server to be resumed
     * @throws ZoneException
     * @throws RequestFailedException
     */
    @SuppressWarnings("nls")
    private void resumeServer(RequestContext rc, Server server) throws ZoneException, RequestFailedException {
        logger.debug(Msg.RESUME_SERVER, server.getId());

        Context context = server.getContext();
        String msg;
        Provider provider = context.getProvider();
        ComputeService service = context.getComputeService();
        while (rc.attempt()) {
            try {
                server.resume();
                break;
            } catch (ContextConnectionException e) {
                msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
                    context.getTenant().getName(), context.getTenant().getId(), e.getMessage(),
                    Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
                    Integer.toString(rc.getRetryLimit()));
                logger.error(msg, e);
                rc.delay();
            }
        }
        if (rc.isFailed()) {
            msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
            logger.error(msg);
            throw new RequestFailedException("Resume Server", msg, HttpStatus.BAD_GATEWAY_502, server);
        }
        rc.reset();
        waitForStateChange(rc, server, Status.RUNNING);
    }

    /**
     * Start the server and wait for it to enter a running state
     *
     * @param rc
     *            The request context that manages the state and recovery of the request for the life of its processing.
     * @param server
     *            The server to be started
     * @throws ZoneException
     * @throws RequestFailedException
     */
    @SuppressWarnings("nls")
    private void startServer(RequestContext rc, Server server) throws ZoneException, RequestFailedException {
        logger.debug(Msg.START_SERVER, server.getId());
        String msg;
        Context context = server.getContext();
        Provider provider = context.getProvider();
        ComputeService service = context.getComputeService();
        while (rc.attempt()) {
            try {
                server.start();
                break;
            } catch (ContextConnectionException e) {
                msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
                    context.getTenant().getName(), context.getTenant().getId(), e.getMessage(),
                    Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
                    Integer.toString(rc.getRetryLimit()));
                logger.error(msg, e);
                rc.delay();
            }
        }
        if (rc.isFailed()) {
            msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
            logger.error(msg);
            throw new RequestFailedException("Start Server", msg, HttpStatus.BAD_GATEWAY_502, server);
        }
        rc.reset();
        waitForStateChange(rc, server, Status.RUNNING);
    }

    /**
     * Stop the specified server and wait for it to stop
     *
     * @param rc
     *            The request context that manages the state and recovery of the request for the life of its processing.
     * @param server
     *            The server to be stopped
     * @throws ZoneException
     * @throws RequestFailedException
     */
    @SuppressWarnings("nls")
    private void stopServer(RequestContext rc, Server server) throws ZoneException, RequestFailedException {
        logger.debug(Msg.STOP_SERVER, server.getId());

        String msg;
        Context context = server.getContext();
        Provider provider = context.getProvider();
        ComputeService service = context.getComputeService();
        while (rc.attempt()) {
            try {
                server.stop();
                break;
            } catch (ContextConnectionException e) {
                msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
                    context.getTenant().getName(), context.getTenant().getId(), e.getMessage(),
                    Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
                    Integer.toString(rc.getRetryLimit()));
                logger.error(msg, e);
                rc.delay();
            }
        }
        if (rc.isFailed()) {
            msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
            logger.error(msg);
            throw new RequestFailedException("Stop Server", msg, HttpStatus.BAD_GATEWAY_502, server);
        }
        rc.reset();
        waitForStateChange(rc, server, Status.READY, Status.ERROR);
    }

    /**
     * Un-Pause a paused server and wait for it to enter a running state
     *
     * @param rc
     *            The request context that manages the state and recovery of the request for the life of its processing.
     * @param server
     *            The server to be un-paused
     * @throws ZoneException
     * @throws RequestFailedException
     */
    @SuppressWarnings("nls")
    private void unpauseServer(RequestContext rc, Server server) throws ZoneException, RequestFailedException {
        logger.debug(Msg.UNPAUSE_SERVER, server.getId());

        String msg;
        Context context = server.getContext();
        Provider provider = context.getProvider();
        ComputeService service = context.getComputeService();
        while (rc.attempt()) {
            try {
                server.unpause();
                break;
            } catch (ContextConnectionException e) {
                msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
                    context.getTenant().getName(), context.getTenant().getId(), e.getMessage(),
                    Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
                    Integer.toString(rc.getRetryLimit()));
                logger.error(msg, e);
                rc.delay();
            }
        }
        if (rc.isFailed()) {
            msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
            logger.error(msg);
            throw new RequestFailedException("Unpause Server", msg, HttpStatus.BAD_GATEWAY_502, server);
        }
        rc.reset();
        waitForStateChange(rc, server, Status.RUNNING, Status.READY);
    }

    /**
     * Enter a pool-wait loop checking the server state to see if it has entered one of the desired states or not.
     * <p>
     * This method checks the state of the server periodically for one of the desired states. When the server enters one
     * of the desired states, the method returns a successful indication (true). If the server never enters one of the
     * desired states within the allocated timeout period, then the method returns a failed response (false). No
     * exceptions are thrown from this method.
     * </p>
     *
     * @param rc
     *            The request context that manages the state and recovery of the request for the life of its processing.
     * @param server
     *            The server to wait on
     * @param desiredStates
     *            A variable list of desired states, any one of which is allowed.
     * @throws RequestFailedException
     *             If the request times out or fails for some reason
     */
    @SuppressWarnings("nls")
    private void waitForStateChange(RequestContext rc, Server server, Server.Status... desiredStates)
        throws RequestFailedException {
        int pollInterval = configuration.getIntegerProperty(Constants.PROPERTY_OPENSTACK_POLL_INTERVAL);
        int timeout = configuration.getIntegerProperty(Constants.PROPERTY_SERVER_STATE_CHANGE_TIMEOUT);
        Context context = server.getContext();
        Provider provider = context.getProvider();
        ComputeService service = context.getComputeService();
        String msg;

        long endTime = System.currentTimeMillis() + (timeout * 1000); //

        while (rc.attempt()) {
            try {
                try {
                    server.waitForStateChange(pollInterval, timeout, desiredStates);
                    break;
                } catch (TimeoutException e) {
                    @SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
                    List<String> list = new ArrayList<>();
                    for (Server.Status desiredState : desiredStates) {
                        list.add(desiredState.name());
                    }
                    msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
                        context.getTenant().getName(), context.getTenant().getId(), e.getMessage(),
                        Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
                        Integer.toString(rc.getRetryLimit()));
                    logger.error(msg, e);
                    rc.delay();
                }
            } catch (ZoneException e) {
                List<String> list = new ArrayList<>();
                for (Server.Status desiredState : desiredStates) {
                    list.add(desiredState.name());
                }
                String reason = EELFResourceManager.format(Msg.STATE_CHANGE_EXCEPTION, e.getClass().getSimpleName(),
                    "server", server.getName(), server.getId(), StringHelper.asList(list), server.getStatus().name(),
                    e.getMessage());
                logger.error(reason);
                logger.error(EELFResourceManager.format(e));

                // Instead of failing we are going to wait and try again.
                // Timeout is reduced by delay time
                logger.info(String.format("Retrying in %ds", rc.getRetryDelay()));
                rc.delay();
                timeout = (int) (endTime - System.currentTimeMillis()) / 1000;
                // throw new RequestFailedException(e, operation, reason,
                // HttpStatus.BAD_GATEWAY_502, server);
            }
        }

        if (rc.isFailed()) {
            msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
            logger.error(msg);
            throw new RequestFailedException("Waiting for State Change", msg, HttpStatus.BAD_GATEWAY_502, server);
        }
        rc.reset();
    }

    /**
     * Enter a pool-wait loop checking the server state to see if it has entered one of the desired states or not.
     * <p>
     * This method checks the state of the server periodically for one of the desired states. When the server enters one
     * of the desired states, the method returns a successful indication (true). If the server never enters one of the
     * desired states within the allocated timeout period, then the method returns a failed response (false). No
     * exceptions are thrown from this method.
     * </p>
     *
     * @param rc
     *            The request context that manages the state and recovery of the request for the life of its processing.
     * @param image
     *            The server to wait on
     * @param desiredStates
     *            A variable list of desired states, any one of which is allowed.
     * @throws RequestFailedException
     *             If the request times out or fails for some reason
     * @throws NotLoggedInException
     */
    @SuppressWarnings("nls")
    private void waitForStateChange(RequestContext rc, Image image, Image.Status... desiredStates)
        throws RequestFailedException, NotLoggedInException {
        int pollInterval = configuration.getIntegerProperty(Constants.PROPERTY_OPENSTACK_POLL_INTERVAL);
        int timeout = configuration.getIntegerProperty(Constants.PROPERTY_SERVER_STATE_CHANGE_TIMEOUT);
        Context context = image.getContext();
        Provider provider = context.getProvider();
        ImageService service = context.getImageService();
        String msg;

        long endTime = System.currentTimeMillis() + (timeout * 1000); //

        while (rc.attempt()) {
            try {
                try {
                    image.waitForStateChange(pollInterval, timeout, desiredStates);
                    break;
                } catch (TimeoutException e) {
                    @SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
                    List<String> list = new ArrayList<>();
                    for (Image.Status desiredState : desiredStates) {
                        list.add(desiredState.name());
                    }
                    msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
                        context.getTenant().getName(), context.getTenant().getId(), e.getMessage(),
                        Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
                        Integer.toString(rc.getRetryLimit()));
                    logger.error(msg, e);
                    rc.delay();
                }
            } catch (ZoneException e) {
                List<String> list = new ArrayList<>();
                for (Image.Status desiredState : desiredStates) {
                    list.add(desiredState.name());
                }
                String reason = EELFResourceManager.format(Msg.STATE_CHANGE_EXCEPTION, e.getClass().getSimpleName(),
                    "server", image.getName(), image.getId(), StringHelper.asList(list), image.getStatus().name(),
                    e.getMessage());
                logger.error(reason);
                logger.error(EELFResourceManager.format(e));

                // Instead of failing we are going to wait and try again.
                // Timeout is reduced by delay time
                logger.info(String.format("Retrying in %ds", rc.getRetryDelay()));
                rc.delay();
                timeout = (int) (endTime - System.currentTimeMillis()) / 1000;
                // throw new RequestFailedException(e, operation, reason,
                // HttpStatus.BAD_GATEWAY_502, server);
            }
        }

        if (rc.isFailed()) {
            msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
            logger.error(msg);
            throw new RequestFailedException("Waiting for State Change", msg, HttpStatus.BAD_GATEWAY_502, new Server());
        }
        rc.reset();
    }

    /**
     * Rebuild the indicated server with the indicated image. This method assumes the server has been determined to be
     * in the correct state to do the rebuild.
     *
     * @param rc
     *            The request context that manages the state and recovery of the request for the life of its processing.
     * @param server
     *            the server to be rebuilt
     * @param image
     *            The image to be used (or snapshot)
     * @throws RequestFailedException
     *             if the server does not change state in the allotted time
     */
    @SuppressWarnings("nls")
    private void rebuildServer(RequestContext rc, Server server, String image) throws RequestFailedException {
        String msg;
        Context context = server.getContext();
        Provider provider = context.getProvider();
        ComputeService service = context.getComputeService();

        try {
            while (rc.attempt()) {
                try {
                    server.rebuild(image);
                    break;
                } catch (ContextConnectionException e) {
                    msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
                        context.getTenant().getName(), context.getTenant().getId(), e.getMessage(),
                        Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
                        Integer.toString(rc.getRetryLimit()));
                    logger.error(msg, e);
                    rc.delay();
                }
            }

            /*
             * We need to provide some time for OpenStack to start processing the request.
             */
            try {
                Thread.sleep(10L * 1000L);
            } catch (InterruptedException e) {
                logger.trace("Sleep threw interrupted exception, should never occur");
            }
        } catch (ZoneException e) {
            msg =
                EELFResourceManager.format(Msg.REBUILD_SERVER_FAILED, server.getName(), server.getId(), e.getMessage());
            logger.error(msg);
            throw new RequestFailedException("Rebuild Server", msg, HttpStatus.BAD_GATEWAY_502, server);
        }

        /*
         * Once we have started the process, now we wait for the final state of stopped. This should be the final state
         * (since we started the rebuild with the server stopped).
         */
        waitForStateChange(rc, server, Status.READY);

        if (rc.isFailed()) {
            msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
            logger.error(msg);
            throw new RequestFailedException("Rebuild Server", msg, HttpStatus.BAD_GATEWAY_502, server);
        }
        rc.reset();
    }

    /**
     * Looks up the indicated server using the provided context and returns the server to the caller
     *
     * @param rc
     *            The request context
     * @param context
     *            The provider context
     * @param id
     *            The id of the server
     * @return The server, or null if there is a problem
     * @throws ZoneException
     *             If the server cannot be found
     * @throws RequestFailedException
     *             If the server cannot be found because we cant connect to the provider
     */
    @SuppressWarnings("nls")
    private Server lookupServer(RequestContext rc, Context context, String id)
        throws ZoneException, RequestFailedException {
        ComputeService service = context.getComputeService();
        Server server = null;
        String msg;
        Provider provider = context.getProvider();

        while (rc.attempt()) {
            try {
                server = service.getServer(id);
                break;
            } catch (ContextConnectionException e) {
                msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
                    context.getTenant().getName(), context.getTenant().getId(), e.getMessage(),
                    Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
                    Integer.toString(rc.getRetryLimit()));
                logger.error(msg, e);
                rc.delay();
            }
        }
        if (rc.isFailed()) {
            msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
            logger.error(msg);
            doFailure(rc, HttpStatus.BAD_GATEWAY_502, msg);
            throw new RequestFailedException("Lookup Server", msg, HttpStatus.BAD_GATEWAY_502, server);
        }
        return server;
    }

    private String getConnectionExceptionMessage(RequestContext rc, Context ctx, ContextConnectionException e)
        throws ZoneException {
        return EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, ctx.getProvider().getName(),
            ctx.getComputeService().getURL(), ctx.getTenant().getName(), ctx.getTenant().getId(), e.getMessage(),
            Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
            Integer.toString(rc.getRetryLimit()));
    }

    private ProviderCache createProviderCache(VMURL vm, IdentityURL ident) {
        if (vm != null && ident != null) {
            ProviderCache cache = new ProviderCache();

            cache.setIdentityURL(ident.toString());
            cache.setProviderName(ident.toString());
            // cache.setProviderType("OpenStack");

            TenantCache tenant = cache.addTenant(vm.getTenantId(),null, DEFAULT_USER, DEFAULT_PASS);

            // Make sure we could initialize the the cache otherwise return null
            if (tenant != null && tenant.isInitialized()) {
                return cache;
            }
        }
        return null;
    }

    /**
     * This method is used to delete an existing virtual machine given the fully qualified URL of the machine.
     * <p>
     * The fully qualified URL contains enough information to locate the appropriate server. The URL is of the form
     * <pre>
     *  [scheme]://[host[:port]] / [path] / [tenant_id] / servers / [vm_id]
     * </pre> Where the various parts of the URL can be parsed and extracted and used to locate the appropriate service
     * in the provider service catalog. This then allows us to open a context using the CDP abstraction, obtain the
     * server by its UUID, and then perform the restart.
     * </p>
     *
     * @throws UnknownProviderException
     *             If the provider cannot be found
     * @throws IllegalArgumentException
     *             if the expected argument(s) are not defined or are invalid
     * @see org.openecomp.appc.adapter.iaas.ProviderAdapter#terminateServer(java.util.Map, org.openecomp.sdnc.sli.SvcLogicContext)
     */
    @SuppressWarnings("nls")
    @Override
    public Server terminateServer(Map<String, String> params, SvcLogicContext ctx)
        throws UnknownProviderException, IllegalArgumentException {
        Server server = null;
        RequestContext rc = new RequestContext(ctx);
        rc.isAlive();
        MDC.put(MDC_ADAPTER, ADAPTER_NAME);
        MDC.put(MDC_SERVICE, TERMINATE_SERVICE);
        MDC.put(MDC_SERVICE_NAME, "App-C IaaS Adapter:Terminate");
        String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
		if (logger.isDebugEnabled()) {
			logger.debug("Inside org.openecomp.appc.adapter.iaas.impl.ProviderAdapter.terminateServer");
		}

        try {
            validateParametersExist(rc, params, ProviderAdapter.PROPERTY_INSTANCE_URL,
                ProviderAdapter.PROPERTY_PROVIDER_NAME);
            debugParameters(params);
            debugContext(ctx);
            String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
            ctx.setAttribute("TERMINATE_STATUS", "SUCCESS");

            VMURL vm = VMURL.parseURL(vm_url);
            if (validateVM(rc, appName, vm_url, vm)) return null;

            IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
            String identStr = (ident == null) ? null : ident.toString();

            Context context = null;
            try {
                context = getContext(rc, vm_url, identStr);
                if (context != null) {
                    server = lookupServer(rc, context, vm.getServerId());
                    logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString());
                    logger.info(EELFResourceManager.format(Msg.TERMINATING_SERVER, server.getName()));
                    terminateServer(rc, server);
                    logger.info(EELFResourceManager.format(Msg.TERMINATE_SERVER, server.getName()));
                    context.close();
                    doSuccess(rc);
                }else{
                    ctx.setAttribute("TERMINATE_STATUS", "SERVER_NOT_FOUND");
                }
            } catch (ResourceNotFoundException e) {
                String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url);
                logger.error(msg);
                doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
                ctx.setAttribute("TERMINATE_STATUS", "SERVER_NOT_FOUND");
            } catch (Throwable t) {
                String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(),
                    RESTART_SERVICE, vm_url, context == null ? "Unknown" : context.getTenantName());
                logger.error(msg, t);
                doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
            }
        } catch (RequestFailedException e) {
            logger.error(EELFResourceManager.format(Msg.TERMINATE_SERVER_FAILED, appName, "n/a", "n/a", e.getMessage()));
            doFailure(rc, e.getStatus(), e.getMessage());
            ctx.setAttribute("TERMINATE_STATUS", "ERROR");
        }

        return server;
    }

    /**
     * This method handles the case of restarting a server once we have found the server and have obtained the abstract
     * representation of the server via the context (i.e., the "Server" object from the CDP-Zones abstraction).
     *
     * @param rc
     *            The request context that manages the state and recovery of the request for the life of its processing.
     * @param server
     *            The server object representing the server we want to operate on
     * @throws ZoneException
     */
    @SuppressWarnings("nls")
    private void terminateServer(RequestContext rc, Server server) throws ZoneException, RequestFailedException {
        /*
         * Pending is a bit of a special case. If we find the server is in a pending state, then the provider is in the
         * process of changing state of the server. So, lets try to wait a little bit and see if the state settles down
         * to one we can deal with. If not, then we have to fail the request.
         */
        String msg;
        if (server.getStatus().equals(Status.PENDING)) {
            waitForStateChange(rc, server, Status.READY, Status.RUNNING, Status.ERROR, Status.SUSPENDED, Status.PAUSED);
        }

        /*
         * We determine what to do based on the current state of the server
         */
        switch (server.getStatus()) {
            case DELETED:
                // Nothing to do, the server is gone
                msg = EELFResourceManager.format(Msg.SERVER_DELETED, server.getName(), server.getId(),
                    server.getTenantId(), "restarted");
                generateEvent(rc, false, msg);
                logger.error(msg);
                break;

            case RUNNING:
                // Attempt to stop and start the server
                logger.info("stopping SERVER");
                stopServer(rc, server);
                deleteServer(rc, server);
                logger.info("after delete SERVER");
                generateEvent(rc, true, OUTCOME_SUCCESS);
                break;

            case ERROR:

            case READY:

            case PAUSED:

            case SUSPENDED:
                // Attempt to delete the suspended server
                deleteServer(rc, server);
                generateEvent(rc, true, OUTCOME_SUCCESS);
                break;

            default:
                // Hmmm, unknown status, should never occur
                msg = EELFResourceManager.format(Msg.UNKNOWN_SERVER_STATE, server.getName(), server.getId(),
                    server.getTenantId(), server.getStatus().name());
                generateEvent(rc, false, msg);
                logger.error(msg);
                break;
        }

    }

    /**
     * Start the server and wait for it to enter a running state
     *
     * @param rc
     *            The request context that manages the state and recovery of the request for the life of its processing.
     * @param server
     *            The server to be started
     * @throws ZoneException
     * @throws RequestFailedException
     */
    @SuppressWarnings("nls")
    private void deleteServer(RequestContext rc, Server server) throws ZoneException, RequestFailedException {
        String msg;
        Context context = server.getContext();
        Provider provider = context.getProvider();
        ComputeService service = context.getComputeService();
        while (rc.attempt()) {
            try {
                logger.info("deleting SERVER");
                server.delete();
                break;
            } catch (ContextConnectionException e) {
                msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
                    context.getTenant().getName(), context.getTenant().getId(), e.getMessage(),
                    Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
                    Integer.toString(rc.getRetryLimit()));
                logger.error(msg, e);
                rc.delay();
            }
        }
        if (rc.isFailed()) {
            msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
            logger.error(msg);
            throw new RequestFailedException("Delete Server", msg, HttpStatus.BAD_GATEWAY_502, server);
        }
        rc.reset();
    }

    private boolean hasImageAccess(@SuppressWarnings("unused") RequestContext rc, Context context) {
        logger.info("Checking permissions for image service.");
        try {
            ImageService service = context.getImageService();
            service.getImageByName("CHECK_IMAGE_ACCESS");
            logger.info("Image service is accessible.");
            return true;
        } catch (ZoneException e) {
            logger.warn("Image service could not be accessed. Some operations may fail.", e);
            return false;
        }
    }

    @SuppressWarnings("nls")
    @Override
    public Stack terminateStack(Map<String, String> params, SvcLogicContext ctx) throws IllegalArgumentException, APPCException {
        Stack stack = null;
        RequestContext rc = new RequestContext(ctx);
        rc.isAlive();

        ctx.setAttribute("TERMINATE_STATUS", "STACK_NOT_FOUND");
        String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);

        try {

            logAndValidate(params, ctx, rc, TERMINATE_STACK, "Terminate Stack",
                            ProviderAdapter.PROPERTY_INSTANCE_URL,
                            ProviderAdapter.PROPERTY_PROVIDER_NAME,
                            ProviderAdapter.PROPERTY_STACK_ID);

            String stackId = params.get(ProviderAdapter.PROPERTY_STACK_ID);
            String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);

            Context context = resolveContext(rc, params, appName, vm_url);

            try {
                if (context != null) {
                    stack = lookupStack(rc, context, stackId);
                    logger.debug(Msg.STACK_FOUND, vm_url, context.getTenantName(), stack.getStatus().toString());
                    logger.info(EELFResourceManager.format(Msg.TERMINATING_STACK, stack.getName()));
                    deleteStack(rc, stack);
                    logger.info(EELFResourceManager.format(Msg.TERMINATE_STACK, stack.getName()));
                    context.close();
                    doSuccess(rc);
                }else{
                    ctx.setAttribute("TERMINATE_STATUS", "SERVER_NOT_FOUND");
                }
            } catch (ResourceNotFoundException e) {
                String msg = EELFResourceManager.format(Msg.STACK_NOT_FOUND, e, vm_url);
                logger.error(msg);
                doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
            } catch (Throwable t) {
                String msg = EELFResourceManager.format(Msg.STACK_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(),
                    TERMINATE_STACK, vm_url, context.getTenantName());
                logger.error(msg, t);
                doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
            }
        } catch (RequestFailedException e) {
            logger.error(EELFResourceManager.format(Msg.TERMINATE_STACK_FAILED, appName, "n/a", "n/a"));
            doFailure(rc, e.getStatus(), e.getMessage());
        }
        return stack;
    }

    @Override
    public Stack snapshotStack(Map<String, String> params, SvcLogicContext ctx) throws IllegalArgumentException, APPCException {
        Stack stack = null;
        RequestContext rc = new RequestContext(ctx);
        rc.isAlive();

        ctx.setAttribute("SNAPSHOT_STATUS", "STACK_NOT_FOUND");
        String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);

        String vm_url = null;
        Context context = null;
        try {

            logAndValidate(params, ctx, rc, SNAPSHOT_STACK, "Snapshot Stack",
                            ProviderAdapter.PROPERTY_INSTANCE_URL,
                            ProviderAdapter.PROPERTY_PROVIDER_NAME,
                            ProviderAdapter.PROPERTY_STACK_ID);

            String stackId = params.get(ProviderAdapter.PROPERTY_STACK_ID);
            vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);

            context = resolveContext(rc, params, appName, vm_url);

            if (context != null) {
                stack = lookupStack(rc, context, stackId);
                logger.debug(Msg.STACK_FOUND, vm_url, context.getTenantName(), stack.getStatus().toString());
                logger.info(EELFResourceManager.format(Msg.SNAPSHOTING_STACK, stack.getName()));

                Snapshot snapshot = snapshotStack(rc, stack);

                ctx.setAttribute(ProviderAdapter.DG_OUTPUT_PARAM_NAMESPACE +
                                ProviderAdapter.PROPERTY_SNAPSHOT_ID, snapshot.getId());

                logger.info(EELFResourceManager.format(Msg.STACK_SNAPSHOTED, stack.getName(), snapshot.getId()));
                context.close();
                doSuccess(rc);
            } else {
                ctx.setAttribute(Constants.DG_ATTRIBUTE_STATUS, "failure");
            }

        } catch (ResourceNotFoundException e) {
            String msg = EELFResourceManager.format(Msg.STACK_NOT_FOUND, e, vm_url);
            logger.error(msg);
            doFailure(rc, HttpStatus.NOT_FOUND_404, msg, e);
        } catch (RequestFailedException e) {
            logger.error(EELFResourceManager.format(Msg.MISSING_PARAMETER_IN_REQUEST, e.getReason(), "snapshotStack"));
            doFailure(rc, e.getStatus(), e.getMessage(), e);
        } catch (Throwable t) {
            String msg = EELFResourceManager.format(Msg.STACK_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(),
                            "snapshotStack", vm_url, null == context ? "n/a" : context.getTenantName());
            logger.error(msg, t);
            doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg, t);
        }
        return stack;
    }

    @Override
    public Stack restoreStack(Map<String, String> params, SvcLogicContext ctx) throws IllegalArgumentException, APPCException {
        Stack stack = null;
        RequestContext rc = new RequestContext(ctx);
        rc.isAlive();

        ctx.setAttribute("SNAPSHOT_STATUS", "STACK_NOT_FOUND");
        String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);

        String vm_url = null;
        Context context = null;

        try {

            logAndValidate(params, ctx, rc, SNAPSHOT_STACK, "Snapshot Stack",
                            ProviderAdapter.PROPERTY_INSTANCE_URL,
                            ProviderAdapter.PROPERTY_PROVIDER_NAME,
                            ProviderAdapter.PROPERTY_STACK_ID,
                            ProviderAdapter.PROPERTY_INPUT_SNAPSHOT_ID);

            String stackId = params.get(ProviderAdapter.PROPERTY_STACK_ID);
            vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);

            String snapshotId = params.get(ProviderAdapter.PROPERTY_INPUT_SNAPSHOT_ID);

            context = resolveContext(rc, params, appName, vm_url);

            if (context != null) {
                stack = lookupStack(rc, context, stackId);
                logger.debug(Msg.STACK_FOUND, vm_url, context.getTenantName(), stack.getStatus().toString());
                logger.info(EELFResourceManager.format(Msg.RESTORING_STACK, stack.getName(), snapshotId));
                restoreStack(stack, snapshotId);
                logger.info(EELFResourceManager.format(Msg.STACK_RESTORED, stack.getName(), snapshotId));
                context.close();
                doSuccess(rc);
            } else {
                ctx.setAttribute(Constants.DG_ATTRIBUTE_STATUS, "failure");
            }

        } catch (ResourceNotFoundException e) {
            String msg = EELFResourceManager.format(Msg.STACK_NOT_FOUND, e, vm_url);
            logger.error(msg);
            doFailure(rc, HttpStatus.NOT_FOUND_404, msg, e);
        } catch (RequestFailedException e) {
            logger.error(EELFResourceManager.format(Msg.MISSING_PARAMETER_IN_REQUEST, e.getReason(), "restoreStack"));
            doFailure(rc, e.getStatus(), e.getMessage(), e);
        } catch (Throwable t) {
            String msg = EELFResourceManager.format(Msg.STACK_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(),
                            "restoreStack", vm_url, null == context ? "n/a" : context.getTenantName());
            logger.error(msg, t);
            doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg, t);
        }
        return stack;
    }

    private void logAndValidate(Map<String, String> params, SvcLogicContext ctx, RequestContext rc, String methodName, String serviceName, String ... attributes)
                    throws RequestFailedException {
        MDC.put(MDC_ADAPTER, ADAPTER_NAME);
        MDC.put(MDC_SERVICE, SNAPSHOT_STACK);
        MDC.put(MDC_SERVICE_NAME, String.format("App-C IaaS Adapter:%s", serviceName));
        if (logger.isDebugEnabled()) {
            logger.debug(String.format("Inside org.openecomp.appc.adapter.iaas.impl.ProviderAdapter.%s", methodName));
        }

        validateParametersExist(rc, params, attributes);

        debugParameters(params);
        debugContext(ctx);
    }

    private Context resolveContext(RequestContext rc, Map<String, String> params, String appName, String vm_url)
                    throws RequestFailedException {

        VMURL vm = VMURL.parseURL(vm_url);
        if (vm == null) {
            String msg = EELFResourceManager.format(Msg.INVALID_SELF_LINK_URL, appName, vm_url);
            doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
            logger.error(msg);
            return null;
        }
        validateVMURL(vm);
        IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
        String identStr = (ident == null) ? null : ident.toString();

        return getContext(rc, vm_url, identStr);

    }

    private void deleteStack(RequestContext rc, Stack stack) throws ZoneException, RequestFailedException {
        SvcLogicContext ctx = rc.getSvcLogicContext();
        Context context = stack.getContext();
        StackService stackService = context.getStackService();
        logger.debug("Deleting Stack: " + "id:{ " + stack.getId() + "}");
        stackService.deleteStack(stack);

        // wait for the stack deletion
        boolean success = waitForStackStatus(rc, stack, Stack.Status.DELETED);
        if (success) {
            ctx.setAttribute("TERMINATE_STATUS", "SUCCESS");
        } else {
            ctx.setAttribute("TERMINATE_STATUS", "ERROR");
            throw new RequestFailedException("Delete Stack failure : " + Msg.STACK_OPERATION_EXCEPTION.toString());
        }
    }

    private boolean waitForStackStatus(RequestContext rc, Stack stack, Stack.Status expectedStatus) throws ZoneException, RequestFailedException {
        SvcLogicContext ctx = rc.getSvcLogicContext();
        Context context = stack.getContext();
        StackService stackService = context.getStackService();

        int pollInterval = configuration.getIntegerProperty(Constants.PROPERTY_OPENSTACK_POLL_INTERVAL);
        int timeout = configuration.getIntegerProperty(Constants.PROPERTY_STACK_STATE_CHANGE_TIMEOUT);
        long maxTimeToWait = System.currentTimeMillis() + (long) timeout * 1000;
        Stack.Status stackStatus;
        while (System.currentTimeMillis() < maxTimeToWait) {
            stackStatus = stackService.getStack(stack.getName(), stack.getId()).getStatus();
            logger.debug("Stack status : " + stackStatus.toString());
            if (stackStatus == expectedStatus) {
                return true;
            } else if (stackStatus == Stack.Status.FAILED) {
                return false;
            } else {
                try {
                    Thread.sleep(pollInterval * 1000);
                } catch (InterruptedException e) {
                    logger.trace("Sleep threw interrupted exception, should never occur");
                }
            }
        }

        ctx.setAttribute("TERMINATE_STATUS", "ERROR");
        throw new TimeoutException("Timeout waiting for stack status change");

    }

    private Snapshot snapshotStack(@SuppressWarnings("unused") RequestContext rc, Stack stack) throws ZoneException, RequestFailedException {
        Snapshot snapshot = new Snapshot();
        Context context = stack.getContext();

        OpenStackContext osContext = (OpenStackContext)context;

        final HeatConnector heatConnector = osContext.getHeatConnector();
        ((OpenStackContext)context).refreshIfStale(heatConnector);

        trackRequest(context);
        RequestState.put("SERVICE", "Orchestration");
        RequestState.put("SERVICE_URL", heatConnector.getEndpoint());

        Heat heat = heatConnector.getClient();

        SnapshotResource snapshotResource = new SnapshotResource(heat);

        try {

            snapshot = snapshotResource.create(stack.getName(), stack.getId(), new CreateSnapshotParams()).execute();

            // wait for the stack deletion
            StackResource stackResource = new StackResource(heat);
            if (!waitForStack(stack, stackResource, "SNAPSHOT_COMPLETE")) {
                throw new RequestFailedException("Stack Snapshot failed.");
            }

        } catch (OpenStackBaseException e) {
            ExceptionMapper.mapException(e);
        }

        return snapshot;
    }

    private void restoreStack(Stack stack, String snapshotId) throws ZoneException, RequestFailedException {
        Context context = stack.getContext();

        OpenStackContext osContext = (OpenStackContext)context;

        final HeatConnector heatConnector = osContext.getHeatConnector();
        ((OpenStackContext)context).refreshIfStale(heatConnector);

        trackRequest(context);
        RequestState.put("SERVICE", "Orchestration");
        RequestState.put("SERVICE_URL", heatConnector.getEndpoint());

        Heat heat = heatConnector.getClient();

        SnapshotResource snapshotResource = new SnapshotResource(heat);

        try {

            snapshotResource.restore(stack.getName(), stack.getId(), snapshotId).execute();

            // wait for the snapshot restore
            StackResource stackResource = new StackResource(heat);
            if (!waitForStack(stack, stackResource, "RESTORE_COMPLETE")) {
                throw new RequestFailedException("Snapshot restore failed.");
            }

        } catch (OpenStackBaseException e) {
            ExceptionMapper.mapException(e);
        }

    }

    private boolean waitForStack(Stack stack, StackResource stackResource, String expectedStatus)
                    throws OpenStackBaseException, TimeoutException {
        int pollInterval = configuration.getIntegerProperty(Constants.PROPERTY_OPENSTACK_POLL_INTERVAL);
        int timeout = configuration.getIntegerProperty(Constants.PROPERTY_STACK_STATE_CHANGE_TIMEOUT);
        long maxTimeToWait = System.currentTimeMillis() + (long) timeout * 1000;

        while (System.currentTimeMillis() < maxTimeToWait) {
            String stackStatus = stackResource.show(stack.getName(), stack.getId()).execute().getStackStatus();
            logger.debug("Stack status : " + stackStatus);
            if (stackStatus.toUpperCase().contains("FAILED")) return false;
            if(checkStatus(expectedStatus, pollInterval, stackStatus)) return true;
        }
        throw new TimeoutException("Timeout waiting for stack status change");
    }

    private boolean checkStatus(String expectedStatus, int pollInterval, String actualStatus) {
        if (actualStatus.toUpperCase().equals(expectedStatus)) {
            return true;
        } else {
            try {
                Thread.sleep(pollInterval * 1000);
            } catch (InterruptedException ignored) {
            }
        }
        return false;
    }

    private void trackRequest(Context context, AbstractService.State... states) {
        RequestState.clear();

        if (null == states) return;
        for (AbstractService.State state : states) {
            RequestState.put(state.getName(), state.getValue());
        }

        Thread currentThread = Thread.currentThread();
        StackTraceElement[] stack = currentThread.getStackTrace();
        if (stack != null && stack.length > 0) {
            int index = 0;
            StackTraceElement element;
            for (; index < stack.length; index++) {
                element = stack[index];
                if ("trackRequest".equals(element.getMethodName())) {  //$NON-NLS-1$
                    break;
                }
            }
            index++;

            if (index < stack.length) {
                element = stack[index];
                RequestState.put(RequestState.METHOD, element.getMethodName());
                RequestState.put(RequestState.CLASS, element.getClassName());
                RequestState.put(RequestState.LINE_NUMBER, Integer.toString(element.getLineNumber()));
                RequestState.put(RequestState.THREAD, currentThread.getName());
                RequestState.put(RequestState.PROVIDER, context.getProvider().getName());
                RequestState.put(RequestState.TENANT, context.getTenantName());
                RequestState.put(RequestState.PRINCIPAL, context.getPrincipal());
            }
        }
    }

    private Stack lookupStack(RequestContext rc, Context context, String id)
        throws ZoneException, RequestFailedException {
        StackService stackService = context.getStackService();
        Stack stack = null;
        String msg;
        Provider provider = context.getProvider();
        while (rc.attempt()) {
            try {
                List<Stack> stackList = stackService.getStacks();
                for (Stack stackObj : stackList) {
                    if (stackObj.getId().equals(id)) {
                        stack = stackObj;
                        break;
                    }
                }
                break;
            } catch (ContextConnectionException e) {
                msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), stackService.getURL(),
                    context.getTenant().getName(), context.getTenant().getId(), e.getMessage(),
                    Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
                    Integer.toString(rc.getRetryLimit()));
                logger.error(msg, e);
                rc.delay();
            }

        }
        if (rc.isFailed()) {
            msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), stackService.getURL());
            logger.error(msg);
            doFailure(rc, HttpStatus.BAD_GATEWAY_502, msg);
            throw new RequestFailedException("Lookup Stack", msg, HttpStatus.BAD_GATEWAY_502, stack);
        }

        if (stack == null) {
            throw new ResourceNotFoundException("Stack not found with Id : {" + id + "}");
        }
        return stack;
    }

    @SuppressWarnings("nls")
    @Override
    public Server lookupServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
        Server server = null;
        RequestContext rc = new RequestContext(ctx);
        rc.isAlive(); //should we test the return and fail if false?
        MDC.put(MDC_ADAPTER, ADAPTER_NAME);
        MDC.put(MDC_SERVICE, LOOKUP_SERVICE);
        MDC.put(MDC_SERVICE_NAME, "App-C IaaS Adapter:LookupServer");
        String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);

        //for debugging merge into single method?
        debugParameters(params);
        debugContext(ctx);

        String vm_url = null;
        VMURL vm = null;
        try {

            //process vm_url
            validateParametersExist(rc, params, ProviderAdapter.PROPERTY_INSTANCE_URL,
                ProviderAdapter.PROPERTY_PROVIDER_NAME);
            vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
            vm = VMURL.parseURL(vm_url);
            if (validateVM(rc, appName, vm_url, vm)) return null;


            //use try with resource to ensure context is closed (returned to pool)
            try(Context context = resolveContext(rc, params, appName, vm_url)){
              //resloveContext & getContext call doFailure and log errors before returning null
                if (context != null){
                    server = lookupServer(rc, context, vm.getServerId());
                    logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString());
                    ctx.setAttribute("serverFound", "success");
                    doSuccess(rc);
                }
            } catch (ZoneException e) {
                //server not found
                String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url);
                logger.error(msg);
                doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
                ctx.setAttribute("serverFound", "failure");
            }  catch (IOException e) {
                //exception closing context
                String msg = EELFResourceManager.format(Msg.CLOSE_CONTEXT_FAILED, e, vm_url);
                logger.error(msg);
            } catch (Throwable t) {
                String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(),
                    LOOKUP_SERVICE, vm_url,  "Unknown" );
                logger.error(msg, t);
                doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
            }

        } catch (RequestFailedException e) {
            // parameters not valid, unable to connect to provider
            String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url);
            logger.error(msg);
            doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
            ctx.setAttribute("serverFound", "failure");
        }
        return server;
    }
}