summaryrefslogtreecommitdiff
path: root/cinder/volume/drivers/hpe/hpe_3par_common.py
blob: 2d9534a16f6a0af4a9b01babe0408a8f6be0bd11 (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
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
#    (c) Copyright 2012-2016 Hewlett Packard Enterprise Development LP
#    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.
#
"""Volume driver common utilities for HPE 3PAR Storage array.

The 3PAR drivers requires 3.1.3 firmware on the 3PAR array.

You will need to install the python hpe3parclient module.
sudo pip install python-3parclient

The drivers uses both the REST service and the SSH
command line to correctly operate.  Since the
ssh credentials and the REST credentials can be different
we need to have settings for both.

The drivers requires the use of the san_ip, san_login,
san_password settings for ssh connections into the 3PAR
array.   It also requires the setting of
hpe3par_api_url, hpe3par_username, hpe3par_password
for credentials to talk to the REST service on the 3PAR
array.
"""

import ast
import json
import math
import pprint
import re
import uuid

from oslo_config import cfg
from oslo_log import log as logging
from oslo_log import versionutils
from oslo_serialization import base64
from oslo_service import loopingcall
from oslo_utils import excutils
from oslo_utils import units
import six
import taskflow.engines
from taskflow.patterns import linear_flow

from cinder import context
from cinder import exception
from cinder import flow_utils
from cinder.i18n import _
from cinder import objects
from cinder.objects import fields
from cinder import utils
from cinder.volume import configuration
from cinder.volume import driver
from cinder.volume import qos_specs
from cinder.volume import volume_types
from cinder.volume import volume_utils

try:
    import hpe3parclient
    from hpe3parclient import client
    from hpe3parclient import exceptions as hpeexceptions
except ImportError:
    hpe3parclient = None
    client = None
    hpeexceptions = None

LOG = logging.getLogger(__name__)

MIN_CLIENT_VERSION = '4.2.10'
DEDUP_API_VERSION = 30201120
FLASH_CACHE_API_VERSION = 30201200
COMPRESSION_API_VERSION = 30301215
SRSTATLD_API_VERSION = 30201200
REMOTE_COPY_API_VERSION = 30202290
API_VERSION_2023 = 100000000

hpe3par_opts = [
    cfg.StrOpt('hpe3par_api_url',
               default='',
               help="WSAPI Server URL. "
                    "This setting applies to: 3PAR, Primera and Alletra 9k "
                    "\n       Example 1: for 3PAR, URL is: "
                    "\n       https://<3par ip>:8080/api/v1 "
                    "\n       Example 2: for Primera/Alletra 9k, URL is: "
                    "\n       https://<primera ip>:443/api/v1"),
    cfg.StrOpt('hpe3par_username',
               default='',
               help="3PAR/Primera/Alletra 9k username with the 'edit' role"),
    cfg.StrOpt('hpe3par_password',
               default='',
               help="3PAR/Primera/Alletra 9k password for the user specified "
                    "in hpe3par_username",
               secret=True),
    cfg.ListOpt('hpe3par_cpg',
                default=["OpenStack"],
                help="List of the 3PAR/Primera/Alletra 9k CPG(s) to use for "
                     "volume creation"),
    cfg.StrOpt('hpe3par_cpg_snap',
               default="",
               help="The 3PAR/Primera/Alletra 9k CPG to use for snapshots of "
                    "volumes. If empty the userCPG will be used."),
    cfg.StrOpt('hpe3par_snapshot_retention',
               default="",
               help="The time in hours to retain a snapshot.  "
                    "You can't delete it before this expires."),
    cfg.StrOpt('hpe3par_snapshot_expiration',
               default="",
               help="The time in hours when a snapshot expires "
                    " and is deleted.  This must be larger than expiration"),
    cfg.BoolOpt('hpe3par_debug',
                default=False,
                help="Enable HTTP debugging to 3PAR/Primera/Alletra 9k"),
    cfg.ListOpt('hpe3par_iscsi_ips',
                default=[],
                help="List of target iSCSI addresses to use."),
    cfg.BoolOpt('hpe3par_iscsi_chap_enabled',
                default=False,
                help="Enable CHAP authentication for iSCSI connections."),
    cfg.StrOpt('hpe3par_target_nsp',
               default="",
               help="The nsp of 3PAR/Primera/Alletra 9k backend to be used "
                    "when: (1) multipath is not enabled in cinder.conf. "
                    "(2) Fiber Channel Zone Manager is not used. "
                    "(3) the backend is prezoned with this "
                    "specific nsp only. For example if nsp is 2 1 2, the "
                    "format of the option's value is 2:1:2"),
]


CONF = cfg.CONF
CONF.register_opts(hpe3par_opts, group=configuration.SHARED_CONF_GROUP)

# Input/output (total read/write) operations per second.
THROUGHPUT = 'throughput'
# Data processed (total read/write) per unit time: kilobytes per second.
BANDWIDTH = 'bandwidth'
# Response time (total read/write): microseconds.
LATENCY = 'latency'
# IO size (total read/write): kilobytes.
IO_SIZE = 'io_size'
# Queue length for processing IO requests
QUEUE_LENGTH = 'queue_length'
# Average busy percentage
AVG_BUSY_PERC = 'avg_busy_perc'


class Invalid3PARDomain(exception.VolumeDriverException):
    message = _("Invalid 3PAR Domain: %(err)s")


class HPE3PARCommon(object):
    """Class that contains common code for the 3PAR drivers.

    Version history:

    .. code-block:: none

        1.2.0 - Updated hp3parclient API use to 2.0.x
        1.2.1 - Check that the VVS exists
        1.2.2 - log prior to raising exceptions
        1.2.3 - Methods to update key/value pair bug #1258033
        1.2.4 - Remove deprecated config option hp3par_domain
        1.2.5 - Raise Ex when deleting snapshot with dependencies bug #1250249
        1.2.6 - Allow optional specifying n:s:p for vlun creation bug #1269515
                This update now requires 3.1.2 MU3 firmware
        1.3.0 - Removed all SSH code.  We rely on the hp3parclient now.
        2.0.0 - Update hp3parclient API uses 3.0.x
        2.0.1 - Updated to use qos_specs, added new qos settings and personas
        2.0.2 - Add back-end assisted volume migrate
        2.0.3 - Allow deleting missing snapshots bug #1283233
        2.0.4 - Allow volumes created from snapshots to be larger bug #1279478
        2.0.5 - Fix extend volume units bug #1284368
        2.0.6 - use loopingcall.wait instead of time.sleep
        2.0.7 - Allow extend volume based on snapshot bug #1285906
        2.0.8 - Fix detach issue for multiple hosts bug #1288927
        2.0.9 - Remove unused 3PAR driver method bug #1310807
        2.0.10 - Fixed an issue with 3PAR vlun location bug #1315542
        2.0.11 - Remove hp3parclient requirement from unit tests #1315195
        2.0.12 - Volume detach hangs when host is in a host set bug #1317134
        2.0.13 - Added support for managing/unmanaging of volumes
        2.0.14 - Modified manage volume to use standard 'source-name' element.
        2.0.15 - Added support for volume retype
        2.0.16 - Add a better log during delete_volume time. Bug #1349636
        2.0.17 - Added iSCSI CHAP support
                 This update now requires 3.1.3 MU1 firmware
                 and hp3parclient 3.1.0
        2.0.18 - HP 3PAR manage_existing with volume-type support
        2.0.19 - Update default persona from Generic to Generic-ALUA
        2.0.20 - Configurable SSH missing key policy and known hosts file
        2.0.21 - Remove bogus invalid snapCPG=None exception
        2.0.22 - HP 3PAR drivers should not claim to have 'infinite' space
        2.0.23 - Increase the hostname size from 23 to 31  Bug #1371242
        2.0.24 - Add pools (hp3par_cpg now accepts a list of CPGs)
        2.0.25 - Migrate without losing type settings bug #1356608
        2.0.26 - Don't ignore extra-specs snap_cpg when missing cpg #1368972
        2.0.27 - Fixing manage source-id error bug #1357075
        2.0.28 - Removing locks bug #1381190
        2.0.29 - Report a limitless cpg's stats better bug #1398651
        2.0.30 - Update the minimum hp3parclient version bug #1402115
        2.0.31 - Removed usage of host name cache #1398914
        2.0.32 - Update LOG usage to fix translations.  bug #1384312
        2.0.33 - Fix host persona to match WSAPI mapping bug #1403997
        2.0.34 - Fix log messages to match guidelines. bug #1411370
        2.0.35 - Fix default snapCPG for manage_existing bug #1393609
        2.0.36 - Added support for dedup provisioning
        2.0.37 - Added support for enabling Flash Cache
        2.0.38 - Add stats for hp3par goodness_function and filter_function
        2.0.39 - Added support for updated detach_volume attachment.
        2.0.40 - Make the 3PAR drivers honor the pool in create  bug #1432876
        2.0.41 - Only log versions at startup.  bug #1447697
        2.0.42 - Fix type for snapshot config settings. bug #1461640
        2.0.43 - Report the capability of supporting multiattach
        2.0.44 - Update help strings to reduce the 3PAR user role requirements
        2.0.45 - Python 3 fixes
        2.0.46 - Improved VLUN creation and deletion logic. #1469816
        2.0.47 - Changed initialize_connection to use getHostVLUNs. #1475064
        2.0.48 - Adding changes to support 3PAR iSCSI multipath.
        2.0.49 - Added client CPG stats to driver volume stats. bug #1482741
        2.0.50 - Add over subscription support
        2.0.51 - Adds consistency group support
        2.0.52 - Added update_migrated_volume. bug #1492023
        2.0.53 - Fix volume size conversion. bug #1513158
        3.0.0 - Rebranded HP to HPE.
        3.0.1 - Fixed find_existing_vluns bug #1515033
        3.0.2 - Python 3 support
        3.0.3 - Remove db access for consistency groups
        3.0.4 - Adds v2 managed replication support
        3.0.5 - Adds v2 unmanaged replication support
        3.0.6 - Adding manage/unmanage snapshot support
        3.0.7 - Enable standard capabilities based on 3PAR licenses
        3.0.8 - Optimize array ID retrieval
        3.0.9 - Bump minimum API version for volume replication
        3.0.10 - Added additional volumes checks to the manage snapshot API
        3.0.11 - Fix the image cache capability bug #1491088
        3.0.12 - Remove client version checks for replication
        3.0.13 - Support creating a cg from a source cg
        3.0.14 - Comparison of WWNs now handles case difference. bug #1546453
        3.0.15 - Update replication to version 2.1
        3.0.16 - Use same LUN ID for each VLUN path #1551994
        3.0.17 - Don't fail on clearing 3PAR object volume key. bug #1546392
        3.0.18 - create_cloned_volume account for larger size.  bug #1554740
        3.0.19 - Remove metadata that tracks the instance ID. bug #1572665
        3.0.20 - Fix lun_id of 0 issue. bug #1573298
        3.0.21 - Driver no longer fails to initialize if
                 System Reporter license is missing. bug #1568078
        3.0.22 - Rework delete_vlun. Bug #1582922
        3.0.23 - Fix CG create failures with long display name or special
                 characters. bug #1573647
        3.0.24 - Fix terminate connection on failover
        3.0.25 - Fix delete volume when online clone is active. bug #1349639
        3.0.26 - Fix concurrent snapshot delete conflict. bug #1600104
        3.0.27 - Fix snapCPG error during backup of attached volume.
                 Bug #1646396 and also ,Fix backup of attached ISCSI
                 and CHAP enabled volume.bug #1644238.
        3.0.28 - Remove un-necessary snapshot creation of source volume
                 while doing online copy in create_cloned_volume call.
                 Bug #1661541
        3.0.29 - Fix convert snapshot volume to base volume type. bug #1656186
        3.0.30 - Handle manage and unmanage hosts present. bug #1648067
        3.0.31 - Enable HPE-3PAR Compression Feature.
        3.0.32 - Add consistency group capability to generic volume group
                 in HPE-3APR
        3.0.33 - Added replication feature in retype flow. bug #1680313
        3.0.34 - Add cloned volume to vvset in online copy. bug #1664464
        3.0.35 - Add volume to consistency group if flag enabled. bug #1702317
        3.0.36 - Swap volume name in migration. bug #1699733
        3.0.37 - Fixed image cache enabled capability. bug #1686985
        3.0.38 - Fixed delete operation of replicated volume which is part
                 of QOS. bug #1717875
        3.0.39 - Add support for revert to snapshot.
        4.0.0 - Code refactor.
        4.0.1 - Added check to modify host after volume detach. bug #1730720
        4.0.2 - Added Tiramisu feature on 3PAR.
        4.0.3 - Fixed create group from source functionality in case of
                tiramisu. bug #1742092.
        4.0.4 - Fixed setting of sync_period value in rcopygroup. bug #1746235
        4.0.5 - Fixed volume created and added in cloned group,
                differs from volume present in the source group in terms of
                extra-specs. bug #1744025
        4.0.6 - Monitor task of promoting a virtual copy. bug #1749642
        4.0.7 - Handle force detach case. bug #1686745
        4.0.8 - Added support for report backend state in service list.
        4.0.9 - Set proper backend on subsequent operation, after group
                failover. bug #1773069
        4.0.10 - Added retry in delete_volume. bug #1783934
        4.0.11 - Added extra spec hpe3par:convert_to_base
        4.0.12 - Added multiattach support
        4.0.13 - Fixed detaching issue for volume with type multiattach
                 enabled. bug #1834660
        4.0.14 - Added Peer Persistence feature
        4.0.15 - Support duplicated FQDN in network. Bug #1834695
        4.0.16 - In multi host env, fix multi-detach operation. Bug #1958122
        4.0.17 - Added get_manageable_volumes and get_manageable_snapshots.
                 Bug #1819903
        4.0.18 - During conversion of volume to base volume,
                 error out if it has child snapshot(s). Bug #1994521
        4.0.19 - Update code to work with new WSAPI (of 2023). Bug #2015746


    """

    VERSION = "4.0.19"

    stats = {}

    # TODO(Ramy): move these to the 3PAR Client
    VLUN_TYPE_EMPTY = 1
    VLUN_TYPE_PORT = 2
    VLUN_TYPE_HOST = 3
    VLUN_TYPE_MATCHED_SET = 4
    VLUN_TYPE_HOST_SET = 5

    THIN = 2
    DEDUP = 6
    CONVERT_TO_THIN = 1
    CONVERT_TO_FULL = 2
    CONVERT_TO_DEDUP = 3

    # v2 replication constants
    SYNC = 1
    PERIODIC = 2
    EXTRA_SPEC_REP_MODE = "replication:mode"
    EXTRA_SPEC_REP_SYNC_PERIOD = "replication:sync_period"
    RC_ACTION_CHANGE_TO_PRIMARY = 7
    DEFAULT_REP_MODE = 'periodic'
    DEFAULT_SYNC_PERIOD = 900
    RC_GROUP_STARTED = 3
    SYNC_STATUS_COMPLETED = 3
    FAILBACK_VALUE = 'default'

    # License values for reported capabilities
    PRIORITY_OPT_LIC = "Priority Optimization"
    THIN_PROV_LIC = "Thin Provisioning"
    REMOTE_COPY_LIC = "Remote Copy"
    SYSTEM_REPORTER_LIC = "System Reporter"
    COMPRESSION_LIC = "Compression"

    # Valid values for volume type extra specs
    # The first value in the list is the default value
    valid_prov_values = ['thin', 'full', 'dedup']
    valid_persona_values = ['2 - Generic-ALUA',
                            '1 - Generic',
                            '3 - Generic-legacy',
                            '4 - HPUX-legacy',
                            '5 - AIX-legacy',
                            '6 - EGENERA',
                            '7 - ONTAP-legacy',
                            '8 - VMware',
                            '9 - OpenVMS',
                            '10 - HPUX',
                            '11 - WindowsServer']
    hpe_qos_keys = ['minIOPS', 'maxIOPS', 'minBWS', 'maxBWS', 'latency',
                    'priority']
    qos_priority_level = {'low': 1, 'normal': 2, 'high': 3}
    hpe3par_valid_keys = ['cpg', 'snap_cpg', 'provisioning', 'persona', 'vvs',
                          'flash_cache', 'compression', 'group_replication',
                          'convert_to_base']

    def __init__(self, config, active_backend_id=None):
        self.config = config
        self.client = None
        self.uuid = uuid.uuid4()
        self._client_conf = {}
        self._replication_targets = []
        self._replication_enabled = False
        self._active_backend_id = active_backend_id

    def get_version(self):
        return self.VERSION

    @classmethod
    def get_driver_options(cls):
        additional_opts = driver.BaseVD._get_oslo_driver_opts(
            'san_ip', 'san_login', 'san_password', 'reserved_percentage',
            'max_over_subscription_ratio', 'replication_device', 'target_port',
            'san_ssh_port', 'ssh_conn_timeout', 'san_private_key',
            'target_ip_address', 'unique_fqdn_network')
        return hpe3par_opts + additional_opts

    def check_flags(self, options, required_flags):
        for flag in required_flags:
            if not getattr(options, flag, None):
                msg = _('%s is not set') % flag
                LOG.error(msg)
                raise exception.InvalidInput(reason=msg)

    def check_replication_flags(self, options, required_flags):
        for flag in required_flags:
            if not options.get(flag, None):
                msg = (_('%s is not set and is required for the replication '
                         'device to be valid.') % flag)
                LOG.error(msg)
                raise exception.InvalidInput(reason=msg)

    def _create_client(self, timeout=None):
        hpe3par_api_url = self._client_conf['hpe3par_api_url']
        cl = client.HPE3ParClient(hpe3par_api_url, timeout=timeout)
        client_version = hpe3parclient.version

        if client_version < MIN_CLIENT_VERSION:
            ex_msg = (_('Invalid hpe3parclient version found (%(found)s). '
                        'Version %(minimum)s or greater required. Run "pip'
                        ' install --upgrade python-3parclient" to upgrade'
                        ' the hpe3parclient.')
                      % {'found': client_version,
                         'minimum': MIN_CLIENT_VERSION})
            LOG.error(ex_msg)
            raise exception.InvalidInput(reason=ex_msg)

        return cl

    def client_login(self):
        try:
            LOG.debug("Connecting to 3PAR")
            self.client.login(self._client_conf['hpe3par_username'],
                              self._client_conf['hpe3par_password'])
        except hpeexceptions.HTTPUnauthorized as ex:
            msg = (_("Failed to Login to 3PAR (%(url)s) because %(err)s") %
                   {'url': self._client_conf['hpe3par_api_url'], 'err': ex})
            LOG.error(msg)
            raise exception.InvalidInput(reason=msg)

    def client_logout(self):
        LOG.debug("Disconnect from 3PAR REST and SSH %s", self.uuid)
        self.client.logout()

    def _create_replication_client(self, remote_array):
        try:
            cl = client.HPE3ParClient(remote_array['hpe3par_api_url'])
            cl.login(remote_array['hpe3par_username'],
                     remote_array['hpe3par_password'])
        except hpeexceptions.HTTPUnauthorized as ex:
            msg = (_("Failed to Login to 3PAR (%(url)s) because %(err)s") %
                   {'url': remote_array['hpe3par_api_url'], 'err': ex})
            LOG.error(msg)
            raise exception.InvalidInput(reason=msg)

        return cl

    def _destroy_replication_client(self, client):
        if client is not None:
            client.logout()

    def do_setup(self, context, timeout=None, stats=None, array_id=None):
        if hpe3parclient is None:
            msg = _('You must install hpe3parclient before using 3PAR'
                    ' drivers. Run "pip install python-3parclient" to'
                    ' install the hpe3parclient.')
            raise exception.VolumeBackendAPIException(data=msg)

        try:
            # This will set self._client_conf with the proper credentials
            # to communicate with the 3PAR array. It will contain either
            # the values for the primary array or secondary array in the
            # case of a fail-over.
            self._get_3par_config(array_id=array_id)
            self.client = self._create_client(timeout=timeout)
            wsapi_version = self.client.getWsApiVersion()
            self.API_VERSION = wsapi_version['build']

            # If replication is properly configured, the primary array's
            # API version must meet the minimum requirements.
            if self._replication_enabled and (
               self.API_VERSION < REMOTE_COPY_API_VERSION):
                self._replication_enabled = False
                LOG.error("The primary array must have an API version of "
                          "%(min_ver)s or higher, but is only on "
                          "%(current_ver)s, therefore replication is not "
                          "supported.",
                          {'min_ver': REMOTE_COPY_API_VERSION,
                           'current_ver': self.API_VERSION})
        except hpeexceptions.UnsupportedVersion as ex:
            # In the event we cannot contact the configured primary array,
            # we want to allow a failover if replication is enabled.
            self._do_replication_setup(array_id=array_id)
            if self._replication_enabled:
                self.client = None
            raise exception.InvalidInput(ex)

        if context:
            # The context is None except at driver startup.
            LOG.info("HPE3PARCommon %(common_ver)s,"
                     "hpe3parclient %(rest_ver)s",
                     {"common_ver": self.VERSION,
                      "rest_ver": hpe3parclient.get_version_string()})
        if self.config.hpe3par_debug:
            self.client.debug_rest(True)
        if self.API_VERSION < SRSTATLD_API_VERSION:
            # Firmware version not compatible with srstatld
            LOG.warning("srstatld requires "
                        "WSAPI version '%(srstatld_version)s' "
                        "version '%(version)s' is installed.",
                        {'srstatld_version': SRSTATLD_API_VERSION,
                         'version': self.API_VERSION})

        # Get the client ID for provider_location. We only need to retrieve
        # the ID directly from the array if the driver stats are not provided.
        if not stats or 'array_id' not in stats:
            try:
                self.client_login()
                info = self.client.getStorageSystemInfo()
                self.client.id = six.text_type(info['id'])
            except Exception:
                self.client.id = 0
            finally:
                self.client_logout()
        else:
            self.client.id = stats['array_id']
        # TODO: This duplicate call is to see SSH logs. Remove it when issue
        # https://github.com/hpe-storage/python-3parclient/pull/77 is fixed.
        if self.config.hpe3par_debug:
            self.client.debug_rest(True)

    def check_for_setup_error(self):
        """Verify that requirements are in place to use HPE driver."""
        if not all((hpe3parclient, client, hpeexceptions)):
            msg = _('HPE driver setup error: some required '
                    'libraries (hpe3parclient, client.*) not found.')
            LOG.error(msg)
            raise exception.VolumeDriverException(message=msg)
        if self.client:
            self.client_login()
            try:
                cpg_names = self._client_conf['hpe3par_cpg']
                for cpg_name in cpg_names:
                    self.validate_cpg(cpg_name)

            finally:
                self.client_logout()

    def validate_cpg(self, cpg_name):
        try:
            self.client.getCPG(cpg_name)
        except hpeexceptions.HTTPNotFound:
            err = (_("CPG (%s) doesn't exist on array") % cpg_name)
            LOG.error(err)
            raise exception.InvalidInput(reason=err)

    def get_domain(self, cpg_name):
        try:
            cpg = self.client.getCPG(cpg_name)
        except hpeexceptions.HTTPNotFound:
            err = (_("Failed to get domain because CPG (%s) doesn't "
                     "exist on array.") % cpg_name)
            LOG.error(err)
            raise exception.InvalidInput(reason=err)

        if 'domain' in cpg:
            return cpg['domain']
        return None

    def extend_volume(self, volume, new_size):
        volume_name = self._get_3par_vol_name(volume)
        old_size = volume['size']
        growth_size = int(new_size) - old_size
        LOG.debug("Extending Volume %(vol)s from %(old)s to %(new)s, "
                  " by %(diff)s GB.",
                  {'vol': volume_name, 'old': old_size, 'new': new_size,
                   'diff': growth_size})
        growth_size_mib = growth_size * units.Ki
        self._extend_volume(volume, volume_name, growth_size_mib)

    def create_group(self, context, group):
        """Creates a group."""

        if (not volume_utils.is_group_a_cg_snapshot_type(group)
                and not group.is_replicated):
            raise NotImplementedError()

        model_update = {'status': fields.GroupStatus.AVAILABLE}

        if group.volume_type_ids is not None:
            for volume_type in group.volume_types:
                allow_type = self.is_volume_group_snap_type(
                    volume_type)
                if not allow_type:
                    msg = _('For a volume type to be a part of consistent '
                            'group, volume type extra spec must have '
                            'consistent_group_snapshot_enabled="<is> True"')
                    LOG.error(msg)
                    raise exception.InvalidInput(reason=msg)

        pool = volume_utils.extract_host(group.host, level='pool')
        domain = self.get_domain(pool)
        cg_name = self._get_3par_vvs_name(group.id)

        extra = {'group_id': group.id}
        if group.group_snapshot_id is not None:
            extra['group_snapshot_id'] = group.group_snapshot_id

        if group.is_replicated:
            LOG.debug("Group: %(group)s is a replication group.",
                      {'group': group.id})
            # Check replication configuration on each volume type
            self._check_replication_configuration_on_volume_types(
                group.volume_types)

            # Check hpe3par:group_replication flag in each volume type.
            self._check_tiramisu_configuration_on_volume_types(
                group.volume_types)

            # Attributes of Remote must be same on each volume type
            self._check_attributes_of_remote_per_volume_type(group)

            # Create remote copy group
            self._create_remote_copy_group_for_group(group)
            # Start Remote copy
            self._start_remote_copy_group(group)
            model_update.update({
                'replication_status': fields.ReplicationStatus.ENABLED})

        self.client.createVolumeSet(cg_name, domain=domain,
                                    comment=six.text_type(extra))

        return model_update

    def create_group_from_src(self, context, group, volumes,
                              group_snapshot=None, snapshots=None,
                              source_group=None, source_vols=None):

        self.create_group(context, group)
        volumes_model_update = []
        task_id_list = []
        volumes_cpg_map = []
        snap_vol_dict = {}
        replication_flag = False
        model_update = {'status': fields.GroupStatus.AVAILABLE}

        vvs_name = self._get_3par_vvs_name(group.id)
        if group_snapshot and snapshots:
            cgsnap_name = self._get_3par_snap_name(group_snapshot.id)
            snap_base = cgsnap_name
        elif source_group and source_vols:
            cg_id = source_group.id
            # Create a brand new uuid for the temp snap.
            snap_uuid = uuid.uuid4().hex

            # Create a temporary snapshot of the volume set in order to
            # perform an online copy. These temp snapshots will be deleted
            # when the source consistency group is deleted.
            temp_snap = self._get_3par_snap_name(snap_uuid, temp_snap=True)
            snap_shot_name = temp_snap + "-@count@"
            copy_of_name = self._get_3par_vvs_name(cg_id)
            optional = {'expirationHours': 1}
            self.client.createSnapshotOfVolumeSet(snap_shot_name, copy_of_name,
                                                  optional=optional)
            snap_base = temp_snap

        if group.is_replicated:
            replication_flag = True
            # Stop remote copy, so we can add volumes in RCG.
            self._stop_remote_copy_group(group)

        for i in range(0, len(volumes)):
            # In case of group created from group,we are mapping
            # source volume with it's snapshot
            snap_name = snap_base + "-" + six.text_type(i)
            snap_detail = self.client.getVolume(snap_name)
            vol_name = snap_detail.get('copyOf')
            src_vol_name = vol_name

            # In case of group created from group snapshots,we are mapping
            # source volume with it's snapshot
            if source_group is None:
                for snapshot in snapshots:
                    # Getting vol_name from snapshot, in case of group created
                    # from group snapshot.
                    # Don't use the "volume_id" from the snapshot directly in
                    # case the volume has been migrated and uses a different ID
                    # in the backend.  This may trigger OVO lazy loading.  Use
                    # dict compatibility to avoid changing all the unit tests.
                    vol_name = self._get_3par_vol_name(snapshot['volume'])
                    if src_vol_name == vol_name:
                        vol_name = (
                            self._get_3par_vol_name(snapshot.get('id')))
                        break
            LOG.debug("Source volume name: %(vol)s of snapshot: %(snap)s",
                      {'vol': src_vol_name, 'snap': snap_name})
            snap_vol_dict[vol_name] = snap_name

        for volume in volumes:
            src_vol_name = volume.get('source_volid')
            if src_vol_name is None:
                src_vol_name = volume.get('snapshot_id')

            # Finding source volume from volume and then use snap_vol_dict
            # to get right snap name from source volume.
            vol_name = self._get_3par_vol_name(src_vol_name)
            snap_name = snap_vol_dict.get(vol_name)

            volume_name = self._get_3par_vol_name(volume)
            type_info = self.get_volume_settings_from_type(volume)
            cpg = type_info['cpg']
            snapcpg = type_info['snap_cpg']
            tpvv = type_info.get('tpvv', False)
            tdvv = type_info.get('tdvv', False)
            volumes_cpg_map.append((volume, volume_name, cpg))

            compression = self.get_compression_policy(
                type_info['hpe3par_keys'])

            optional = {'online': True,
                        'tpvv': tpvv, 'tdvv': tdvv}

            if self.API_VERSION < API_VERSION_2023:
                optional['snapCPG'] = snapcpg

            if compression is not None:
                optional['compression'] = compression

            body = self.client.copyVolume(snap_name, volume_name, cpg,
                                          optional)
            task_id = body['taskid']
            task_id_list.append((task_id, volume.get('id')))

        # Only in case of replication, we are waiting for tasks to complete.
        if group.is_replicated:
            for task_id, vol_id in task_id_list:
                task_status = self._wait_for_task_completion(task_id)
                if task_status['status'] is not self.client.TASK_DONE:
                    dbg = {'status': task_status, 'id': vol_id}
                    msg = _('Copy volume task failed:  '
                            'create_group_from_src_group '
                            'id=%(id)s, status=%(status)s.') % dbg
                    LOG.error(msg)
                    raise exception.CinderException(msg)
                else:
                    LOG.debug('Online copy volume completed: '
                              'create_group_from_src_group: id=%s.', vol_id)

        for volume, volume_name, cpg in volumes_cpg_map:
            if group.is_replicated:
                # Add volume to remote copy group
                self._add_vol_to_remote_copy_group(group, volume)
            self.client.addVolumeToVolumeSet(vvs_name, volume_name)

            volume_model_update = self._get_model_update(
                volume.get('host'), cpg, replication=replication_flag,
                provider_location=self.client.id)

            if volume_model_update is not None:
                volume_model_update.update({'id': volume.get('id')})
                # Update volumes_model_update
                volumes_model_update.append(volume_model_update)

        if group.is_replicated:
            # Start remote copy.
            self._start_remote_copy_group(group)
            model_update.update({
                'replication_status': fields.ReplicationStatus.ENABLED})

        return model_update, volumes_model_update

    def delete_group(self, context, group, volumes):
        """Deletes a group."""

        if (not volume_utils.is_group_a_cg_snapshot_type(group)
           and not group.is_replicated):
            raise NotImplementedError()

        if group.is_replicated:
            self._remove_volumes_and_remote_copy_group(group, volumes)
        try:
            cg_name = self._get_3par_vvs_name(group.id)
            self.client.deleteVolumeSet(cg_name)
        except hpeexceptions.HTTPNotFound:
            LOG.warning("Virtual Volume Set '%s' doesn't exist on array.",
                        cg_name)
        except hpeexceptions.HTTPConflict as e:
            LOG.error("Conflict detected in Virtual Volume Set"
                      " %(volume_set)s: %(error)s",
                      {"volume_set": cg_name,
                       "error": e})

        volume_model_updates = []
        for volume in volumes:
            volume_update = {'id': volume.get('id')}
            try:
                self.delete_volume(volume)
                volume_update['status'] = 'deleted'
            except Exception as ex:
                LOG.error("There was an error deleting volume %(id)s: "
                          "%(error)s.",
                          {'id': volume.id,
                           'error': ex})
                volume_update['status'] = 'error'
            volume_model_updates.append(volume_update)
        model_update = {'status': group.status}
        return model_update, volume_model_updates

    def update_group(self, context, group, add_volumes=None,
                     remove_volumes=None):
        grp_snap_enable = volume_utils.is_group_a_cg_snapshot_type(group)
        if not grp_snap_enable and not group.is_replicated:
            raise NotImplementedError()
        add_volume = []
        remove_volume = []
        vol_rep_status = fields.ReplicationStatus.ENABLED

        volume_set_name = self._get_3par_vvs_name(group.id)

        # If replication is enabled on a group then we need
        # to stop RCG, so we can add/remove in/from RCG.
        if group.is_replicated:
            # Check replication status on a group.
            self._check_rep_status_enabled_on_group(group)
            # Stop remote copy.
            self._stop_remote_copy_group(group)

        # TODO(kushal) : we will use volume as object when we re-write
        # the design for unit tests to use objects instead of dicts.
        for volume in add_volumes:
            volume_name = self._get_3par_vol_name(volume)
            vol_snap_enable = self.is_volume_group_snap_type(
                volume.get('volume_type'))
            try:
                if vol_snap_enable:
                    self._check_replication_matched(volume, group)
                    if group.is_replicated:
                        # Add volume to remote copy group
                        self._add_vol_to_remote_copy_group(group, volume)
                        # We have introduced one flag hpe3par:group_replication
                        # in extra_spec of volume_type,which denotes group
                        # level replication on 3par,so when a volume from this
                        # type is added into group we need to set
                        # replication_status on a volume.
                        update = {'id': volume.get('id'),
                                  'replication_status': vol_rep_status}
                        add_volume.append(update)
                    self.client.addVolumeToVolumeSet(volume_set_name,
                                                     volume_name)
                else:
                    msg = (_('Volume with volume id %s is not '
                             'supported as extra specs of this '
                             'volume does not have '
                             'consistent_group_snapshot_enabled="<is> True"'
                             ) % volume['id'])
                    LOG.error(msg)
                    raise exception.InvalidInput(reason=msg)
            except hpeexceptions.HTTPNotFound:
                msg = (_('Virtual Volume Set %s does not exist.') %
                       volume_set_name)
                LOG.error(msg)
                raise exception.InvalidInput(reason=msg)

        for volume in remove_volumes:
            volume_name = self._get_3par_vol_name(volume)

            if group.is_replicated:
                # Remove a volume from remote copy group
                self._remove_vol_from_remote_copy_group(
                    group, volume)
                update = {'id': volume.get('id'),
                          'replication_status': None}
                remove_volume.append(update)
            try:
                self.client.removeVolumeFromVolumeSet(
                    volume_set_name, volume_name)
            except hpeexceptions.HTTPNotFound:
                msg = (_('Virtual Volume Set %s does not exist.') %
                       volume_set_name)
                LOG.error(msg)
                raise exception.InvalidInput(reason=msg)

        if group.is_replicated:
            # Start remote copy.
            self._start_remote_copy_group(group)

        return None, add_volume, remove_volume

    def create_group_snapshot(self, context, group_snapshot, snapshots):
        """Creates a group snapshot."""
        if not volume_utils.is_group_a_cg_snapshot_type(group_snapshot):
            raise NotImplementedError()

        cg_id = group_snapshot.group_id
        snap_shot_name = self._get_3par_snap_name(group_snapshot.id) + (
            "-@count@")
        copy_of_name = self._get_3par_vvs_name(cg_id)

        extra = {'group_snapshot_id': group_snapshot.id}
        extra['group_id'] = cg_id
        extra['description'] = group_snapshot.description

        optional = {'comment': json.dumps(extra),
                    'readOnly': False}
        if self.config.hpe3par_snapshot_expiration:
            optional['expirationHours'] = (
                int(self.config.hpe3par_snapshot_expiration))

        if self.config.hpe3par_snapshot_retention:
            optional['retentionHours'] = (
                int(self.config.hpe3par_snapshot_retention))

        try:
            self.client.createSnapshotOfVolumeSet(snap_shot_name, copy_of_name,
                                                  optional=optional)
        except Exception as ex:
            msg = (_('There was an error creating the cgsnapshot: %s'),
                   six.text_type(ex))
            LOG.error(msg)
            raise exception.InvalidInput(reason=msg)

        snapshot_model_updates = []
        for snapshot in snapshots:
            snapshot_update = {'id': snapshot['id'],
                               'status': fields.SnapshotStatus.AVAILABLE}
            snapshot_model_updates.append(snapshot_update)

        model_update = {'status': fields.GroupSnapshotStatus.AVAILABLE}

        return model_update, snapshot_model_updates

    def delete_group_snapshot(self, context, group_snapshot, snapshots):
        """Deletes a group snapshot."""
        if not volume_utils.is_group_a_cg_snapshot_type(group_snapshot):
            raise NotImplementedError()
        cgsnap_name = self._get_3par_snap_name(group_snapshot.id)

        snapshot_model_updates = []
        for i, snapshot in enumerate(snapshots):
            snapshot_update = {'id': snapshot['id']}
            try:
                snap_name = cgsnap_name + "-" + six.text_type(i)
                self.client.deleteVolume(snap_name)
                snapshot_update['status'] = fields.SnapshotStatus.DELETED
            except hpeexceptions.HTTPNotFound as ex:
                # We'll let this act as if it worked
                # it helps clean up the cinder entries.
                LOG.warning("Delete Snapshot id not found. Removing from "
                            "cinder: %(id)s Ex: %(msg)s",
                            {'id': snapshot['id'], 'msg': ex})
                snapshot_update['status'] = fields.SnapshotStatus.ERROR
            except Exception as ex:
                LOG.error("There was an error deleting snapshot %(id)s: "
                          "%(error)s.",
                          {'id': snapshot['id'],
                           'error': six.text_type(ex)})
                snapshot_update['status'] = fields.SnapshotStatus.ERROR
            snapshot_model_updates.append(snapshot_update)

        model_update = {'status': fields.GroupSnapshotStatus.DELETED}

        return model_update, snapshot_model_updates

    def manage_existing(self, volume, existing_ref):
        """Manage an existing 3PAR volume.

        existing_ref is a dictionary of the form:
        {'source-name': <name of the virtual volume>}
        """
        target_vol_name = self._get_existing_volume_ref_name(existing_ref)

        # Check for the existence of the virtual volume.
        old_comment_str = ""
        try:
            vol = self.client.getVolume(target_vol_name)
            if 'comment' in vol:
                old_comment_str = vol['comment']
        except hpeexceptions.HTTPNotFound:
            err = (_("Virtual volume '%s' doesn't exist on array.") %
                   target_vol_name)
            LOG.error(err)
            raise exception.InvalidInput(reason=err)

        new_comment = {}

        # Use the display name from the existing volume if no new name
        # was chosen by the user.
        if volume['display_name']:
            display_name = volume['display_name']
            new_comment['display_name'] = volume['display_name']
        elif 'comment' in vol:
            display_name = self._get_3par_vol_comment_value(vol['comment'],
                                                            'display_name')
            if display_name:
                new_comment['display_name'] = display_name
        else:
            display_name = None

        # Generate the new volume information based on the new ID.
        new_vol_name = self._get_3par_vol_name(volume)
        # No need to worry about "_name_id" because this is a newly created
        # volume that cannot have been migrated.
        name = 'volume-' + volume['id']

        new_comment['volume_id'] = volume['id']
        new_comment['name'] = name
        new_comment['type'] = 'OpenStack'
        self._add_name_id_to_comment(new_comment, volume)

        volume_type = None
        if volume['volume_type_id']:
            try:
                volume_type = self._get_volume_type(volume['volume_type_id'])
            except Exception:
                reason = (_("Volume type ID '%s' is invalid.") %
                          volume['volume_type_id'])
                raise exception.ManageExistingVolumeTypeMismatch(reason=reason)

        new_vals = {'newName': new_vol_name,
                    'comment': json.dumps(new_comment)}

        # Ensure that snapCPG is set
        if 'snapCPG' not in vol and self.API_VERSION < API_VERSION_2023:
            new_vals['snapCPG'] = vol['userCPG']
            LOG.info("Virtual volume %(disp)s '%(new)s' snapCPG "
                     "is empty so it will be set to: %(cpg)s",
                     {'disp': display_name, 'new': new_vol_name,
                      'cpg': new_vals['snapCPG']})

        # Update the existing volume with the new name and comments.
        self.client.modifyVolume(target_vol_name, new_vals)

        LOG.info("Virtual volume '%(ref)s' renamed to '%(new)s'.",
                 {'ref': existing_ref['source-name'], 'new': new_vol_name})

        retyped = False
        model_update = None
        if volume_type:
            LOG.info("Virtual volume %(disp)s '%(new)s' is being retyped.",
                     {'disp': display_name, 'new': new_vol_name})

            try:
                retyped, model_update = self._retype_from_no_type(volume,
                                                                  volume_type)
                LOG.info("Virtual volume %(disp)s successfully retyped to "
                         "%(new_type)s.",
                         {'disp': display_name,
                          'new_type': volume_type.get('name')})
            except Exception:
                with excutils.save_and_reraise_exception():
                    LOG.warning("Failed to manage virtual volume %(disp)s "
                                "due to error during retype.",
                                {'disp': display_name})
                    # Try to undo the rename and clear the new comment.
                    self.client.modifyVolume(
                        new_vol_name,
                        {'newName': target_vol_name,
                         'comment': old_comment_str})

        updates = {'display_name': display_name}
        if retyped and model_update:
            updates.update(model_update)

        LOG.info("Virtual volume %(disp)s '%(new)s' is now being managed.",
                 {'disp': display_name, 'new': new_vol_name})

        # Return display name to update the name displayed in the GUI and
        # any model updates from retype.
        return updates

    def manage_existing_snapshot(self, snapshot, existing_ref):
        """Manage an existing 3PAR snapshot.

        existing_ref is a dictionary of the form:
        {'source-name': <name of the snapshot>}
        """
        # Potential parent volume for the snapshot
        volume = snapshot['volume']

        # Do not allow for managing of snapshots for 'failed-over' volumes.
        if volume.get('replication_status') == 'failed-over':
            err = (_("Managing of snapshots to failed-over volumes is "
                     "not allowed."))
            raise exception.InvalidInput(reason=err)

        target_snap_name = self._get_existing_volume_ref_name(existing_ref,
                                                              is_snapshot=True)

        # Check for the existence of the snapshot.
        try:
            snap = self.client.getVolume(target_snap_name)
        except hpeexceptions.HTTPNotFound:
            err = (_("Snapshot '%s' doesn't exist on array.") %
                   target_snap_name)
            LOG.error(err)
            raise exception.InvalidInput(reason=err)

        # Make sure the snapshot is being associated with the correct volume.
        parent_vol_name = self._get_3par_vol_name(volume)
        if parent_vol_name != snap['copyOf']:
            err = (_("The provided snapshot '%s' is not a snapshot of "
                     "the provided volume.") % target_snap_name)
            LOG.error(err)
            raise exception.InvalidInput(reason=err)

        new_comment = {}

        # Use the display name from the existing snapshot if no new name
        # was chosen by the user.
        if snapshot['display_name']:
            display_name = snapshot['display_name']
            new_comment['display_name'] = snapshot['display_name']
        elif 'comment' in snap:
            display_name = self._get_3par_vol_comment_value(snap['comment'],
                                                            'display_name')
            if display_name:
                new_comment['display_name'] = display_name
        else:
            display_name = None

        # Generate the new snapshot information based on the new ID.
        new_snap_name = self._get_3par_snap_name(snapshot['id'])
        new_comment['volume_id'] = volume['id']
        new_comment['volume_name'] = 'volume-' + volume['id']
        self._add_name_id_to_comment(new_comment, volume)
        if snapshot.get('display_description', None):
            new_comment['description'] = snapshot['display_description']
        else:
            new_comment['description'] = ""

        new_vals = {'newName': new_snap_name,
                    'comment': json.dumps(new_comment)}

        # Update the existing snapshot with the new name and comments.
        self.client.modifyVolume(target_snap_name, new_vals)

        LOG.info("Snapshot '%(ref)s' renamed to '%(new)s'.",
                 {'ref': existing_ref['source-name'], 'new': new_snap_name})

        updates = {'display_name': display_name}

        LOG.info("Snapshot %(disp)s '%(new)s' is now being managed.",
                 {'disp': display_name, 'new': new_snap_name})

        # Return display name to update the name displayed in the GUI.
        return updates

    def manage_existing_get_size(self, volume, existing_ref):
        """Return size of volume to be managed by manage_existing.

        existing_ref is a dictionary of the form:
        {'source-name': <name of the virtual volume>}
        """
        target_vol_name = self._get_existing_volume_ref_name(existing_ref)

        # Make sure the reference is not in use.
        if re.match('osv-*|oss-*|vvs-*', target_vol_name):
            reason = _("Reference must be for an unmanaged virtual volume.")
            raise exception.ManageExistingInvalidReference(
                existing_ref=target_vol_name,
                reason=reason)

        # Check for the existence of the virtual volume.
        try:
            vol = self.client.getVolume(target_vol_name)
        except hpeexceptions.HTTPNotFound:
            err = (_("Virtual volume '%s' doesn't exist on array.") %
                   target_vol_name)
            LOG.error(err)
            raise exception.InvalidInput(reason=err)

        return int(math.ceil(float(vol['sizeMiB']) / units.Ki))

    def manage_existing_snapshot_get_size(self, snapshot, existing_ref):
        """Return size of snapshot to be managed by manage_existing_snapshot.

        existing_ref is a dictionary of the form:
        {'source-name': <name of the snapshot>}
        """
        target_snap_name = self._get_existing_volume_ref_name(existing_ref,
                                                              is_snapshot=True)

        # Make sure the reference is not in use.
        if re.match('osv-*|oss-*|vvs-*|unm-*', target_snap_name):
            reason = _("Reference must be for an unmanaged snapshot.")
            raise exception.ManageExistingInvalidReference(
                existing_ref=target_snap_name,
                reason=reason)

        # Check for the existence of the snapshot.
        try:
            snap = self.client.getVolume(target_snap_name)
        except hpeexceptions.HTTPNotFound:
            err = (_("Snapshot '%s' doesn't exist on array.") %
                   target_snap_name)
            LOG.error(err)
            raise exception.InvalidInput(reason=err)

        return int(math.ceil(float(snap['sizeMiB']) / units.Ki))

    def unmanage(self, volume):
        """Removes the specified volume from Cinder management."""
        # Rename the volume's name to unm-* format so that it can be
        # easily found later.
        vol_name = self._get_3par_vol_name(volume)
        # Rename using the user visible ID ignoring the internal "_name_id"
        # that may have been generated during a retype.  This makes it easier
        # to locate volumes in the backend.
        new_vol_name = self._get_3par_unm_name(volume['id'])
        self.client.modifyVolume(vol_name, {'newName': new_vol_name})

        LOG.info("Virtual volume %(disp)s '%(vol)s' is no longer managed. "
                 "Volume renamed to '%(new)s'.",
                 {'disp': volume['display_name'],
                  'vol': vol_name,
                  'new': new_vol_name})

    def unmanage_snapshot(self, snapshot):
        """Removes the specified snapshot from Cinder management."""
        # Parent volume for the snapshot
        volume = snapshot['volume']

        # Do not allow unmanaging of snapshots from 'failed-over' volumes.
        if volume.get('replication_status') == 'failed-over':
            err = (_("Unmanaging of snapshots from failed-over volumes is "
                     "not allowed."))
            LOG.error(err)
            # TODO(leeantho) Change this exception to Invalid when the volume
            # manager supports handling that.
            raise exception.SnapshotIsBusy(snapshot_name=snapshot['id'])

        # Rename the snapshots's name to ums-* format so that it can be
        # easily found later.
        snap_name = self._get_3par_snap_name(snapshot['id'])
        new_snap_name = self._get_3par_ums_name(snapshot['id'])
        self.client.modifyVolume(snap_name, {'newName': new_snap_name})

        LOG.info("Snapshot %(disp)s '%(vol)s' is no longer managed. "
                 "Snapshot renamed to '%(new)s'.",
                 {'disp': snapshot['display_name'],
                  'vol': snap_name,
                  'new': new_snap_name})

    def get_manageable_volumes(self, cinder_volumes, marker, limit, offset,
                               sort_keys, sort_dirs):
        already_managed = {}
        for vol_obj in cinder_volumes:
            cinder_id = vol_obj.id
            volume_name = self._get_3par_vol_name(cinder_id)
            already_managed[volume_name] = cinder_id

        cinder_cpg = self._client_conf['hpe3par_cpg'][0]

        manageable_vols = []

        body = self.client.getVolumes()
        all_volumes = body['members']
        for vol in all_volumes:
            cpg = vol.get('userCPG')
            if cpg == cinder_cpg:
                size_gb = int(vol['sizeMiB'] / 1024)
                vol_name = vol['name']
                if vol_name in already_managed:
                    is_safe = False
                    reason_not_safe = _('Volume already managed')
                    cinder_id = already_managed[vol_name]
                else:
                    is_safe = False
                    hostname = None
                    cinder_id = None
                    # Check if the unmanaged volume is attached to any host
                    try:
                        vlun = self.client.getVLUN(vol_name)
                        hostname = vlun['hostname']
                    except hpe3parclient.exceptions.HTTPNotFound:
                        # not attached to any host
                        is_safe = True

                    if is_safe:
                        reason_not_safe = None
                    else:
                        reason_not_safe = _('Volume attached to host ' +
                                            hostname)

                manageable_vols.append({
                    'reference': {'name': vol_name},
                    'size': size_gb,
                    'safe_to_manage': is_safe,
                    'reason_not_safe': reason_not_safe,
                    'cinder_id': cinder_id,
                })

        return volume_utils.paginate_entries_list(
            manageable_vols, marker, limit, offset, sort_keys, sort_dirs)

    def get_manageable_snapshots(self, cinder_snapshots, marker, limit, offset,
                                 sort_keys, sort_dirs):
        already_managed = {}
        for snap_obj in cinder_snapshots:
            cinder_snap_id = snap_obj.id
            snap_name = self._get_3par_snap_name(cinder_snap_id)
            already_managed[snap_name] = cinder_snap_id

        cinder_cpg = self._client_conf['hpe3par_cpg'][0]

        cpg_volumes = []

        body = self.client.getVolumes()
        all_volumes = body['members']
        for vol in all_volumes:
            cpg = vol.get('userCPG')
            if cpg == cinder_cpg:
                cpg_volumes.append(vol)

        manageable_snaps = []

        for vol in cpg_volumes:
            size_gb = int(vol['sizeMiB'] / 1024)
            snapshots = self.client.getSnapshotsOfVolume(cinder_cpg,
                                                         vol['name'])
            for snap_name in snapshots:
                if snap_name in already_managed:
                    is_safe = False
                    reason_not_safe = _('Snapshot already managed')
                    cinder_snap_id = already_managed[snap_name]
                else:
                    is_safe = True
                    reason_not_safe = None
                    cinder_snap_id = None

                manageable_snaps.append({
                    'reference': {'name': snap_name},
                    'size': size_gb,
                    'safe_to_manage': is_safe,
                    'reason_not_safe': reason_not_safe,
                    'cinder_id': cinder_snap_id,
                    'source_reference': {'name': vol['name']},
                })

        return volume_utils.paginate_entries_list(
            manageable_snaps, marker, limit, offset, sort_keys, sort_dirs)

    def _get_existing_volume_ref_name(self, existing_ref, is_snapshot=False):
        """Returns the volume name of an existing reference.

        Checks if an existing volume reference has a source-name or
        source-id element. If source-name or source-id is not present an
        error will be thrown.
        """
        vol_name = None
        if 'source-name' in existing_ref:
            vol_name = existing_ref['source-name']
        elif 'source-id' in existing_ref:
            if is_snapshot:
                vol_name = self._get_3par_ums_name(existing_ref['source-id'])
            else:
                vol_name = self._get_3par_unm_name(existing_ref['source-id'])
        else:
            reason = _("Reference must contain source-name or source-id.")
            raise exception.ManageExistingInvalidReference(
                existing_ref=existing_ref,
                reason=reason)

        return vol_name

    def _extend_volume(self, volume, volume_name, growth_size_mib,
                       _convert_to_base=False):
        model_update = None
        rcg_name = self._get_3par_rcg_name(volume)
        is_volume_replicated = self._volume_of_replicated_type(
            volume, hpe_tiramisu_check=True)
        volume_part_of_group = (
            self._volume_of_hpe_tiramisu_type_and_part_of_group(volume))
        if volume_part_of_group:
            group = volume.get('group')
            rcg_name = self._get_3par_rcg_name_of_group(group.id)
        try:
            if _convert_to_base:
                LOG.debug("Converting to base volume prior to growing.")
                model_update = self._convert_to_base_volume(volume)
            # If the volume is replicated and we are not failed over,
            # remote copy has to be stopped before the volume can be extended.
            failed_over = volume.get("replication_status", None)
            is_failed_over = failed_over == "failed-over"
            if ((is_volume_replicated or volume_part_of_group) and
               not is_failed_over):
                self.client.stopRemoteCopy(rcg_name)
            self.client.growVolume(volume_name, growth_size_mib)
            if ((is_volume_replicated or volume_part_of_group) and
               not is_failed_over):
                self.client.startRemoteCopy(rcg_name)
        except Exception as ex:
            # If the extend fails, we must restart remote copy.
            if is_volume_replicated or volume_part_of_group:
                self.client.startRemoteCopy(rcg_name)
            with excutils.save_and_reraise_exception() as ex_ctxt:
                if (not _convert_to_base and
                    isinstance(ex, hpeexceptions.HTTPForbidden) and
                        ex.get_code() == 150):
                    # Error code 150 means 'invalid operation: Cannot grow
                    # this type of volume'.
                    # Suppress raising this exception because we can
                    # resolve it by converting it into a base volume.
                    # Afterwards, extending the volume should succeed, or
                    # fail with a different exception/error code.
                    ex_ctxt.reraise = False
                    model_update = self._extend_volume(
                        volume, volume_name,
                        growth_size_mib,
                        _convert_to_base=True)
                else:
                    LOG.error("Error extending volume: %(vol)s. "
                              "Exception: %(ex)s",
                              {'vol': volume_name, 'ex': ex})
        return model_update

    @classmethod
    def _get_3par_vol_name(cls, volume_id, temp_vol=False):
        """Get converted 3PAR volume name.

        Converts the openstack volume id from
        ecffc30f-98cb-4cf5-85ee-d7309cc17cd2
        to
        osv-7P.DD5jLTPWF7tcwnMF80g

        We convert the 128 bits of the uuid into a 24character long
        base64 encoded string to ensure we don't exceed the maximum
        allowed 31 character name limit on 3Par

        We strip the padding '=' and replace + with .
        and / with -

        volume_id is a polymorphic parameter and can be either a string or a
        volume (OVO or dict representation).
        """
        # Accept OVOs (what we should only receive), dict (so we don't have to
        # change all our unit tests), and ORM (because we some methods still
        # pass it, such as terminate_connection).
        if isinstance(volume_id, (objects.Volume, objects.Volume.model, dict)):
            volume_id = volume_id.get('_name_id') or volume_id['id']
        volume_name = cls._encode_name(volume_id)
        if temp_vol:
            # is this a temporary volume
            # this is done during migration
            prefix = "tsv-%s"
        else:
            prefix = "osv-%s"
        return prefix % volume_name

    def _get_3par_snap_name(self, snapshot_id, temp_snap=False):
        snapshot_name = self._encode_name(snapshot_id)
        if temp_snap:
            # is this a temporary snapshot
            # this is done during cloning
            prefix = "tss-%s"
        else:
            prefix = "oss-%s"
        return prefix % snapshot_name

    def _get_3par_ums_name(self, snapshot_id):
        ums_name = self._encode_name(snapshot_id)
        return "ums-%s" % ums_name

    def _get_3par_vvs_name(self, volume_id):
        vvs_name = self._encode_name(volume_id)
        return "vvs-%s" % vvs_name

    def _get_3par_unm_name(self, volume_id):
        unm_name = self._encode_name(volume_id)
        return "unm-%s" % unm_name

    # v2 replication conversion
    def _get_3par_rcg_name(self, volume):
        rcg_name = self._encode_name(volume.get('_name_id') or volume['id'])
        rcg = "rcg-%s" % rcg_name
        return rcg[:22]

    def _get_3par_remote_rcg_name(self, volume, provider_location):
        return self._get_3par_rcg_name(volume) + ".r" + (
            six.text_type(provider_location))

    @staticmethod
    def _encode_name(name):
        uuid_str = name.replace("-", "")
        vol_uuid = uuid.UUID('urn:uuid:%s' % uuid_str)
        vol_encoded = base64.encode_as_text(vol_uuid.bytes)

        # 3par doesn't allow +, nor /
        vol_encoded = vol_encoded.replace('+', '.')
        vol_encoded = vol_encoded.replace('/', '-')
        # strip off the == as 3par doesn't like those.
        vol_encoded = vol_encoded.replace('=', '')
        return vol_encoded

    def _capacity_from_size(self, vol_size):
        # because 3PAR volume sizes are in Mebibytes.
        if int(vol_size) == 0:
            capacity = units.Gi  # default: 1GiB
        else:
            capacity = vol_size * units.Gi

        capacity = int(math.ceil(capacity / units.Mi))
        return capacity

    def _delete_3par_host(self, hostname, client_obj):
        client_obj.deleteHost(hostname)

    def _get_prioritized_host_on_3par(self, host, hosts, hostname):
        # Check whether host with wwn/iqn of initiator present on 3par
        if hosts and hosts['members'] and 'name' in hosts['members'][0]:
            # Retrieving 'host' and 'hosts' from 3par using hostname
            # and wwn/iqn respectively. Compare hostname of 'host' and 'hosts',
            # if they do not match it means 3par has a pre-existing host
            # with some other name.
            if host['name'] != hosts['members'][0]['name']:
                hostname = hosts['members'][0]['name']
                LOG.info(("Prioritize the host retrieved from wwn/iqn "
                          "Hostname : %(hosts)s  is used instead "
                          "of Hostname: %(host)s"),
                         {'hosts': hostname,
                          'host': host['name']})
                host = self._get_3par_host(hostname)
                return host, hostname

        return host, hostname

    def _create_3par_vlun(self, volume, hostname, nsp, lun_id=None,
                          remote_client=None):
        try:
            location = None
            auto = True

            if lun_id is not None:
                auto = False

            if remote_client:
                client_obj = remote_client
            else:
                client_obj = self.client

            if nsp is None:
                location = client_obj.createVLUN(volume, hostname=hostname,
                                                 auto=auto, lun=lun_id)
            else:
                port = self.build_portPos(nsp)
                location = client_obj.createVLUN(volume, hostname=hostname,
                                                 auto=auto, portPos=port,
                                                 lun=lun_id)

            vlun_info = None
            if location:
                # The LUN id is returned as part of the location URI
                vlun = location.split(',')
                vlun_info = {'volume_name': vlun[0],
                             'lun_id': int(vlun[1]),
                             'host_name': vlun[2],
                             }
                if len(vlun) > 3:
                    vlun_info['nsp'] = vlun[3]

            return vlun_info

        except hpeexceptions.HTTPBadRequest as e:
            if 'must be in the same domain' in e.get_description():
                LOG.error(e.get_description())
                raise Invalid3PARDomain(err=e.get_description())
            else:
                raise exception.VolumeBackendAPIException(
                    data=e.get_description())

    def _safe_hostname(self, connector, configuration):
        """We have to use a safe hostname length for 3PAR host names."""
        hostname = connector['host']
        unique_fqdn_network = configuration.unique_fqdn_network
        if(not unique_fqdn_network and connector.get('initiator')):
            iqn = connector.get('initiator')
            iqn = iqn.replace(":", "-")
            return iqn[::-1][:31]
        else:
            try:
                index = hostname.index('.')
            except ValueError:
                # couldn't find it
                index = len(hostname)

            # we'll just chop this off for now.
            if index > 31:
                index = 31

            return hostname[:index]

    def _get_3par_host(self, hostname):
        return self.client.getHost(hostname)

    def get_ports(self):
        return self.client.getPorts()

    def get_active_target_ports(self, remote_client=None):
        if remote_client:
            client_obj = remote_client
            ports = remote_client.getPorts()
        else:
            client_obj = self.client
            ports = self.get_ports()

        target_ports = []
        for port in ports['members']:
            if (
                port['mode'] == client_obj.PORT_MODE_TARGET and
                port['linkState'] == client_obj.PORT_STATE_READY
            ):
                port['nsp'] = self.build_nsp(port['portPos'])
                target_ports.append(port)

        return target_ports

    def get_active_fc_target_ports(self, remote_client=None):
        ports = self.get_active_target_ports(remote_client)
        if remote_client:
            client_obj = remote_client
        else:
            client_obj = self.client

        fc_ports = []
        for port in ports:
            if port['protocol'] == client_obj.PORT_PROTO_FC:
                fc_ports.append(port)

        return fc_ports

    def get_active_iscsi_target_ports(self, remote_client=None):
        ports = self.get_active_target_ports(remote_client)
        if remote_client:
            client_obj = remote_client
        else:
            client_obj = self.client

        iscsi_ports = []
        for port in ports:
            if port['protocol'] == client_obj.PORT_PROTO_ISCSI:
                iscsi_ports.append(port)

        return iscsi_ports

    def get_volume_stats(self,
                         refresh,
                         filter_function=None,
                         goodness_function=None):
        if refresh:
            self._update_volume_stats(
                filter_function=filter_function,
                goodness_function=goodness_function)

        return self.stats

    def _update_volume_stats(self,
                             filter_function=None,
                             goodness_function=None):
        # const to convert MiB to GB
        const = 0.0009765625

        # storage_protocol and volume_backend_name are
        # set in the child classes

        pools = []
        try:
            info = self.client.getStorageSystemInfo()
            backend_state = 'up'
        except Exception as ex:
            info = {}
            backend_state = 'down'
            LOG.warning("Exception at getStorageSystemInfo() "
                        "Reason: '%(reason)s'", {'reason': ex})

        qos_support = True
        thin_support = True
        remotecopy_support = True
        sr_support = True
        compression_support = False
        if 'licenseInfo' in info:
            if 'licenses' in info['licenseInfo']:
                valid_licenses = info['licenseInfo']['licenses']
                qos_support = self._check_license_enabled(
                    valid_licenses, self.PRIORITY_OPT_LIC,
                    "QoS_support")
                thin_support = self._check_license_enabled(
                    valid_licenses, self.THIN_PROV_LIC,
                    "Thin_provisioning_support")
                remotecopy_support = self._check_license_enabled(
                    valid_licenses, self.REMOTE_COPY_LIC,
                    "Replication")
                sr_support = self._check_license_enabled(
                    valid_licenses, self.SYSTEM_REPORTER_LIC,
                    "System_reporter_support")
                compression_support = self._check_license_enabled(
                    valid_licenses, self.COMPRESSION_LIC,
                    "Compression")

        for cpg_name in self._client_conf['hpe3par_cpg']:
            try:
                stat_capabilities = {
                    THROUGHPUT: None,
                    BANDWIDTH: None,
                    LATENCY: None,
                    IO_SIZE: None,
                    QUEUE_LENGTH: None,
                    AVG_BUSY_PERC: None
                }
                cpg = self.client.getCPG(cpg_name)
                if (self.API_VERSION >= SRSTATLD_API_VERSION and sr_support):
                    interval = 'daily'
                    history = '7d'
                    try:
                        stat_capabilities = self.client.getCPGStatData(
                            cpg_name,
                            interval,
                            history)
                    except Exception as ex:
                        LOG.warning("Exception at getCPGStatData() "
                                    "for cpg: '%(cpg_name)s' "
                                    "Reason: '%(reason)s'",
                                    {'cpg_name': cpg_name, 'reason': ex})
                if 'numTDVVs' in cpg:
                    total_volumes = int(
                        cpg['numFPVVs'] + cpg['numTPVVs'] + cpg['numTDVVs']
                    )
                else:
                    total_volumes = int(
                        cpg['numFPVVs'] + cpg['numTPVVs']
                    )

                if 'limitMiB' not in cpg['SDGrowth']:
                    # cpg usable free space
                    cpg_avail_space = (
                        self.client.getCPGAvailableSpace(cpg_name))
                    free_capacity = int(
                        cpg_avail_space['usableFreeMiB'] * const)
                    # total_capacity is the best we can do for a limitless cpg
                    total_capacity = int(
                        (cpg['SDUsage']['usedMiB'] +
                         cpg['UsrUsage']['usedMiB'] +
                         cpg_avail_space['usableFreeMiB']) * const)
                else:
                    total_capacity = int(cpg['SDGrowth']['limitMiB'] * const)
                    free_capacity = int((cpg['SDGrowth']['limitMiB'] -
                                        (cpg['UsrUsage']['usedMiB'] +
                                         cpg['SDUsage']['usedMiB'])) * const)
                capacity_utilization = (
                    (float(total_capacity - free_capacity) /
                     float(total_capacity)) * 100)
                provisioned_capacity = int((cpg['UsrUsage']['totalMiB'] +
                                            cpg['SAUsage']['totalMiB'] +
                                            cpg['SDUsage']['totalMiB']) *
                                           const)

            except hpeexceptions.HTTPNotFound:
                err = (_("CPG (%s) doesn't exist on array")
                       % cpg_name)
                LOG.error(err)
                raise exception.InvalidInput(reason=err)

            pool = {'pool_name': cpg_name,
                    'total_capacity_gb': total_capacity,
                    'free_capacity_gb': free_capacity,
                    'provisioned_capacity_gb': provisioned_capacity,
                    'QoS_support': qos_support,
                    'thin_provisioning_support': thin_support,
                    'thick_provisioning_support': True,
                    'max_over_subscription_ratio': (
                        self.config.safe_get('max_over_subscription_ratio')),
                    'reserved_percentage': (
                        self.config.safe_get('reserved_percentage')),
                    'location_info': ('HPE3PARDriver:%(sys_id)s:%(dest_cpg)s' %
                                      {'sys_id': info.get('serialNumber'),
                                       'dest_cpg': cpg_name}),
                    'total_volumes': total_volumes,
                    'capacity_utilization': capacity_utilization,
                    THROUGHPUT: stat_capabilities[THROUGHPUT],
                    BANDWIDTH: stat_capabilities[BANDWIDTH],
                    LATENCY: stat_capabilities[LATENCY],
                    IO_SIZE: stat_capabilities[IO_SIZE],
                    QUEUE_LENGTH: stat_capabilities[QUEUE_LENGTH],
                    AVG_BUSY_PERC: stat_capabilities[AVG_BUSY_PERC],
                    'filter_function': filter_function,
                    'goodness_function': goodness_function,
                    'multiattach': True,
                    'consistent_group_snapshot_enabled': True,
                    'compression': compression_support,
                    'consistent_group_replication_enabled':
                        self._replication_enabled,
                    'backend_state': backend_state
                    }

            if remotecopy_support:
                pool['replication_enabled'] = self._replication_enabled
                pool['replication_type'] = ['sync', 'periodic']
                pool['replication_count'] = len(self._replication_targets)

            pools.append(pool)

        self.stats = {'driver_version': '4.0',
                      'storage_protocol': None,
                      'vendor_name': 'Hewlett Packard Enterprise',
                      'volume_backend_name': None,
                      'array_id': info.get('id'),
                      'replication_enabled': self._replication_enabled,
                      'replication_targets': self._get_replication_targets(),
                      'pools': pools}

    def _check_license_enabled(self, valid_licenses,
                               license_to_check, capability):
        """Check a license against valid licenses on the array."""
        if valid_licenses:
            for license in valid_licenses:
                if license_to_check in license.get('name'):
                    return True
            LOG.debug("'%(capability)s' requires a '%(license)s' "
                      "license which is not installed.",
                      {'capability': capability,
                       'license': license_to_check})
        return False

    def _get_vlun(self, volume_name, hostname, lun_id=None, nsp=None,
                  remote_client=None):
        """find a VLUN on a 3PAR host."""
        if remote_client:
            vluns = remote_client.getHostVLUNs(hostname)
        else:
            vluns = self.client.getHostVLUNs(hostname)

        found_vlun = None
        for vlun in vluns:
            if volume_name in vlun['volumeName']:
                if lun_id is not None:
                    if vlun['lun'] == lun_id:
                        if nsp:
                            port = self.build_portPos(nsp)
                            if vlun['portPos'] == port:
                                found_vlun = vlun
                                break
                        else:
                            found_vlun = vlun
                            break
                else:
                    found_vlun = vlun
                    break

        if found_vlun is None:
            LOG.info("3PAR vlun %(name)s not found on host %(host)s",
                     {'name': volume_name, 'host': hostname})
        return found_vlun

    def create_vlun(self, volume, host, nsp=None, lun_id=None,
                    remote_client=None):
        """Create a VLUN.

        In order to export a volume on a 3PAR box, we have to create a VLUN.
        """
        volume_name = self._get_3par_vol_name(volume)
        vlun_info = self._create_3par_vlun(volume_name, host['name'], nsp,
                                           lun_id=lun_id,
                                           remote_client=remote_client)
        return self._get_vlun(volume_name,
                              host['name'],
                              vlun_info['lun_id'],
                              nsp,
                              remote_client)

    def _delete_vlun(self, client_obj, volume, hostname, wwn=None, iqn=None):
        volume_name = self._get_3par_vol_name(volume)
        if hostname:
            vluns = client_obj.getHostVLUNs(hostname)
        else:
            # In case of 'force detach', hostname is None
            vluns = client_obj.getVLUNs()['members']

        # When deleteing VLUNs, you simply need to remove the template VLUN
        # and any active VLUNs will be automatically removed.  The template
        # VLUN are marked as active: False

        modify_host = True
        volume_vluns = []

        for vlun in vluns:
            if volume_name in vlun['volumeName']:
                # template VLUNs are 'active' = False
                if not vlun['active']:
                    volume_vluns.append(vlun)

        if not volume_vluns:
            LOG.warning("3PAR vlun for volume %(name)s not found on host "
                        "%(host)s", {'name': volume_name, 'host': hostname})
            return

        # VLUN Type of MATCHED_SET 4 requires the port to be provided
        for vlun in volume_vluns:
            if hostname is None:
                hostname = vlun.get('hostname')
            if 'portPos' in vlun:
                client_obj.deleteVLUN(volume_name, vlun['lun'],
                                      hostname=hostname,
                                      port=vlun['portPos'])
            else:
                client_obj.deleteVLUN(volume_name, vlun['lun'],
                                      hostname=hostname)

        # Determine if there are other volumes attached to the host.
        # This will determine whether we should try removing host from host set
        # and deleting the host.
        vluns = []
        try:
            vluns = client_obj.getHostVLUNs(hostname)
        except hpeexceptions.HTTPNotFound:
            LOG.debug("All VLUNs removed from host %s", hostname)

        if wwn is not None and not isinstance(wwn, list):
            wwn = [wwn]
        if iqn is not None and not isinstance(iqn, list):
            iqn = [iqn]

        for vlun in vluns:
            if vlun.get('active'):
                if (wwn is not None and vlun.get('remoteName').lower() in wwn)\
                    or (iqn is not None and vlun.get('remoteName').lower() in
                        iqn):
                    # vlun with wwn/iqn exists so do not modify host.
                    modify_host = False
                    break

        if len(vluns) == 0:
            # We deleted the last vlun, so try to delete the host too.
            # This check avoids the old unnecessary try/fail when vluns exist
            # but adds a minor race condition if a vlun is manually deleted
            # externally at precisely the wrong time. Worst case is leftover
            # host, so it is worth the unlikely risk.

            try:
                # TODO(sonivi): since multiattach is not supported for now,
                # delete only single host, if its not exported to volume.
                self._delete_3par_host(hostname, client_obj)
            except Exception as ex:
                # Any exception down here is only logged.  The vlun is deleted.

                # If the host is in a host set, the delete host will fail and
                # the host will remain in the host set.  This is desired
                # because cinder was not responsible for the host set
                # assignment.  The host set could be used outside of cinder
                # for future needs (e.g. export volume to host set).

                # The log info explains why the host was left alone.
                LOG.info("3PAR vlun for volume '%(name)s' was deleted, "
                         "but the host '%(host)s' was not deleted "
                         "because: %(reason)s",
                         {'name': volume_name, 'host': hostname,
                          'reason': ex.get_description()})
        elif modify_host:
            if wwn is not None:
                mod_request = {'pathOperation': client_obj.HOST_EDIT_REMOVE,
                               'FCWWNs': wwn}
            else:
                mod_request = {'pathOperation': client_obj.HOST_EDIT_REMOVE,
                               'iSCSINames': iqn}
            try:
                client_obj.modifyHost(hostname, mod_request)
            except Exception as ex:
                LOG.info("3PAR vlun for volume '%(name)s' was deleted, "
                         "but the host '%(host)s' was not Modified "
                         "because: %(reason)s",
                         {'name': volume_name, 'host': hostname,
                          'reason': ex.get_description()})

    def delete_vlun(self, volume, hostname, wwn=None, iqn=None,
                    remote_client=None):
        self._delete_vlun(self.client, volume, hostname, wwn, iqn)
        if remote_client:
            self._delete_vlun(remote_client, volume, hostname, wwn, iqn)

    def _get_volume_type(self, type_id):
        ctxt = context.get_admin_context()
        return volume_types.get_volume_type(ctxt, type_id)

    def _get_key_value(self, hpe3par_keys, key, default=None):
        if hpe3par_keys is not None and key in hpe3par_keys:
            return hpe3par_keys[key]
        else:
            return default

    def _get_boolean_key_value(self, hpe3par_keys, key, default=False):
        value = self._get_key_value(
            hpe3par_keys, key, default)
        if isinstance(value, six.string_types):
            if value.lower() == 'true':
                value = True
            else:
                value = False
        return value

    def _get_qos_value(self, qos, key, default=None):
        if key in qos:
            return qos[key]
        else:
            return default

    def _get_qos_by_volume_type(self, volume_type):
        qos = {}
        qos_specs_id = volume_type.get('qos_specs_id')
        specs = volume_type.get('extra_specs')

        # NOTE(kmartin): We prefer the qos_specs association
        # and override any existing extra-specs settings
        # if present.
        if qos_specs_id is not None:
            kvs = qos_specs.get_qos_specs(context.get_admin_context(),
                                          qos_specs_id)['specs']
        else:
            kvs = specs

        for key, value in kvs.items():
            if 'qos:' in key:
                fields = key.split(':')
                key = fields[1]
            if key in self.hpe_qos_keys:
                qos[key] = value
        return qos

    def _get_keys_by_volume_type(self, volume_type):
        hpe3par_keys = {}
        specs = volume_type.get('extra_specs')
        for key, value in specs.items():
            if ':' in key:
                fields = key.split(':')
                key = fields[1]
            if key in self.hpe3par_valid_keys:
                hpe3par_keys[key] = value
        return hpe3par_keys

    def _set_qos_rule(self, qos, vvs_name):
        min_io = self._get_qos_value(qos, 'minIOPS')
        max_io = self._get_qos_value(qos, 'maxIOPS')
        min_bw = self._get_qos_value(qos, 'minBWS')
        max_bw = self._get_qos_value(qos, 'maxBWS')
        latency = self._get_qos_value(qos, 'latency')
        priority = self._get_qos_value(qos, 'priority', 'normal')

        qosRule = {}
        if min_io:
            qosRule['ioMinGoal'] = int(min_io)
            if max_io is None:
                qosRule['ioMaxLimit'] = int(min_io)
        if max_io:
            qosRule['ioMaxLimit'] = int(max_io)
            if min_io is None:
                qosRule['ioMinGoal'] = int(max_io)
        if min_bw:
            qosRule['bwMinGoalKB'] = int(min_bw) * units.Ki
            if max_bw is None:
                qosRule['bwMaxLimitKB'] = int(min_bw) * units.Ki
        if max_bw:
            qosRule['bwMaxLimitKB'] = int(max_bw) * units.Ki
            if min_bw is None:
                qosRule['bwMinGoalKB'] = int(max_bw) * units.Ki
        if latency:
            qosRule['latencyGoal'] = int(latency)
        if priority:
            qosRule['priority'] = self.qos_priority_level.get(priority.lower())

        try:
            self.client.createQoSRules(vvs_name, qosRule)
        except Exception:
            with excutils.save_and_reraise_exception():
                LOG.error("Error creating QOS rule %s", qosRule)

    def get_flash_cache_policy(self, hpe3par_keys):
        if hpe3par_keys is not None:
            # First check list of extra spec keys
            val = self._get_key_value(hpe3par_keys, 'flash_cache', None)
            if val is not None:
                # If requested, see if supported on back end
                if self.API_VERSION < FLASH_CACHE_API_VERSION:
                    err = (_("Flash Cache Policy requires "
                             "WSAPI version '%(fcache_version)s' "
                             "version '%(version)s' is installed.") %
                           {'fcache_version': FLASH_CACHE_API_VERSION,
                            'version': self.API_VERSION})
                    LOG.error(err)
                    raise exception.InvalidInput(reason=err)
                else:
                    if val.lower() == 'true':
                        return self.client.FLASH_CACHE_ENABLED
                    else:
                        return self.client.FLASH_CACHE_DISABLED

        return None

    def get_compression_policy(self, hpe3par_keys):
        if hpe3par_keys is not None:
            # here it should return true/false/None
            val = self._get_key_value(hpe3par_keys, 'compression', None)
            compression_support = False
        if val is not None:
            info = self.client.getStorageSystemInfo()
            if 'licenseInfo' in info:
                if 'licenses' in info['licenseInfo']:
                    valid_licenses = info['licenseInfo']['licenses']
                    compression_support = self._check_license_enabled(
                        valid_licenses, self.COMPRESSION_LIC,
                        "Compression")
            # here check the wsapi version
            if self.API_VERSION < COMPRESSION_API_VERSION:
                err = (_("Compression Policy requires "
                         "WSAPI version '%(compression_version)s' "
                         "version '%(version)s' is installed.") %
                       {'compression_version': COMPRESSION_API_VERSION,
                        'version': self.API_VERSION})
                LOG.error(err)
                raise exception.InvalidInput(reason=err)
            else:
                if val.lower() == 'true':
                    if not compression_support:
                        msg = _('Compression is not supported on '
                                'underlying hardware')
                        LOG.error(msg)
                        raise exception.InvalidInput(reason=msg)
                    return True
                else:
                    return False
        return None

    def _set_flash_cache_policy_in_vvs(self, flash_cache, vvs_name):
        # Update virtual volume set
        if flash_cache:
            try:
                self.client.modifyVolumeSet(vvs_name,
                                            flashCachePolicy=flash_cache)
                LOG.info("Flash Cache policy set to %s", flash_cache)
            except Exception:
                with excutils.save_and_reraise_exception():
                    LOG.error("Error setting Flash Cache policy "
                              "to %s - exception", flash_cache)

    def _add_volume_to_volume_set(self, volume, volume_name,
                                  cpg, vvs_name, qos, flash_cache):
        if vvs_name is not None:
            # Admin has set a volume set name to add the volume to
            try:
                self.client.addVolumeToVolumeSet(vvs_name, volume_name)
            except hpeexceptions.HTTPNotFound:
                msg = _('VV Set %s does not exist.') % vvs_name
                LOG.error(msg)
                raise exception.InvalidInput(reason=msg)
        else:
            vvs_name = self._get_3par_vvs_name(volume['id'])
            domain = self.get_domain(cpg)
            self.client.createVolumeSet(vvs_name, domain)
            try:
                self._set_qos_rule(qos, vvs_name)
                self._set_flash_cache_policy_in_vvs(flash_cache, vvs_name)
                self.client.addVolumeToVolumeSet(vvs_name, volume_name)
            except Exception as ex:
                # Cleanup the volume set if unable to create the qos rule
                # or flash cache policy or add the volume to the volume set
                self.client.deleteVolumeSet(vvs_name)
                raise exception.CinderException(ex)

    def get_cpg(self, volume, allowSnap=False):
        volume_name = self._get_3par_vol_name(volume)
        vol = self.client.getVolume(volume_name)
        # Search for 'userCPG' in the get volume REST API,
        # if found return userCPG , else search for snapCPG attribute
        # when allowSnap=True. For the cases where 3PAR REST call for
        # get volume doesn't have either userCPG or snapCPG ,
        # take the default value of cpg from 'host' attribute from volume param
        LOG.debug("get volume response is: %s", vol)
        if 'userCPG' in vol:
            return vol['userCPG']
        elif allowSnap and 'snapCPG' in vol:
            return vol['snapCPG']
        else:
            return volume_utils.extract_host(volume['host'], 'pool')

    def _get_3par_vol_comment(self, volume_name):
        vol = self.client.getVolume(volume_name)
        if 'comment' in vol:
            return vol['comment']
        return None

    def validate_persona(self, persona_value):
        """Validate persona value.

        If the passed in persona_value is not valid, raise InvalidInput,
        otherwise return the persona ID.

        :param persona_value:
        :raises exception.InvalidInput:
        :returns: persona ID
        """
        if persona_value not in self.valid_persona_values:
            err = (_("Must specify a valid persona %(valid)s,"
                     "value '%(persona)s' is invalid.") %
                   {'valid': self.valid_persona_values,
                   'persona': persona_value})
            LOG.error(err)
            raise exception.InvalidInput(reason=err)
        # persona is set by the id so remove the text and return the id
        # i.e for persona '1 - Generic' returns 1
        persona_id = persona_value.split(' ')
        return persona_id[0]

    def get_persona_type(self, volume, hpe3par_keys=None):
        default_persona = self.valid_persona_values[0]
        type_id = volume.get('volume_type_id', None)
        if type_id is not None:
            volume_type = self._get_volume_type(type_id)
            if hpe3par_keys is None:
                hpe3par_keys = self._get_keys_by_volume_type(volume_type)
        persona_value = self._get_key_value(hpe3par_keys, 'persona',
                                            default_persona)
        return self.validate_persona(persona_value)

    def get_type_info(self, type_id):
        """Get 3PAR type info for the given type_id.

        Reconciles VV Set, old-style extra-specs, and QOS specs
        and returns commonly used info about the type.

        :returns: hpe3par_keys, qos, volume_type, vvs_name
        """
        volume_type = None
        vvs_name = None
        hpe3par_keys = {}
        qos = {}
        if type_id is not None:
            volume_type = self._get_volume_type(type_id)
            hpe3par_keys = self._get_keys_by_volume_type(volume_type)
            vvs_name = self._get_key_value(hpe3par_keys, 'vvs')
            if vvs_name is None:
                qos = self._get_qos_by_volume_type(volume_type)
        return hpe3par_keys, qos, volume_type, vvs_name

    def get_volume_settings_from_type_id(self, type_id, pool):
        """Get 3PAR volume settings given a type_id.

        Combines type info and config settings to return a dictionary
        describing the 3PAR volume settings.  Does some validation (CPG).
        Uses pool as the default cpg (when not specified in volume type specs).

        :param type_id: id of type to get settings for
        :param pool: CPG to use if type does not have one set
        :returns: dict
        """

        hpe3par_keys, qos, volume_type, vvs_name = self.get_type_info(type_id)

        # Default to pool extracted from host.
        # If that doesn't work use the 1st CPG in the config as the default.
        default_cpg = pool or self._client_conf['hpe3par_cpg'][0]

        cpg = self._get_key_value(hpe3par_keys, 'cpg', default_cpg)
        if cpg is not default_cpg:
            # The cpg was specified in a volume type extra spec so it
            # needs to be validated that it's in the correct domain.
            # log warning here
            msg = ("'hpe3par:cpg' is not supported as an extra spec "
                   "in a volume type.  CPG's are chosen by "
                   "the cinder scheduler, as a pool, from the "
                   "cinder.conf entry 'hpe3par_cpg', which can "
                   "be a list of CPGs.")
            versionutils.report_deprecated_feature(LOG, msg)
            LOG.info("Using pool %(pool)s instead of %(cpg)s",
                     {'pool': pool, 'cpg': cpg})

            cpg = pool
            self.validate_cpg(cpg)
        # Look to see if the snap_cpg was specified in volume type
        # extra spec, if not use hpe3par_cpg_snap from config as the
        # default.
        snap_cpg = self.config.hpe3par_cpg_snap
        snap_cpg = self._get_key_value(hpe3par_keys, 'snap_cpg', snap_cpg)
        # If it's still not set or empty then set it to the cpg.
        if not snap_cpg:
            snap_cpg = cpg

        # Check group level replication
        hpe3par_tiramisu = (
            self._get_key_value(hpe3par_keys, 'group_replication'))

        # by default, set convert_to_base to False
        convert_to_base = self._get_boolean_key_value(
            hpe3par_keys, 'convert_to_base')

        # if provisioning is not set use thin
        default_prov = self.valid_prov_values[0]
        prov_value = self._get_key_value(hpe3par_keys, 'provisioning',
                                         default_prov)
        # check for valid provisioning type
        if prov_value not in self.valid_prov_values:
            err = (_("Must specify a valid provisioning type %(valid)s, "
                     "value '%(prov)s' is invalid.") %
                   {'valid': self.valid_prov_values,
                    'prov': prov_value})
            LOG.error(err)
            raise exception.InvalidInput(reason=err)

        tpvv = True
        tdvv = False
        if prov_value == "full":
            tpvv = False
        elif prov_value == "dedup":
            tpvv = False
            tdvv = True

        if tdvv and (self.API_VERSION < DEDUP_API_VERSION):
            err = (_("Dedup is a valid provisioning type, "
                     "but requires WSAPI version '%(dedup_version)s' "
                     "version '%(version)s' is installed.") %
                   {'dedup_version': DEDUP_API_VERSION,
                    'version': self.API_VERSION})
            LOG.error(err)
            raise exception.InvalidInput(reason=err)

        return {'hpe3par_keys': hpe3par_keys,
                'cpg': cpg, 'snap_cpg': snap_cpg,
                'vvs_name': vvs_name, 'qos': qos,
                'tpvv': tpvv, 'tdvv': tdvv,
                'volume_type': volume_type,
                'group_replication': hpe3par_tiramisu,
                'convert_to_base': convert_to_base}

    def get_volume_settings_from_type(self, volume, host=None):
        """Get 3PAR volume settings given a volume.

        Combines type info and config settings to return a dictionary
        describing the 3PAR volume settings.  Does some validation (CPG and
        persona).

        :param volume:
        :param host: Optional host to use for default pool.
        :returns: dict
        """

        type_id = volume.get('volume_type_id', None)

        pool = None
        if host:
            pool = volume_utils.extract_host(host['host'], 'pool')
        else:
            pool = volume_utils.extract_host(volume['host'], 'pool')

        volume_settings = self.get_volume_settings_from_type_id(type_id, pool)

        # check for valid persona even if we don't use it until
        # attach time, this will give the end user notice that the
        # persona type is invalid at volume creation time
        self.get_persona_type(volume, volume_settings['hpe3par_keys'])

        return volume_settings

    def create_volume(self, volume):
        LOG.debug('CREATE VOLUME (%(disp_name)s: %(vol_name)s %(id)s on '
                  '%(host)s)',
                  {'disp_name': volume['display_name'],
                   'vol_name': volume['name'],
                   'id': self._get_3par_vol_name(volume),
                   'host': volume['host']})
        try:
            comments = {'volume_id': volume['id'],
                        'name': volume['name'],
                        'type': 'OpenStack'}
            self._add_name_id_to_comment(comments, volume)

            # This flag denotes group level replication on
            # hpe 3par.
            hpe_tiramisu = False
            name = volume.get('display_name', None)
            if name:
                comments['display_name'] = name

            # get the options supported by volume types
            type_info = self.get_volume_settings_from_type(volume)
            volume_type = type_info['volume_type']
            vvs_name = type_info['vvs_name']
            qos = type_info['qos']
            cpg = type_info['cpg']
            snap_cpg = type_info['snap_cpg']
            tpvv = type_info['tpvv']
            tdvv = type_info['tdvv']
            flash_cache = self.get_flash_cache_policy(
                type_info['hpe3par_keys'])
            compression = self.get_compression_policy(
                type_info['hpe3par_keys'])

            consis_group_snap_type = False
            if volume_type is not None:
                consis_group_snap_type = self.is_volume_group_snap_type(
                    volume_type)

            cg_id = volume.get('group_id', None)
            group = volume.get('group', None)
            if cg_id and consis_group_snap_type:
                vvs_name = self._get_3par_vvs_name(cg_id)

            type_id = volume.get('volume_type_id', None)
            if type_id is not None:
                comments['volume_type_name'] = volume_type.get('name')
                comments['volume_type_id'] = type_id
                if vvs_name is not None:
                    comments['vvs'] = vvs_name
                else:
                    comments['qos'] = qos

            extras = {'comment': json.dumps(comments),
                      'tpvv': tpvv}

            LOG.debug("self.API_VERSION: %(version)s",
                      {'version': self.API_VERSION})

            if self.API_VERSION < API_VERSION_2023:
                extras['snapCPG'] = snap_cpg

            # Only set the dedup option if the backend supports it.
            if self.API_VERSION >= DEDUP_API_VERSION:
                extras['tdvv'] = tdvv

            capacity = self._capacity_from_size(volume['size'])
            volume_name = self._get_3par_vol_name(volume)

            if compression is not None:
                extras['compression'] = compression

            self.client.createVolume(volume_name, cpg, capacity, extras)
            # v2 replication check
            replication_flag = False

            if consis_group_snap_type:
                if (self._volume_of_hpe_tiramisu_type(volume)):
                    hpe_tiramisu = True

            # Add volume to remote group.
            if (group is not None and hpe_tiramisu):
                if group.is_replicated:
                    self._check_rep_status_enabled_on_group(group)
                    self._add_vol_to_remote_group(group, volume)
                    replication_flag = True

            if qos or vvs_name or flash_cache is not None:
                try:
                    self._add_volume_to_volume_set(volume, volume_name,
                                                   cpg, vvs_name, qos,
                                                   flash_cache)
                except exception.InvalidInput as ex:
                    # Delete the volume if unable to add it to the volume set
                    self.client.deleteVolume(volume_name)
                    LOG.error("Exception: %s", ex)
                    raise exception.CinderException(ex)

            if (self._volume_of_replicated_type(volume,
                                                hpe_tiramisu_check=True)
               and self._do_volume_replication_setup(volume)):
                replication_flag = True

        except hpeexceptions.HTTPConflict:
            msg = _("Volume (%s) already exists on array") % volume_name
            LOG.error(msg)
            raise exception.Duplicate(msg)
        except hpeexceptions.HTTPBadRequest as ex:
            LOG.error("Exception: %s", ex)
            raise exception.Invalid(ex.get_description())
        except exception.InvalidInput as ex:
            LOG.error("Exception: %s", ex)
            raise
        except exception.CinderException as ex:
            LOG.error("Exception: %s", ex)
            raise
        except Exception as ex:
            LOG.error("Exception: %s", ex)
            raise exception.CinderException(ex)

        return self._get_model_update(volume['host'], cpg,
                                      replication=replication_flag,
                                      provider_location=self.client.id,
                                      hpe_tiramisu=hpe_tiramisu)

    def _copy_volume(self, src_name, dest_name, cpg, snap_cpg=None,
                     tpvv=True, tdvv=False, compression=None):
        # Virtual volume sets are not supported with the -online option
        LOG.debug('Creating clone of a volume %(src)s to %(dest)s.',
                  {'src': src_name, 'dest': dest_name})

        optional = {'tpvv': tpvv, 'online': True}
        if snap_cpg is not None and self.API_VERSION < API_VERSION_2023:
            optional['snapCPG'] = snap_cpg

        if self.API_VERSION >= DEDUP_API_VERSION:
            optional['tdvv'] = tdvv

        if (compression is not None and
                self.API_VERSION >= COMPRESSION_API_VERSION):
            optional['compression'] = compression

        body = self.client.copyVolume(src_name, dest_name, cpg, optional)
        return body['taskid']

    def get_next_word(self, s, search_string):
        """Return the next word.

        Search 's' for 'search_string', if found return the word preceding
        'search_string' from 's'.
        """
        word = re.search(search_string.strip(' ') + ' ([^ ]*)', s)
        return word.groups()[0].strip(' ')

    def _get_3par_vol_comment_value(self, vol_comment, key):
        comment_dict = dict(ast.literal_eval(vol_comment))
        if key in comment_dict:
            return comment_dict[key]
        return None

    def _get_model_update(self, volume_host, cpg, replication=False,
                          provider_location=None, hpe_tiramisu=None):
        """Get model_update dict to use when we select a pool.

        The pools implementation uses a volume['host'] suffix of :poolname.
        When the volume comes in with this selected pool, we sometimes use
        a different pool (e.g. because the type says to use a different pool).
        So in the several places that we do this, we need to return a model
        update so that the volume will have the actual pool name in the host
        suffix after the operation.

        Given a volume_host, which should (might) have the pool suffix, and
        given the CPG we actually chose to use, return a dict to use for a
        model update iff an update is needed.

        :param volume_host: The volume's host string.
        :param cpg: The actual pool (cpg) used, for example from the type.
        :returns: dict Model update if we need to update volume host, else None
        """
        model_update = {}
        host = volume_utils.extract_host(volume_host, 'backend')
        host_and_pool = volume_utils.append_host(host, cpg)
        if volume_host != host_and_pool:
            # Since we selected a pool based on type, update the model.
            model_update['host'] = host_and_pool
        if replication:
            model_update['replication_status'] = 'enabled'
        if (replication or hpe_tiramisu) and provider_location:
            model_update['provider_location'] = provider_location
        if not model_update:
            model_update = None
        return model_update

    def _create_temp_snapshot(self, volume):
        """This creates a temporary snapshot of a volume.

        This is used by cloning a volume so that we can then
        issue extend volume against the original volume.
        """
        vol_name = self._get_3par_vol_name(volume)
        # create a brand new uuid for the temp snap
        snap_uuid = uuid.uuid4().hex

        # this will be named tss-%s
        snap_name = self._get_3par_snap_name(snap_uuid, temp_snap=True)

        extra = {'volume_name': volume['name'],
                 'volume_id': volume['id']}
        self._add_name_id_to_comment(extra, volume)

        optional = {'comment': json.dumps(extra)}

        # let the snapshot die in an hour
        optional['expirationHours'] = 1

        LOG.info("Creating temp snapshot %(snap)s from volume %(vol)s",
                 {'snap': snap_name, 'vol': vol_name})

        self.client.createSnapshot(snap_name, vol_name, optional)
        return self.client.getVolume(snap_name)

    def create_cloned_volume(self, volume, src_vref):
        try:
            vol_name = self._get_3par_vol_name(volume)
            src_vol_name = self._get_3par_vol_name(src_vref)
            back_up_process = False
            vol_chap_enabled = False
            hpe_tiramisu = False

            # Check whether a volume is ISCSI and CHAP enabled on it.
            if self._client_conf['hpe3par_iscsi_chap_enabled']:
                try:
                    vol_chap_enabled = self.client.getVolumeMetaData(
                        src_vol_name, 'HPQ-cinder-CHAP-name')['value']
                except hpeexceptions.HTTPNotFound:
                    LOG.debug("CHAP is not enabled on volume %(vol)s ",
                              {'vol': src_vref['id']})
                    vol_chap_enabled = False

            # Check whether a process is a backup
            if str(src_vref['status']) == 'backing-up':
                back_up_process = True

            # if the sizes of the 2 volumes are the same and except backup
            # process for ISCSI volume with chap enabled on it.
            # we can do an online copy, which is a background process
            # on the 3PAR that makes the volume instantly available.
            # We can't resize a volume, while it's being copied.
            if volume['size'] == src_vref['size'] and not (
               back_up_process and vol_chap_enabled):
                LOG.debug("Creating a clone of volume, using online copy.")

                type_info = self.get_volume_settings_from_type(volume)
                snapshot = self._create_temp_snapshot(src_vref)
                cpg = type_info['cpg']
                qos = type_info['qos']
                vvs_name = type_info['vvs_name']
                flash_cache = self.get_flash_cache_policy(
                    type_info['hpe3par_keys'])

                compression_val = self.get_compression_policy(
                    type_info['hpe3par_keys'])
                # make the 3PAR copy the contents.
                # can't delete the original until the copy is done.
                self._copy_volume(snapshot['name'], vol_name, cpg=cpg,
                                  snap_cpg=type_info['snap_cpg'],
                                  tpvv=type_info['tpvv'],
                                  tdvv=type_info['tdvv'],
                                  compression=compression_val)

                if qos or vvs_name or flash_cache is not None:
                    try:
                        self._add_volume_to_volume_set(
                            volume, vol_name, cpg, vvs_name, qos, flash_cache)
                    except exception.InvalidInput as ex:
                        # Delete volume if unable to add it to the volume set
                        self.client.deleteVolume(vol_name)
                        dbg = {'volume': vol_name,
                               'vvs_name': vvs_name,
                               'err': six.text_type(ex)}
                        msg = _("Failed to add volume '%(volume)s' to vvset "
                                "'%(vvs_name)s' because '%(err)s'") % dbg
                        LOG.error(msg)
                        raise exception.CinderException(msg)

                # v2 replication check
                replication_flag = False
                if (self._volume_of_replicated_type(volume,
                                                    hpe_tiramisu_check=True)
                   and self._do_volume_replication_setup(volume)):
                    replication_flag = True

                if self._volume_of_hpe_tiramisu_type(volume):
                    hpe_tiramisu = True

                return self._get_model_update(volume['host'], cpg,
                                              replication=replication_flag,
                                              provider_location=self.client.id,
                                              hpe_tiramisu=hpe_tiramisu)
            else:
                # The size of the new volume is different, so we have to
                # copy the volume and wait.  Do the resize after the copy
                # is complete.
                LOG.debug("Creating a clone of volume, using non-online copy.")

                # we first have to create the destination volume
                model_update = self.create_volume(volume)

                optional = {'priority': 1}
                body = self.client.copyVolume(src_vol_name, vol_name, None,
                                              optional=optional)
                task_id = body['taskid']

                task_status = self._wait_for_task_completion(task_id)
                if task_status['status'] is not self.client.TASK_DONE:
                    dbg = {'status': task_status, 'id': volume['id']}
                    msg = _('Copy volume task failed: create_cloned_volume '
                            'id=%(id)s, status=%(status)s.') % dbg
                    raise exception.CinderException(msg)
                else:
                    LOG.debug('Copy volume completed: create_cloned_volume: '
                              'id=%s.', volume['id'])

                return model_update

        except hpeexceptions.HTTPForbidden:
            raise exception.NotAuthorized()
        except hpeexceptions.HTTPNotFound:
            raise exception.NotFound()
        except Exception as ex:
            LOG.error("Exception: %s", ex)
            raise exception.CinderException(ex)

    def delete_volume(self, volume):

        @utils.retry(exception.VolumeIsBusy, interval=2, retries=10)
        def _try_remove_volume(volume_name):
            try:
                self.client.deleteVolume(volume_name)
            except Exception:
                msg = _("The volume is currently busy on the 3PAR "
                        "and cannot be deleted at this time. "
                        "You can try again later.")
                raise exception.VolumeIsBusy(message=msg)

        # v2 replication check
        # If the volume type is replication enabled, we want to call our own
        # method of deconstructing the volume and its dependencies
        if self._volume_of_replicated_type(volume, hpe_tiramisu_check=True):
            replication_status = volume.get('replication_status', None)
            if replication_status and replication_status == "failed-over":
                self._delete_replicated_failed_over_volume(volume)
            else:
                self._do_volume_replication_destroy(volume)
            return

        try:
            volume_name = self._get_3par_vol_name(volume)
            # Try and delete the volume, it might fail here because
            # the volume is part of a volume set which will have the
            # volume set name in the error.
            try:
                self.client.deleteVolume(volume_name)
            except hpeexceptions.HTTPBadRequest as ex:
                if ex.get_code() == 29:
                    if self.client.isOnlinePhysicalCopy(volume_name):
                        LOG.debug("Found an online copy for %(volume)s",
                                  {'volume': volume_name})
                        # the volume is in process of being cloned.
                        # stopOnlinePhysicalCopy will also delete
                        # the volume once it stops the copy.
                        self.client.stopOnlinePhysicalCopy(volume_name)
                    else:
                        LOG.error("Exception: %s", ex)
                        raise
                else:
                    LOG.error("Exception: %s", ex)
                    raise
            except hpeexceptions.HTTPConflict as ex:
                if ex.get_code() == 34:
                    # This is a special case which means the
                    # volume is part of a volume set.
                    self._delete_vvset(volume)
                    self.client.deleteVolume(volume_name)
                elif ex.get_code() == 151:
                    if self.client.isOnlinePhysicalCopy(volume_name):
                        LOG.debug("Found an online copy for %(volume)s",
                                  {'volume': volume_name})
                        # the volume is in process of being cloned.
                        # stopOnlinePhysicalCopy will also delete
                        # the volume once it stops the copy.
                        self.client.stopOnlinePhysicalCopy(volume_name)
                    else:
                        # the volume is being operated on in a background
                        # task on the 3PAR.
                        _try_remove_volume(volume_name)
                elif (ex.get_code() == 32):
                    # Error 32 means that the volume has children

                    # see if we have any temp snapshots
                    snaps = self.client.getVolumeSnapshots(volume_name)
                    for snap in snaps:
                        if snap.startswith('tss-'):
                            # looks like we found a temp snapshot.
                            LOG.info(
                                "Found a temporary snapshot %(name)s",
                                {'name': snap})
                            try:
                                self.client.deleteVolume(snap)
                            except hpeexceptions.HTTPNotFound:
                                # if the volume is gone, it's as good as a
                                # successful delete
                                pass
                            except Exception:
                                msg = _("Volume has a temporary snapshot that "
                                        "can't be deleted at this time.")
                                raise exception.VolumeIsBusy(message=msg)

                    try:
                        self.delete_volume(volume)
                    except Exception:
                        msg = _("Volume has children and cannot be deleted!")
                        raise exception.VolumeIsBusy(message=msg)
                else:
                    LOG.error("Exception: %s", ex)
                    raise exception.VolumeIsBusy(message=ex.get_description())

        except hpeexceptions.HTTPNotFound as ex:
            # We'll let this act as if it worked
            # it helps clean up the cinder entries.
            LOG.warning("Delete volume id not found. Removing from "
                        "cinder: %(id)s Ex: %(msg)s",
                        {'id': volume['id'], 'msg': ex})
        except hpeexceptions.HTTPForbidden as ex:
            LOG.error("Exception: %s", ex)
            raise exception.NotAuthorized(ex.get_description())
        except hpeexceptions.HTTPConflict as ex:
            LOG.error("Exception: %s", ex)
            raise exception.VolumeIsBusy(message=ex.get_description())
        except Exception as ex:
            LOG.error("Exception: %s", ex)
            raise exception.CinderException(ex)

    def create_volume_from_snapshot(self, volume, snapshot, snap_name=None,
                                    vvs_name=None):
        """Creates a volume from a snapshot."""
        LOG.debug("Create Volume from Snapshot\n%(vol_name)s\n%(ss_name)s",
                  {'vol_name': pprint.pformat(volume['display_name']),
                   'ss_name': pprint.pformat(snapshot['display_name'])})

        model_update = {}

        try:
            if not snap_name:
                snap_name = self._get_3par_snap_name(snapshot['id'])
            volume_name = self._get_3par_vol_name(volume)

            extra = {'volume_id': volume['id'],
                     'snapshot_id': snapshot['id']}
            self._add_name_id_to_comment(extra, volume)

            type_id = volume.get('volume_type_id', None)

            hpe3par_keys, qos, _volume_type, vvs = self.get_type_info(
                type_id)
            if vvs:
                vvs_name = vvs

            name = volume.get('display_name', None)
            if name:
                extra['display_name'] = name

            description = volume.get('display_description', None)
            if description:
                extra['description'] = description

            optional = {'comment': json.dumps(extra),
                        'readOnly': False}

            self.client.createSnapshot(volume_name, snap_name, optional)

            # by default, set convert_to_base to False
            convert_to_base = self._get_boolean_key_value(
                hpe3par_keys, 'convert_to_base')

            LOG.debug("convert_to_base: %(convert)s",
                      {'convert': convert_to_base})

            growth_size = volume['size'] - snapshot['volume_size']
            LOG.debug("growth_size: %(size)s", {'size': growth_size})
            if growth_size > 0 or convert_to_base:
                # Convert snapshot volume to base volume type
                LOG.debug('Converting to base volume type: %(id)s.',
                          {'id': volume['id']})
                model_update = self._convert_to_base_volume(volume)
            else:
                LOG.debug("volume is created as child of snapshot")

            if growth_size > 0:
                try:
                    growth_size_mib = growth_size * units.Gi / units.Mi
                    LOG.debug('Growing volume: %(id)s by %(size)s GiB.',
                              {'id': volume['id'], 'size': growth_size})
                    self.client.growVolume(volume_name, growth_size_mib)
                except Exception as ex:
                    LOG.error("Error extending volume %(id)s. "
                              "Ex: %(ex)s",
                              {'id': volume['id'], 'ex': ex})
                    # Delete the volume if unable to grow it
                    self.client.deleteVolume(volume_name)
                    raise exception.CinderException(ex)

            # Check for flash cache setting in extra specs
            flash_cache = self.get_flash_cache_policy(hpe3par_keys)

            if qos or vvs_name or flash_cache is not None:
                cpg_names = self._get_key_value(
                    hpe3par_keys, 'cpg', self._client_conf['hpe3par_cpg'])
                try:
                    self._add_volume_to_volume_set(volume, volume_name,
                                                   cpg_names[0], vvs_name,
                                                   qos, flash_cache)
                except Exception as ex:
                    # Delete the volume if unable to add it to the volume set
                    self.client.deleteVolume(volume_name)
                    LOG.error("Exception: %s", ex)
                    raise exception.CinderException(ex)

            if self._volume_of_hpe_tiramisu_type(volume):
                model_update['provider_location'] = self.client.id

            # v2 replication check
            if (self._volume_of_replicated_type(volume,
                                                hpe_tiramisu_check=True)
               and self._do_volume_replication_setup(volume)):
                model_update['replication_status'] = 'enabled'
                model_update['provider_location'] = self.client.id

        except hpeexceptions.HTTPForbidden as ex:
            LOG.error("Exception: %s", ex)
            raise exception.NotAuthorized()
        except hpeexceptions.HTTPNotFound as ex:
            LOG.error("Exception: %s", ex)
            raise exception.NotFound()
        except Exception as ex:
            LOG.error("Exception: %s", ex)
            raise exception.CinderException(ex)
        return model_update

    def create_snapshot(self, snapshot):
        LOG.debug("Create Snapshot\n%s", pprint.pformat(snapshot))

        try:
            snap_name = self._get_3par_snap_name(snapshot['id'])
            # Don't use the "volume_id" from the snapshot directly in case the
            # volume has been migrated and uses a different ID in the backend.
            # This may trigger OVO lazy loading.  Use dict compatibility to
            # avoid changing all the unit tests.
            vol_name = self._get_3par_vol_name(snapshot['volume'])

            extra = {'volume_name': snapshot['volume_name'],
                     'volume_id': snapshot.get('volume_id')}
            self._add_name_id_to_comment(extra, snapshot['volume'])

            try:
                extra['display_name'] = snapshot['display_name']
            except AttributeError:
                pass

            try:
                extra['description'] = snapshot['display_description']
            except AttributeError:
                pass

            optional = {'comment': json.dumps(extra),
                        'readOnly': True}
            if self.config.hpe3par_snapshot_expiration:
                optional['expirationHours'] = (
                    int(self.config.hpe3par_snapshot_expiration))

            if self.config.hpe3par_snapshot_retention:
                optional['retentionHours'] = (
                    int(self.config.hpe3par_snapshot_retention))

            self.client.createSnapshot(snap_name, vol_name, optional)
        except hpeexceptions.HTTPForbidden as ex:
            LOG.error("Exception: %s", ex)
            raise exception.NotAuthorized()
        except hpeexceptions.HTTPNotFound as ex:
            LOG.error("Exception: %s", ex)
            raise exception.NotFound()

    def migrate_volume(self, volume, host):
        """Migrate directly if source and dest are managed by same storage.

        :param volume: A dictionary describing the volume to migrate
        :param host: A dictionary describing the host to migrate to, where
                     host['host'] is its name, and host['capabilities'] is a
                     dictionary of its reported capabilities.
        :returns: (False, None) if the driver does not support migration,
                 (True, model_update) if successful

        """

        dbg = {'id': volume['id'],
               'host': host['host'],
               'status': volume['status']}
        LOG.debug('enter: migrate_volume: id=%(id)s, host=%(host)s, '
                  'status=%(status)s.', dbg)
        ret = False, None

        if volume['status'] in ['available', 'in-use']:
            volume_type = None
            if volume['volume_type_id']:
                volume_type = self._get_volume_type(volume['volume_type_id'])

            try:
                ret = self.retype(volume, volume_type, None, host)
            except Exception as e:
                LOG.info('3PAR driver cannot perform migration. '
                         'Retype exception: %s', e)

        LOG.debug('leave: migrate_volume: id=%(id)s, host=%(host)s, '
                  'status=%(status)s.', dbg)
        dbg_ret = {'supported': ret[0], 'model_update': ret[1]}
        LOG.debug('migrate_volume result: %(supported)s, %(model_update)s',
                  dbg_ret)
        return ret

    def _rename_migrated(self, volume, dest_volume):
        """Rename the destination volume after a migration.

        Returns whether the destination volume has the name matching the source
        volume or not.

        That way we know whether we need to set the _name_id or not.
        """
        def log_error(vol_type, error, src, dest, rename_name=None,
                      original_name=None):
            LOG.error("Changing the %(vol_type)s volume name from %(src)s to "
                      "%(dest)s failed because %(reason)s",
                      {'vol_type': vol_type, 'src': src, 'dest': dest,
                       'reason': error})
            if rename_name:
                original_name = original_name or dest
                # Don't fail the migration, but help the user fix the
                # source volume stuck in error_deleting.
                LOG.error("Migration will fail to delete the original volume. "
                          "It must be manually renamed from %(rename_name)s to"
                          "  %(original_name)s in the backend, and then we "
                          "have to tell cinder to delete volume %(vol_id)s",
                          {'rename_name': rename_name,
                           'original_name': original_name,
                           'vol_id': dest_volume['id']})

        original_volume_renamed = False
        # We don't need to rename the source volume if it uses a _name_id,
        # since the id we want to use to rename the new volume is available.
        if volume['id'] == (volume.get('_name_id') or volume['id']):
            original_name = self._get_3par_vol_name(volume)
            temp_name = self._get_3par_vol_name(volume, temp_vol=True)

            # In case the original volume is on the same backend, try
            # renaming it to a temporary name.
            try:
                volumeTempMods = {'newName': temp_name}
                self.client.modifyVolume(original_name, volumeTempMods)
                original_volume_renamed = True
            except hpeexceptions.HTTPNotFound:
                pass
            except Exception as e:
                log_error('original', e, original_name, temp_name)
                return False

        # Change the destination volume name to the source's ID name
        current_name = self._get_3par_vol_name(dest_volume)
        volume_id_name = self._get_3par_vol_name(volume['id'])
        try:
            # After this call the volume manager will call
            # finish_volume_migration and swap the fields, so we want to
            # have the right info on the comments if we succeed in renaming
            # the volumes in the backend.
            new_comment = self._get_updated_comment(current_name,
                                                    volume_id=volume['id'],
                                                    _name_id=None)
            volumeMods = {'newName': volume_id_name, 'comment': new_comment}
            self.client.modifyVolume(current_name, volumeMods)
            LOG.info("Current volume changed from %(cur)s to %(orig)s",
                     {'cur': current_name, 'orig': volume_id_name})
        except Exception as e:
            if original_volume_renamed:
                _name = temp_name
            else:
                _name = original_name = None
            log_error('migrating', e, current_name, volume_id_name, _name,
                      original_name)
            return False

        # If it was renamed, rename the original volume again to the
        # migrated volume's name (effectively swapping the names). If
        # this operation fails, the newly migrated volume is OK but the
        # original volume (with the temp name) may need to be manually
        # cleaned up on the backend.
        if original_volume_renamed:
            try:
                old_comment = self._get_updated_comment(
                    original_name,
                    volume_id=dest_volume['id'],
                    _name_id=volume.get('_name_id'))
                volumeCurrentMods = {'newName': current_name,
                                     'comment': old_comment}
                self.client.modifyVolume(temp_name, volumeCurrentMods)
            except Exception as e:
                log_error('original', e, temp_name, current_name, temp_name)
        return True

    def update_migrated_volume(self, context, volume, new_volume,
                               original_volume_status):
        """Rename the new (temp) volume to it's original name.


        This method tries to rename the new volume to it's original
        name after the migration has completed.

        """
        LOG.debug("Update volume name for %(id)s", {'id': new_volume['id']})

        # For available volumes we'll try renaming the destination volume to
        # match the id of the source volume.
        if original_volume_status == 'available':
            new_volume_renamed = self._rename_migrated(volume, new_volume)
        else:
            new_volume_renamed = False

        if new_volume_renamed:
            name_id = None
            # NOTE: I think this will break with replicated volumes.
            provider_location = None

        else:
            # the backend can't change the name.
            name_id = new_volume['_name_id'] or new_volume['id']
            provider_location = new_volume['provider_location']
            # Update the comment in the backend to reflect the _name_id
            current_name = self._get_3par_vol_name(new_volume)
            self._update_comment(current_name, volume_id=volume['id'],
                                 _name_id=name_id)

        return {'_name_id': name_id, 'provider_location': provider_location}

    @staticmethod
    def _add_name_id_to_comment(comment, volume):
        name_id = volume.get('_name_id')
        if name_id:
            comment['_name_id'] = name_id

    def _get_updated_comment(self, vol_name, **values):
        vol = self.client.getVolume(vol_name)
        comment = json.loads(vol['comment']) if vol.get('comment') else {}
        comment.update(values)

    def _update_comment(self, vol_name, **values):
        """Update key-value pairs on the comment of a volume in the backend."""
        if not values:
            return
        comment = self._get_updated_comment(vol_name, **values)
        self.client.modifyVolume(vol_name, {'comment': json.dumps(comment)})

    def _wait_for_task_completion(self, task_id):
        """This waits for a 3PAR background task complete or fail.

        This looks for a task to get out of the 'active' state.
        """
        # Wait for the physical copy task to complete
        def _wait_for_task(task_id):
            status = self.client.getTask(task_id)
            LOG.debug("3PAR Task id %(id)s status = %(status)s",
                      {'id': task_id,
                       'status': status['status']})
            if status['status'] is not self.client.TASK_ACTIVE:
                self._task_status = status
                raise loopingcall.LoopingCallDone()

        self._task_status = None
        timer = loopingcall.FixedIntervalLoopingCall(
            _wait_for_task, task_id)
        timer.start(interval=1).wait()

        return self._task_status

    def _convert_to_base_volume(self, volume, new_cpg=None):
        try:
            type_info = self.get_volume_settings_from_type(volume)
            if new_cpg:
                cpg = new_cpg
            else:
                cpg = type_info['cpg']

            # Change the name such that it is unique since 3PAR
            # names must be unique across all CPGs
            volume_name = self._get_3par_vol_name(volume)
            temp_vol_name = volume_name.replace("osv-", "omv-")

            compression = self.get_compression_policy(
                type_info['hpe3par_keys'])

            # If volume (osv-) has snapshot, while converting the volume
            # to base volume (omv-), snapshot cannot be transferred to
            # new base volume (omv-) i.e it remain with volume (osv-).
            # So error out for such volume.
            snap_list = self.client.getVolumeSnapshots(volume_name)
            if snap_list:
                snap_str = ",".join(snap_list)
                msg = (_("Volume %(name)s has dependent snapshots: %(snap)s."
                         " Either flatten or remove the dependent snapshots:"
                         " %(snap)s for the conversion of volume %(name)s to"
                         " succeed." % {'name': volume_name,
                                        'snap': snap_str}))
                raise exception.VolumeIsBusy(message=msg)

            # Create a physical copy of the volume
            task_id = self._copy_volume(volume_name, temp_vol_name,
                                        cpg, cpg, type_info['tpvv'],
                                        type_info['tdvv'],
                                        compression)

            LOG.debug('Copy volume scheduled: convert_to_base_volume: '
                      'id=%s.', volume['id'])

            task_status = self._wait_for_task_completion(task_id)

            if task_status['status'] is not self.client.TASK_DONE:
                dbg = {'status': task_status, 'id': volume['id']}
                msg = _('Copy volume task failed: convert_to_base_volume: '
                        'id=%(id)s, status=%(status)s.') % dbg
                raise exception.CinderException(msg)
            else:
                LOG.debug('Copy volume completed: convert_to_base_volume: '
                          'id=%s.', volume['id'])

            comment = self._get_3par_vol_comment(volume_name)
            if comment:
                self.client.modifyVolume(temp_vol_name, {'comment': comment})
                LOG.debug('Assigned the comment: convert_to_base_volume: '
                          'id=%s.', volume['id'])

            # Delete source volume (osv-) after the copy is complete
            self.client.deleteVolume(volume_name)
            LOG.debug('Delete src volume completed: convert_to_base_volume: '
                      'id=%s.', volume['id'])

            # Rename the new volume (omv-) to the original name (osv-)
            self.client.modifyVolume(temp_vol_name, {'newName': volume_name})
            LOG.debug('Volume rename completed: convert_to_base_volume: '
                      'id=%s.', volume['id'])

            LOG.info('Completed: convert_to_base_volume: '
                     'id=%s.', volume['id'])
        except hpeexceptions.HTTPConflict:
            msg = _("Volume (%s) already exists on array.") % temp_vol_name
            LOG.error(msg)
            raise exception.Duplicate(msg)
        except hpeexceptions.HTTPBadRequest as ex:
            LOG.error("Exception: %s", ex)
            raise exception.Invalid(ex.get_description())
        except exception.CinderException as ex:
            LOG.error("Exception: %s", ex)
            raise
        except Exception as ex:
            LOG.error("Exception: %s", ex)
            raise exception.CinderException(ex)

        return self._get_model_update(volume['host'], cpg)

    def delete_snapshot(self, snapshot):
        LOG.debug("Delete Snapshot id %(id)s %(name)s",
                  {'id': snapshot['id'], 'name': pprint.pformat(snapshot)})

        try:
            snap_name = self._get_3par_snap_name(snapshot['id'])
            self.client.deleteVolume(snap_name)
        except hpeexceptions.HTTPForbidden as ex:
            LOG.error("Exception: %s", ex)
            raise exception.NotAuthorized()
        except hpeexceptions.HTTPNotFound as ex:
            # We'll let this act as if it worked
            # it helps clean up the cinder entries.
            LOG.warning("Delete Snapshot id not found. Removing from "
                        "cinder: %(id)s Ex: %(msg)s",
                        {'id': snapshot['id'], 'msg': ex})
        except hpeexceptions.HTTPConflict as ex:
            if (ex.get_code() == 32):
                # Error 32 means that the snapshot has children
                # see if we have any temp snapshots
                snaps = self.client.getVolumeSnapshots(snap_name)
                for snap in snaps:
                    if snap.startswith('tss-'):
                        LOG.info(
                            "Found a temporary snapshot %(name)s",
                            {'name': snap})
                        try:
                            self.client.deleteVolume(snap)
                        except hpeexceptions.HTTPNotFound:
                            # if the volume is gone, it's as good as a
                            # successful delete
                            pass
                        except Exception:
                            msg = _("Snapshot has a temporary snapshot that "
                                    "can't be deleted at this time.")
                            raise exception.SnapshotIsBusy(message=msg)

                    if snap.startswith('osv-'):
                        LOG.info(
                            "Found a volume %(name)s",
                            {'name': snap})

                        # Get details of original volume v1
                        # These details would be required to form v2
                        s1_detail = self.client.getVolume(snap_name)
                        v1_name = s1_detail.get('copyOf')
                        v1 = self.client.getVolume(v1_name)

                        # Get details of volume v2,
                        # which is child of snapshot s1
                        v2_name = snap
                        v2 = self.client.getVolume(v2_name)

                        # Update v2 object as required for
                        # _convert_to_base function
                        v2['volume_type_id'] = (
                            self._get_3par_vol_comment_value(
                                v1['comment'], 'volume_type_id'))

                        v2['id'] = self._get_3par_vol_comment_value(
                            v2['comment'], 'volume_id')
                        v2['_name_id'] = self._get_3par_vol_comment_value(
                            v2['comment'], '_name_id')

                        v2['host'] = '#' + v1['userCPG']

                        LOG.debug('Converting to base volume type: '
                                  '%(id)s.', {'id': v2['id']})
                        self._convert_to_base_volume(v2)

                try:
                    self.client.deleteVolume(snap_name)
                except Exception:
                    msg = _("Snapshot has children and cannot be deleted!")
                    raise exception.SnapshotIsBusy(message=msg)
            else:
                LOG.error("Exception: %s", ex)
                raise exception.SnapshotIsBusy(message=ex.get_description())

    def _get_3par_hostname_from_wwn_iqn(self, wwns, iqns):
        if wwns is not None and not isinstance(wwns, list):
            wwns = [wwns]
        if iqns is not None and not isinstance(iqns, list):
            iqns = [iqns]

        out = self.client.getHosts()
        hosts = out['members']
        for host in hosts:
            if 'iSCSIPaths' in host and iqns is not None:
                iscsi_paths = host['iSCSIPaths']
                for iscsi in iscsi_paths:
                    for iqn in iqns:
                        if iqn == iscsi['name']:
                            return host['name']

            if 'FCPaths' in host and wwns is not None:
                fc_paths = host['FCPaths']
                for fc in fc_paths:
                    for wwn in wwns:
                        if wwn.upper() == fc['wwn'].upper():
                            return host['name']

    def terminate_connection(self, volume, hostname, wwn=None, iqn=None,
                             remote_client=None):
        """Driver entry point to detach a volume from an instance."""
        if volume.multiattach:
            attachment_list = volume.volume_attachment
            LOG.debug("Volume attachment list: %(atl)s",
                      {'atl': attachment_list})

            try:
                attachment_list = attachment_list.objects
            except AttributeError:
                pass

            if attachment_list is not None and len(attachment_list) > 1:
                # There are two possibilities: the instances can reside:
                # [1] either on same host.
                # [2] or on different hosts.
                #
                # case [1]:
                # In such case, behaviour is same as earlier i.e vlun is
                # not deleted now i.e skip remainder of terminate volume
                # connection.
                #
                # case [2]:
                # In such case, vlun of that host on 3par array should
                # be deleted now. Otherwise, it remains as stale entry on
                # 3par array; which later leads to error during volume
                # deletion.

                same_host = False
                num_hosts = len(attachment_list)
                all_hostnames = []
                all_hostnames.append(hostname)

                count = 0
                for i in range(num_hosts):
                    hostname_i = str(attachment_list[i].attached_host)
                    if hostname == hostname_i:
                        # current host
                        count = count + 1
                        if count > 1:
                            # volume attached to multiple instances on
                            # current host
                            same_host = True
                    else:
                        # different host
                        all_hostnames.append(hostname_i)

                if same_host:
                    LOG.info("Volume %(volume)s is attached to multiple "
                             "instances on same host %(host_name)s, "
                             "skip terminate volume connection",
                             {'volume': volume.name,
                              'host_name': volume.host.split('@')[0]})
                    return
                else:
                    hostnames = ",".join(all_hostnames)
                    LOG.info("Volume %(volume)s is attached to instances "
                             "on multiple hosts %(hostnames)s. Proceed with "
                             "deletion of vlun on this host.",
                             {'volume': volume.name, 'hostnames': hostnames})

        # does 3par know this host by a different name?
        hosts = None
        if wwn:
            hosts = self.client.queryHost(wwns=wwn)
        elif iqn:
            hosts = self.client.queryHost(iqns=[iqn])

        if hosts is not None:
            if hosts and hosts['members'] and 'name' in hosts['members'][0]:
                hostname = hosts['members'][0]['name']

        try:
            self.delete_vlun(volume, hostname, wwn=wwn, iqn=iqn,
                             remote_client=remote_client)
            return
        except hpeexceptions.HTTPNotFound as e:
            if 'host does not exist' in e.get_description():
                # If a host is failed-over, we want to allow the detach to
                # 'succeed' when it cannot find the host. We can simply
                # return out of the terminate connection in order for things
                # to be updated correctly.
                if self._active_backend_id:
                    LOG.warning("Because the host is currently in a "
                                "failed-over state, the volume will not "
                                "be properly detached from the primary "
                                "array. The detach will be considered a "
                                "success as far as Cinder is concerned. "
                                "The volume can now be attached to the "
                                "secondary target.")
                    return
                else:
                    if hosts is None:
                        # In case of 'force detach', hosts is None
                        LOG.exception("Exception: %s", e)
                        raise
                    else:
                        # use the wwn to see if we can find the hostname
                        hostname = self._get_3par_hostname_from_wwn_iqn(
                            wwn,
                            iqn)
                        # no 3par host, re-throw
                        if hostname is None:
                            LOG.exception("Exception: %s", e)
                            raise
            else:
                # not a 'host does not exist' HTTPNotFound exception, re-throw
                LOG.error("Exception: %s", e)
                raise

        # try again with name retrieved from 3par
        self.delete_vlun(volume, hostname, wwn=wwn, iqn=iqn,
                         remote_client=remote_client)

    def build_nsp(self, portPos):
        return '%s:%s:%s' % (portPos['node'],
                             portPos['slot'],
                             portPos['cardPort'])

    def build_portPos(self, nsp):
        split = nsp.split(":")
        portPos = {}
        portPos['node'] = int(split[0])
        portPos['slot'] = int(split[1])
        portPos['cardPort'] = int(split[2])
        return portPos

    def tune_vv(self, old_tpvv, new_tpvv, old_tdvv, new_tdvv,
                old_cpg, new_cpg, volume_name, new_compression):
        """Tune the volume to change the userCPG and/or provisioningType.

        The volume will be modified/tuned/converted to the new userCPG and
        provisioningType, as needed.

        TaskWaiter is used to make this function wait until the 3PAR task
        is no longer active.  When the task is no longer active, then it must
        either be done or it is in a state that we need to treat as an error.
        """

        compression = False
        if new_compression is not None:
            compression = new_compression

        if old_tpvv == new_tpvv and old_tdvv == new_tdvv:
            if new_cpg != old_cpg:
                LOG.info("Modifying %(volume_name)s userCPG "
                         "from %(old_cpg)s"
                         " to %(new_cpg)s",
                         {'volume_name': volume_name,
                          'old_cpg': old_cpg, 'new_cpg': new_cpg})
                _response, body = self.client.modifyVolume(
                    volume_name,
                    {'action': 6,
                     'tuneOperation': 1,
                     'userCPG': new_cpg})
                task_id = body['taskid']
                status = self.TaskWaiter(self.client, task_id).wait_for_task()
                if status['status'] is not self.client.TASK_DONE:
                    msg = (_('Tune volume task stopped before it was done: '
                             'volume_name=%(volume_name)s, '
                             'task-status=%(status)s.') %
                           {'status': status, 'volume_name': volume_name})
                    raise exception.VolumeBackendAPIException(msg)
        else:
            if new_tpvv:
                cop = self.CONVERT_TO_THIN
                LOG.info("Converting %(volume_name)s to thin provisioning "
                         "with userCPG=%(new_cpg)s",
                         {'volume_name': volume_name, 'new_cpg': new_cpg})
            elif new_tdvv:
                cop = self.CONVERT_TO_DEDUP
                LOG.info("Converting %(volume_name)s to thin dedup "
                         "provisioning with userCPG=%(new_cpg)s",
                         {'volume_name': volume_name, 'new_cpg': new_cpg})
            else:
                cop = self.CONVERT_TO_FULL
                LOG.info("Converting %(volume_name)s to full provisioning "
                         "with userCPG=%(new_cpg)s",
                         {'volume_name': volume_name, 'new_cpg': new_cpg})

            try:
                if self.API_VERSION < COMPRESSION_API_VERSION:
                    response, body = self.client.modifyVolume(
                        volume_name,
                        {'action': 6,
                         'tuneOperation': 1,
                         'userCPG': new_cpg,
                         'conversionOperation': cop})
                else:
                    response, body = self.client.modifyVolume(
                        volume_name,
                        {'action': 6,
                         'tuneOperation': 1,
                         'userCPG': new_cpg,
                         'compression': compression,
                         'conversionOperation': cop})
            except hpeexceptions.HTTPBadRequest as ex:
                if ex.get_code() == 40 and "keepVV" in six.text_type(ex):
                    # Cannot retype with snapshots because we don't want to
                    # use keepVV and have straggling volumes.  Log additional
                    # info and then raise.
                    LOG.info("tunevv failed because the volume '%s' "
                             "has snapshots.", volume_name)
                    raise

            task_id = body['taskid']
            status = self.TaskWaiter(self.client, task_id).wait_for_task()
            if status['status'] is not self.client.TASK_DONE:
                msg = (_('Tune volume task stopped before it was done: '
                         'volume_name=%(volume_name)s, '
                         'task-status=%(status)s.') %
                       {'status': status, 'volume_name': volume_name})
                raise exception.VolumeBackendAPIException(msg)

    def _retype_pre_checks(self, volume, host, new_persona,
                           old_cpg, new_cpg,
                           new_snap_cpg):
        """Test retype parameters before making retype changes.

        Do pre-retype parameter validation.  These checks will
        raise an exception if we should not attempt this retype.
        """

        if new_persona:
            self.validate_persona(new_persona)

        if host is not None:
            (host_type, host_id, _host_cpg) = (
                host['capabilities']['location_info']).split(':')

            if not (host_type == 'HPE3PARDriver'):
                reason = (_("Cannot retype from HPE3PARDriver to %s.") %
                          host_type)
                raise exception.InvalidHost(reason=reason)

            sys_info = self.client.getStorageSystemInfo()
            if not (host_id == sys_info['serialNumber']):
                reason = (_("Cannot retype from one 3PAR array to another."))
                raise exception.InvalidHost(reason=reason)

        # Validate new_snap_cpg.  A white-space snapCPG will fail eventually,
        # but we'd prefer to fail fast -- if this ever happens.
        if not new_snap_cpg or new_snap_cpg.isspace():
            reason = (_("Invalid new snapCPG name for retype.  "
                        "new_snap_cpg='%s'.") % new_snap_cpg)
            raise exception.InvalidInput(reason)

        # Check to make sure CPGs are in the same domain
        domain = self.get_domain(old_cpg)
        if domain != self.get_domain(new_cpg):
            reason = (_('Cannot retype to a CPG in a different domain.'))
            raise Invalid3PARDomain(reason)

        if domain != self.get_domain(new_snap_cpg):
            reason = (_('Cannot retype to a snap CPG in a different domain.'))
            raise Invalid3PARDomain(reason)

    def _retype(self, volume, volume_name, new_type_name, new_type_id, host,
                new_persona, old_cpg, new_cpg, old_snap_cpg, new_snap_cpg,
                old_tpvv, new_tpvv, old_tdvv, new_tdvv,
                old_vvs, new_vvs, old_qos, new_qos,
                old_flash_cache, new_flash_cache,
                old_comment, new_compression):

        action = "volume:retype"

        self._retype_pre_checks(volume, host, new_persona,
                                old_cpg, new_cpg,
                                new_snap_cpg)

        flow_name = action.replace(":", "_") + "_api"
        retype_flow = linear_flow.Flow(flow_name)
        # Keep this linear and do the big tunevv last.  Everything leading
        # up to that is reversible, but we'd let the 3PAR deal with tunevv
        # errors on its own.
        retype_flow.add(
            ModifyVolumeTask(action),
            ModifySpecsTask(action),
            TuneVolumeTask(action),
            ReplicateVolumeTask(action))

        taskflow.engines.run(
            retype_flow,
            store={'common': self,
                   'volume_name': volume_name, 'volume': volume,
                   'old_tpvv': old_tpvv, 'new_tpvv': new_tpvv,
                   'old_tdvv': old_tdvv, 'new_tdvv': new_tdvv,
                   'old_cpg': old_cpg, 'new_cpg': new_cpg,
                   'old_snap_cpg': old_snap_cpg, 'new_snap_cpg': new_snap_cpg,
                   'old_vvs': old_vvs, 'new_vvs': new_vvs,
                   'old_qos': old_qos, 'new_qos': new_qos,
                   'old_flash_cache': old_flash_cache,
                   'new_flash_cache': new_flash_cache,
                   'new_type_name': new_type_name, 'new_type_id': new_type_id,
                   'old_comment': old_comment,
                   'new_compression': new_compression
                   })

    def _retype_from_old_to_new(self, volume, new_type, old_volume_settings,
                                host):
        """Convert the volume to be of the new type.  Given old type settings.

        Returns True if the retype was successful.
        Uses taskflow to revert changes if errors occur.

        :param volume: A dictionary describing the volume to retype
        :param new_type: A dictionary describing the volume type to convert to
        :param old_volume_settings: Volume settings describing the old type.
        :param host: A dictionary describing the host, where
                     host['host'] is its name, and host['capabilities'] is a
                     dictionary of its reported capabilities.  Host validation
                     is just skipped if host is None.
        """
        volume_name = self._get_3par_vol_name(volume)
        new_type_name = None
        new_type_id = None
        if new_type:
            new_type_name = new_type['name']
            new_type_id = new_type['id']
        pool = None
        if host:
            pool = volume_utils.extract_host(host['host'], 'pool')
        else:
            pool = volume_utils.extract_host(volume['host'], 'pool')
        new_volume_settings = self.get_volume_settings_from_type_id(
            new_type_id, pool)
        new_cpg = new_volume_settings['cpg']
        new_snap_cpg = new_volume_settings['snap_cpg']
        new_tpvv = new_volume_settings['tpvv']
        new_tdvv = new_volume_settings['tdvv']
        new_qos = new_volume_settings['qos']
        new_vvs = new_volume_settings['vvs_name']
        new_persona = None
        new_hpe3par_keys = new_volume_settings['hpe3par_keys']
        if 'persona' in new_hpe3par_keys:
            new_persona = new_hpe3par_keys['persona']
        new_flash_cache = self.get_flash_cache_policy(new_hpe3par_keys)

        # it will return None / True /False$
        new_compression = self.get_compression_policy(new_hpe3par_keys)

        old_qos = old_volume_settings['qos']
        old_vvs = old_volume_settings['vvs_name']
        old_hpe3par_keys = old_volume_settings['hpe3par_keys']
        old_flash_cache = self.get_flash_cache_policy(old_hpe3par_keys)

        # Get the current volume info because we can get in a bad state
        # if we trust that all the volume type settings are still the
        # same settings that were used with this volume.
        old_volume_info = self.client.getVolume(volume_name)
        old_tpvv = old_volume_info['provisioningType'] == self.THIN
        old_tdvv = old_volume_info['provisioningType'] == self.DEDUP
        old_cpg = old_volume_info['userCPG']
        old_comment = old_volume_info['comment']
        old_snap_cpg = None
        if 'snapCPG' in old_volume_info:
            old_snap_cpg = old_volume_info['snapCPG']

        LOG.debug("retype old_volume_info=%s", old_volume_info)
        LOG.debug("retype old_volume_settings=%s", old_volume_settings)
        LOG.debug("retype new_volume_settings=%s", new_volume_settings)

        self._retype(volume, volume_name, new_type_name, new_type_id,
                     host, new_persona, old_cpg, new_cpg,
                     old_snap_cpg, new_snap_cpg, old_tpvv, new_tpvv,
                     old_tdvv, new_tdvv, old_vvs, new_vvs,
                     old_qos, new_qos, old_flash_cache, new_flash_cache,
                     old_comment, new_compression)

        if host:
            return True, self._get_model_update(host['host'], new_cpg)
        else:
            return True, self._get_model_update(volume['host'], new_cpg)

    def _retype_from_no_type(self, volume, new_type):
        """Convert the volume to be of the new type.  Starting from no type.

        Returns True if the retype was successful.
        Uses taskflow to revert changes if errors occur.

        :param volume: A dictionary describing the volume to retype. Except the
                       volume-type is not used here. This method uses None.
        :param new_type: A dictionary describing the volume type to convert to
        """
        pool = volume_utils.extract_host(volume['host'], 'pool')
        none_type_settings = self.get_volume_settings_from_type_id(None, pool)
        return self._retype_from_old_to_new(volume, new_type,
                                            none_type_settings, None)

    def retype(self, volume, new_type, diff, host):
        """Convert the volume to be of the new type.

        Returns True if the retype was successful.
        Uses taskflow to revert changes if errors occur.

        :param volume: A dictionary describing the volume to retype
        :param new_type: A dictionary describing the volume type to convert to
        :param diff: A dictionary with the difference between the two types
        :param host: A dictionary describing the host, where
                     host['host'] is its name, and host['capabilities'] is a
                     dictionary of its reported capabilities.  Host validation
                     is just skipped if host is None.
        """
        LOG.debug(("enter: retype: id=%(id)s, new_type=%(new_type)s,"
                   "diff=%(diff)s, host=%(host)s"), {'id': volume['id'],
                                                     'new_type': new_type,
                                                     'diff': diff,
                                                     'host': host})
        self.remove_temporary_snapshots(volume)
        old_volume_settings = self.get_volume_settings_from_type(volume, host)
        return self._retype_from_old_to_new(volume, new_type,
                                            old_volume_settings, host)

    def remove_temporary_snapshots(self, volume):
        vol_name = self._get_3par_vol_name(volume)
        snapshots_list = self.client.getVolumeSnapshots(vol_name)
        tmp_snapshots_list = [snap
                              for snap in snapshots_list
                              if snap.startswith('tss-')]
        LOG.debug("temporary snapshot list %(name)s",
                  {'name': tmp_snapshots_list})
        for temp_snap in tmp_snapshots_list:
            LOG.debug("Found a temporary snapshot %(name)s",
                      {'name': temp_snap})
            try:
                self.client.deleteVolume(temp_snap)
            except hpeexceptions.HTTPNotFound:
                # if the volume is gone, it's as good as a
                # successful delete
                pass
            except Exception:
                msg = _("Volume has a temporary snapshot.")
                raise exception.VolumeIsBusy(message=msg)

    def revert_to_snapshot(self, volume, snapshot):
        """Revert volume to snapshot.

        :param volume: A dictionary describing the volume to revert
        :param snapshot: A dictionary describing the latest snapshot
        """
        volume_name = self._get_3par_vol_name(volume)
        snapshot_name = self._get_3par_snap_name(snapshot['id'])
        rcg_name = self._get_3par_rcg_name(volume)
        volume_part_of_group = (
            self._volume_of_hpe_tiramisu_type_and_part_of_group(volume))
        if volume_part_of_group:
            group = volume.get('group')
            rcg_name = self._get_3par_rcg_name_of_group(group.id)

        optional = {}
        replication_flag = self._volume_of_replicated_type(
            volume, hpe_tiramisu_check=True)
        if replication_flag or volume_part_of_group:
            LOG.debug("Found replicated volume: %(volume)s.",
                      {'volume': volume_name})
            optional['allowRemoteCopyParent'] = True
            try:
                self.client.stopRemoteCopy(rcg_name)
            except Exception as ex:
                msg = (_("There was an error stopping remote copy: %s.") %
                       six.text_type(ex))
                LOG.error(msg)
                raise exception.VolumeBackendAPIException(data=msg)

        if self.client.isOnlinePhysicalCopy(volume_name):
            LOG.debug("Found an online copy for %(volume)s.",
                      {'volume': volume_name})
            optional['online'] = True

        body = self.client.promoteVirtualCopy(snapshot_name, optional=optional)

        task_id = body.get('taskid')

        task_status = self._wait_for_task_completion(task_id)
        if task_status['status'] is not self.client.TASK_DONE:
            dbg = {'status': task_status, 'id': volume['id']}
            msg = _('Promote virtual copy failed: '
                    'id=%(id)s, status=%(status)s.') % dbg
            raise exception.CinderException(msg)
        else:
            LOG.debug('Promote virtual copy completed: '
                      'id=%s.', volume['id'])

        if replication_flag or volume_part_of_group:
            try:
                self.client.startRemoteCopy(rcg_name)
            except Exception as ex:
                msg = (_("There was an error starting remote copy: %s.") %
                       six.text_type(ex))
                LOG.error(msg)
                raise exception.VolumeBackendAPIException(data=msg)

        LOG.info("Volume %(volume)s succesfully reverted to %(snap)s.",
                 {'volume': volume_name, 'snap': snapshot_name})

    def find_existing_vlun(self, volume, host, remote_client=None):
        """Finds an existing VLUN for a volume on a host.

        Returns an existing VLUN's information. If no existing VLUN is found,
        None is returned.

        :param volume: A dictionary describing a volume.
        :param host: A dictionary describing a host.
        """
        existing_vlun = None
        try:
            vol_name = self._get_3par_vol_name(volume)
            if remote_client:
                host_vluns = remote_client.getHostVLUNs(host['name'])
            else:
                host_vluns = self.client.getHostVLUNs(host['name'])

            # The first existing VLUN found will be returned.
            for vlun in host_vluns:
                if vlun['volumeName'] == vol_name:
                    existing_vlun = vlun
                    break
        except hpeexceptions.HTTPNotFound:
            # ignore, no existing VLUNs were found
            LOG.debug("No existing VLUNs were found for host/volume "
                      "combination: %(host)s, %(vol)s",
                      {'host': host['name'],
                       'vol': vol_name})
        return existing_vlun

    def find_existing_vluns(self, volume, host, remote_client=None):
        existing_vluns = []
        try:
            vol_name = self._get_3par_vol_name(volume)
            if remote_client:
                host_vluns = remote_client.getHostVLUNs(host['name'])
            else:
                host_vluns = self.client.getHostVLUNs(host['name'])

            for vlun in host_vluns:
                if vlun['volumeName'] == vol_name:
                    existing_vluns.append(vlun)
        except hpeexceptions.HTTPNotFound:
            # ignore, no existing VLUNs were found
            LOG.debug("No existing VLUNs were found for host/volume "
                      "combination: %(host)s, %(vol)s",
                      {'host': host['name'],
                       'vol': vol_name})
        return existing_vluns

    # v2 replication methods
    def failover_host(self, context, volumes, secondary_backend_id, groups):
        """Force failover to a secondary replication target."""
        volume_update_list = []
        group_update_list = []

        # Ensure replication is enabled before we try and failover.
        if not self._replication_enabled:
            msg = _("Issuing a fail-over failed because replication is "
                    "not properly configured.")
            LOG.error(msg)
            raise exception.VolumeBackendAPIException(data=msg)

        # We are removing volumes which are part of group,
        # So creating volume_copy before doing that.
        # After failover/failback operation,making volumes as like
        # previous with the help of volume_copy.
        volumes_copy = []
        volumes_copy[:] = volumes

        # Check to see if the user requested to failback.
        if (secondary_backend_id and
           secondary_backend_id == self.FAILBACK_VALUE):
            failover = False
            target_id = None
            group_target_id = self.FAILBACK_VALUE
        else:
            # Find the failover target.
            failover_target = None
            for target in self._replication_targets:
                if target['backend_id'] == secondary_backend_id:
                    failover_target = target
                    break
            if not failover_target:
                msg = _("A valid secondary target MUST be specified in order "
                        "to failover.")
                LOG.error(msg)
                raise exception.InvalidReplicationTarget(reason=msg)
            failover = True
            target_id = failover_target['backend_id']
            group_target_id = target_id

        if groups:
            for group in groups:
                vol_list = []
                vols_obj = []
                for index, vol in enumerate(volumes):
                    if vol.get('group_id') == group.id:
                        vols_obj.append(vol)
                        vol_list.append(volumes[index])

                for vol_obj in vols_obj:
                    # Remove volumes which are part of a group.
                    volumes.remove(vol_obj)

                grp_update, vol_updates = (
                    self.failover_replication(
                        None, group, vol_list, group_target_id, host=True))
                group_update_list.append({'group_id': group.id,
                                          'updates': grp_update})
                volume_update_list += vol_updates

        # user requested failback.
        if not failover:
            vol_updates = self._replication_failback(volumes)
            volume_update_list += vol_updates

        # user requested failover.
        else:
            # For each volume, if it is replicated, we want to fail it over.
            for volume in volumes:
                if self._volume_of_replicated_type(volume,
                                                   hpe_tiramisu_check=True):
                    try:
                        # Try and stop remote-copy on main array. We eat the
                        # exception here because when an array goes down, the
                        # groups will stop automatically.
                        rcg_name = self._get_3par_rcg_name(volume)
                        self.client.stopRemoteCopy(rcg_name)
                    except Exception:
                        pass

                    try:
                        # Failover to secondary array.
                        remote_rcg_name = self._get_3par_remote_rcg_name(
                            volume, volume['provider_location'])
                        cl = self._create_replication_client(failover_target)
                        cl.recoverRemoteCopyGroupFromDisaster(
                            remote_rcg_name, self.RC_ACTION_CHANGE_TO_PRIMARY)
                        volume_update_list.append(
                            {'volume_id': volume['id'],
                             'updates': {'replication_status': 'failed-over',
                                         'replication_driver_data':
                                         failover_target['id']}})
                    except Exception as ex:
                        LOG.error("There was a problem with the failover "
                                  "(%(error)s) and it was unsuccessful. "
                                  "Volume '%(volume)s will not be available "
                                  "on the failed over target.",
                                  {'error': ex,
                                   'volume': volume['id']})
                        LOG.error(msg)
                        volume_update_list.append(
                            {'volume_id': volume['id'],
                             'updates': {'replication_status': 'error'}})
                    finally:
                        self._destroy_replication_client(cl)
                else:
                    # If the volume is not of replicated type, we need to
                    # force the status into error state so a user knows they
                    # do not have access to the volume.
                    volume_update_list.append(
                        {'volume_id': volume['id'],
                         'updates': {'status': 'error'}})

        volumes[:] = volumes_copy
        return target_id, volume_update_list, group_update_list

    def _replication_failback(self, volumes):
        # Make sure the proper steps on the backend have been completed before
        # we allow a fail-over.
        if not self._is_host_ready_for_failback(volumes):
            msg = _("The host is not ready to be failed back. Please "
                    "resynchronize the volumes and resume replication on the "
                    "3PAR backends.")
            LOG.error(msg)
            raise exception.InvalidReplicationTarget(reason=msg)

        # Update the volumes status to available.
        volume_update_list = []
        for volume in volumes:
            if self._volume_of_replicated_type(volume,
                                               hpe_tiramisu_check=True):
                volume_update_list.append(
                    {'volume_id': volume['id'],
                     'updates': {'replication_status': 'available',
                                 'replication_driver_data': self.client.id}})
            else:
                # Upon failing back, we can move the non-replicated volumes
                # back into available state.
                volume_update_list.append(
                    {'volume_id': volume['id'],
                     'updates': {'status': 'available'}})

        return volume_update_list

    def _is_host_ready_for_failback(self, volumes):
        """Checks to make sure the volume has been synchronized

        This ensures that all the remote copy targets have been restored
        to their natural direction, and all of the volumes have been
        fully synchronized.
        """
        try:
            for volume in volumes:
                if self._volume_of_replicated_type(volume,
                                                   hpe_tiramisu_check=True):
                    location = volume.get('provider_location')
                    remote_rcg_name = self._get_3par_remote_rcg_name(volume,
                                                                     location)
                    rcg = self.client.getRemoteCopyGroup(remote_rcg_name)
                    if not self._are_targets_in_their_natural_direction(rcg):
                        return False

        except Exception:
            # If there was a problem, we will return false so we can
            # log an error in the parent function.
            return False

        return True

    def _do_replication_setup(self, array_id=None):
        replication_targets = []
        replication_devices = self.config.replication_device
        if replication_devices:
            for dev in replication_devices:
                remote_array = dict(dev.items())
                # Override and set defaults for certain entries
                remote_array['managed_backend_name'] = (
                    dev.get('managed_backend_name'))
                remote_array['replication_mode'] = (
                    self._get_remote_copy_mode_num(
                        dev.get('replication_mode')))
                remote_array['san_ssh_port'] = (
                    dev.get('san_ssh_port', self.config.san_ssh_port))
                remote_array['ssh_conn_timeout'] = (
                    dev.get('ssh_conn_timeout', self.config.ssh_conn_timeout))
                remote_array['san_private_key'] = (
                    dev.get('san_private_key', self.config.san_private_key))
                # Format iscsi IPs correctly
                iscsi_ips = dev.get('hpe3par_iscsi_ips')
                if iscsi_ips:
                    remote_array['hpe3par_iscsi_ips'] = iscsi_ips.split(' ')
                # Format hpe3par_iscsi_chap_enabled as a bool
                remote_array['hpe3par_iscsi_chap_enabled'] = (
                    dev.get('hpe3par_iscsi_chap_enabled') == 'True')
                array_name = remote_array['backend_id']

                # Make sure we can log into the array, that it has been
                # correctly configured, and its API version meets the
                # minimum requirement.
                cl = None
                try:
                    cl = self._create_replication_client(remote_array)
                    info = cl.getStorageSystemInfo()
                    remote_array['id'] = six.text_type(info['id'])
                    if array_id and array_id == info['id']:
                        self._active_backend_id = six.text_type(info['name'])

                    wsapi_version = cl.getWsApiVersion()['build']

                    if wsapi_version < REMOTE_COPY_API_VERSION:
                        LOG.warning("The secondary array must have an API "
                                    "version of %(min_ver)s or higher. Array "
                                    "'%(target)s' is on %(target_ver)s, "
                                    "therefore it will not be added as a "
                                    "valid replication target.",
                                    {'target': array_name,
                                     'min_ver': REMOTE_COPY_API_VERSION,
                                     'target_ver': wsapi_version})
                    elif not self._is_valid_replication_array(remote_array):
                        LOG.warning("'%s' is not a valid replication array. "
                                    "In order to be valid, backend_id, "
                                    "replication_mode, "
                                    "hpe3par_api_url, hpe3par_username, "
                                    "hpe3par_password, cpg_map, san_ip, "
                                    "san_login, and san_password "
                                    "must be specified. If the target is "
                                    "managed, managed_backend_name must be "
                                    "set as well.", array_name)
                    else:
                        replication_targets.append(remote_array)
                except Exception:
                    LOG.error("Could not log in to 3PAR array (%s) with the "
                              "provided credentials.", array_name)
                finally:
                    self._destroy_replication_client(cl)

            self._replication_targets = replication_targets
            if self._is_replication_configured_correct():
                self._replication_enabled = True

    def _is_valid_replication_array(self, target):
        required_flags = ['hpe3par_api_url', 'hpe3par_username',
                          'hpe3par_password', 'san_ip', 'san_login',
                          'san_password', 'backend_id',
                          'replication_mode', 'cpg_map']
        try:
            self.check_replication_flags(target, required_flags)
            return True
        except Exception:
            return False

    def _is_replication_configured_correct(self):
        rep_flag = True
        # Make sure there is at least one replication target.
        if len(self._replication_targets) < 1:
            LOG.error("There must be at least one valid replication "
                      "device configured.")
            rep_flag = False
        return rep_flag

    def _is_replication_mode_correct(self, mode, sync_num):
        rep_flag = True
        # Make sure replication_mode is set to either sync|periodic.
        mode = self._get_remote_copy_mode_num(mode)
        if not mode:
            LOG.error("Extra spec replication:mode must be set and must "
                      "be either 'sync' or 'periodic'.")
            rep_flag = False
        else:
            # If replication:mode is periodic, replication_sync_period must be
            # set between 300 - 31622400 seconds.
            if mode == self.PERIODIC and (
               sync_num < 300 or sync_num > 31622400):
                LOG.error("Extra spec replication:sync_period must be "
                          "greater than 299 and less than 31622401 "
                          "seconds.")
                rep_flag = False
        return rep_flag

    def is_volume_group_snap_type(self, volume_type):
        consis_group_snap_type = False
        if volume_type:
            extra_specs = volume_type.get('extra_specs')
            if 'consistent_group_snapshot_enabled' in extra_specs:
                gsnap_val = extra_specs['consistent_group_snapshot_enabled']
                consis_group_snap_type = (gsnap_val == "<is> True")
        return consis_group_snap_type

    def _volume_of_replicated_type(self, volume, hpe_tiramisu_check=None):
        replicated_type = False
        volume_type_id = volume.get('volume_type_id')
        if volume_type_id:
            volume_type = self._get_volume_type(volume_type_id)

            extra_specs = volume_type.get('extra_specs')
            if extra_specs and 'replication_enabled' in extra_specs:
                rep_val = extra_specs['replication_enabled']
                replicated_type = (rep_val == "<is> True")

            if hpe_tiramisu_check and replicated_type:
                hpe3par_tiramisu = self._get_hpe3par_tiramisu_value(
                    volume_type)
                if hpe3par_tiramisu:
                    replicated_type = False

        return replicated_type

    def _volume_of_hpe_tiramisu_type(self, volume):
        hpe_tiramisu_type = False
        replicated_type = False
        volume_type_id = volume.get('volume_type_id')
        if volume_type_id:
            volume_type = self._get_volume_type(volume_type_id)

            extra_specs = volume_type.get('extra_specs')
            if extra_specs and 'replication_enabled' in extra_specs:
                rep_val = extra_specs['replication_enabled']
                replicated_type = (rep_val == "<is> True")

            if replicated_type:
                hpe3par_tiramisu = self._get_hpe3par_tiramisu_value(
                    volume_type)
                if hpe3par_tiramisu:
                    hpe_tiramisu_type = True

        return hpe_tiramisu_type

    def _volume_of_hpe_tiramisu_type_and_part_of_group(self, volume):
        volume_part_of_group = False
        hpe_tiramisu_type = self._volume_of_hpe_tiramisu_type(volume)
        if hpe_tiramisu_type:
            if volume.get('group'):
                volume_part_of_group = True
        return volume_part_of_group

    def _is_volume_type_replicated(self, volume_type):
        replicated_type = False
        extra_specs = volume_type.get('extra_specs')
        if extra_specs and 'replication_enabled' in extra_specs:
            rep_val = extra_specs['replication_enabled']
            replicated_type = (rep_val == "<is> True")

        return replicated_type

    def _is_volume_in_remote_copy_group(self, volume):
        rcg_name = self._get_3par_rcg_name(volume)
        try:
            self.client.getRemoteCopyGroup(rcg_name)
            return True
        except hpeexceptions.HTTPNotFound:
            return False

    def _get_remote_copy_mode_num(self, mode):
        ret_mode = None
        if mode == "sync":
            ret_mode = self.SYNC
        if mode == "periodic":
            ret_mode = self.PERIODIC
        return ret_mode

    def _get_3par_config(self, array_id=None):
        self._do_replication_setup(array_id=array_id)
        conf = None
        if self._replication_enabled:
            for target in self._replication_targets:
                if target['backend_id'] == self._active_backend_id:
                    conf = target
                    break
        self._build_3par_config(conf)

    def _build_3par_config(self, conf=None):
        """Build 3PAR client config dictionary.

        self._client_conf will contain values from self.config if the volume
        is located on the primary array in order to properly contact it. If
        the volume has been failed over and therefore on a secondary array,
        self._client_conf will contain values on how to contact that array.
        The only time we will return with entries from a secondary array is
        with unmanaged replication.
        """
        if conf:
            self._client_conf['hpe3par_cpg'] = self._generate_hpe3par_cpgs(
                conf.get('cpg_map'))
            self._client_conf['hpe3par_username'] = (
                conf.get('hpe3par_username'))
            self._client_conf['hpe3par_password'] = (
                conf.get('hpe3par_password'))
            self._client_conf['san_ip'] = conf.get('san_ip')
            self._client_conf['san_login'] = conf.get('san_login')
            self._client_conf['san_password'] = conf.get('san_password')
            self._client_conf['san_ssh_port'] = conf.get('san_ssh_port')
            self._client_conf['ssh_conn_timeout'] = (
                conf.get('ssh_conn_timeout'))
            self._client_conf['san_private_key'] = conf.get('san_private_key')
            self._client_conf['hpe3par_api_url'] = conf.get('hpe3par_api_url')
            self._client_conf['hpe3par_iscsi_ips'] = (
                conf.get('hpe3par_iscsi_ips'))
            self._client_conf['hpe3par_iscsi_chap_enabled'] = (
                conf.get('hpe3par_iscsi_chap_enabled'))
            self._client_conf['iscsi_ip_address'] = (
                conf.get('target_ip_address'))
            self._client_conf['iscsi_port'] = conf.get('iscsi_port')
        else:
            self._client_conf['hpe3par_cpg'] = (
                self.config.hpe3par_cpg)
            self._client_conf['hpe3par_username'] = (
                self.config.hpe3par_username)
            self._client_conf['hpe3par_password'] = (
                self.config.hpe3par_password)
            self._client_conf['san_ip'] = self.config.san_ip
            self._client_conf['san_login'] = self.config.san_login
            self._client_conf['san_password'] = self.config.san_password
            self._client_conf['san_ssh_port'] = self.config.san_ssh_port
            self._client_conf['ssh_conn_timeout'] = (
                self.config.ssh_conn_timeout)
            self._client_conf['san_private_key'] = self.config.san_private_key
            self._client_conf['hpe3par_api_url'] = self.config.hpe3par_api_url
            self._client_conf['hpe3par_iscsi_ips'] = (
                self.config.hpe3par_iscsi_ips)
            self._client_conf['hpe3par_iscsi_chap_enabled'] = (
                self.config.hpe3par_iscsi_chap_enabled)
            self._client_conf['iscsi_ip_address'] = (
                self.config.target_ip_address)
            self._client_conf['iscsi_port'] = self.config.target_port

    def _get_cpg_from_cpg_map(self, cpg_map, target_cpg):
        ret_target_cpg = None
        cpg_pairs = cpg_map.split(' ')
        for cpg_pair in cpg_pairs:
            cpgs = cpg_pair.split(':')
            cpg = cpgs[0]
            dest_cpg = cpgs[1]
            if cpg == target_cpg:
                ret_target_cpg = dest_cpg

        return ret_target_cpg

    def _generate_hpe3par_cpgs(self, cpg_map):
        hpe3par_cpgs = []
        cpg_pairs = cpg_map.split(' ')
        for cpg_pair in cpg_pairs:
            cpgs = cpg_pair.split(':')
            hpe3par_cpgs.append(cpgs[1])

        return hpe3par_cpgs

    def _get_replication_targets(self):
        replication_targets = []
        for target in self._replication_targets:
            replication_targets.append(target['backend_id'])

        return replication_targets

    def _do_volume_replication_setup(self, volume, retype=False,
                                     dist_type_id=None):
        """This function will do or ensure the following:

        -Create volume on main array (already done in create_volume)
        -Create Remote Copy Group on main array
        -Add volume to Remote Copy Group on main array
        -Start remote copy

        If anything here fails, we will need to clean everything up in
        reverse order, including the original volume.
        """

        rcg_name = self._get_3par_rcg_name(volume)
        # If the volume is already in a remote copy group, return True
        # after starting remote copy. If remote copy is already started,
        # issuing this command again will be fine.
        if self._is_volume_in_remote_copy_group(volume):
            try:
                self.client.startRemoteCopy(rcg_name)
            except Exception:
                pass
            return True

        try:
            # Grab the extra_spec entries for replication and make sure they
            # are set correctly.
            volume_type = self._get_volume_type(volume["volume_type_id"])
            if retype and dist_type_id is not None:
                dist_type = self._get_volume_type(dist_type_id)
                extra_specs = dist_type.get("extra_specs")
            else:
                extra_specs = volume_type.get("extra_specs")
            replication_mode = extra_specs.get(
                self.EXTRA_SPEC_REP_MODE, self.DEFAULT_REP_MODE)
            replication_mode_num = self._get_remote_copy_mode_num(
                replication_mode)
            replication_sync_period = extra_specs.get(
                self.EXTRA_SPEC_REP_SYNC_PERIOD, self.DEFAULT_SYNC_PERIOD)
            if replication_sync_period:
                replication_sync_period = int(replication_sync_period)
            if not self._is_replication_mode_correct(replication_mode,
                                                     replication_sync_period):
                msg = _("The replication mode was not configured correctly "
                        "in the volume type extra_specs. If replication:mode "
                        "is periodic, replication:sync_period must also be "
                        "specified and be between 300 and 31622400 seconds.")
                LOG.error(msg)
                raise exception.VolumeBackendAPIException(data=msg)

            vol_settings = self.get_volume_settings_from_type(volume)
            local_cpg = vol_settings['cpg']
            vol_name = self._get_3par_vol_name(volume)

            # Create remote copy group on main array.
            rcg_targets = []
            sync_targets = []
            for target in self._replication_targets:
                # Only add targets that match the volumes replication mode.
                if target['replication_mode'] == replication_mode_num:
                    cpg = self._get_cpg_from_cpg_map(target['cpg_map'],
                                                     local_cpg)
                    rcg_target = {'targetName': target['backend_id'],
                                  'mode': replication_mode_num,
                                  'userCPG': cpg}
                    if self.API_VERSION < API_VERSION_2023:
                        rcg_target['snapCPG'] = cpg
                    rcg_targets.append(rcg_target)
                    sync_target = {'targetName': target['backend_id'],
                                   'syncPeriod': replication_sync_period}
                    sync_targets.append(sync_target)

            optional = {'localUserCPG': local_cpg}
            if self.API_VERSION < API_VERSION_2023:
                optional['localSnapCPG'] = vol_settings['snap_cpg']
            pool = volume_utils.extract_host(volume['host'], level='pool')
            domain = self.get_domain(pool)
            if domain:
                optional["domain"] = domain
            try:
                self.client.createRemoteCopyGroup(rcg_name, rcg_targets,
                                                  optional)
            except Exception as ex:
                msg = (_("There was an error creating the remote copy "
                         "group: %s.") %
                       six.text_type(ex))
                LOG.error(msg)
                raise exception.VolumeBackendAPIException(data=msg)

            LOG.debug("created rcg %(name)s", {'name': rcg_name})

            # Add volume to remote copy group.
            rcg_targets = []
            for target in self._replication_targets:
                # Only add targets that match the volumes replication mode.
                if target['replication_mode'] == replication_mode_num:
                    rcg_target = {'targetName': target['backend_id'],
                                  'secVolumeName': vol_name}
                    rcg_targets.append(rcg_target)
            optional = {'volumeAutoCreation': True}
            try:
                self.client.addVolumeToRemoteCopyGroup(rcg_name, vol_name,
                                                       rcg_targets,
                                                       optional=optional)
            except Exception as ex:
                msg = (_("There was an error adding the volume to the remote "
                         "copy group: %s.") %
                       six.text_type(ex))
                LOG.error(msg)
                raise exception.VolumeBackendAPIException(data=msg)

            # Check and see if we are in periodic mode. If we are, update
            # Remote Copy Group to have a sync period.
            if replication_sync_period and (
               replication_mode_num == self.PERIODIC):
                opt = {'targets': sync_targets}
                try:
                    self.client.modifyRemoteCopyGroup(rcg_name, opt)
                except Exception as ex:
                    msg = (_("There was an error setting the sync period for "
                             "the remote copy group: %s.") %
                           six.text_type(ex))
                    LOG.error(msg)
                    raise exception.VolumeBackendAPIException(data=msg)

            # Check if we are in sync mode and quorum_witness_ip is present.
            # If yes, add options for Peer Persistence (PP)
            quorum_witness_ip = None
            if replication_mode_num == self.SYNC:
                remote_target = self._replication_targets[0]
                quorum_witness_ip = remote_target.get('quorum_witness_ip')

                if quorum_witness_ip:
                    LOG.debug('setting pp_params')
                    pp_params = {'targets': [
                        {'policies': {'autoFailover': True,
                                      'pathManagement': True,
                                      'autoRecover': True}}]}
                    try:
                        self.client.modifyRemoteCopyGroup(rcg_name, pp_params)
                    except Exception as ex:
                        msg = (_("There was an error while modifying remote "
                                 "copy group: %s.") % six.text_type(ex))
                        LOG.error(msg)
                        raise exception.VolumeBackendAPIException(data=msg)

            # Start the remote copy.
            try:
                self.client.startRemoteCopy(rcg_name)
            except Exception as ex:
                msg = (_("There was an error starting remote copy: %s.") %
                       six.text_type(ex))
                LOG.error(msg)
                raise exception.VolumeBackendAPIException(data=msg)

            return True
        except Exception as ex:
            self._do_volume_replication_destroy(volume)
            msg = (_("There was an error setting up a remote copy group "
                     "on the 3PAR arrays: ('%s'). The volume will not be "
                     "recognized as replication type.") %
                   six.text_type(ex))
            LOG.error(msg)
            raise exception.VolumeBackendAPIException(data=msg)

    def _do_volume_replication_destroy(self, volume, rcg_name=None,
                                       retype=False):
        """This will completely remove all traces of a remote copy group.

        It should be used when deleting a replication enabled volume
        or if setting up a remote copy group fails. It will try and do the
        following:
        -Stop remote copy
        -Remove volume from Remote Copy Group on main array
        -Delete Remote Copy Group from main array
        -Delete volume from main array
        """
        if not rcg_name:
            rcg_name = self._get_3par_rcg_name(volume)
        vol_name = self._get_3par_vol_name(volume)

        # Stop remote copy.
        try:
            self.client.stopRemoteCopy(rcg_name)
        except Exception:
            pass

        # Delete volume from remote copy group on main array.
        try:
            self.client.removeVolumeFromRemoteCopyGroup(
                rcg_name, vol_name, removeFromTarget=True)
        except Exception:
            pass

        # Delete remote copy group on main array.
        try:
            self.client.removeRemoteCopyGroup(rcg_name)
        except Exception:
            pass

        # Delete volume on the main array.
        try:
            if not retype:
                self.client.deleteVolume(vol_name)
        except hpeexceptions.HTTPConflict as ex:
            if ex.get_code() == 34:
                # This is a special case which means the
                # volume is part of a volume set.
                self._delete_vvset(volume)
                self.client.deleteVolume(vol_name)
        except Exception:
            pass

    def _delete_replicated_failed_over_volume(self, volume):
        location = volume.get('provider_location')
        rcg_name = self._get_3par_remote_rcg_name(volume, location)
        targets = self.client.getRemoteCopyGroup(rcg_name)['targets']
        # When failed over, we want to temporarily disable config mirroring
        # in order to be allowed to delete the volume and remote copy group
        for target in targets:
            target_name = target['targetName']
            self.client.toggleRemoteCopyConfigMirror(target_name,
                                                     mirror_config=False)

        # Do regular volume replication destroy now config mirroring is off
        try:
            self._do_volume_replication_destroy(volume, rcg_name)
        except Exception as ex:
            msg = (_("The failed-over volume could not be deleted: %s") %
                   six.text_type(ex))
            LOG.error(msg)
            raise exception.VolumeIsBusy(message=msg)
        finally:
            # Turn config mirroring back on
            for target in targets:
                target_name = target['targetName']
                self.client.toggleRemoteCopyConfigMirror(target_name,
                                                         mirror_config=True)

    def _delete_vvset(self, volume):

        # volume is part of a volume set.
        volume_name = self._get_3par_vol_name(volume)
        vvset_name = self.client.findVolumeSet(volume_name)
        LOG.debug("Returned vvset_name = %s", vvset_name)
        if vvset_name is not None:
            if vvset_name.startswith('vvs-'):
                # We have a single volume per volume set, so
                # remove the volume set.
                self.client.deleteVolumeSet(
                    self._get_3par_vvs_name(volume['id']))
            else:
                # We have a pre-defined volume set just remove the
                # volume and leave the volume set.
                self.client.removeVolumeFromVolumeSet(vvset_name,
                                                      volume_name)

    def _get_3par_rcg_name_of_group(self, group_id):
        rcg_name = self._encode_name(group_id)
        rcg = "rcg-%s" % rcg_name
        return rcg[:22]

    def _get_3par_remote_rcg_name_of_group(self, group_id, provider_location):
        return self._get_3par_rcg_name_of_group(group_id) + ".r" + (
            six.text_type(provider_location))

    def _get_hpe3par_tiramisu_value(self, volume_type):
        hpe3par_tiramisu = False
        hpe3par_keys = self._get_keys_by_volume_type(volume_type)
        if hpe3par_keys.get('group_replication'):
            hpe3par_tiramisu = (
                hpe3par_keys['group_replication'] == "<is> True")

        return hpe3par_tiramisu

    def _stop_remote_copy_group(self, group):
        # Stop remote copy.
        rcg_name = self._get_3par_rcg_name_of_group(group.id)
        try:
            self.client.stopRemoteCopy(rcg_name)
        except Exception:
            LOG.debug("Stopping remote copy group on group: %(group_id)s is "
                      "failed", {'group_id': group.id})

    def _start_remote_copy_group(self, group):
        # Start remote copy.
        rcg_name = self._get_3par_rcg_name_of_group(group.id)
        rcg = self.client.getRemoteCopyGroup(rcg_name)
        if not rcg['volumes']:
            return
        try:
            self.client.startRemoteCopy(rcg_name)
        except Exception as ex:
            msg = (_("There was an error starting remote copy: %s.") %
                   six.text_type(ex))
            LOG.error(msg)
            raise exception.VolumeBackendAPIException(data=msg)

    def _check_rep_status_enabled_on_group(self, group):
        """Check replication status for group.

        Group status must be enabled before proceeding with certain
        operations.
        :param group: the group object
        :raises: InvalidInput
        """
        if group.is_replicated:
            if group.replication_status != fields.ReplicationStatus.ENABLED:
                msg = (_('Replication status should be %(status)s for '
                         'replication-enabled group: %(group)s.')
                       % {'status': fields.ReplicationStatus.ENABLED,
                          'group': group.id})
                LOG.error(msg)
                raise exception.InvalidInput(reason=msg)

            if not self._replication_enabled:
                host_backend = volume_utils.extract_host(group.host, 'backend')
                msg = _("replication is not properly configured on backend: "
                        "(backend)%s") % {'backend': host_backend}
                LOG.error(msg)
                raise exception.VolumeBackendAPIException(data=msg)
        else:
            LOG.debug('Replication is not enabled on group %s, '
                      'skip status check.', group.id)

    def _get_replication_mode_from_volume(self, volume):
        volume_type = self._get_volume_type(volume["volume_type_id"])
        replication_mode_num = (
            self._get_replication_mode_from_volume_type(volume_type))

        return replication_mode_num

    def _get_replication_mode_from_volume_type(self, volume_type):
        # Default replication mode is PERIODIC
        replication_mode_num = self.PERIODIC
        extra_specs = volume_type.get("extra_specs")
        if extra_specs:
            replication_mode = extra_specs.get(
                self.EXTRA_SPEC_REP_MODE, self.DEFAULT_REP_MODE)

            replication_mode_num = self._get_remote_copy_mode_num(
                replication_mode)

        return replication_mode_num

    def _get_replication_sync_period_from_volume(self, volume):
        volume_type = self._get_volume_type(volume["volume_type_id"])
        replication_sync_period = (
            self._get_replication_sync_period_from_volume_type(volume_type))

        return replication_sync_period

    def _get_replication_sync_period_from_volume_type(self, volume_type):
        # Default replication sync period is 900s
        replication_sync_period = self.DEFAULT_SYNC_PERIOD
        rep_mode = self.DEFAULT_REP_MODE
        extra_specs = volume_type.get("extra_specs")
        if extra_specs:
            replication_sync_period = extra_specs.get(
                self.EXTRA_SPEC_REP_SYNC_PERIOD, self.DEFAULT_SYNC_PERIOD)

            replication_sync_period = int(replication_sync_period)
            if not self._is_replication_mode_correct(rep_mode,
                                                     replication_sync_period):
                msg = _("The replication mode was not configured "
                        "correctly in the volume type extra_specs. "
                        "If replication:mode is periodic, "
                        "replication:sync_period must also be specified "
                        "and be between 300 and 31622400 seconds.")
                LOG.error(msg)
                raise exception.VolumeBackendAPIException(data=msg)

        return replication_sync_period

    def _check_replication_matched(self, volume, group):
        """Check volume type and group type.

        This will make sure they do not conflict with each other.
        :param volume: volume to be checked
        :param extra_specs: the extra specifications
        :raises: InvalidInput
        """

        vol_is_re = self._volume_of_replicated_type(volume)
        group_is_re = group.is_replicated

        if not (vol_is_re == group_is_re):
            msg = _('Replication should be enabled or disabled for both '
                    'volume or group. Volume replication status: '
                    '%(vol_status)s, group replication status: '
                    '%(group_status)s') % {
                        'vol_status': vol_is_re, 'group_status': group_is_re}
            raise exception.InvalidInput(reason=msg)

    def _remove_vol_from_remote_copy_group(self, group, volume):
        rcg_name = self._get_3par_rcg_name_of_group(group.id)
        vol_name = self._get_3par_vol_name(volume)

        try:
            # Delete volume from remote copy group on secondary array.
            self.client.removeVolumeFromRemoteCopyGroup(
                rcg_name, vol_name, removeFromTarget=True)
        except Exception as ex:
            # Start RCG even if we fail to remove volume from it.
            self._start_remote_copy_group(group)
            msg = (_("There was an error removing a volume: %(volume)s from "
                     "Group: %(group)s : %(err)s") %
                   {'volume': volume.get('id'), 'group': group.id,
                    'err': six.text_type(ex)})
            LOG.error(msg)
            raise exception.VolumeBackendAPIException(data=msg)

    def _add_vol_to_remote_group(self, group, volume):
        # Stop remote copy, so we can add volumes in RCG.
        self._stop_remote_copy_group(group)
        # Add a volume to RCG
        self._add_vol_to_remote_copy_group(group, volume)
        # Start RCG
        self._start_remote_copy_group(group)

    def _add_vol_to_remote_copy_group(self, group, volume):
        rcg_name = self._get_3par_rcg_name_of_group(group.id)
        try:
            rcg = self.client.getRemoteCopyGroup(rcg_name)
            # If volumes are not present in RCG, which means we need to set,
            # RCG attributes.
            if not len(rcg['volumes']):
                self._set_rcg_attributes(volume, rcg_name)

            self._add_vol_to_remote(volume, rcg_name)
            # If replication mode is periodic then set sync period on RCG.
            self._set_rcg_sync_period(volume, rcg_name)
        except Exception as ex:
            # Start RCG even if we fail to add volume to it
            self._start_remote_copy_group(group)
            msg = (_("There was an error adding a volume: %(volume)s to "
                     "Group: %(group)s : %(err)s") %
                   {'volume': volume.get('id'), 'group': group.id,
                    'err': six.text_type(ex)})
            LOG.error(msg)
            raise exception.VolumeBackendAPIException(data=msg)

    def _set_rcg_sync_period(self, volume, rcg_name):
        sync_targets = []
        replication_mode_num = self._get_replication_mode_from_volume(volume)
        replication_sync_period = (
            self._get_replication_sync_period_from_volume(volume))
        if not (replication_mode_num == self.PERIODIC):
            return

        rcg = self.client.getRemoteCopyGroup(rcg_name)

        # Check and see if we are in periodic mode. If we are, update
        # Remote Copy Group to have a sync period.
        if len(rcg['volumes']) and 'syncPeriod' in rcg['targets'][0]:
            if replication_sync_period != int(rcg['targets'][0]['syncPeriod']):
                for target in self._replication_targets:
                    if target['replication_mode'] == replication_mode_num:
                        sync_target = {'targetName': target['backend_id'],
                                       'syncPeriod': replication_sync_period}
                        sync_targets.append(sync_target)

                opt = {'targets': sync_targets}

                try:
                    self.client.modifyRemoteCopyGroup(rcg_name, opt)
                except Exception as ex:
                    msg = (_("There was an error setting the sync period for "
                             "the remote copy group: %s.") %
                           six.text_type(ex))
                    LOG.error(msg)
                    raise exception.VolumeBackendAPIException(data=msg)

    def _set_rcg_attributes(self, volume, rcg_name):
        rcg_targets = []
        vol_settings = self.get_volume_settings_from_type(volume)
        local_cpg = vol_settings['cpg']
        replication_mode_num = self._get_replication_mode_from_volume(volume)

        for target in self._replication_targets:
            if target['replication_mode'] == replication_mode_num:
                cpg = self._get_cpg_from_cpg_map(target['cpg_map'],
                                                 local_cpg)
                rcg_target = {'targetName': target['backend_id'],
                              'remoteUserCPG': cpg,
                              'remoteSnapCPG': cpg}
                rcg_targets.append(rcg_target)

        optional = {'localSnapCPG': vol_settings['snap_cpg'],
                    'localUserCPG': local_cpg,
                    'targets': rcg_targets}

        try:
            self.client.modifyRemoteCopyGroup(rcg_name, optional)
        except Exception as ex:
            msg = (_("There was an error modifying the remote copy "
                     "group: %s.") %
                   six.text_type(ex))
            LOG.error(msg)
            raise exception.VolumeBackendAPIException(data=msg)

    def _add_vol_to_remote(self, volume, rcg_name):
        # Add a volume to remote copy group.
        rcg_targets = []
        vol_name = self._get_3par_vol_name(volume)
        replication_mode_num = self._get_replication_mode_from_volume(volume)
        for target in self._replication_targets:
            if target['replication_mode'] == replication_mode_num:
                rcg_target = {'targetName': target['backend_id'],
                              'secVolumeName': vol_name}
                rcg_targets.append(rcg_target)
        optional = {'volumeAutoCreation': True}
        try:
            self.client.addVolumeToRemoteCopyGroup(rcg_name, vol_name,
                                                   rcg_targets,
                                                   optional=optional)
        except Exception as ex:
            msg = (_("There was an error adding the volume to the remote "
                     "copy group: %s.") %
                   six.text_type(ex))
            LOG.error(msg)
            raise exception.VolumeBackendAPIException(data=msg)

    def _is_group_in_remote_copy_group(self, group):
        rcg_name = self._get_3par_rcg_name_of_group(group.id)
        try:
            self.client.getRemoteCopyGroup(rcg_name)
            return True
        except hpeexceptions.HTTPNotFound:
            return False

    def _remove_volumes_and_remote_copy_group(self, group, volumes):
        if not self._is_group_in_remote_copy_group(group):
            return True

        rcg_name = self._get_3par_rcg_name_of_group(group.id)
        # Stop remote copy.
        try:
            self.client.stopRemoteCopy(rcg_name)
        except Exception:
            pass

        for volume in volumes:
            vol_name = self._get_3par_vol_name(volume)
            # Delete volume from remote copy group on secondary array.
            try:
                self.client.removeVolumeFromRemoteCopyGroup(
                    rcg_name, vol_name, removeFromTarget=True)
            except Exception:
                pass

        # Delete remote copy group on main array.
        try:
            self.client.removeRemoteCopyGroup(rcg_name)
        except Exception as ex:
            msg = (_("There was an error deleting RCG %(rcg_name)s: "
                     "%(error)s.") % {'rcg_name': rcg_name, 'error': ex})
            LOG.error(msg)
            raise exception.VolumeBackendAPIException(data=msg)

    def _check_tiramisu_configuration_on_volume_types(self, volume_types):
        for volume_type in volume_types:
            self._check_tiramisu_configuration_on_volume_type(volume_type)

    def _check_tiramisu_configuration_on_volume_type(self, volume_type):
        hpe3par_tiramisu = self._get_hpe3par_tiramisu_value(volume_type)
        if not hpe3par_tiramisu:
            msg = _("hpe3par:group_replication is not set on volume type: "
                    "(id)%s") % {'id': volume_type.get('id')}
            LOG.error(msg)
            raise exception.VolumeBackendAPIException(data=msg)
        return hpe3par_tiramisu

    def _check_replication_configuration_on_volume_types(self, volume_types):
        for volume_type in volume_types:
            replicated_type = self._is_volume_type_replicated(volume_type)
            if not replicated_type:
                msg = _("replication is not set on volume type: "
                        "(id)%s") % {'id': volume_type.get('id')}
                LOG.error(msg)
                raise exception.VolumeBackendAPIException(data=msg)

    def _check_attributes_of_remote_per_volume_type(self, group):
        rep_modes = []
        rep_sync_periods = []

        for volume_type in group.volume_types:
            replication_mode_num = (
                self._get_replication_mode_from_volume_type(volume_type))
            rep_modes.append(replication_mode_num)

            if replication_mode_num == self.PERIODIC:
                rep_sync_period = (
                    self._get_replication_sync_period_from_volume_type(
                        volume_type))
                rep_sync_periods.append(rep_sync_period)

        # Check attributes of Remote on all volume types are same or not?
        if not (all(x == rep_modes[0] for x in rep_modes) and
           all(y == rep_sync_periods[0] for y in rep_sync_periods)):

            msg = _("replication mode or replication sync period must be same "
                    "on each volume type of Group:(id)%s") % {'id': group.id}
            LOG.error(msg)
            raise exception.VolumeBackendAPIException(data=msg)

    def _create_remote_copy_group_for_group(self, group):
        # Create remote copy group on main array.
        host_backend = volume_utils.extract_host(group.host, 'backend')
        rcg_targets = []
        optional = {}
        if not self._replication_enabled:
            msg = _("replication is not properly configured on backend: "
                    "(backend)%s") % {'backend': host_backend}
            LOG.error(msg)
            raise exception.VolumeBackendAPIException(data=msg)

        rcg_name = self._get_3par_rcg_name_of_group(group.id)
        replication_mode_num = (
            self._get_replication_mode_from_volume_type(group.volume_types[0]))

        for target in self._replication_targets:
            if (target['replication_mode'] == replication_mode_num):

                rcg_target = {'targetName': target['backend_id'],
                              'mode': target['replication_mode']}
                rcg_targets.append(rcg_target)

        pool = volume_utils.extract_host(group.host, level='pool')
        domain = self.get_domain(pool)
        if domain:
            optional = {"domain": domain}
        try:
            self.client.createRemoteCopyGroup(rcg_name, rcg_targets,
                                              optional)
        except Exception as ex:
            msg = (_("There was an error creating the remote copy "
                     "group: %s.") %
                   six.text_type(ex))
            LOG.error(msg)
            raise exception.VolumeBackendAPIException(data=msg)

    def _are_targets_in_their_natural_direction(self, rcg):

        targets = rcg['targets']
        for target in targets:
            if target['roleReversed'] or (
               target['state'] != self.RC_GROUP_STARTED):
                return False

        # Make sure all volumes are fully synced.
        volumes = rcg['volumes']
        for volume in volumes:
            remote_volumes = volume['remoteVolumes']
            for remote_volume in remote_volumes:
                if remote_volume['syncStatus'] != (
                   self.SYNC_STATUS_COMPLETED):
                    return False
        return True

    def _group_failover_replication(self, failover_target, group,
                                    provider_location):
        rcg_name = self._get_3par_rcg_name_of_group(group.id)
        try:
            # Try and stop remote-copy on main array. We eat the
            # exception here because when an array goes down, the
            # groups will stop automatically.
            self.client.stopRemoteCopy(rcg_name)
        except Exception:
            pass

        try:
            # Failover to secondary array.
            remote_rcg_name = self._get_3par_remote_rcg_name_of_group(
                group.id, provider_location)
            cl = self._create_replication_client(failover_target)
            cl.recoverRemoteCopyGroupFromDisaster(
                remote_rcg_name, self.RC_ACTION_CHANGE_TO_PRIMARY)
        except Exception as ex:
            msg = (_("There was a problem with the failover: "
                     "(%(error)s) and it was unsuccessful.") %
                   {'err': six.text_type(ex)})
            LOG.error(msg)
            raise exception.VolumeBackendAPIException(data=msg)
        finally:
            self._destroy_replication_client(cl)

    def _group_failback_replication(self, failback_target, group,
                                    provider_location):
        remote_rcg_name = self._get_3par_remote_rcg_name_of_group(
            group.id, provider_location)
        try:
            cl = self._create_replication_client(failback_target)
            remote_rcg = cl.getRemoteCopyGroup(remote_rcg_name)
        except Exception as ex:
            msg = (_("There was a problem with the failback: "
                     "(%(error)s) and it was unsuccessful.") %
                   {'err': six.text_type(ex)})
            LOG.error(msg)
            raise exception.VolumeBackendAPIException(data=msg)
        finally:
            self._destroy_replication_client(cl)

        if not self._are_targets_in_their_natural_direction(remote_rcg):
            msg = _("The host is not ready to be failed back. Please "
                    "resynchronize the volumes and resume replication on the "
                    "3PAR backends.")
            LOG.error(msg)
            raise exception.InvalidReplicationTarget(reason=msg)

    def enable_replication(self, context, group, volumes):
        """Enable replication for a group.

        :param context: the context
        :param group: the group object
        :param volumes: the list of volumes
        :returns: model_update, None
        """

        model_update = {}
        if not group.is_replicated:
            raise NotImplementedError()

        if not volumes:
            # Return if empty group
            return model_update, None

        try:
            vvs_name = self._get_3par_vvs_name(group.id)
            rcg_name = self._get_3par_rcg_name_of_group(group.id)

            # Check VV and RCG exist on 3par,
            # if RCG exist then start RCG
            self.client.getVolumeSet(vvs_name)
            self.client.startRemoteCopy(rcg_name)
        except hpeexceptions.HTTPNotFound as ex:
            # The remote-copy group does not exist or
            # set does not exist.
            if (ex.get_code() == 187 or ex.get_code() == 102):
                raise exception.GroupNotFound(group_id=group.id)
        except hpeexceptions.HTTPForbidden as ex:
            # The remote-copy group has already been started.
            if ex.get_code() == 215:
                pass
        except Exception as ex:
            model_update.update({
                'replication_status': fields.ReplicationStatus.ERROR})
            LOG.error("Error enabling replication on group %(group)s. "
                      "Exception received: %(e)s.",
                      {'group': group.id, 'e': ex})

        return model_update, None

    def disable_replication(self, context, group, volumes):
        """Disable replication for a group.

        :param context: the context
        :param group: the group object
        :param volumes: the list of volumes
        :returns: model_update, None
        """

        model_update = {}
        if not group.is_replicated:
            raise NotImplementedError()

        if not volumes:
            # Return if empty group
            return model_update, None

        try:
            vvs_name = self._get_3par_vvs_name(group.id)
            rcg_name = self._get_3par_rcg_name_of_group(group.id)

            # Check VV and RCG exist on 3par,
            # if RCG exist then stop RCG
            self.client.getVolumeSet(vvs_name)
            self.client.stopRemoteCopy(rcg_name)
        except hpeexceptions.HTTPNotFound as ex:
            # The remote-copy group does not exist or
            # set does not exist.
            if (ex.get_code() == 187 or ex.get_code() == 102):
                raise exception.GroupNotFound(group_id=group.id)

        except Exception as ex:
            model_update.update({
                'replication_status': fields.ReplicationStatus.ERROR})
            LOG.error("Error disabling replication on group %(group)s. "
                      "Exception received: %(e)s.",
                      {'group': group.id, 'e': ex})

        return model_update, None

    def failover_replication(self, context, group, volumes,
                             secondary_backend_id=None, host=False):
        """Failover replication for a group.

        :param context: the context
        :param group: the group object
        :param volumes: the list of volumes
        :param secondary_backend_id: the secondary backend id - default None
        :param host: flag to indicate if whole host is being failed over
        :returns: model_update, None
        """

        model_update = {}
        vol_model_updates = []
        failover_target = None
        failback_target = None
        rep_data = None
        if not group.is_replicated:
            raise NotImplementedError()

        if not volumes:
            # Return if empty group
            return model_update, vol_model_updates

        if not self._replication_enabled:
            msg = _("Issuing a fail-over failed because replication is "
                    "not properly configured.")
            LOG.error(msg)
            raise exception.VolumeBackendAPIException(data=msg)
        try:
            provider_location = volumes[0].get('provider_location')
            replication_driver_data = volumes[0].get('replication_driver_data')

            failover = False if secondary_backend_id == 'default' else True

            if failover:
                # Find the failover target.
                for target in self._replication_targets:
                    if target['backend_id'] == secondary_backend_id:
                        failover_target = target
                        break
                if not failover_target:
                    msg = _("A valid secondary target MUST be specified "
                            "in order to failover.")
                    LOG.error(msg)
                    raise exception.InvalidReplicationTarget(reason=msg)

                self._group_failover_replication(failover_target, group,
                                                 provider_location)
                model_update.update({
                    'replication_status':
                        fields.ReplicationStatus.FAILED_OVER})
                vol_rep_status = fields.ReplicationStatus.FAILED_OVER
            else:
                # Find the failback target.
                for target in self._replication_targets:
                    if target['id'] == replication_driver_data:
                        failback_target = target
                        break
                if not failback_target:
                    msg = _("A valid target is not found "
                            "in order to failback.")
                    LOG.error(msg)
                    raise exception.InvalidReplicationTarget(reason=msg)
                self._group_failback_replication(failback_target, group,
                                                 provider_location)
                model_update.update({
                    'replication_status': fields.ReplicationStatus.ENABLED})
                vol_rep_status = fields.ReplicationStatus.ENABLED

        except Exception as ex:
            model_update.update({
                'replication_status': fields.ReplicationStatus.ERROR})
            vol_rep_status = fields.ReplicationStatus.ERROR
            LOG.error("Error failover replication on group %(group)s. "
                      "Exception received: %(e)s.",
                      {'group': group.id, 'e': ex})

        rep_data = target['id']
        for vol in volumes:
            loc = vol.get('provider_location')
            update = {'id': vol.get('id'),
                      'replication_status': vol_rep_status,
                      'provider_location': loc,
                      'replication_driver_data': rep_data}
            if host:
                update = {'volume_id': vol.get('id'), 'updates': update}
            vol_model_updates.append(update)
        return model_update, vol_model_updates

    class TaskWaiter(object):
        """TaskWaiter waits for task to be not active and returns status."""

        def __init__(self, client, task_id, interval=1, initial_delay=0):
            self.client = client
            self.task_id = task_id
            self.interval = interval
            self.initial_delay = initial_delay

        def _wait_for_task(self):
            status = self.client.getTask(self.task_id)
            LOG.debug("3PAR Task id %(id)s status = %(status)s",
                      {'id': self.task_id,
                       'status': status['status']})
            if status['status'] is not self.client.TASK_ACTIVE:
                raise loopingcall.LoopingCallDone(status)

        def wait_for_task(self):
            timer = loopingcall.FixedIntervalLoopingCall(self._wait_for_task)
            return timer.start(interval=self.interval,
                               initial_delay=self.initial_delay).wait()


class ReplicateVolumeTask(flow_utils.CinderTask):

    """Task to replicate a volume.

    This is a task for adding/removing the replication feature to volume.
    It is intended for use during retype(). This task has no revert.
    # TODO(sumit): revert back to original volume extra-spec
    """

    def __init__(self, action, **kwargs):
        super(ReplicateVolumeTask, self).__init__(addons=[action])

    def execute(self, common, volume, new_type_id):

        new_replicated_type = False

        if new_type_id:
            new_volume_type = common._get_volume_type(new_type_id)

            extra_specs = new_volume_type.get('extra_specs', None)
            if extra_specs and 'replication_enabled' in extra_specs:
                rep_val = extra_specs['replication_enabled']
                new_replicated_type = (rep_val == "<is> True")

        if (common._volume_of_replicated_type(volume, hpe_tiramisu_check=True)
           and new_replicated_type):
            # Retype from replication enabled to replication enable.
            common._do_volume_replication_destroy(volume, retype=True)
            common._do_volume_replication_setup(
                volume,
                retype=True,
                dist_type_id=new_type_id)
        elif (not common._volume_of_replicated_type(volume,
              hpe_tiramisu_check=True) and new_replicated_type):
            # Retype from replication disabled to replication enable.
            common._do_volume_replication_setup(
                volume,
                retype=True,
                dist_type_id=new_type_id)
        elif common._volume_of_replicated_type(volume,
                                               hpe_tiramisu_check=True):
            # Retype from replication enabled to replication disable.
            common._do_volume_replication_destroy(volume, retype=True)


class ModifyVolumeTask(flow_utils.CinderTask):

    """Task to change a volume's snapCPG and comment.

    This is a task for changing the snapCPG and comment.  It is intended for
    use during retype().  These changes are done together with a single
    modify request which should be fast and easy to revert.

    Because we do not support retype with existing snapshots, we can change
    the snapCPG without using a keepVV.  If snapshots exist, then this will
    fail, as desired.

    This task does not change the userCPG or provisioningType.  Those changes
    may require tunevv, so they are done by the TuneVolumeTask.

    The new comment will contain the new type, VVS and QOS information along
    with whatever else was in the old comment dict.

    The old comment and snapCPG are restored if revert is called.
    """

    def __init__(self, action):
        self.needs_revert = False
        super(ModifyVolumeTask, self).__init__(addons=[action])

    def _get_new_comment(self, old_comment, new_vvs, new_qos,
                         new_type_name, new_type_id):

        # Modify the comment during ModifyVolume
        comment_dict = dict(ast.literal_eval(old_comment))
        if 'vvs' in comment_dict:
            del comment_dict['vvs']
        if 'qos' in comment_dict:
            del comment_dict['qos']
        if new_vvs:
            comment_dict['vvs'] = new_vvs
        elif new_qos:
            comment_dict['qos'] = new_qos
        else:
            comment_dict['qos'] = {}

        if new_type_name:
            comment_dict['volume_type_name'] = new_type_name
        else:
            comment_dict.pop('volume_type_name', None)

        if new_type_id:
            comment_dict['volume_type_id'] = new_type_id
        else:
            comment_dict.pop('volume_type_id', None)

        return comment_dict

    def execute(self, common, volume_name, old_snap_cpg, new_snap_cpg,
                old_comment, new_vvs, new_qos, new_type_name, new_type_id):

        comment_dict = self._get_new_comment(
            old_comment, new_vvs, new_qos, new_type_name, new_type_id)

        LOG.debug("API_VERSION: %(ver_1)s, API_VERSION_2023: %(ver_2)s",
                  {'ver_1': common.API_VERSION,
                   'ver_2': API_VERSION_2023})
        if (new_snap_cpg != old_snap_cpg and
                common.API_VERSION < API_VERSION_2023):
            # Modify the snap_cpg.  This will fail with snapshots.
            LOG.info("Modifying %(volume_name)s snap_cpg from "
                     "%(old_snap_cpg)s to %(new_snap_cpg)s.",
                     {'volume_name': volume_name,
                      'old_snap_cpg': old_snap_cpg,
                      'new_snap_cpg': new_snap_cpg})
            common.client.modifyVolume(
                volume_name,
                {'snapCPG': new_snap_cpg,
                 'comment': json.dumps(comment_dict)})
            self.needs_revert = True
        else:
            LOG.info("Modifying %s comments.", volume_name)
            common.client.modifyVolume(
                volume_name,
                {'comment': json.dumps(comment_dict)})
            self.needs_revert = True

    def revert(self, common, volume_name, old_snap_cpg, new_snap_cpg,
               old_comment, **kwargs):
        if self.needs_revert:
            LOG.info("Retype revert %(volume_name)s snap_cpg from "
                     "%(new_snap_cpg)s back to %(old_snap_cpg)s.",
                     {'volume_name': volume_name,
                      'new_snap_cpg': new_snap_cpg,
                      'old_snap_cpg': old_snap_cpg})
            try:
                common.client.modifyVolume(
                    volume_name,
                    {'snapCPG': old_snap_cpg, 'comment': old_comment})
            except Exception as ex:
                LOG.error("Exception during snapCPG revert: %s", ex)


class TuneVolumeTask(flow_utils.CinderTask):

    """Task to change a volume's CPG and/or provisioning type.

    This is a task for changing the CPG and/or provisioning type.
    It is intended for use during retype().

    This task has no revert.  The current design is to do this task last
    and do revert-able tasks first. Un-doing a tunevv can be expensive
    and should be avoided.
    """

    def __init__(self, action, **kwargs):
        super(TuneVolumeTask, self).__init__(addons=[action])

    def execute(self, common, old_tpvv, new_tpvv, old_tdvv, new_tdvv,
                old_cpg, new_cpg, volume_name, new_compression):
        common.tune_vv(old_tpvv, new_tpvv, old_tdvv, new_tdvv,
                       old_cpg, new_cpg, volume_name, new_compression)


class ModifySpecsTask(flow_utils.CinderTask):

    """Set/unset the QOS settings and/or VV set for the volume's new type.

    This is a task for changing the QOS settings and/or VV set.  It is intended
    for use during retype().  If changes are made during execute(), then they
    need to be undone if revert() is called (i.e., if a later task fails).

    For 3PAR, we ignore QOS settings if a VVS is explicitly set, otherwise we
    create a VV set and use that for QOS settings.  That is why they are lumped
    together here.  Most of the decision-making about VVS vs. QOS settings vs.
    old-style scoped extra-specs is handled in existing reusable code.  Here
    we mainly need to know what old stuff to remove before calling the function
    that knows how to set the new stuff.

    Basic task flow is as follows:  Remove the volume from the old externally
    created VVS (when appropriate), delete the old cinder-created VVS, call
    the function that knows how to set a new VVS or QOS settings.

    If any changes are made during execute, then revert needs to reverse them.
    """

    def __init__(self, action):
        self.needs_revert = False
        super(ModifySpecsTask, self).__init__(addons=[action])

    def execute(self, common, volume_name, volume, old_cpg, new_cpg,
                old_vvs, new_vvs, old_qos, new_qos,
                old_flash_cache, new_flash_cache):

        if (old_vvs != new_vvs or
                old_qos != new_qos or
                old_flash_cache != new_flash_cache):

            # Remove VV from old VV Set.
            if old_vvs is not None and old_vvs != new_vvs:
                common.client.removeVolumeFromVolumeSet(old_vvs,
                                                        volume_name)
                self.needs_revert = True

            # If any extra or qos specs changed then remove the old
            # special VV set that we create.  We'll recreate it
            # as needed.
            vvs_name = common._get_3par_vvs_name(volume['id'])
            try:
                common.client.deleteVolumeSet(vvs_name)
                self.needs_revert = True
            except hpeexceptions.HTTPNotFound as ex:
                # HTTPNotFound(code=102) is OK.  Set does not exist.
                if ex.get_code() != 102:
                    LOG.error("Unexpected error when retype() tried to "
                              "deleteVolumeSet(%s)", vvs_name)
                    raise

            if new_vvs or new_qos or new_flash_cache:
                common._add_volume_to_volume_set(
                    volume, volume_name, new_cpg, new_vvs, new_qos,
                    new_flash_cache)
                self.needs_revert = True

    def revert(self, common, volume_name, volume, old_vvs, new_vvs, old_qos,
               old_cpg, **kwargs):
        if self.needs_revert:
            # If any extra or qos specs changed then remove the old
            # special VV set that we create and recreate it per
            # the old type specs.
            vvs_name = common._get_3par_vvs_name(volume['id'])
            try:
                common.client.deleteVolumeSet(vvs_name)
            except hpeexceptions.HTTPNotFound as ex:
                # HTTPNotFound(code=102) is OK.  Set does not exist.
                if ex.get_code() != 102:
                    LOG.error("Unexpected error when retype() revert "
                              "tried to deleteVolumeSet(%s)", vvs_name)
            except Exception:
                LOG.error("Unexpected error when retype() revert "
                          "tried to deleteVolumeSet(%s)", vvs_name)

            if old_vvs is not None or old_qos is not None:
                try:
                    common._add_volume_to_volume_set(
                        volume, volume_name, old_cpg, old_vvs, old_qos)
                except Exception as ex:
                    LOG.error("%(exception)s: Exception during revert of "
                              "retype for volume %(volume_name)s. "
                              "Original volume set/QOS settings may not "
                              "have been fully restored.",
                              {'exception': ex, 'volume_name': volume_name})

            if new_vvs is not None and old_vvs != new_vvs:
                try:
                    common.client.removeVolumeFromVolumeSet(
                        new_vvs, volume_name)
                except Exception as ex:
                    LOG.error("%(exception)s: Exception during revert of "
                              "retype for volume %(volume_name)s. "
                              "Failed to remove from new volume set "
                              "%(new_vvs)s.",
                              {'exception': ex,
                               'volume_name': volume_name,
                               'new_vvs': new_vvs})