summaryrefslogtreecommitdiff
path: root/openstackclient/compute/v2/server.py
blob: 8496a13eb96ccbd5cd4f476edbd108a6819748f0 (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
#   Copyright 2012-2013 OpenStack Foundation
#
#   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.
#

"""Compute v2 Server action implementations"""

import argparse
import getpass
import io
import json
import logging
import os

from cliff import columns as cliff_columns
import iso8601
from novaclient import api_versions
from novaclient.v2 import servers
from openstack import exceptions as sdk_exceptions
from openstack import utils as sdk_utils
from osc_lib.cli import format_columns
from osc_lib.cli import parseractions
from osc_lib.command import command
from osc_lib import exceptions
from osc_lib import utils
from oslo_utils import strutils

from openstackclient.i18n import _
from openstackclient.identity import common as identity_common
from openstackclient.network import common as network_common


LOG = logging.getLogger(__name__)

IMAGE_STRING_FOR_BFV = 'N/A (booted from volume)'


class PowerStateColumn(cliff_columns.FormattableColumn):
    """Generate a formatted string of a server's power state."""

    power_states = [
        'NOSTATE',      # 0x00
        'Running',      # 0x01
        '',             # 0x02
        'Paused',       # 0x03
        'Shutdown',     # 0x04
        '',             # 0x05
        'Crashed',      # 0x06
        'Suspended'     # 0x07
    ]

    def human_readable(self):
        try:
            return self.power_states[self._value]
        except Exception:
            return 'N/A'


class AddressesColumn(cliff_columns.FormattableColumn):
    """Generate a formatted string of a server's addresses."""

    def human_readable(self):
        try:
            return utils.format_dict_of_list({
                k: [i['addr'] for i in v if 'addr' in i]
                for k, v in self._value.items()})
        except Exception:
            return 'N/A'

    def machine_readable(self):
        return {k: [i['addr'] for i in v if 'addr' in i]
                for k, v in self._value.items()}


class HostColumn(cliff_columns.FormattableColumn):
    """Generate a formatted string of a hostname."""

    def human_readable(self):
        if self._value is None:
            return ''

        return self._value


def _get_ip_address(addresses, address_type, ip_address_family):
    # Old style addresses
    if address_type in addresses:
        for addy in addresses[address_type]:
            if int(addy['version']) in ip_address_family:
                return addy['addr']

    # New style addresses
    new_address_type = address_type
    if address_type == 'public':
        new_address_type = 'floating'
    if address_type == 'private':
        new_address_type = 'fixed'
    for network in addresses:
        for addy in addresses[network]:
            # Case where it is list of strings
            if isinstance(addy, str):
                if new_address_type == 'fixed':
                    return addresses[network][0]
                else:
                    return addresses[network][-1]
            # Case where it is a dict
            if 'OS-EXT-IPS:type' not in addy:
                continue
            if addy['OS-EXT-IPS:type'] == new_address_type:
                if int(addy['version']) in ip_address_family:
                    return addy['addr']
    msg = _("ERROR: No %(type)s IP version %(family)s address found")
    raise exceptions.CommandError(
        msg % {"type": address_type,
               "family": ip_address_family}
    )


def _prep_server_detail(compute_client, image_client, server, refresh=True):
    """Prepare the detailed server dict for printing

    :param compute_client: a compute client instance
    :param image_client: an image client instance
    :param server: a Server resource
    :param refresh: Flag indicating if ``server`` is already the latest version
                    or if it needs to be refreshed, for example when showing
                    the latest details of a server after creating it.
    :rtype: a dict of server details
    """
    # Note: Some callers of this routine pass a novaclient server, and others
    # pass an SDK server. Column names may be different across those cases.
    info = server.to_dict()
    if refresh:
        server = utils.find_resource(compute_client.servers, info['id'])
        info.update(server.to_dict())

    # Some commands using this routine were originally implemented with the
    # nova python wrappers, and were later migrated to use the SDK. Map the
    # SDK's property names to the original property names to maintain backward
    # compatibility for existing users. Data is duplicated under both the old
    # and new name so users can consume the data by either name.
    column_map = {
        'access_ipv4': 'accessIPv4',
        'access_ipv6': 'accessIPv6',
        'admin_password': 'adminPass',
        'admin_password': 'adminPass',
        'volumes': 'os-extended-volumes:volumes_attached',
        'availability_zone': 'OS-EXT-AZ:availability_zone',
        'block_device_mapping': 'block_device_mapping_v2',
        'compute_host': 'OS-EXT-SRV-ATTR:host',
        'created_at': 'created',
        'disk_config': 'OS-DCF:diskConfig',
        'flavor_id': 'flavorRef',
        'has_config_drive': 'config_drive',
        'host_id': 'hostId',
        'fault': 'fault',
        'hostname': 'OS-EXT-SRV-ATTR:hostname',
        'hypervisor_hostname': 'OS-EXT-SRV-ATTR:hypervisor_hostname',
        'image_id': 'imageRef',
        'instance_name': 'OS-EXT-SRV-ATTR:instance_name',
        'is_locked': 'locked',
        'kernel_id': 'OS-EXT-SRV-ATTR:kernel_id',
        'launch_index': 'OS-EXT-SRV-ATTR:launch_index',
        'launched_at': 'OS-SRV-USG:launched_at',
        'power_state': 'OS-EXT-STS:power_state',
        'project_id': 'tenant_id',
        'ramdisk_id': 'OS-EXT-SRV-ATTR:ramdisk_id',
        'reservation_id': 'OS-EXT-SRV-ATTR:reservation_id',
        'root_device_name': 'OS-EXT-SRV-ATTR:root_device_name',
        'scheduler_hints': 'OS-SCH-HNT:scheduler_hints',
        'task_state': 'OS-EXT-STS:task_state',
        'terminated_at': 'OS-SRV-USG:terminated_at',
        'updated_at': 'updated',
        'user_data': 'OS-EXT-SRV-ATTR:user_data',
        'vm_state': 'OS-EXT-STS:vm_state',
    }

    info.update({
        column_map[column]: data for column, data in info.items()
        if column in column_map})

    # Convert the image blob to a name
    image_info = info.get('image', {})
    if image_info and any(image_info.values()):
        image_id = image_info.get('id', '')
        try:
            image = image_client.get_image(image_id)
            info['image'] = "%s (%s)" % (image.name, image_id)
        except Exception:
            info['image'] = image_id
    else:
        # NOTE(melwitt): An server booted from a volume will have no image
        # associated with it. We fill in the image with "N/A (booted from
        # volume)" to help users who want to be able to grep for
        # boot-from-volume servers when using the CLI.
        info['image'] = IMAGE_STRING_FOR_BFV

    # Convert the flavor blob to a name
    flavor_info = info.get('flavor', {})
    # Microversion 2.47 puts the embedded flavor into the server response
    # body but omits the id, so if not present we just expose the flavor
    # dict in the server output.
    if 'id' in flavor_info:
        flavor_id = flavor_info.get('id', '')
        try:
            flavor = utils.find_resource(compute_client.flavors, flavor_id)
            info['flavor'] = "%s (%s)" % (flavor.name, flavor_id)
        except Exception:
            info['flavor'] = flavor_id
    else:
        info['flavor'] = format_columns.DictColumn(flavor_info)

    if 'os-extended-volumes:volumes_attached' in info:
        info.update(
            {
                'volumes_attached': format_columns.ListDictColumn(
                    info.pop('os-extended-volumes:volumes_attached'))
            }
        )
    if 'security_groups' in info:
        info.update(
            {
                'security_groups': format_columns.ListDictColumn(
                    info.pop('security_groups'))
            }
        )
    if 'tags' in info:
        info.update({'tags': format_columns.ListColumn(info.pop('tags'))})

    # NOTE(dtroyer): novaclient splits these into separate entries...
    # Format addresses in a useful way
    info['addresses'] = (
        AddressesColumn(info['addresses']) if 'addresses' in info
        else format_columns.DictListColumn(info.get('networks')))

    # Map 'metadata' field to 'properties'
    info['properties'] = format_columns.DictColumn(info.pop('metadata'))

    # Migrate tenant_id to project_id naming
    if 'tenant_id' in info:
        info['project_id'] = info.pop('tenant_id')

    # Map power state num to meaningful string
    if 'OS-EXT-STS:power_state' in info:
        info['OS-EXT-STS:power_state'] = PowerStateColumn(
            info['OS-EXT-STS:power_state'])

    # Remove values that are long and not too useful
    info.pop('links', None)

    return info


def boolenv(*vars, default=False):
    """Search for the first defined of possibly many bool-like env vars.

    Returns the first environment variable defined in vars, or returns the
    default.

    :param vars: Arbitrary strings to search for. Case sensitive.
    :param default: The default to return if no value found.
    :returns: A boolean corresponding to the value found, else the default if
        no value found.
    """
    for v in vars:
        value = os.environ.get(v, None)
        if value:
            return strutils.bool_from_string(value)
    return default


class AddFixedIP(command.ShowOne):
    _description = _("Add fixed IP address to server")

    def get_parser(self, prog_name):
        parser = super(AddFixedIP, self).get_parser(prog_name)
        parser.add_argument(
            "server",
            metavar="<server>",
            help=_("Server to receive the fixed IP address (name or ID)"),
        )
        parser.add_argument(
            "network",
            metavar="<network>",
            help=_(
                "Network to allocate the fixed IP address from (name or ID)"
            ),
        )
        parser.add_argument(
            "--fixed-ip-address",
            metavar="<ip-address>",
            help=_("Requested fixed IP address"),
        )
        parser.add_argument(
            '--tag',
            metavar='<tag>',
            help=_(
                'Tag for the attached interface. '
                '(supported by --os-compute-api-version 2.49 or above)'
            )
        )
        return parser

    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.sdk_connection.compute
        server = compute_client.find_server(
            parsed_args.server,
            ignore_missing=False
        )

        if parsed_args.tag:
            if not sdk_utils.supports_microversion(compute_client, '2.49'):
                msg = _(
                    '--os-compute-api-version 2.49 or greater is required to '
                    'support the --tag option'
                )
                raise exceptions.CommandError(msg)

        if self.app.client_manager.is_network_endpoint_enabled():
            network_client = self.app.client_manager.network
            net_id = network_client.find_network(
                parsed_args.network,
                ignore_missing=False
            ).id
        else:
            net_id = parsed_args.network

        if not sdk_utils.supports_microversion(compute_client, '2.44'):
            compute_client.add_fixed_ip_to_server(
                server.id,
                net_id
            )
            return ((), ())

        kwargs = {
            'net_id': net_id
        }
        if parsed_args.fixed_ip_address:
            kwargs['fixed_ips'] = [
                {"ip_address": parsed_args.fixed_ip_address}]
        if parsed_args.tag:
            kwargs['tag'] = parsed_args.tag

        interface = compute_client.create_server_interface(server.id, **kwargs)

        columns = (
            'port_id', 'server_id', 'net_id', 'mac_addr', 'port_state',
            'fixed_ips',
        )
        column_headers = (
            'Port ID', 'Server ID', 'Network ID', 'MAC Address', 'Port State',
            'Fixed IPs',
        )
        if sdk_utils.supports_microversion(compute_client, '2.49'):
            columns += ('tag',)
            column_headers += ('Tag',)

        return (
            column_headers,
            utils.get_item_properties(
                interface,
                columns,
                formatters={
                    'fixed_ips': format_columns.ListDictColumn,
                },
            ),
        )


class AddFloatingIP(network_common.NetworkAndComputeCommand):
    _description = _("Add floating IP address to server")

    def update_parser_common(self, parser):
        parser.add_argument(
            "server",
            metavar="<server>",
            help=_("Server to receive the floating IP address (name or ID)"),
        )
        parser.add_argument(
            "ip_address",
            metavar="<ip-address>",
            help=_("Floating IP address to assign to the first available "
                   "server port (IP only)"),
        )
        parser.add_argument(
            "--fixed-ip-address",
            metavar="<ip-address>",
            help=_(
                "Fixed IP address to associate with this floating IP address. "
                "The first server port containing the fixed IP address will "
                "be used"
            ),
        )
        return parser

    def take_action_network(self, client, parsed_args):
        compute_client = self.app.client_manager.compute

        attrs = {}
        obj = client.find_ip(
            parsed_args.ip_address,
            ignore_missing=False,
        )
        server = utils.find_resource(
            compute_client.servers,
            parsed_args.server,
        )
        ports = list(client.ports(device_id=server.id))
        if not ports:
            msg = _('No attached ports found to associate floating IP with')
            raise exceptions.CommandError(msg)

        # If the fixed IP address was specified, we need to find the
        # corresponding port.
        if parsed_args.fixed_ip_address:
            fip_address = parsed_args.fixed_ip_address
            attrs['fixed_ip_address'] = fip_address
            for port in ports:
                for ip in port.fixed_ips:
                    if ip['ip_address'] == fip_address:
                        attrs['port_id'] = port.id
                        break
                else:
                    continue
                break
            if 'port_id' not in attrs:
                msg = _('No port found for fixed IP address %s')
                raise exceptions.CommandError(msg % fip_address)
            client.update_ip(obj, **attrs)
        else:
            # It's possible that one or more ports are not connected to a
            # router and thus could fail association with a floating IP.
            # Try each port until one succeeds. If none succeed, re-raise the
            # last exception.
            error = None
            for port in ports:
                attrs['port_id'] = port.id
                try:
                    client.update_ip(obj, **attrs)
                except sdk_exceptions.NotFoundException as exp:
                    # 404 ExternalGatewayForFloatingIPNotFound from neutron
                    LOG.info('Skipped port %s because it is not attached to '
                             'an external gateway', port.id)
                    error = exp
                    continue
                else:
                    error = None
                    break
            if error:
                raise error

    def take_action_compute(self, client, parsed_args):
        client.api.floating_ip_add(
            parsed_args.server,
            parsed_args.ip_address,
            fixed_address=parsed_args.fixed_ip_address,
        )


class AddPort(command.Command):
    _description = _("Add port to server")

    def get_parser(self, prog_name):
        parser = super(AddPort, self).get_parser(prog_name)
        parser.add_argument(
            "server",
            metavar="<server>",
            help=_("Server to add the port to (name or ID)"),
        )
        parser.add_argument(
            "port",
            metavar="<port>",
            help=_("Port to add to the server (name or ID)"),
        )
        parser.add_argument(
            '--tag',
            metavar='<tag>',
            help=_(
                'Tag for the attached interface '
                '(supported by --os-compute-api-version 2.49 or later)'
            )
        )
        return parser

    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.sdk_connection.compute

        server = compute_client.find_server(
            parsed_args.server, ignore_missing=False)

        if self.app.client_manager.is_network_endpoint_enabled():
            network_client = self.app.client_manager.network
            port_id = network_client.find_port(
                parsed_args.port, ignore_missing=False).id
        else:
            port_id = parsed_args.port

        kwargs = {
            'port_id': port_id
        }

        if parsed_args.tag:
            if not sdk_utils.supports_microversion(compute_client, '2.49'):
                msg = _(
                    '--os-compute-api-version 2.49 or greater is required to '
                    'support the --tag option'
                )
                raise exceptions.CommandError(msg)
            kwargs['tag'] = parsed_args.tag

        compute_client.create_server_interface(server, **kwargs)


class AddNetwork(command.Command):
    _description = _("Add network to server")

    def get_parser(self, prog_name):
        parser = super(AddNetwork, self).get_parser(prog_name)
        parser.add_argument(
            "server",
            metavar="<server>",
            help=_("Server to add the network to (name or ID)"),
        )
        parser.add_argument(
            "network",
            metavar="<network>",
            help=_("Network to add to the server (name or ID)"),
        )
        parser.add_argument(
            '--tag',
            metavar='<tag>',
            help=_(
                'Tag for the attached interface. '
                '(supported by --os-compute-api-version 2.49 or above)'
            ),
        )
        return parser

    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.sdk_connection.compute

        server = compute_client.find_server(
            parsed_args.server, ignore_missing=False)

        if self.app.client_manager.is_network_endpoint_enabled():
            network_client = self.app.client_manager.network
            net_id = network_client.find_network(
                parsed_args.network, ignore_missing=False).id
        else:
            net_id = parsed_args.network

        kwargs = {
            'net_id': net_id
        }

        if parsed_args.tag:
            if not sdk_utils.supports_microversion(compute_client, '2.49'):
                msg = _(
                    '--os-compute-api-version 2.49 or greater is required to '
                    'support the --tag option'
                )
                raise exceptions.CommandError(msg)

            kwargs['tag'] = parsed_args.tag

        compute_client.create_server_interface(server, **kwargs)


class AddServerSecurityGroup(command.Command):
    _description = _("Add security group to server")

    def get_parser(self, prog_name):
        parser = super(AddServerSecurityGroup, self).get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            help=_('Server (name or ID)'),
        )
        parser.add_argument(
            'group',
            metavar='<group>',
            help=_('Security group to add (name or ID)'),
        )
        return parser

    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.compute

        server = utils.find_resource(
            compute_client.servers,
            parsed_args.server,
        )
        security_group = compute_client.api.security_group_find(
            parsed_args.group,
        )

        server.add_security_group(security_group['id'])


class AddServerVolume(command.ShowOne):
    _description = _(
        "Add volume to server. "
        "Specify ``--os-compute-api-version 2.20`` or higher to add a volume "
        "to a server with status ``SHELVED`` or ``SHELVED_OFFLOADED``.")

    def get_parser(self, prog_name):
        parser = super(AddServerVolume, self).get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            help=_('Server (name or ID)'),
        )
        parser.add_argument(
            'volume',
            metavar='<volume>',
            help=_('Volume to add (name or ID)'),
        )
        parser.add_argument(
            '--device',
            metavar='<device>',
            help=_('Server internal device name for volume'),
        )
        parser.add_argument(
            '--tag',
            metavar='<tag>',
            help=_(
                'Tag for the attached volume '
                '(supported by --os-compute-api-version 2.49 or above)'
            ),
        )
        # TODO(stephenfin): These should be called 'delete-on-termination' and
        # 'preserve-on-termination'
        termination_group = parser.add_mutually_exclusive_group()
        termination_group.add_argument(
            '--enable-delete-on-termination',
            action='store_true',
            help=_(
                'Delete the volume when the server is destroyed '
                '(supported by --os-compute-api-version 2.79 or above)'
            ),
        )
        termination_group.add_argument(
            '--disable-delete-on-termination',
            action='store_true',
            help=_(
                'Do not delete the volume when the server is destroyed '
                '(supported by --os-compute-api-version 2.79 or above)'
            ),
        )
        return parser

    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.sdk_connection.compute
        volume_client = self.app.client_manager.sdk_connection.volume

        server = compute_client.find_server(
            parsed_args.server,
            ignore_missing=False,
        )
        volume = volume_client.find_volume(
            parsed_args.volume,
            ignore_missing=False,
        )

        kwargs = {
            "volumeId": volume.id,
            "device": parsed_args.device
        }

        if parsed_args.tag:
            if not sdk_utils.supports_microversion(compute_client, '2.49'):
                msg = _(
                    '--os-compute-api-version 2.49 or greater is required to '
                    'support the --tag option'
                )
                raise exceptions.CommandError(msg)

            kwargs['tag'] = parsed_args.tag

        if parsed_args.enable_delete_on_termination:
            if not sdk_utils.supports_microversion(compute_client, '2.79'):
                msg = _(
                    '--os-compute-api-version 2.79 or greater is required to '
                    'support the --enable-delete-on-termination option.'
                )
                raise exceptions.CommandError(msg)

            kwargs['delete_on_termination'] = True

        if parsed_args.disable_delete_on_termination:
            if not sdk_utils.supports_microversion(compute_client, '2.79'):
                msg = _(
                    '--os-compute-api-version 2.79 or greater is required to '
                    'support the --disable-delete-on-termination option.'
                )
                raise exceptions.CommandError(msg)

            kwargs['delete_on_termination'] = False

        volume_attachment = compute_client.create_volume_attachment(
            server,
            **kwargs,
        )

        columns = ('id', 'server id', 'volume id', 'device')
        column_headers = ('ID', 'Server ID', 'Volume ID', 'Device')
        if sdk_utils.supports_microversion(compute_client, '2.49'):
            columns += ('tag',)
            column_headers += ('Tag',)
        if sdk_utils.supports_microversion(compute_client, '2.79'):
            columns += ('delete_on_termination',)
            column_headers += ('Delete On Termination',)

        return (
            column_headers,
            utils.get_item_properties(volume_attachment, columns,)
        )


class NoneNICAction(argparse.Action):

    def __init__(self, option_strings, dest, help=None):
        super().__init__(
            option_strings=option_strings,
            dest=dest,
            nargs=0,
            default=[],
            required=False,
            help=help,
        )

    def __call__(self, parser, namespace, values, option_string=None):
        # Make sure we have an empty dict rather than None
        if getattr(namespace, self.dest, None) is None:
            setattr(namespace, self.dest, [])

        getattr(namespace, self.dest).append('none')


class AutoNICAction(argparse.Action):

    def __init__(self, option_strings, dest, help=None):
        super().__init__(
            option_strings=option_strings,
            dest=dest,
            nargs=0,
            default=[],
            required=False,
            help=help,
        )

    def __call__(self, parser, namespace, values, option_string=None):
        # Make sure we have an empty dict rather than None
        if getattr(namespace, self.dest, None) is None:
            setattr(namespace, self.dest, [])

        getattr(namespace, self.dest).append('auto')


class NICAction(argparse.Action):

    def __init__(
        self,
        option_strings,
        dest,
        help=None,
        metavar=None,
        key=None,
    ):
        self.key = key
        super().__init__(
            option_strings=option_strings,
            dest=dest,
            nargs=None,
            const=None,
            default=[],
            type=None,
            choices=None,
            required=False,
            help=help,
            metavar=metavar,
        )

    def __call__(self, parser, namespace, values, option_string=None):
        # Make sure we have an empty dict rather than None
        if getattr(namespace, self.dest, None) is None:
            setattr(namespace, self.dest, [])

        if self.key:
            if ',' in values or '=' in values:
                msg = _(
                    "Invalid argument %s; characters ',' and '=' are not "
                    "allowed"
                )
                raise argparse.ArgumentTypeError(msg % values)

            values = '='.join([self.key, values])
        else:
            # Handle the special auto/none cases but only when a key isn't set
            # (otherwise those could be valid values for the key)
            if values in ('auto', 'none'):
                getattr(namespace, self.dest).append(values)
                return

        # We don't include 'tag' here by default since that requires a
        # particular microversion
        info = {
            'net-id': '',
            'port-id': '',
            'v4-fixed-ip': '',
            'v6-fixed-ip': '',
        }

        for kv_str in values.split(','):
            k, sep, v = kv_str.partition('=')

            if k not in list(info) + ['tag'] or not v:
                msg = _(
                    "Invalid argument %s; argument must be of form "
                    "'net-id=net-uuid,port-id=port-uuid,v4-fixed-ip=ip-addr,"
                    "v6-fixed-ip=ip-addr,tag=tag'"
                )
                raise argparse.ArgumentTypeError(msg % values)

            info[k] = v

        if info['net-id'] and info['port-id']:
            msg = _(
                'Invalid argument %s; either network or port should be '
                'specified but not both'
            )
            raise argparse.ArgumentTypeError(msg % values)

        getattr(namespace, self.dest).append(info)


class BDMLegacyAction(argparse.Action):

    def __call__(self, parser, namespace, values, option_string=None):
        # Make sure we have an empty list rather than None
        if getattr(namespace, self.dest, None) is None:
            setattr(namespace, self.dest, [])

        dev_name, sep, dev_map = values.partition('=')
        dev_map = dev_map.split(':') if dev_map else dev_map
        if not dev_name or not dev_map or len(dev_map) > 4:
            msg = _(
                "Invalid argument %s; argument must be of form "
                "'dev-name=id[:type[:size[:delete-on-terminate]]]'"
            )
            raise argparse.ArgumentTypeError(msg % values)

        mapping = {
            'device_name': dev_name,
            # store target; this may be a name and will need verification later
            'uuid': dev_map[0],
            'source_type': 'volume',
            'destination_type': 'volume',
        }

        # decide source and destination type
        if len(dev_map) > 1 and dev_map[1]:
            if dev_map[1] not in ('volume', 'snapshot', 'image'):
                msg = _(
                    "Invalid argument %s; 'type' must be one of: volume, "
                    "snapshot, image"
                )
                raise argparse.ArgumentTypeError(msg % values)

            mapping['source_type'] = dev_map[1]

        # 3. append size and delete_on_termination, if present
        if len(dev_map) > 2 and dev_map[2]:
            mapping['volume_size'] = dev_map[2]

        if len(dev_map) > 3 and dev_map[3]:
            mapping['delete_on_termination'] = dev_map[3]

        getattr(namespace, self.dest).append(mapping)


class BDMAction(parseractions.MultiKeyValueAction):

    def __init__(self, option_strings, dest, **kwargs):
        required_keys = []
        optional_keys = [
            'uuid', 'source_type', 'destination_type',
            'disk_bus', 'device_type', 'device_name', 'volume_size',
            'guest_format', 'boot_index', 'delete_on_termination', 'tag',
            'volume_type',
        ]
        super().__init__(
            option_strings, dest, required_keys=required_keys,
            optional_keys=optional_keys, **kwargs,
        )

    # TODO(stephenfin): Remove once I549d0897ef3704b7f47000f867d6731ad15d3f2b
    # or similar lands in a release
    def validate_keys(self, keys):
        """Validate the provided keys.

        :param keys: A list of keys to validate.
        """
        valid_keys = self.required_keys | self.optional_keys
        invalid_keys = [k for k in keys if k not in valid_keys]
        if invalid_keys:
            msg = _(
                "Invalid keys %(invalid_keys)s specified.\n"
                "Valid keys are: %(valid_keys)s"
            )
            raise argparse.ArgumentTypeError(msg % {
                'invalid_keys': ', '.join(invalid_keys),
                'valid_keys': ', '.join(valid_keys),
            })

        missing_keys = [k for k in self.required_keys if k not in keys]
        if missing_keys:
            msg = _(
                "Missing required keys %(missing_keys)s.\n"
                "Required keys are: %(required_keys)s"
            )
            raise argparse.ArgumentTypeError(msg % {
                'missing_keys': ', '.join(missing_keys),
                'required_keys': ', '.join(self.required_keys),
            })

    def __call__(self, parser, namespace, values, option_string=None):
        if getattr(namespace, self.dest, None) is None:
            setattr(namespace, self.dest, [])

        if os.path.exists(values):
            with open(values) as fh:
                data = json.load(fh)

            # Validate the keys - other validation is left to later
            self.validate_keys(list(data))

            getattr(namespace, self.dest, []).append(data)
        else:
            super().__call__(parser, namespace, values, option_string)


class CreateServer(command.ShowOne):
    _description = _("Create a new server")

    def get_parser(self, prog_name):
        parser = super(CreateServer, self).get_parser(prog_name)
        parser.add_argument(
            'server_name',
            metavar='<server-name>',
            help=_('New server name'),
        )
        parser.add_argument(
            '--flavor',
            metavar='<flavor>',
            required=True,
            help=_('Create server with this flavor (name or ID)'),
        )
        disk_group = parser.add_mutually_exclusive_group()
        disk_group.add_argument(
            '--image',
            metavar='<image>',
            help=_('Create server boot disk from this image (name or ID)'),
        )
        # TODO(stephenfin): Is this actually useful? Looks like a straight port
        # from 'nova boot --image-with'. Perhaps we should deprecate this.
        disk_group.add_argument(
            '--image-property',
            metavar='<key=value>',
            action=parseractions.KeyValueAction,
            dest='image_properties',
            help=_(
                "Create server using the image that matches the specified "
                "property. Property must match exactly one property."
            ),
        )
        disk_group.add_argument(
            '--volume',
            metavar='<volume>',
            help=_(
                'Create server using this volume as the boot disk (name or ID)'
                '\n'
                'This option automatically creates a block device mapping '
                'with a boot index of 0. On many hypervisors (libvirt/kvm '
                'for example) this will be device vda. Do not create a '
                'duplicate mapping using --block-device-mapping for this '
                'volume.'
            ),
        )
        disk_group.add_argument(
            '--snapshot',
            metavar='<snapshot>',
            help=_(
                'Create server using this snapshot as the boot disk (name or '
                'ID)\n'
                'This option automatically creates a block device mapping '
                'with a boot index of 0. On many hypervisors (libvirt/kvm '
                'for example) this will be device vda. Do not create a '
                'duplicate mapping using --block-device-mapping for this '
                'volume.'
            ),
        )
        parser.add_argument(
            '--boot-from-volume',
            metavar='<volume-size>',
            type=int,
            help=_(
                'When used in conjunction with the ``--image`` or '
                '``--image-property`` option, this option automatically '
                'creates a block device mapping with a boot index of 0 '
                'and tells the compute service to create a volume of the '
                'given size (in GB) from the specified image and use it '
                'as the root disk of the server. The root volume will not '
                'be deleted when the server is deleted. This option is '
                'mutually exclusive with the ``--volume`` and ``--snapshot`` '
                'options.'
            )
        )
        # TODO(stephenfin): Remove this in the v7.0
        parser.add_argument(
            '--block-device-mapping',
            metavar='<dev-name=mapping>',
            action=BDMLegacyAction,
            default=[],
            # NOTE(RuiChen): Add '\n' to the end of line to improve formatting;
            # see cliff's _SmartHelpFormatter for more details.
            help=_(
                '**Deprecated** Create a block device on the server.\n'
                'Block device mapping in the format\n'
                '<dev-name>=<id>:<type>:<size(GB)>:<delete-on-terminate>\n'
                '<dev-name>: block device name, like: vdb, xvdc '
                '(required)\n'
                '<id>: Name or ID of the volume, volume snapshot or image '
                '(required)\n'
                '<type>: volume, snapshot or image; default: volume '
                '(optional)\n'
                '<size(GB)>: volume size if create from image or snapshot '
                '(optional)\n'
                '<delete-on-terminate>: true or false; default: false '
                '(optional)\n'
                'Replaced by --block-device'
            ),
        )
        parser.add_argument(
            '--block-device',
            metavar='',
            action=BDMAction,
            dest='block_devices',
            default=[],
            help=_(
                'Create a block device on the server.\n'
                'Either a path to a JSON file or a CSV-serialized string '
                'describing the block device mapping.\n'
                'The following keys are accepted for both:\n'
                'uuid=<uuid>: UUID of the volume, snapshot or ID '
                '(required if using source image, snapshot or volume),\n'
                'source_type=<source_type>: source type '
                '(one of: image, snapshot, volume, blank),\n'
                'destination_type=<destination_type>: destination type '
                '(one of: volume, local) (optional),\n'
                'disk_bus=<disk_bus>: device bus '
                '(one of: uml, lxc, virtio, ...) (optional),\n'
                'device_type=<device_type>: device type '
                '(one of: disk, cdrom, etc. (optional),\n'
                'device_name=<device_name>: name of the device (optional),\n'
                'volume_size=<volume_size>: size of the block device in MiB '
                '(for swap) or GiB (for everything else) (optional),\n'
                'guest_format=<guest_format>: format of device (optional),\n'
                'boot_index=<boot_index>: index of disk used to order boot '
                'disk '
                '(required for volume-backed instances),\n'
                'delete_on_termination=<true|false>: whether to delete the '
                'volume upon deletion of server (optional),\n'
                'tag=<tag>: device metadata tag (optional),\n'
                'volume_type=<volume_type>: type of volume to create (name or '
                'ID) when source if blank, image or snapshot and dest is '
                'volume (optional)'
            ),
        )
        parser.add_argument(
            '--swap',
            metavar='<swap>',
            type=int,
            help=(
                "Create and attach a local swap block device of <swap_size> "
                "MiB."
            ),
        )
        parser.add_argument(
            '--ephemeral',
            metavar='<size=size[,format=format]>',
            action=parseractions.MultiKeyValueAction,
            dest='ephemerals',
            default=[],
            required_keys=['size'],
            optional_keys=['format'],
            help=(
                "Create and attach a local ephemeral block device of <size> "
                "GiB and format it to <format>."
            ),
        )
        parser.add_argument(
            '--network',
            metavar='<network>',
            dest='nics',
            action=NICAction,
            key='net-id',
            help=_(
                "Create a NIC on the server and connect it to network. "
                "Specify option multiple times to create multiple NICs. "
                "This is a wrapper for the '--nic net-id=<network>' "
                "parameter that provides simple syntax for the standard "
                "use case of connecting a new server to a given network. "
                "For more advanced use cases, refer to the '--nic' parameter."
            ),
        )
        parser.add_argument(
            '--port',
            metavar='<port>',
            dest='nics',
            action=NICAction,
            key='port-id',
            help=_(
                "Create a NIC on the server and connect it to port. "
                "Specify option multiple times to create multiple NICs. "
                "This is a wrapper for the '--nic port-id=<port>' "
                "parameter that provides simple syntax for the standard "
                "use case of connecting a new server to a given port. For "
                "more advanced use cases, refer to the '--nic' parameter."
            ),
        )
        parser.add_argument(
            '--no-network',
            dest='nics',
            action=NoneNICAction,
            help=_(
                "Do not attach a network to the server. "
                "This is a wrapper for the '--nic none' option that provides "
                "a simple syntax for disabling network connectivity for a new "
                "server. "
                "For more advanced use cases, refer to the '--nic' parameter. "
                "(supported by --os-compute-api-version 2.37 or above)"
            ),
        )
        parser.add_argument(
            '--auto-network',
            dest='nics',
            action=AutoNICAction,
            help=_(
                "Automatically allocate a network to the server. "
                "This is the default network allocation policy. "
                "This is a wrapper for the '--nic auto' option that provides "
                "a simple syntax for enabling automatic configuration of "
                "network connectivity for a new server. "
                "For more advanced use cases, refer to the '--nic' parameter. "
                "(supported by --os-compute-api-version 2.37 or above)"
            ),
        )
        parser.add_argument(
            '--nic',
            metavar="<net-id=net-uuid,port-id=port-uuid,v4-fixed-ip=ip-addr,"
                    "v6-fixed-ip=ip-addr,tag=tag,auto,none>",
            dest='nics',
            action=NICAction,
            # NOTE(RuiChen): Add '\n' to the end of line to improve formatting;
            # see cliff's _SmartHelpFormatter for more details.
            help=_(
                "Create a NIC on the server.\n"
                "NIC in the format:\n"
                "net-id=<net-uuid>: attach NIC to network with this UUID,\n"
                "port-id=<port-uuid>: attach NIC to port with this UUID,\n"
                "v4-fixed-ip=<ip-addr>: IPv4 fixed address for NIC (optional),"
                "\n"
                "v6-fixed-ip=<ip-addr>: IPv6 fixed address for NIC (optional),"
                "\n"
                "tag: interface metadata tag (optional) "
                "(supported by --os-compute-api-version 2.43 or above),\n"
                "none: (v2.37+) no network is attached,\n"
                "auto: (v2.37+) the compute service will automatically "
                "allocate a network.\n"
                "\n"
                "Specify option multiple times to create multiple NICs.\n"
                "Specifying a --nic of auto or none cannot be used with any "
                "other --nic value.\n"
                "Either net-id or port-id must be provided, but not both."
            ),
        )
        parser.add_argument(
            '--password',
            metavar='<password>',
            help=_(
                'Set the password to this server. '
                'This option requires cloud support.'
            ),
        )
        parser.add_argument(
            '--security-group',
            metavar='<security-group>',
            action='append',
            default=[],
            help=_(
                'Security group to assign to this server (name or ID) '
                '(repeat option to set multiple groups)'
            ),
        )
        parser.add_argument(
            '--key-name',
            metavar='<key-name>',
            help=_('Keypair to inject into this server'),
        )
        parser.add_argument(
            '--property',
            metavar='<key=value>',
            action=parseractions.KeyValueAction,
            dest='properties',
            help=_(
                'Set a property on this server '
                '(repeat option to set multiple values)'
            ),
        )
        parser.add_argument(
            '--file',
            metavar='<dest-filename=source-filename>',
            action='append',
            default=[],
            help=_(
                'File(s) to inject into image before boot '
                '(repeat option to set multiple files)'
                '(supported by --os-compute-api-version 2.57 or below)'
            ),
        )
        parser.add_argument(
            '--user-data',
            metavar='<user-data>',
            help=_('User data file to serve from the metadata server'),
        )
        parser.add_argument(
            '--description',
            metavar='<description>',
            help=_(
                'Set description for the server '
                '(supported by --os-compute-api-version 2.19 or above)'
            ),
        )
        parser.add_argument(
            '--availability-zone',
            metavar='<zone-name>',
            help=_(
                'Select an availability zone for the server. '
                'Host and node are optional parameters. '
                'Availability zone in the format '
                '<zone-name>:<host-name>:<node-name>, '
                '<zone-name>::<node-name>, <zone-name>:<host-name> '
                'or <zone-name>'
            ),
        )
        parser.add_argument(
            '--host',
            metavar='<host>',
            help=_(
                'Requested host to create servers. '
                '(admin only) '
                '(supported by --os-compute-api-version 2.74 or above)'
            ),
        )
        parser.add_argument(
            '--hypervisor-hostname',
            metavar='<hypervisor-hostname>',
            help=_(
                'Requested hypervisor hostname to create servers. '
                '(admin only) '
                '(supported by --os-compute-api-version 2.74 or above)'
            ),
        )
        parser.add_argument(
            '--hint',
            metavar='<key=value>',
            action=parseractions.KeyValueAppendAction,
            default={},
            help=_('Hints for the scheduler'),
        )
        config_drive_group = parser.add_mutually_exclusive_group()
        config_drive_group.add_argument(
            '--use-config-drive',
            action='store_true',
            dest='config_drive',
            help=_("Enable config drive."),
        )
        config_drive_group.add_argument(
            '--no-config-drive',
            action='store_false',
            dest='config_drive',
            help=_("Disable config drive."),
        )
        # TODO(stephenfin): Drop support in the next major version bump after
        # Victoria
        config_drive_group.add_argument(
            '--config-drive',
            metavar='<config-drive-volume>|True',
            default=False,
            help=_(
                "**Deprecated** Use specified volume as the config drive, "
                "or 'True' to use an ephemeral drive. Replaced by "
                "'--use-config-drive'."
            ),
        )
        parser.add_argument(
            '--min',
            metavar='<count>',
            type=int,
            default=1,
            help=_('Minimum number of servers to launch (default=1)'),
        )
        parser.add_argument(
            '--max',
            metavar='<count>',
            type=int,
            default=1,
            help=_('Maximum number of servers to launch (default=1)'),
        )
        parser.add_argument(
            '--tag',
            metavar='<tag>',
            action='append',
            default=[],
            dest='tags',
            help=_(
                'Tags for the server. '
                'Specify multiple times to add multiple tags. '
                '(supported by --os-compute-api-version 2.52 or above)'
            ),
        )
        parser.add_argument(
            '--hostname',
            metavar='<hostname>',
            help=_(
                'Hostname configured for the server in the metadata service. '
                'If unset, a hostname will be automatically generated from '
                'the server name. '
                'A utility such as cloud-init is required to propagate the '
                'hostname in the metadata service to the guest OS itself. '
                '(supported by --os-compute-api-version 2.90 or above)'
            ),
        )
        parser.add_argument(
            '--wait',
            action='store_true',
            help=_('Wait for build to complete'),
        )
        parser.add_argument(
            '--trusted-image-cert',
            metavar='<trusted-cert-id>',
            action='append',
            dest='trusted_image_certs',
            help=_(
                'Trusted image certificate IDs used to validate certificates '
                'during the image signature verification process. '
                'May be specified multiple times to pass multiple trusted '
                'image certificate IDs. '
                '(supported by --os-compute-api-version 2.63 or above)'
            ),
        )
        return parser

    def take_action(self, parsed_args):

        def _show_progress(progress):
            if progress:
                self.app.stdout.write('\rProgress: %s' % progress)
                self.app.stdout.flush()

        compute_client = self.app.client_manager.compute
        volume_client = self.app.client_manager.volume
        image_client = self.app.client_manager.image

        # Lookup parsed_args.image
        image = None
        if parsed_args.image:
            image = image_client.find_image(
                parsed_args.image, ignore_missing=False)

        if not image and parsed_args.image_properties:
            def emit_duplicated_warning(img):
                img_uuid_list = [str(image.id) for image in img]
                LOG.warning(
                    'Multiple matching images: %(img_uuid_list)s\n'
                    'Using image: %(chosen_one)s',
                    {
                        'img_uuid_list': img_uuid_list,
                        'chosen_one': img_uuid_list[0],
                    })

            def _match_image(image_api, wanted_properties):
                image_list = image_api.images()
                images_matched = []
                for img in image_list:
                    img_dict = {}

                    # exclude any unhashable entries
                    img_dict_items = list(img.items())
                    if img.properties:
                        img_dict_items.extend(list(img.properties.items()))
                    for key, value in img_dict_items:
                        try:
                            set([key, value])
                        except TypeError:
                            if key != 'properties':
                                LOG.debug(
                                    'Skipped the \'%s\' attribute. '
                                    'That cannot be compared. '
                                    '(image: %s, value: %s)',
                                    key, img.id, value,
                                )
                            pass
                        else:
                            img_dict[key] = value

                    if all(
                        k in img_dict and img_dict[k] == v
                        for k, v in wanted_properties.items()
                    ):
                        images_matched.append(img)

                return images_matched

            images = _match_image(image_client, parsed_args.image_properties)
            if len(images) > 1:
                emit_duplicated_warning(images, parsed_args.image_properties)
            if images:
                image = images[0]
            else:
                msg = _(
                    'No images match the property expected by '
                    '--image-property'
                )
                raise exceptions.CommandError(msg)

        volume = None
        if parsed_args.volume:
            # --volume and --boot-from-volume are mutually exclusive.
            if parsed_args.boot_from_volume:
                msg = _('--volume is not allowed with --boot-from-volume')
                raise exceptions.CommandError(msg)

            volume = utils.find_resource(
                volume_client.volumes,
                parsed_args.volume,
            ).id

        snapshot = None
        if parsed_args.snapshot:
            # --snapshot and --boot-from-volume are mutually exclusive.
            if parsed_args.boot_from_volume:
                msg = _('--snapshot is not allowed with --boot-from-volume')
                raise exceptions.CommandError(msg)

            snapshot = utils.find_resource(
                volume_client.volume_snapshots,
                parsed_args.snapshot,
            ).id

        flavor = utils.find_resource(
            compute_client.flavors, parsed_args.flavor)

        if parsed_args.file:
            if compute_client.api_version >= api_versions.APIVersion('2.57'):
                msg = _(
                    'Personality files are deprecated and are not supported '
                    'for --os-compute-api-version greater than 2.56; use '
                    'user data instead'
                )
                raise exceptions.CommandError(msg)

        files = {}
        for f in parsed_args.file:
            dst, src = f.split('=', 1)
            try:
                files[dst] = io.open(src, 'rb')
            except IOError as e:
                msg = _("Can't open '%(source)s': %(exception)s")
                raise exceptions.CommandError(
                    msg % {'source': src, 'exception': e}
                )

        if parsed_args.min > parsed_args.max:
            msg = _("min instances should be <= max instances")
            raise exceptions.CommandError(msg)

        if parsed_args.min < 1:
            msg = _("min instances should be > 0")
            raise exceptions.CommandError(msg)

        if parsed_args.max < 1:
            msg = _("max instances should be > 0")
            raise exceptions.CommandError(msg)

        userdata = None
        if parsed_args.user_data:
            try:
                userdata = io.open(parsed_args.user_data)
            except IOError as e:
                msg = _("Can't open '%(data)s': %(exception)s")
                raise exceptions.CommandError(
                    msg % {'data': parsed_args.user_data, 'exception': e}
                )

        if parsed_args.description:
            if compute_client.api_version < api_versions.APIVersion("2.19"):
                msg = _("Description is not supported for "
                        "--os-compute-api-version less than 2.19")
                raise exceptions.CommandError(msg)

        block_device_mapping_v2 = []
        if volume:
            block_device_mapping_v2 = [{
                'uuid': volume,
                'boot_index': 0,
                'source_type': 'volume',
                'destination_type': 'volume'
            }]
        elif snapshot:
            block_device_mapping_v2 = [{
                'uuid': snapshot,
                'boot_index': 0,
                'source_type': 'snapshot',
                'destination_type': 'volume',
                'delete_on_termination': False
            }]
        elif parsed_args.boot_from_volume:
            # Tell nova to create a root volume from the image provided.
            block_device_mapping_v2 = [{
                'uuid': image.id,
                'boot_index': 0,
                'source_type': 'image',
                'destination_type': 'volume',
                'volume_size': parsed_args.boot_from_volume
            }]
            # If booting from volume we do not pass an image to compute.
            image = None

        if parsed_args.swap:
            block_device_mapping_v2.append({
                'boot_index': -1,
                'source_type': 'blank',
                'destination_type': 'local',
                'guest_format': 'swap',
                'volume_size': parsed_args.swap,
                'delete_on_termination': True,
            })

        for mapping in parsed_args.ephemerals:
            block_device_mapping_dict = {
                'boot_index': -1,
                'source_type': 'blank',
                'destination_type': 'local',
                'delete_on_termination': True,
                'volume_size': mapping['size'],
            }

            if 'format' in mapping:
                block_device_mapping_dict['guest_format'] = mapping['format']

            block_device_mapping_v2.append(block_device_mapping_dict)

        # Handle block device by device name order, like: vdb -> vdc -> vdd
        for mapping in parsed_args.block_device_mapping:
            # The 'uuid' field isn't necessarily a UUID yet; let's validate it
            # just in case
            if mapping['source_type'] == 'volume':
                volume_id = utils.find_resource(
                    volume_client.volumes, mapping['uuid'],
                ).id
                mapping['uuid'] = volume_id
            elif mapping['source_type'] == 'snapshot':
                snapshot_id = utils.find_resource(
                    volume_client.volume_snapshots, mapping['uuid'],
                ).id
                mapping['uuid'] = snapshot_id
            elif mapping['source_type'] == 'image':
                # NOTE(mriedem): In case --image is specified with the same
                # image, that becomes the root disk for the server. If the
                # block device is specified with a root device name, e.g.
                # vda, then the compute API will likely fail complaining
                # that there is a conflict. So if using the same image ID,
                # which doesn't really make sense but it's allowed, the
                # device name would need to be a non-root device, e.g. vdb.
                # Otherwise if the block device image is different from the
                # one specified by --image, then the compute service will
                # create a volume from the image and attach it to the
                # server as a non-root volume.
                image_id = image_client.find_image(
                    mapping['uuid'], ignore_missing=False,
                ).id
                mapping['uuid'] = image_id

            block_device_mapping_v2.append(mapping)

        for mapping in parsed_args.block_devices:
            if 'boot_index' in mapping:
                try:
                    mapping['boot_index'] = int(mapping['boot_index'])
                except ValueError:
                    msg = _(
                        'The boot_index key of --block-device should be an '
                        'integer'
                    )
                    raise exceptions.CommandError(msg)

            if 'tag' in mapping and (
                compute_client.api_version < api_versions.APIVersion('2.42')
            ):
                msg = _(
                    '--os-compute-api-version 2.42 or greater is '
                    'required to support the tag key of --block-device'
                )
                raise exceptions.CommandError(msg)

            if 'volume_type' in mapping and (
                compute_client.api_version < api_versions.APIVersion('2.67')
            ):
                msg = _(
                    '--os-compute-api-version 2.67 or greater is '
                    'required to support the volume_type key of --block-device'
                )
                raise exceptions.CommandError(msg)

            if 'source_type' in mapping:
                if mapping['source_type'] not in (
                    'volume', 'image', 'snapshot', 'blank',
                ):
                    msg = _(
                        'The source_type key of --block-device should be one '
                        'of: volume, image, snapshot, blank'
                    )
                    raise exceptions.CommandError(msg)
            else:
                mapping['source_type'] = 'blank'

            if 'destination_type' in mapping:
                if mapping['destination_type'] not in ('local', 'volume'):
                    msg = _(
                        'The destination_type key of --block-device should be '
                        'one of: local, volume'
                    )
                    raise exceptions.CommandError(msg)
            else:
                if mapping['source_type'] in ('blank',):
                    mapping['destination_type'] = 'local'
                else:  # volume, image, snapshot
                    mapping['destination_type'] = 'volume'

            if 'delete_on_termination' in mapping:
                try:
                    value = strutils.bool_from_string(
                        mapping['delete_on_termination'], strict=True)
                except ValueError:
                    msg = _(
                        'The delete_on_termination key of --block-device '
                        'should be a boolean-like value'
                    )
                    raise exceptions.CommandError(msg)

                mapping['delete_on_termination'] = value
            else:
                if mapping['destination_type'] == 'local':
                    mapping['delete_on_termination'] = True

            block_device_mapping_v2.append(mapping)

        if not image and not any(
            [bdm.get('boot_index') == 0 for bdm in block_device_mapping_v2]
        ):
            msg = _(
                'An image (--image, --image-property) or bootable volume '
                '(--volume, --snapshot, --block-device) is required'
            )
            raise exceptions.CommandError(msg)

        nics = parsed_args.nics

        if 'auto' in nics or 'none' in nics:
            if len(nics) > 1:
                msg = _(
                    'Specifying a --nic of auto or none cannot '
                    'be used with any other --nic, --network '
                    'or --port value.'
                )
                raise exceptions.CommandError(msg)

            if compute_client.api_version < api_versions.APIVersion('2.37'):
                msg = _(
                    '--os-compute-api-version 2.37 or greater is '
                    'required to support explicit auto-allocation of a '
                    'network or to disable network allocation'
                )
                raise exceptions.CommandError(msg)

            nics = nics[0]
        else:
            for nic in nics:
                if 'tag' in nic:
                    if (
                        compute_client.api_version <
                        api_versions.APIVersion('2.43')
                    ):
                        msg = _(
                            '--os-compute-api-version 2.43 or greater is '
                            'required to support the --nic tag field'
                        )
                        raise exceptions.CommandError(msg)

                if self.app.client_manager.is_network_endpoint_enabled():
                    network_client = self.app.client_manager.network

                    if nic['net-id']:
                        net = network_client.find_network(
                            nic['net-id'], ignore_missing=False,
                        )
                        nic['net-id'] = net.id

                    if nic['port-id']:
                        port = network_client.find_port(
                            nic['port-id'], ignore_missing=False,
                        )
                        nic['port-id'] = port.id
                else:
                    if nic['net-id']:
                        nic['net-id'] = compute_client.api.network_find(
                            nic['net-id'],
                        )['id']

                    if nic['port-id']:
                        msg = _(
                            "Can't create server with port specified "
                            "since network endpoint not enabled"
                        )
                        raise exceptions.CommandError(msg)

        if not nics:
            # Compute API version >= 2.37 requires a value, so default to
            # 'auto' to maintain legacy behavior if a nic wasn't specified.
            if compute_client.api_version >= api_versions.APIVersion('2.37'):
                nics = 'auto'
            else:
                # Default to empty list if nothing was specified and let nova
                # decide the default behavior.
                nics = []

        # Check security group exist and convert ID to name
        security_group_names = []
        if self.app.client_manager.is_network_endpoint_enabled():
            network_client = self.app.client_manager.network
            for each_sg in parsed_args.security_group:
                sg = network_client.find_security_group(each_sg,
                                                        ignore_missing=False)
                # Use security group ID to avoid multiple security group have
                # same name in neutron networking backend
                security_group_names.append(sg.id)
        else:
            # Handle nova-network case
            for each_sg in parsed_args.security_group:
                sg = compute_client.api.security_group_find(each_sg)
                security_group_names.append(sg['name'])

        hints = {}
        for key, values in parsed_args.hint.items():
            # only items with multiple values will result in a list
            if len(values) == 1:
                hints[key] = values[0]
            else:
                hints[key] = values

        if isinstance(parsed_args.config_drive, bool):
            # NOTE(stephenfin): The API doesn't accept False as a value :'(
            config_drive = parsed_args.config_drive or None
        else:
            # TODO(stephenfin): Remove when we drop support for
            # '--config-drive'
            if str(parsed_args.config_drive).lower() in ("true", "1"):
                config_drive = True
            elif str(parsed_args.config_drive).lower() in ("false", "0",
                                                           "", "none"):
                config_drive = None
            else:
                config_drive = parsed_args.config_drive

        boot_args = [parsed_args.server_name, image, flavor]

        boot_kwargs = dict(
            meta=parsed_args.properties,
            files=files,
            reservation_id=None,
            min_count=parsed_args.min,
            max_count=parsed_args.max,
            security_groups=security_group_names,
            userdata=userdata,
            key_name=parsed_args.key_name,
            availability_zone=parsed_args.availability_zone,
            admin_pass=parsed_args.password,
            block_device_mapping_v2=block_device_mapping_v2,
            nics=nics,
            scheduler_hints=hints,
            config_drive=config_drive)

        if parsed_args.description:
            boot_kwargs['description'] = parsed_args.description

        if parsed_args.tags:
            if compute_client.api_version < api_versions.APIVersion('2.52'):
                msg = _(
                    '--os-compute-api-version 2.52 or greater is required to '
                    'support the --tag option'
                )
                raise exceptions.CommandError(msg)

            boot_kwargs['tags'] = parsed_args.tags

        if parsed_args.host:
            if compute_client.api_version < api_versions.APIVersion("2.74"):
                msg = _(
                    '--os-compute-api-version 2.74 or greater is required to '
                    'support the --host option'
                )
                raise exceptions.CommandError(msg)

            boot_kwargs['host'] = parsed_args.host

        if parsed_args.hypervisor_hostname:
            if compute_client.api_version < api_versions.APIVersion("2.74"):
                msg = _(
                    '--os-compute-api-version 2.74 or greater is required to '
                    'support the --hypervisor-hostname option'
                )
                raise exceptions.CommandError(msg)

            boot_kwargs['hypervisor_hostname'] = (
                parsed_args.hypervisor_hostname)

        if parsed_args.hostname:
            if compute_client.api_version < api_versions.APIVersion("2.90"):
                msg = _(
                    '--os-compute-api-version 2.90 or greater is required to '
                    'support the --hostname option'
                )
                raise exceptions.CommandError(msg)

            boot_kwargs['hostname'] = parsed_args.hostname

        # TODO(stephenfin): Handle OS_TRUSTED_IMAGE_CERTIFICATE_IDS
        if parsed_args.trusted_image_certs:
            if not (image and not parsed_args.boot_from_volume):
                msg = _(
                    '--trusted-image-cert option is only supported for '
                    'servers booted directly from images'
                )
                raise exceptions.CommandError(msg)
            if compute_client.api_version < api_versions.APIVersion('2.63'):
                msg = _(
                    '--os-compute-api-version 2.63 or greater is required to '
                    'support the --trusted-image-cert option'
                )
                raise exceptions.CommandError(msg)

            certs = parsed_args.trusted_image_certs
            boot_kwargs['trusted_image_certificates'] = certs

        LOG.debug('boot_args: %s', boot_args)
        LOG.debug('boot_kwargs: %s', boot_kwargs)

        # Wrap the call to catch exceptions in order to close files
        try:
            server = compute_client.servers.create(*boot_args, **boot_kwargs)
        finally:
            # Clean up open files - make sure they are not strings
            for f in files:
                if hasattr(f, 'close'):
                    f.close()
            if hasattr(userdata, 'close'):
                userdata.close()

        if parsed_args.wait:
            if utils.wait_for_status(
                compute_client.servers.get,
                server.id,
                callback=_show_progress,
            ):
                self.app.stdout.write('\n')
            else:
                LOG.error('Error creating server: %s', parsed_args.server_name)
                self.app.stdout.write(_('Error creating server\n'))
                raise SystemExit

        details = _prep_server_detail(compute_client, image_client, server)
        return zip(*sorted(details.items()))


class CreateServerDump(command.Command):
    """Create a dump file in server(s)

    Trigger crash dump in server(s) with features like kdump in Linux.
    It will create a dump file in the server(s) dumping the server(s)'
    memory, and also crash the server(s). This is contingent on guest operating
    system support, and the location of the dump file inside the guest will
    depend on the exact guest operating system.

    This command requires ``--os-compute-api-version`` 2.17 or greater.
    """

    def get_parser(self, prog_name):
        parser = super(CreateServerDump, self).get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            nargs='+',
            help=_('Server(s) to create dump file (name or ID)'),
        )
        return parser

    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.sdk_connection.compute
        for name_or_id in parsed_args.server:
            server = compute_client.find_server(name_or_id)
            server.trigger_crash_dump(compute_client)


class DeleteServer(command.Command):
    _description = _("Delete server(s)")

    def get_parser(self, prog_name):
        parser = super(DeleteServer, self).get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            nargs="+",
            help=_('Server(s) to delete (name or ID)'),
        )
        parser.add_argument(
            '--force',
            action='store_true',
            help=_('Force delete server(s)'),
        )
        parser.add_argument(
            '--all-projects',
            action='store_true',
            default=boolenv('ALL_PROJECTS'),
            help=_(
                'Delete server(s) in another project by name (admin only)'
                '(can be specified using the ALL_PROJECTS envvar)'
            ),
        )
        parser.add_argument(
            '--wait',
            action='store_true',
            help=_('Wait for delete to complete'),
        )
        return parser

    def take_action(self, parsed_args):

        def _show_progress(progress):
            if progress:
                self.app.stdout.write('\rProgress: %s' % progress)
                self.app.stdout.flush()

        compute_client = self.app.client_manager.compute
        for server in parsed_args.server:
            server_obj = utils.find_resource(
                compute_client.servers, server,
                all_tenants=parsed_args.all_projects)

            if parsed_args.force:
                compute_client.servers.force_delete(server_obj.id)
            else:
                compute_client.servers.delete(server_obj.id)

            if parsed_args.wait:
                if not utils.wait_for_delete(
                    compute_client.servers,
                    server_obj.id,
                    callback=_show_progress,
                ):
                    msg = _('Error deleting server: %s')
                    LOG.error(msg, server_obj.id)
                    self.app.stdout.write(_('Error deleting server\n'))
                    raise SystemExit


def percent_type(x):
    x = int(x)
    if not 0 < x <= 100:
        raise argparse.ArgumentTypeError("Must be between 0 and 100")
    return x


class ListServer(command.Lister):
    _description = _("List servers")

    def get_parser(self, prog_name):
        parser = super(ListServer, self).get_parser(prog_name)
        parser.add_argument(
            '--reservation-id',
            metavar='<reservation-id>',
            help=_('Only return instances that match the reservation'),
        )
        parser.add_argument(
            '--ip',
            metavar='<ip-address-regex>',
            help=_('Regular expression to match IP addresses'),
        )
        parser.add_argument(
            '--ip6',
            metavar='<ip-address-regex>',
            help=_(
                'Regular expression to match IPv6 addresses. Note '
                'that this option only applies for non-admin users '
                'when using ``--os-compute-api-version`` 2.5 or greater.'
            ),
        )
        parser.add_argument(
            '--name',
            metavar='<name-regex>',
            help=_('Regular expression to match names'),
        )
        parser.add_argument(
            '--instance-name',
            metavar='<server-name>',
            help=_('Regular expression to match instance name (admin only)'),
        )
        # taken from 'task_and_vm_state_from_status' function in nova
        # the API sadly reports these in upper case and while it would be
        # wonderful to plaster over this ugliness client-side, there are
        # already users in the wild doing this in upper case that we need to
        # support
        parser.add_argument(
            '--status',
            metavar='<status>',
            choices=(
                'ACTIVE',
                'BUILD',
                'DELETED',
                'ERROR',
                'HARD_REBOOT',
                'MIGRATING',
                'PASSWORD',
                'PAUSED',
                'REBOOT',
                'REBUILD',
                'RESCUE',
                'RESIZE',
                'REVERT_RESIZE',
                'SHELVED',
                'SHELVED_OFFLOADED',
                'SHUTOFF',
                'SOFT_DELETED',
                'SUSPENDED',
                'VERIFY_RESIZE'
            ),
            help=_('Search by server status'),
        )
        parser.add_argument(
            '--flavor',
            metavar='<flavor>',
            help=_('Search by flavor (name or ID)'),
        )
        parser.add_argument(
            '--image',
            metavar='<image>',
            help=_('Search by image (name or ID)'),
        )
        parser.add_argument(
            '--host',
            metavar='<hostname>',
            help=_('Search by hostname'),
        )
        parser.add_argument(
            '--all-projects',
            action='store_true',
            default=boolenv('ALL_PROJECTS'),
            help=_(
                'Include all projects (admin only) '
                '(can be specified using the ALL_PROJECTS envvar)'
            ),
        )
        parser.add_argument(
            '--project',
            metavar='<project>',
            help=_("Search by project (admin only) (name or ID)")
        )
        identity_common.add_project_domain_option_to_parser(parser)
        parser.add_argument(
            '--user',
            metavar='<user>',
            help=_(
                'Search by user (name or ID) '
                '(admin only before microversion 2.83)'
            ),
        )
        identity_common.add_user_domain_option_to_parser(parser)
        parser.add_argument(
            '--deleted',
            action='store_true',
            default=False,
            help=_('Only display deleted servers (admin only)'),
        )
        parser.add_argument(
            '--availability-zone',
            default=None,
            help=_(
                'Search by availability zone '
                '(admin only before microversion 2.83)'
            ),
        )
        parser.add_argument(
            '--key-name',
            help=_(
                'Search by keypair name '
                '(admin only before microversion 2.83)'
            ),
        )
        config_drive_group = parser.add_mutually_exclusive_group()
        config_drive_group.add_argument(
            '--config-drive',
            action='store_true',
            dest='has_config_drive',
            default=None,
            help=_(
                'Only display servers with a config drive attached '
                '(admin only before microversion 2.83)'
            ),
        )
        # NOTE(gibi): this won't actually do anything until bug 1871409 is
        # fixed and the REST API is cleaned up regarding the values of
        # config_drive
        config_drive_group.add_argument(
            '--no-config-drive',
            action='store_false',
            dest='has_config_drive',
            help=_(
                'Only display servers without a config drive attached '
                '(admin only before microversion 2.83)'
            ),
        )
        parser.add_argument(
            '--progress',
            type=percent_type,
            default=None,
            help=_(
                'Search by progress value (%%) '
                '(admin only before microversion 2.83)'
            ),
        )
        parser.add_argument(
            '--vm-state',
            metavar='<state>',
            # taken from 'InstanceState' object field in nova
            choices=(
                'active',
                'building',
                'deleted',
                'error',
                'paused',
                'stopped',
                'suspended',
                'rescued',
                'resized',
                'shelved',
                'shelved_offloaded',
                'soft-delete',
            ),
            help=_(
                'Search by vm_state value '
                '(admin only before microversion 2.83)'
            ),
        )
        parser.add_argument(
            '--task-state',
            metavar='<state>',
            # taken from 'InstanceTaskState' object field in nova
            choices=(
                'block_device_mapping',
                'deleting',
                'image_backup',
                'image_pending_upload',
                'image_snapshot',
                'image_snapshot_pending',
                'image_uploading',
                'migrating',
                'networking',
                'pausing',
                'powering-off',
                'powering-on',
                'rebooting',
                'reboot_pending',
                'reboot_started',
                'reboot_pending_hard',
                'reboot_started_hard',
                'rebooting_hard',
                'rebuilding',
                'rebuild_block_device_mapping',
                'rebuild_spawning',
                'rescuing',
                'resize_confirming',
                'resize_finish',
                'resize_migrated',
                'resize_migrating',
                'resize_prep',
                'resize_reverting',
                'restoring',
                'resuming',
                'scheduling',
                'shelving',
                'shelving_image_pending_upload',
                'shelving_image_uploading',
                'shelving_offloading',
                'soft-deleting',
                'spawning',
                'suspending',
                'updating_password',
                'unpausing',
                'unrescuing',
                'unshelving',
            ),
            help=_(
                'Search by task_state value '
                '(admin only before microversion 2.83)'
            ),
        )
        parser.add_argument(
            '--power-state',
            metavar='<state>',
            # taken from 'InstancePowerState' object field in nova
            choices=(
                'pending',
                'running',
                'paused',
                'shutdown',
                'crashed',
                'suspended',
            ),
            help=_(
                'Search by power_state value '
                '(admin only before microversion 2.83)'
            ),
        )
        parser.add_argument(
            '--long',
            action='store_true',
            default=False,
            help=_('List additional fields in output'),
        )
        name_lookup_group = parser.add_mutually_exclusive_group()
        name_lookup_group.add_argument(
            '-n', '--no-name-lookup',
            action='store_true',
            default=False,
            help=_(
                'Skip flavor and image name lookup. '
                'Mutually exclusive with "--name-lookup-one-by-one" option.'
            ),
        )
        name_lookup_group.add_argument(
            '--name-lookup-one-by-one',
            action='store_true',
            default=False,
            help=_(
                'When looking up flavor and image names, look them up'
                'one by one as needed instead of all together (default). '
                'Mutually exclusive with "--no-name-lookup|-n" option.'
            ),
        )
        parser.add_argument(
            '--marker',
            metavar='<server>',
            default=None,
            help=_(
                'The last server of the previous page. Display '
                'list of servers after marker. Display all servers if not '
                'specified. When used with ``--deleted``, the marker must '
                'be an ID, otherwise a name or ID can be used.'
            ),
        )
        parser.add_argument(
            '--limit',
            metavar='<num-servers>',
            type=int,
            default=None,
            help=_(
                "Maximum number of servers to display. If limit equals -1, "
                "all servers will be displayed. If limit is greater than "
                "'osapi_max_limit' option of Nova API, "
                "'osapi_max_limit' will be used instead."
            ),
        )
        parser.add_argument(
            '--changes-before',
            metavar='<changes-before>',
            default=None,
            help=_(
                "List only servers changed before a certain point of time. "
                "The provided time should be an ISO 8061 formatted time "
                "(e.g., 2016-03-05T06:27:59Z). "
                '(supported by --os-compute-api-version 2.66 or above)'
            ),
        )
        parser.add_argument(
            '--changes-since',
            metavar='<changes-since>',
            default=None,
            help=_(
                "List only servers changed after a certain point of time. "
                "The provided time should be an ISO 8061 formatted time "
                "(e.g., 2016-03-04T06:27:59Z)."
            ),
        )
        lock_group = parser.add_mutually_exclusive_group()
        lock_group.add_argument(
            '--locked',
            action='store_true',
            default=False,
            help=_(
                'Only display locked servers '
                '(supported by --os-compute-api-version 2.73 or above)'
            ),
        )
        lock_group.add_argument(
            '--unlocked',
            action='store_true',
            default=False,
            help=_(
                'Only display unlocked servers '
                '(supported by --os-compute-api-version 2.73 or above)'
            ),
        )
        parser.add_argument(
            '--tags',
            metavar='<tag>',
            action='append',
            default=[],
            dest='tags',
            help=_(
                'Only list servers with the specified tag. '
                'Specify multiple times to filter on multiple tags. '
                '(supported by --os-compute-api-version 2.26 or above)'
            ),
        )
        parser.add_argument(
            '--not-tags',
            metavar='<tag>',
            action='append',
            default=[],
            dest='not_tags',
            help=_(
                'Only list servers without the specified tag. '
                'Specify multiple times to filter on multiple tags. '
                '(supported by --os-compute-api-version 2.26 or above)'
            ),
        )
        return parser

    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.sdk_connection.compute
        identity_client = self.app.client_manager.identity
        image_client = self.app.client_manager.image

        project_id = None
        if parsed_args.project:
            project_id = identity_common.find_project(
                identity_client,
                parsed_args.project,
                parsed_args.project_domain,
            ).id
            parsed_args.all_projects = True

        user_id = None
        if parsed_args.user:
            user_id = identity_common.find_user(
                identity_client,
                parsed_args.user,
                parsed_args.user_domain,
            ).id

        # Nova only supports list servers searching by flavor ID. So if a
        # flavor name is given, map it to ID.
        flavor_id = None
        if parsed_args.flavor:
            flavor = compute_client.find_flavor(parsed_args.flavor)
            if flavor is None:
                msg = _('Unable to find flavor: %s') % parsed_args.flavor
                raise exceptions.CommandError(msg)
            flavor_id = flavor.id

        # Nova only supports list servers searching by image ID. So if a
        # image name is given, map it to ID.
        image_id = None
        if parsed_args.image:
            image_id = image_client.find_image(
                parsed_args.image,
                ignore_missing=False,
            ).id

        search_opts = {
            'reservation_id': parsed_args.reservation_id,
            'ip': parsed_args.ip,
            'ip6': parsed_args.ip6,
            'name': parsed_args.name,
            'status': parsed_args.status,
            'flavor': flavor_id,
            'image': image_id,
            'host': parsed_args.host,
            'project_id': project_id,
            'all_projects': parsed_args.all_projects,
            'user_id': user_id,
            'deleted': parsed_args.deleted,
            'changes-before': parsed_args.changes_before,
            'changes-since': parsed_args.changes_since,
        }

        if parsed_args.instance_name is not None:
            search_opts['instance_name'] = parsed_args.instance_name

        if parsed_args.availability_zone:
            search_opts['availability_zone'] = parsed_args.availability_zone

        if parsed_args.key_name:
            search_opts['key_name'] = parsed_args.key_name

        if parsed_args.has_config_drive is not None:
            search_opts['config_drive'] = parsed_args.has_config_drive

        if parsed_args.progress is not None:
            search_opts['progress'] = str(parsed_args.progress)

        if parsed_args.vm_state:
            search_opts['vm_state'] = parsed_args.vm_state

        if parsed_args.task_state:
            search_opts['task_state'] = parsed_args.task_state

        if parsed_args.power_state:
            # taken from 'InstancePowerState' object field in nova
            power_state = {
                'pending': 0,
                'running': 1,
                'paused': 3,
                'shutdown': 4,
                'crashed': 6,
                'suspended': 7,
            }[parsed_args.power_state]
            search_opts['power_state'] = power_state

        if parsed_args.tags:
            if not sdk_utils.supports_microversion(compute_client, '2.26'):
                msg = _(
                    '--os-compute-api-version 2.26 or greater is required to '
                    'support the --tag option'
                )
                raise exceptions.CommandError(msg)

            search_opts['tags'] = ','.join(parsed_args.tags)

        if parsed_args.not_tags:
            if not sdk_utils.supports_microversion(compute_client, '2.26'):
                msg = _(
                    '--os-compute-api-version 2.26 or greater is required to '
                    'support the --not-tag option'
                )
                raise exceptions.CommandError(msg)

            search_opts['not-tags'] = ','.join(parsed_args.not_tags)

        if parsed_args.locked:
            if not sdk_utils.supports_microversion(compute_client, '2.73'):
                msg = _(
                    '--os-compute-api-version 2.73 or greater is required to '
                    'support the --locked option'
                )
                raise exceptions.CommandError(msg)

            search_opts['locked'] = True
        elif parsed_args.unlocked:
            if not sdk_utils.supports_microversion(compute_client, '2.73'):
                msg = _(
                    '--os-compute-api-version 2.73 or greater is required to '
                    'support the --unlocked option'
                )
                raise exceptions.CommandError(msg)

            search_opts['locked'] = False

        if parsed_args.limit is not None:
            search_opts['limit'] = parsed_args.limit
            search_opts['paginated'] = False

        LOG.debug('search options: %s', search_opts)

        if search_opts['changes-before']:
            if not sdk_utils.supports_microversion(compute_client, '2.66'):
                msg = _('--os-compute-api-version 2.66 or later is required')
                raise exceptions.CommandError(msg)

            try:
                iso8601.parse_date(search_opts['changes-before'])
            except (TypeError, iso8601.ParseError):
                raise exceptions.CommandError(
                    _('Invalid changes-before value: %s') %
                    search_opts['changes-before']
                )

        if search_opts['changes-since']:
            try:
                iso8601.parse_date(search_opts['changes-since'])
            except (TypeError, iso8601.ParseError):
                msg = _('Invalid changes-since value: %s')
                raise exceptions.CommandError(
                    msg % search_opts['changes-since']
                )

        columns = (
            'id',
            'name',
            'status',
        )
        column_headers = (
            'ID',
            'Name',
            'Status',
        )

        if parsed_args.long:
            columns += (
                'task_state',
                'power_state',
            )
            column_headers += (
                'Task State',
                'Power State',
            )

        columns += ('addresses',)
        column_headers += ('Networks',)

        if parsed_args.long:
            columns += (
                'image_name',
                'image_id',
            )
            column_headers += (
                'Image Name',
                'Image ID',
            )
        else:
            if parsed_args.no_name_lookup:
                columns += ('image_id',)
            else:
                columns += ('image_name',)
            column_headers += ('Image',)

        # microversion 2.47 puts the embedded flavor into the server response
        # body but omits the id, so if not present we just expose the original
        # flavor name in the output
        if sdk_utils.supports_microversion(compute_client, '2.47'):
            columns += ('flavor_name',)
            column_headers += ('Flavor',)
        else:
            if parsed_args.long:
                columns += (
                    'flavor_name',
                    'flavor_id',
                )
                column_headers += (
                    'Flavor Name',
                    'Flavor ID',
                )
            else:
                if parsed_args.no_name_lookup:
                    columns += ('flavor_id',)
                else:
                    columns += ('flavor_name',)
                column_headers += ('Flavor',)

        if parsed_args.long:
            columns += (
                'availability_zone',
                'hypervisor_hostname',
                'metadata',
            )
            column_headers += (
                'Availability Zone',
                'Host',
                'Properties',
            )

        # support for additional columns
        if parsed_args.columns:
            for c in parsed_args.columns:
                if c in ('Project ID', 'project_id'):
                    columns += ('project_id',)
                    column_headers += ('Project ID',)
                if c in ('User ID', 'user_id'):
                    columns += ('user_id',)
                    column_headers += ('User ID',)
                if c in ('Created At', 'created_at'):
                    columns += ('created_at',)
                    column_headers += ('Created At',)
                if c in ('Security Groups', 'security_groups'):
                    columns += ('security_groups_name',)
                    column_headers += ('Security Groups',)
                if c in ("Task State", "task_state"):
                    columns += ('task_state',)
                    column_headers += ('Task State',)
                if c in ("Power State", "power_state"):
                    columns += ('power_state',)
                    column_headers += ('Power State',)
                if c in ("Image ID", "image_id"):
                    columns += ('Image ID',)
                    column_headers += ('Image ID',)
                if c in ("Flavor ID", "flavor_id"):
                    columns += ('flavor_id',)
                    column_headers += ('Flavor ID',)
                if c in ('Availability Zone', "availability_zone"):
                    columns += ('availability_zone',)
                    column_headers += ('Availability Zone',)
                if c in ('Host', "host"):
                    columns += ('hypervisor_hostname',)
                    column_headers += ('Host',)
                if c in ('Properties', "properties"):
                    columns += ('Metadata',)
                    column_headers += ('Properties',)

            # remove duplicates
            column_headers = tuple(dict.fromkeys(column_headers))
            columns = tuple(dict.fromkeys(columns))

        if parsed_args.marker is not None:
            # Check if both "--marker" and "--deleted" are used.
            # In that scenario a lookup is not needed as the marker
            # needs to be an ID, because find_resource does not
            # handle deleted resources
            if parsed_args.deleted:
                marker_id = parsed_args.marker
            else:
                marker_id = compute_client.find_server(parsed_args.marker).id
            search_opts['marker'] = marker_id

        data = list(compute_client.servers(**search_opts))

        images = {}
        flavors = {}
        if data and not parsed_args.no_name_lookup:
            # partial responses from down cells will not have an image
            # attribute so we use getattr
            image_ids = {
                s.image['id'] for s in data
                if getattr(s, 'image', None) and s.image.get('id')
            }

            # create a dict that maps image_id to image object, which is used
            # to display the "Image Name" column. Note that 'image.id' can be
            # empty for BFV instances and 'image' can be missing entirely if
            # there are infra failures
            if parsed_args.name_lookup_one_by_one or image_id:
                for image_id in image_ids:
                    # "Image Name" is not crucial, so we swallow any exceptions
                    try:
                        images[image_id] = image_client.get_image(image_id)
                    except Exception:
                        pass
            else:
                try:
                    # some deployments can have *loads* of images so we only
                    # want to list the ones we care about. It would be better
                    # to only retrun the *fields* we care about (name) but
                    # glance doesn't support that
                    # NOTE(stephenfin): This could result in super long URLs
                    # but it seems unlikely to cause issues. Apache supports
                    # URL lengths of up to 8190 characters by default, which
                    # should allow for more than 220 unique image ID (different
                    # servers are likely use the same image ID) in the filter.
                    # Who'd need more than that in a single command?
                    images_list = image_client.images(
                        id=f"in:{','.join(image_ids)}"
                    )
                    for i in images_list:
                        images[i.id] = i
                except Exception:
                    pass

            # create a dict that maps flavor_id to flavor object, which is used
            # to display the "Flavor Name" column. Note that 'flavor.id' is not
            # present on microversion 2.47 or later and 'flavor' won't be
            # present if there are infra failures
            if parsed_args.name_lookup_one_by_one or flavor_id:
                for f_id in set(
                    s.flavor['id'] for s in data
                    if s.flavor and s.flavor.get('id')
                ):
                    # "Flavor Name" is not crucial, so we swallow any
                    # exceptions
                    try:
                        flavors[f_id] = compute_client.find_flavor(f_id)
                    except Exception:
                        pass
            else:
                try:
                    flavors_list = compute_client.flavors(is_public=None)
                    for i in flavors_list:
                        flavors[i.id] = i
                except Exception:
                    pass

        # Populate image_name, image_id, flavor_name and flavor_id attributes
        # of server objects so that we can display those columns.
        for s in data:
            if sdk_utils.supports_microversion(compute_client, '2.69'):
                # NOTE(tssurya): From 2.69, we will have the keys 'flavor'
                # and 'image' missing in the server response during
                # infrastructure failure situations.
                # For those servers with partial constructs we just skip the
                # processing of the image and flavor information.
                if not hasattr(s, 'image') or not hasattr(s, 'flavor'):
                    continue

            if 'id' in s.image and s.image.id is not None:
                image = images.get(s.image['id'])
                if image:
                    s.image_name = image.name
                s.image_id = s.image['id']
            else:
                # NOTE(melwitt): An server booted from a volume will have no
                # image associated with it. We fill in the Image Name and ID
                # with "N/A (booted from volume)" to help users who want to be
                # able to grep for boot-from-volume servers when using the CLI.
                s.image_name = IMAGE_STRING_FOR_BFV
                s.image_id = IMAGE_STRING_FOR_BFV

            if not sdk_utils.supports_microversion(compute_client, '2.47'):
                flavor = flavors.get(s.flavor['id'])
                if flavor:
                    s.flavor_name = flavor.name
                s.flavor_id = s.flavor['id']
            else:
                s.flavor_name = s.flavor['original_name']

        # Add a list with security group name as attribute
        for s in data:
            if hasattr(s, 'security_groups') and s.security_groups is not None:
                s.security_groups_name = [x["name"] for x in s.security_groups]
            else:
                s.security_groups_name = []

        # The host_status field contains the status of the compute host the
        # server is on. It is only returned by the API when the nova-api
        # policy allows. Users can look at the host_status field when, for
        # example, their server has status ACTIVE but is unresponsive. The
        # host_status field can indicate a possible problem on the host
        # it's on, providing useful information to a user in this
        # situation.
        if (
            sdk_utils.supports_microversion(compute_client, '2.16') and
            parsed_args.long
        ):
            if any([s.host_status is not None for s in data]):
                columns += ('Host Status',)
                column_headers += ('Host Status',)

        table = (
            column_headers,
            (
                utils.get_item_properties(
                    s, columns,
                    mixed_case_fields=(
                        'task_state',
                        'power_state',
                        'availability_zone',
                        'host',
                    ),
                    formatters={
                        'power_state': PowerStateColumn,
                        'addresses': AddressesColumn,
                        'metadata': format_columns.DictColumn,
                        'security_groups_name': format_columns.ListColumn,
                        'hypervisor_hostname': HostColumn,
                    },
                ) for s in data
            ),
        )
        return table


class LockServer(command.Command):

    _description = _("""Lock server(s)

A non-admin user will not be able to execute actions.""")

    def get_parser(self, prog_name):
        parser = super(LockServer, self).get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            nargs='+',
            help=_('Server(s) to lock (name or ID)'),
        )
        parser.add_argument(
            '--reason',
            metavar='<reason>',
            default=None,
            help=_(
                'Reason for locking the server(s) '
                '(supported by --os-compute-api-version 2.73 or above)'
            ),
        )
        return parser

    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.sdk_connection.compute

        kwargs = {}
        if parsed_args.reason:
            if not sdk_utils.supports_microversion(compute_client, '2.73'):
                msg = _(
                    '--os-compute-api-version 2.73 or greater is required to '
                    'use the --reason option'
                )
                raise exceptions.CommandError(msg)

            kwargs['locked_reason'] = parsed_args.reason

        for server in parsed_args.server:
            server_id = compute_client.find_server(
                server,
                ignore_missing=False
            ).id
            compute_client.lock_server(server_id, **kwargs)


# FIXME(dtroyer): Here is what I want, how with argparse/cliff?
# server migrate [--wait] \
#   [--live <hostname>
#     [--shared-migration | --block-migration]
#     [--disk-overcommit | --no-disk-overcommit]]
#   <server>
#
# live_parser = parser.add_argument_group(title='Live migration options')
# then adding the groups doesn't seem to work

class MigrateServer(command.Command):
    _description = _("""Migrate server to different host.

A migrate operation is implemented as a resize operation using the same flavor
as the old server. This means that, like resize, migrate works by creating a
new server using the same flavor and copying the contents of the original disk
into a new one. As with resize, the migrate operation is a two-step process for
the user: the first step is to perform the migrate, and the second step is to
either confirm (verify) success and release the old server, or to declare a
revert to release the new server and restart the old one.""")

    def get_parser(self, prog_name):
        parser = super(MigrateServer, self).get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            help=_('Server (name or ID)'),
        )
        parser.add_argument(
            '--live-migration',
            dest='live_migration',
            action='store_true',
            help=_(
                'Live migrate the server; use the ``--host`` option to '
                'specify a target host for the migration which will be '
                'validated by the scheduler'
            ),
        )
        parser.add_argument(
            '--host',
            metavar='<hostname>',
            help=_(
                'Migrate the server to the specified host. '
                '(supported with --os-compute-api-version 2.30 or above '
                'when used with the --live-migration option) '
                '(supported with --os-compute-api-version 2.56 or above '
                'when used without the --live-migration option)'
            ),
        )
        migration_group = parser.add_mutually_exclusive_group()
        migration_group.add_argument(
            '--shared-migration',
            dest='block_migration',
            action='store_false',
            default=None,
            help=_(
                'Perform a shared live migration '
                '(default before --os-compute-api-version 2.25, auto after)'
            ),
        )
        migration_group.add_argument(
            '--block-migration',
            dest='block_migration',
            action='store_true',
            help=_(
                'Perform a block live migration '
                '(auto-configured from --os-compute-api-version 2.25)'
            ),
        )
        disk_group = parser.add_mutually_exclusive_group()
        disk_group.add_argument(
            '--disk-overcommit',
            action='store_true',
            default=None,
            help=_(
                'Allow disk over-commit on the destination host'
                '(supported with --os-compute-api-version 2.24 or below)'
            ),
        )
        disk_group.add_argument(
            '--no-disk-overcommit',
            dest='disk_overcommit',
            action='store_false',
            help=_(
                'Do not over-commit disk on the destination host (default)'
                '(supported with --os-compute-api-version 2.24 or below)'
            ),
        )
        parser.add_argument(
            '--wait',
            action='store_true',
            help=_('Wait for migrate to complete'),
        )
        return parser

    def take_action(self, parsed_args):

        def _show_progress(progress):
            if progress:
                self.app.stdout.write('\rProgress: %s' % progress)
                self.app.stdout.flush()

        compute_client = self.app.client_manager.compute

        server = utils.find_resource(
            compute_client.servers,
            parsed_args.server,
        )

        if parsed_args.live_migration:
            kwargs = {}

            block_migration = parsed_args.block_migration
            if block_migration is None:
                if (
                    compute_client.api_version <
                    api_versions.APIVersion('2.25')
                ):
                    block_migration = False
                else:
                    block_migration = 'auto'

            kwargs['block_migration'] = block_migration

            # Technically we could pass a non-None host with
            # --os-compute-api-version < 2.30 but that is the same thing
            # as the --live option bypassing the scheduler which we don't
            # want to support, so if the user is using --live-migration
            # and --host, we want to enforce that they are using version
            # 2.30 or greater.
            if (
                parsed_args.host and
                compute_client.api_version < api_versions.APIVersion('2.30')
            ):
                raise exceptions.CommandError(
                    '--os-compute-api-version 2.30 or greater is required '
                    'when using --host'
                )

            # The host parameter is required in the API even if None.
            kwargs['host'] = parsed_args.host

            if compute_client.api_version < api_versions.APIVersion('2.25'):
                kwargs['disk_over_commit'] = parsed_args.disk_overcommit
                # We can't use an argparse default value because then we can't
                # distinguish between explicit 'False' and unset for the below
                # case (microversion >= 2.25)
                if kwargs['disk_over_commit'] is None:
                    kwargs['disk_over_commit'] = False
            elif parsed_args.disk_overcommit is not None:
                # TODO(stephenfin): Raise an error here in OSC 7.0
                msg = _(
                    'The --disk-overcommit and --no-disk-overcommit '
                    'options are only supported by '
                    '--os-compute-api-version 2.24 or below; this will '
                    'be an error in a future release'
                )
                self.log.warning(msg)

            server.live_migrate(**kwargs)
        else:  # cold migration
            if parsed_args.block_migration or parsed_args.disk_overcommit:
                raise exceptions.CommandError(
                    "--live-migration must be specified if "
                    "--block-migration or --disk-overcommit is "
                    "specified")
            if parsed_args.host:
                if (compute_client.api_version <
                        api_versions.APIVersion('2.56')):
                    msg = _(
                        '--os-compute-api-version 2.56 or greater is '
                        'required to use --host without --live-migration.'
                    )
                    raise exceptions.CommandError(msg)

            kwargs = {'host': parsed_args.host} if parsed_args.host else {}
            server.migrate(**kwargs)

        if parsed_args.wait:
            if utils.wait_for_status(
                compute_client.servers.get,
                server.id,
                success_status=['active', 'verify_resize'],
                callback=_show_progress,
            ):
                self.app.stdout.write(_('Complete\n'))
            else:
                LOG.error(_('Error migrating server: %s'),
                          server.id)
                self.app.stdout.write(_('Error migrating server\n'))
                raise SystemExit


class PauseServer(command.Command):
    _description = _("Pause server(s)")

    def get_parser(self, prog_name):
        parser = super(PauseServer, self).get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            nargs='+',
            help=_('Server(s) to pause (name or ID)'),
        )
        return parser

    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.sdk_connection.compute
        for server in parsed_args.server:
            server_id = compute_client.find_server(
                server,
                ignore_missing=False,
            ).id
            compute_client.pause_server(server_id)


class RebootServer(command.Command):
    _description = _("Perform a hard or soft server reboot")

    def get_parser(self, prog_name):
        parser = super(RebootServer, self).get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            help=_('Server (name or ID)'),
        )
        group = parser.add_mutually_exclusive_group()
        group.add_argument(
            '--hard',
            dest='reboot_type',
            action='store_const',
            const=servers.REBOOT_HARD,
            default=servers.REBOOT_SOFT,
            help=_('Perform a hard reboot'),
        )
        group.add_argument(
            '--soft',
            dest='reboot_type',
            action='store_const',
            const=servers.REBOOT_SOFT,
            default=servers.REBOOT_SOFT,
            help=_('Perform a soft reboot'),
        )
        parser.add_argument(
            '--wait',
            action='store_true',
            help=_('Wait for reboot to complete'),
        )
        return parser

    def take_action(self, parsed_args):

        def _show_progress(progress):
            if progress:
                self.app.stdout.write('\rProgress: %s' % progress)
                self.app.stdout.flush()

        compute_client = self.app.client_manager.compute
        server = utils.find_resource(
            compute_client.servers, parsed_args.server)
        server.reboot(parsed_args.reboot_type)

        if parsed_args.wait:
            if utils.wait_for_status(
                compute_client.servers.get,
                server.id,
                callback=_show_progress,
            ):
                self.app.stdout.write(_('Complete\n'))
            else:
                LOG.error(_('Error rebooting server: %s'),
                          server.id)
                self.app.stdout.write(_('Error rebooting server\n'))
                raise SystemExit


class RebuildServer(command.ShowOne):
    _description = _("Rebuild server")

    def get_parser(self, prog_name):
        parser = super(RebuildServer, self).get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            help=_('Server (name or ID)'),
        )
        parser.add_argument(
            '--image',
            metavar='<image>',
            help=_(
                'Recreate server from the specified image (name or ID).'
                'Defaults to the currently used one.'
            ),
        )
        parser.add_argument(
            '--name',
            metavar='<name>',
            help=_('Set the new name of the rebuilt server'),
        )
        parser.add_argument(
            '--password',
            metavar='<password>',
            help=_(
                'Set the password on the rebuilt server. '
                'This option requires cloud support.'
            ),
        )
        parser.add_argument(
            '--property',
            metavar='<key=value>',
            action=parseractions.KeyValueAction,
            dest='properties',
            help=_(
                'Set a new property on the rebuilt server '
                '(repeat option to set multiple values)'
            ),
        )
        parser.add_argument(
            '--description',
            metavar='<description>',
            help=_(
                'Set a new description on the rebuilt server '
                '(supported by --os-compute-api-version 2.19 or above)'
            ),
        )
        preserve_ephemeral_group = parser.add_mutually_exclusive_group()
        preserve_ephemeral_group.add_argument(
            '--preserve-ephemeral',
            action='store_true',
            default=None,
            help=_(
                'Preserve the default ephemeral storage partition on rebuild.'
            ),
        )
        preserve_ephemeral_group.add_argument(
            '--no-preserve-ephemeral',
            action='store_false',
            dest='preserve_ephemeral',
            help=_(
                'Do not preserve the default ephemeral storage partition on '
                'rebuild.'
            ),
        )
        key_group = parser.add_mutually_exclusive_group()
        key_group.add_argument(
            '--key-name',
            metavar='<key-name>',
            help=_(
                'Set the key name of key pair on the rebuilt server. '
                'Cannot be specified with the --key-unset option. '
                '(supported by --os-compute-api-version 2.54 or above)'
            ),
        )
        key_group.add_argument(
            '--no-key-name',
            action='store_true',
            dest='no_key_name',
            help=_(
                'Unset the key name of key pair on the rebuilt server. '
                'Cannot be specified with the --key-name option. '
                '(supported by --os-compute-api-version 2.54 or above)'
            ),
        )
        # TODO(stephenfin): Remove this in a future major version bump
        key_group.add_argument(
            '--key-unset',
            action='store_true',
            dest='no_key_name',
            help=argparse.SUPPRESS,
        )
        user_data_group = parser.add_mutually_exclusive_group()
        user_data_group.add_argument(
            '--user-data',
            metavar='<user-data>',
            help=_(
                'Add a new user data file to the rebuilt server. '
                'Cannot be specified with the --no-user-data option. '
                '(supported by --os-compute-api-version 2.57 or above)'
            ),
        )
        user_data_group.add_argument(
            '--no-user-data',
            action='store_true',
            default=False,
            help=_(
                'Remove existing user data when rebuilding server. '
                'Cannot be specified with the --user-data option. '
                '(supported by --os-compute-api-version 2.57 or above)'
            ),
        )
        trusted_certs_group = parser.add_mutually_exclusive_group()
        trusted_certs_group.add_argument(
            '--trusted-image-cert',
            metavar='<trusted-cert-id>',
            action='append',
            dest='trusted_image_certs',
            help=_(
                'Trusted image certificate IDs used to validate certificates '
                'during the image signature verification process. '
                'May be specified multiple times to pass multiple trusted '
                'image certificate IDs. '
                'Cannot be specified with the --no-trusted-certs option. '
                '(supported by --os-compute-api-version 2.63 or above)'
            ),
        )
        trusted_certs_group.add_argument(
            '--no-trusted-image-certs',
            action='store_true',
            default=False,
            help=_(
                'Remove any existing trusted image certificates from the '
                'server. '
                'Cannot be specified with the --trusted-certs option. '
                '(supported by --os-compute-api-version 2.63 or above)'
            ),
        )
        parser.add_argument(
            '--hostname',
            metavar='<hostname>',
            help=_(
                'Hostname configured for the server in the metadata service. '
                'A separate utility running in the guest is required to '
                'propagate changes to this value to the guest OS itself. '
                '(supported by --os-compute-api-version 2.90 or above)'
            ),
        )
        parser.add_argument(
            '--reimage-boot-volume',
            action='store_true',
            dest='reimage_boot_volume',
            default=None,
            help=_(
                'Rebuild a volume-backed server. This will wipe the root '
                'volume data and overwrite it with the provided image. '
                'Defaults to False. '
                '(supported by --os-compute-api-version 2.93 or above)'
            ),
        )
        parser.add_argument(
            '--no-reimage-boot-volume',
            action='store_false',
            dest='reimage_boot_volume',
            default=None,
            help=_(
                'Do not rebuild a volume-backed server. '
                '(supported by --os-compute-api-version 2.93 or above)'
            ),
        )
        parser.add_argument(
            '--wait',
            action='store_true',
            help=_('Wait for rebuild to complete'),
        )
        return parser

    def take_action(self, parsed_args):

        def _show_progress(progress):
            if progress:
                self.app.stdout.write('\rProgress: %s' % progress)
                self.app.stdout.flush()

        compute_client = self.app.client_manager.compute
        image_client = self.app.client_manager.image

        server = utils.find_resource(
            compute_client.servers, parsed_args.server)

        # If parsed_args.image is not set and if the instance is image backed,
        # default to the currently used one. If the instance is volume backed,
        # it is not trivial to fetch the current image and probably better
        # to error out in this case and ask user to supply the image.
        if parsed_args.image:
            image = image_client.find_image(
                parsed_args.image, ignore_missing=False)
        else:
            if not server.image:
                msg = _(
                    'The --image option is required when rebuilding a '
                    'volume-backed server'
                )
                raise exceptions.CommandError(msg)
            image = image_client.get_image(server.image['id'])

        kwargs = {}

        if parsed_args.name is not None:
            kwargs['name'] = parsed_args.name

        if parsed_args.preserve_ephemeral is not None:
            kwargs['preserve_ephemeral'] = parsed_args.preserve_ephemeral

        if parsed_args.properties:
            kwargs['meta'] = parsed_args.properties

        if parsed_args.description:
            if compute_client.api_version < api_versions.APIVersion('2.19'):
                msg = _(
                    '--os-compute-api-version 2.19 or greater is required to '
                    'support the --description option'
                )
                raise exceptions.CommandError(msg)

            kwargs['description'] = parsed_args.description

        if parsed_args.key_name:
            if compute_client.api_version < api_versions.APIVersion('2.54'):
                msg = _(
                    '--os-compute-api-version 2.54 or greater is required to '
                    'support the --key-name option'
                )
                raise exceptions.CommandError(msg)

            kwargs['key_name'] = parsed_args.key_name
        elif parsed_args.no_key_name:
            if compute_client.api_version < api_versions.APIVersion('2.54'):
                msg = _(
                    '--os-compute-api-version 2.54 or greater is required to '
                    'support the --no-key-name option'
                )
                raise exceptions.CommandError(msg)

            kwargs['key_name'] = None

        userdata = None
        if parsed_args.user_data:
            if compute_client.api_version < api_versions.APIVersion('2.54'):
                msg = _(
                    '--os-compute-api-version 2.54 or greater is required to '
                    'support the --user-data option'
                )
                raise exceptions.CommandError(msg)

            try:
                userdata = io.open(parsed_args.user_data)
            except IOError as e:
                msg = _("Can't open '%(data)s': %(exception)s")
                raise exceptions.CommandError(
                    msg % {'data': parsed_args.user_data, 'exception': e}
                )

            kwargs['userdata'] = userdata
        elif parsed_args.no_user_data:
            if compute_client.api_version < api_versions.APIVersion('2.54'):
                msg = _(
                    '--os-compute-api-version 2.54 or greater is required to '
                    'support the --no-user-data option'
                )
                raise exceptions.CommandError(msg)

            kwargs['userdata'] = None

        # TODO(stephenfin): Handle OS_TRUSTED_IMAGE_CERTIFICATE_IDS
        if parsed_args.trusted_image_certs:
            if compute_client.api_version < api_versions.APIVersion('2.63'):
                msg = _(
                    '--os-compute-api-version 2.63 or greater is required to '
                    'support the --trusted-certs option'
                )
                raise exceptions.CommandError(msg)

            certs = parsed_args.trusted_image_certs
            kwargs['trusted_image_certificates'] = certs
        elif parsed_args.no_trusted_image_certs:
            if compute_client.api_version < api_versions.APIVersion('2.63'):
                msg = _(
                    '--os-compute-api-version 2.63 or greater is required to '
                    'support the --no-trusted-certs option'
                )
                raise exceptions.CommandError(msg)

            kwargs['trusted_image_certificates'] = None

        if parsed_args.hostname:
            if compute_client.api_version < api_versions.APIVersion('2.90'):
                msg = _(
                    '--os-compute-api-version 2.90 or greater is required to '
                    'support the --hostname option'
                )
                raise exceptions.CommandError(msg)

            kwargs['hostname'] = parsed_args.hostname

        v2_93 = api_versions.APIVersion('2.93')
        if parsed_args.reimage_boot_volume:
            if compute_client.api_version < v2_93:
                msg = _(
                    '--os-compute-api-version 2.93 or greater is required to '
                    'support the --reimage-boot-volume option'
                )
                raise exceptions.CommandError(msg)
        else:
            # force user to explicitly request reimaging of volume-backed
            # server
            if not server.image:
                if compute_client.api_version >= v2_93:
                    msg = (
                        '--reimage-boot-volume is required to rebuild a '
                        'volume-backed server'
                    )
                    raise exceptions.CommandError(msg)
                else:  # microversion < 2.93
                    # attempts to rebuild a volume-backed server before API
                    # microversion 2.93 will fail in all cases except one: if
                    # the user attempts the rebuild with the exact same image
                    # that the server was initially built with. We can't check
                    # for this since we don't have the original image ID to
                    # hand, so we simply warn the user.
                    # TODO(stephenfin): Make this a failure in a future
                    # version
                    self.log.warning(
                        'Attempting to rebuild a volume-backed server using '
                        '--os-compute-api-version 2.92 or earlier, which '
                        'will only succeed if the image is identical to the '
                        'one initially used. This will be an error in a '
                        'future release.'
                    )

        try:
            server = server.rebuild(image, parsed_args.password, **kwargs)
        finally:
            if userdata and hasattr(userdata, 'close'):
                userdata.close()

        if parsed_args.wait:
            if utils.wait_for_status(
                compute_client.servers.get,
                server.id,
                callback=_show_progress,
            ):
                self.app.stdout.write(_('Complete\n'))
            else:
                LOG.error(_('Error rebuilding server: %s'), server.id)
                self.app.stdout.write(_('Error rebuilding server\n'))
                raise SystemExit

        details = _prep_server_detail(
            compute_client, image_client, server, refresh=False)
        return zip(*sorted(details.items()))


class EvacuateServer(command.ShowOne):
    _description = _("""Evacuate a server to a different host.

This command is used to recreate a server after the host it was on has failed.
It can only be used if the compute service that manages the server is down.
This command should only be used by an admin after they have confirmed that the
instance is not running on the failed host.

If the server instance was created with an ephemeral root disk on non-shared
storage the server will be rebuilt using the original glance image preserving
the ports and any attached data volumes.

If the server uses boot for volume or has its root disk on shared storage the
root disk will be preserved and reused for the evacuated instance on the new
host.""")

    def get_parser(self, prog_name):
        parser = super(EvacuateServer, self).get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            help=_('Server (name or ID)'),
        )

        parser.add_argument(
            '--wait', action='store_true',
            help=_('Wait for evacuation to complete'),
        )
        parser.add_argument(
            '--host', metavar='<host>', default=None,
            help=_(
                'Set the preferred host on which to rebuild the evacuated '
                'server. The host will be validated by the scheduler. '
                '(supported by --os-compute-api-version 2.29 or above)'
            ),
        )
        shared_storage_group = parser.add_mutually_exclusive_group()
        shared_storage_group.add_argument(
            '--password', metavar='<password>', default=None,
            help=_(
                'Set the password on the evacuated instance. This option is '
                'mutually exclusive with the --shared-storage option. '
                'This option requires cloud support.'
            ),
        )
        shared_storage_group.add_argument(
            '--shared-storage', action='store_true', dest='shared_storage',
            help=_(
                'Indicate that the instance is on shared storage. '
                'This will be auto-calculated with '
                '--os-compute-api-version 2.14 and greater and should not '
                'be used with later microversions. This option is mutually '
                'exclusive with the --password option'
            ),
        )
        return parser

    def take_action(self, parsed_args):

        def _show_progress(progress):
            if progress:
                self.app.stdout.write('\rProgress: %s' % progress)
                self.app.stdout.flush()

        compute_client = self.app.client_manager.compute
        image_client = self.app.client_manager.image

        if parsed_args.host:
            if compute_client.api_version < api_versions.APIVersion('2.29'):
                msg = _(
                    '--os-compute-api-version 2.29 or later is required '
                    'to specify a preferred host.'
                )
                raise exceptions.CommandError(msg)

        if parsed_args.shared_storage:
            if compute_client.api_version > api_versions.APIVersion('2.13'):
                msg = _(
                    '--os-compute-api-version 2.13 or earlier is required '
                    'to specify shared-storage.'
                )
                raise exceptions.CommandError(msg)

        kwargs = {
            'host': parsed_args.host,
            'password': parsed_args.password,
        }

        if compute_client.api_version <= api_versions.APIVersion('2.13'):
            kwargs['on_shared_storage'] = parsed_args.shared_storage

        server = utils.find_resource(
            compute_client.servers, parsed_args.server)

        server.evacuate(**kwargs)

        if parsed_args.wait:
            if utils.wait_for_status(
                compute_client.servers.get,
                server.id,
                callback=_show_progress,
            ):
                self.app.stdout.write(_('Complete\n'))
            else:
                LOG.error(_('Error evacuating server: %s'), server.id)
                self.app.stdout.write(_('Error evacuating server\n'))
                raise SystemExit

        details = _prep_server_detail(
            compute_client, image_client, server, refresh=True)
        return zip(*sorted(details.items()))


class RemoveFixedIP(command.Command):
    _description = _("Remove fixed IP address from server")

    def get_parser(self, prog_name):
        parser = super(RemoveFixedIP, self).get_parser(prog_name)
        parser.add_argument(
            "server",
            metavar="<server>",
            help=_("Server to remove the fixed IP address from (name or ID)"),
        )
        parser.add_argument(
            "ip_address",
            metavar="<ip-address>",
            help=_("Fixed IP address to remove from the server (IP only)"),
        )
        return parser

    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.compute

        server = utils.find_resource(
            compute_client.servers, parsed_args.server)

        server.remove_fixed_ip(parsed_args.ip_address)


class RemoveFloatingIP(network_common.NetworkAndComputeCommand):
    _description = _("Remove floating IP address from server")

    def update_parser_common(self, parser):
        parser.add_argument(
            "server",
            metavar="<server>",
            help=_(
                "Server to remove the floating IP address from (name or ID)"
            ),
        )
        parser.add_argument(
            "ip_address",
            metavar="<ip-address>",
            help=_("Floating IP address to remove from server (IP only)"),
        )
        return parser

    def take_action_network(self, client, parsed_args):
        attrs = {}
        obj = client.find_ip(
            parsed_args.ip_address,
            ignore_missing=False,
        )
        attrs['port_id'] = None

        client.update_ip(obj, **attrs)

    def take_action_compute(self, client, parsed_args):
        client.api.floating_ip_remove(
            parsed_args.server,
            parsed_args.ip_address,
        )


class RemovePort(command.Command):
    _description = _("Remove port from server")

    def get_parser(self, prog_name):
        parser = super(RemovePort, self).get_parser(prog_name)
        parser.add_argument(
            "server",
            metavar="<server>",
            help=_("Server to remove the port from (name or ID)"),
        )
        parser.add_argument(
            "port",
            metavar="<port>",
            help=_("Port to remove from the server (name or ID)"),
        )
        return parser

    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.sdk_connection.compute

        server = compute_client.find_server(
            parsed_args.server, ignore_missing=False)

        if self.app.client_manager.is_network_endpoint_enabled():
            network_client = self.app.client_manager.network
            port_id = network_client.find_port(
                parsed_args.port, ignore_missing=False).id
        else:
            port_id = parsed_args.port

        compute_client.delete_server_interface(
            port_id,
            server=server,
            ignore_missing=False,
        )


class RemoveNetwork(command.Command):
    _description = _("Remove all ports of a network from server")

    def get_parser(self, prog_name):
        parser = super(RemoveNetwork, self).get_parser(prog_name)
        parser.add_argument(
            "server",
            metavar="<server>",
            help=_("Server to remove the port from (name or ID)"),
        )
        parser.add_argument(
            "network",
            metavar="<network>",
            help=_("Network to remove from the server (name or ID)"),
        )
        return parser

    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.sdk_connection.compute

        server = compute_client.find_server(
            parsed_args.server, ignore_missing=False)

        if self.app.client_manager.is_network_endpoint_enabled():
            network_client = self.app.client_manager.network
            net_id = network_client.find_network(
                parsed_args.network, ignore_missing=False).id
        else:
            net_id = parsed_args.network

        for inf in compute_client.server_interfaces(server):
            if inf.net_id == net_id:
                compute_client.delete_server_interface(
                    inf.port_id,
                    server=server,
                )


class RemoveServerSecurityGroup(command.Command):
    _description = _("Remove security group from server")

    def get_parser(self, prog_name):
        parser = super(RemoveServerSecurityGroup, self).get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            help=_('Name or ID of server to use'),
        )
        parser.add_argument(
            'group',
            metavar='<group>',
            help=_('Name or ID of security group to remove from server'),
        )
        return parser

    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.compute

        server = utils.find_resource(
            compute_client.servers,
            parsed_args.server,
        )
        security_group = compute_client.api.security_group_find(
            parsed_args.group,
        )

        server.remove_security_group(security_group['id'])


class RemoveServerVolume(command.Command):
    _description = _(
        "Remove volume from server. "
        "Specify ``--os-compute-api-version 2.20`` or higher to remove a "
        "volume from a server with status ``SHELVED`` or "
        "``SHELVED_OFFLOADED``.")

    def get_parser(self, prog_name):
        parser = super(RemoveServerVolume, self).get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            help=_('Server (name or ID)'),
        )
        parser.add_argument(
            'volume',
            metavar='<volume>',
            help=_('Volume to remove (name or ID)'),
        )
        return parser

    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.sdk_connection.compute
        volume_client = self.app.client_manager.sdk_connection.volume

        server = compute_client.find_server(
            parsed_args.server,
            ignore_missing=False,
        )
        volume = volume_client.find_volume(
            parsed_args.volume,
            ignore_missing=False,
        )

        compute_client.delete_volume_attachment(
            volume,
            server,
            ignore_missing=False,
        )


class RescueServer(command.Command):
    _description = _(
        "Put server in rescue mode. "
        "Specify ``--os-compute-api-version 2.87`` or higher to rescue a "
        "server booted from a volume."
    )

    def get_parser(self, prog_name):
        parser = super(RescueServer, self).get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            help=_('Server (name or ID)'),
        )
        parser.add_argument(
            '--image',
            metavar='<image>',
            help=_('Image (name or ID) to use for the rescue mode.'
                   ' Defaults to the currently used one.'),
        )
        parser.add_argument(
            '--password',
            metavar='<password>',
            help=_(
                'Set the password on the rescued instance. '
                'This option requires cloud support.'
            ),
        )
        return parser

    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.compute
        image_client = self.app.client_manager.image

        image = None
        if parsed_args.image:
            image = image_client.find_image(parsed_args.image)

        utils.find_resource(
            compute_client.servers,
            parsed_args.server,
        ).rescue(image=image,
                 password=parsed_args.password)


class ResizeServer(command.Command):
    _description = _("""Scale server to a new flavor.

A resize operation is implemented by creating a new server and copying the
contents of the original disk into a new one. It is a two-step process for the
user: the first step is to perform the resize, and the second step is to either
confirm (verify) success and release the old server or to declare a revert to
release the new server and restart the old one.""")

    def get_parser(self, prog_name):
        parser = super(ResizeServer, self).get_parser(prog_name)
        phase_group = parser.add_mutually_exclusive_group()
        parser.add_argument(
            'server',
            metavar='<server>',
            help=_('Server (name or ID)'),
        )
        phase_group.add_argument(
            '--flavor',
            metavar='<flavor>',
            help=_('Resize server to specified flavor'),
        )
        phase_group.add_argument(
            '--confirm',
            action="store_true",
            help=_(
                "**Deprecated** Confirm server resize is complete. "
                "Replaced by the 'openstack server resize confirm' and "
                "'openstack server migration confirm' commands"
            ),
        )
        phase_group.add_argument(
            '--revert',
            action="store_true",
            help=_(
                '**Deprecated** Restore server state before resize'
                "Replaced by the 'openstack server resize revert' and "
                "'openstack server migration revert' commands"
            ),
        )
        parser.add_argument(
            '--wait',
            action='store_true',
            help=_('Wait for resize to complete'),
        )
        return parser

    def take_action(self, parsed_args):

        def _show_progress(progress):
            if progress:
                self.app.stdout.write('\rProgress: %s' % progress)
                self.app.stdout.flush()

        compute_client = self.app.client_manager.compute
        server = utils.find_resource(
            compute_client.servers,
            parsed_args.server,
        )
        if parsed_args.flavor:
            flavor = utils.find_resource(
                compute_client.flavors,
                parsed_args.flavor,
            )
            compute_client.servers.resize(server, flavor)
            if parsed_args.wait:
                if utils.wait_for_status(
                    compute_client.servers.get,
                    server.id,
                    success_status=['active', 'verify_resize'],
                    callback=_show_progress,
                ):
                    self.app.stdout.write(_('Complete\n'))
                else:
                    LOG.error(_('Error resizing server: %s'),
                              server.id)
                    self.app.stdout.write(_('Error resizing server\n'))
                    raise SystemExit
        elif parsed_args.confirm:
            self.log.warning(_(
                "The --confirm option has been deprecated. Please use the "
                "'openstack server resize confirm' command instead."))
            compute_client.servers.confirm_resize(server)
        elif parsed_args.revert:
            self.log.warning(_(
                "The --revert option has been deprecated. Please use the "
                "'openstack server resize revert' command instead."))
            compute_client.servers.revert_resize(server)


class ResizeConfirm(command.Command):
    _description = _("""Confirm server resize.

Confirm (verify) success of resize operation and release the old server.""")

    def get_parser(self, prog_name):
        parser = super(ResizeConfirm, self).get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            help=_('Server (name or ID)'),
        )
        return parser

    def take_action(self, parsed_args):

        compute_client = self.app.client_manager.compute
        server = utils.find_resource(
            compute_client.servers,
            parsed_args.server,
        )
        server.confirm_resize()


# TODO(stephenfin): Remove in OSC 7.0
class MigrateConfirm(ResizeConfirm):
    _description = _("""DEPRECATED: Confirm server migration.

Use 'server migration confirm' instead.""")

    def take_action(self, parsed_args):
        msg = _(
            "The 'server migrate confirm' command has been deprecated in "
            "favour of the 'server migration confirm' command."
        )
        self.log.warning(msg)

        super().take_action(parsed_args)


class ConfirmMigration(ResizeConfirm):
    _description = _("""Confirm server migration.

Confirm (verify) success of the migration operation and release the old
server.""")


class ResizeRevert(command.Command):
    _description = _("""Revert server resize.

Revert the resize operation. Release the new server and restart the old
one.""")

    def get_parser(self, prog_name):
        parser = super(ResizeRevert, self).get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            help=_('Server (name or ID)'),
        )
        return parser

    def take_action(self, parsed_args):

        compute_client = self.app.client_manager.compute
        server = utils.find_resource(
            compute_client.servers,
            parsed_args.server,
        )
        server.revert_resize()


# TODO(stephenfin): Remove in OSC 7.0
class MigrateRevert(ResizeRevert):
    _description = _("""Revert server migration.

Use 'server migration revert' instead.""")

    def take_action(self, parsed_args):
        msg = _(
            "The 'server migrate revert' command has been deprecated in "
            "favour of the 'server migration revert' command."
        )
        self.log.warning(msg)

        super().take_action(parsed_args)


class RevertMigration(ResizeRevert):
    _description = _("""Revert server migration.

Revert the migration operation. Release the new server and restart the old
one.""")


class RestoreServer(command.Command):
    _description = _("Restore server(s)")

    def get_parser(self, prog_name):
        parser = super(RestoreServer, self).get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            nargs='+',
            help=_('Server(s) to restore (name or ID)'),
        )
        return parser

    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.compute
        for server in parsed_args.server:
            utils.find_resource(
                compute_client.servers,
                server
            ).restore()


class ResumeServer(command.Command):
    _description = _("Resume server(s)")

    def get_parser(self, prog_name):
        parser = super(ResumeServer, self).get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            nargs='+',
            help=_('Server(s) to resume (name or ID)'),
        )
        return parser

    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.sdk_connection.compute
        for server in parsed_args.server:
            server_id = compute_client.find_server(
                server,
                ignore_missing=False,
            ).id
            compute_client.resume_server(server_id)


class SetServer(command.Command):
    _description = _("Set server properties")

    def get_parser(self, prog_name):
        parser = super(SetServer, self).get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            help=_('Server (name or ID)'),
        )
        parser.add_argument(
            '--name',
            metavar='<new-name>',
            help=_('New server name'),
        )
        password_group = parser.add_mutually_exclusive_group()
        password_group.add_argument(
            '--password',
            help=_(
                'Set the server password. '
                'This option requires cloud support.'
            ),
        )
        password_group.add_argument(
            '--no-password',
            action='store_true',
            help=_(
                'Clear the admin password for the server from the metadata '
                'service; note that this action does not actually change the '
                'server password'
            ),
        )
        # TODO(stephenfin): Remove this in a future major version
        password_group.add_argument(
            '--root-password',
            action="store_true",
            help=argparse.SUPPRESS,
        )
        parser.add_argument(
            '--property',
            metavar='<key=value>',
            action=parseractions.KeyValueAction,
            dest='properties',
            help=_(
                'Property to add/change for this server '
                '(repeat option to set multiple properties)'
            ),
        )
        parser.add_argument(
            '--state',
            metavar='<state>',
            choices=['active', 'error'],
            help=_(
                'New server state '
                '**WARNING** This can result in instances that are no longer '
                'usable and should be used with caution '
                '(admin only)'
            ),
        )
        parser.add_argument(
            '--description',
            metavar='<description>',
            help=_(
                'New server description '
                '(supported by --os-compute-api-version 2.19 or above)'
            ),
        )
        parser.add_argument(
            '--tag',
            metavar='<tag>',
            action='append',
            default=[],
            dest='tags',
            help=_(
                'Tag for the server. '
                'Specify multiple times to add multiple tags. '
                '(supported by --os-compute-api-version 2.26 or above)'
            ),
        )
        parser.add_argument(
            '--hostname',
            metavar='<hostname>',
            help=_(
                'Hostname configured for the server in the metadata service. '
                'A separate utility running in the guest is required to '
                'propagate changes to this value to the guest OS itself. '
                '(supported by --os-compute-api-version 2.90 or above)'
            ),
        )
        return parser

    def take_action(self, parsed_args):

        compute_client = self.app.client_manager.compute
        server = utils.find_resource(
            compute_client.servers,
            parsed_args.server,
        )

        if parsed_args.description:
            if server.api_version < api_versions.APIVersion("2.19"):
                msg = _(
                    '--os-compute-api-version 2.19 or greater is required to '
                    'support the --description option'
                )
                raise exceptions.CommandError(msg)

        if parsed_args.tags:
            if server.api_version < api_versions.APIVersion('2.26'):
                msg = _(
                    '--os-compute-api-version 2.26 or greater is required to '
                    'support the --tag option'
                )
                raise exceptions.CommandError(msg)

        if parsed_args.hostname:
            if server.api_version < api_versions.APIVersion('2.90'):
                msg = _(
                    '--os-compute-api-version 2.90 or greater is required to '
                    'support the --hostname option'
                )
                raise exceptions.CommandError(msg)

        update_kwargs = {}

        if parsed_args.name:
            update_kwargs['name'] = parsed_args.name

        if parsed_args.description:
            update_kwargs['description'] = parsed_args.description

        if parsed_args.hostname:
            update_kwargs['hostname'] = parsed_args.hostname

        if update_kwargs:
            server.update(**update_kwargs)

        if parsed_args.properties:
            compute_client.servers.set_meta(server, parsed_args.properties)

        if parsed_args.state:
            server.reset_state(state=parsed_args.state)

        if parsed_args.root_password:
            p1 = getpass.getpass(_('New password: '))
            p2 = getpass.getpass(_('Retype new password: '))
            if p1 == p2:
                server.change_password(p1)
            else:
                msg = _("Passwords do not match, password unchanged")
                raise exceptions.CommandError(msg)
        elif parsed_args.password:
            server.change_password(parsed_args.password)
        elif parsed_args.no_password:
            server.clear_password()

        if parsed_args.tags:
            for tag in parsed_args.tags:
                server.add_tag(tag=tag)


class ShelveServer(command.Command):
    """Shelve and optionally offload server(s).

    Shelving a server creates a snapshot of the server and stores this
    snapshot before shutting down the server. This shelved server can then be
    offloaded or deleted from the host, freeing up remaining resources on the
    host, such as network interfaces. Shelved servers can be unshelved,
    restoring the server from the snapshot. Shelving is therefore useful where
    users wish to retain the UUID and IP of a server, without utilizing other
    resources or disks.

    Most clouds are configured to automatically offload shelved servers
    immediately or after a small delay. For clouds where this is not
    configured, or where the delay is larger, offloading can be manually
    specified. This is an admin-only operation by default.
    """

    def get_parser(self, prog_name):
        parser = super(ShelveServer, self).get_parser(prog_name)
        parser.add_argument(
            'servers',
            metavar='<server>',
            nargs='+',
            help=_('Server(s) to shelve (name or ID)'),
        )
        parser.add_argument(
            '--offload',
            action='store_true',
            default=False,
            help=_(
                'Remove the shelved server(s) from the host (admin only). '
                'Invoking this option on an unshelved server(s) will result '
                'in the server being shelved first'
            ),
        )
        parser.add_argument(
            '--wait',
            action='store_true',
            default=False,
            help=_('Wait for shelve and/or offload operation to complete'),
        )
        return parser

    def take_action(self, parsed_args):

        def _show_progress(progress):
            if progress:
                self.app.stdout.write('\rProgress: %s' % progress)
                self.app.stdout.flush()

        compute_client = self.app.client_manager.compute

        for server in parsed_args.servers:
            server_obj = utils.find_resource(
                compute_client.servers,
                server,
            )
            if server_obj.status.lower() in ('shelved', 'shelved_offloaded'):
                continue

            server_obj.shelve()

        # if we don't have to wait, either because it was requested explicitly
        # or is required implicitly, then our job is done
        if not parsed_args.wait and not parsed_args.offload:
            return

        for server in parsed_args.servers:
            # TODO(stephenfin): We should wait for these in parallel using e.g.
            # https://review.opendev.org/c/openstack/osc-lib/+/762503/
            if not utils.wait_for_status(
                compute_client.servers.get, server_obj.id,
                success_status=('shelved', 'shelved_offloaded'),
                callback=_show_progress,
            ):
                LOG.error(_('Error shelving server: %s'), server_obj.id)
                self.app.stdout.write(
                    _('Error shelving server: %s\n') % server_obj.id)
                raise SystemExit

        if not parsed_args.offload:
            return

        for server in parsed_args.servers:
            server_obj = utils.find_resource(
                compute_client.servers,
                server,
            )
            if server_obj.status.lower() == 'shelved_offloaded':
                continue

            server_obj.shelve_offload()

        if not parsed_args.wait:
            return

        for server in parsed_args.servers:
            # TODO(stephenfin): We should wait for these in parallel using e.g.
            # https://review.opendev.org/c/openstack/osc-lib/+/762503/
            if not utils.wait_for_status(
                compute_client.servers.get, server_obj.id,
                success_status=('shelved_offloaded',),
                callback=_show_progress,
            ):
                LOG.error(
                    _('Error offloading shelved server %s'), server_obj.id)
                self.app.stdout.write(
                    _('Error offloading shelved server: %s\n') % (
                        server_obj.id))
                raise SystemExit


class ShowServer(command.ShowOne):
    _description = _(
        "Show server details. Specify ``--os-compute-api-version 2.47`` "
        "or higher to see the embedded flavor information for the server."
    )

    def get_parser(self, prog_name):
        parser = super(ShowServer, self).get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            help=_('Server (name or ID)'),
        )
        # TODO(stephenfin): This should be a separate command, not a flag
        diagnostics_group = parser.add_mutually_exclusive_group()
        diagnostics_group.add_argument(
            '--diagnostics',
            action='store_true',
            default=False,
            help=_('Display server diagnostics information'),
        )
        diagnostics_group.add_argument(
            '--topology',
            action='store_true',
            default=False,
            help=_(
                'Include topology information in the output '
                '(supported by --os-compute-api-version 2.78 or above)'
            ),
        )
        return parser

    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.sdk_connection.compute

        # Find by name or ID, then get the full details of the server
        server = compute_client.find_server(
            parsed_args.server, ignore_missing=False)
        server = compute_client.get_server(server)

        if parsed_args.diagnostics:
            data = compute_client.get_server_diagnostics(server)
            return zip(*sorted(data.items()))

        topology = None
        if parsed_args.topology:
            if not sdk_utils.supports_microversion(compute_client, '2.78'):
                msg = _(
                    '--os-compute-api-version 2.78 or greater is required to '
                    'support the --topology option'
                )
                raise exceptions.CommandError(msg)

            topology = server.fetch_topology(compute_client)

        data = _prep_server_detail(
            # TODO(dannosliwcd): Replace these clients with SDK clients after
            # all callers of _prep_server_detail() are using the SDK.
            self.app.client_manager.compute,
            self.app.client_manager.image,
            server,
            refresh=False)

        if topology:
            data['topology'] = format_columns.DictColumn(topology)

        return zip(*sorted(data.items()))


class SshServer(command.Command):
    _description = _("SSH to server")

    def get_parser(self, prog_name):
        parser = super(SshServer, self).get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            help=_('Server (name or ID)'),
        )
        # Deprecated during the Yoga cycle
        parser.add_argument(
            '--login', '-l',
            metavar='<login-name>',
            help=argparse.SUPPRESS,
        )
        # Deprecated during the Yoga cycle
        parser.add_argument(
            '--port', '-p',
            metavar='<port>',
            type=int,
            help=argparse.SUPPRESS,
        )
        # Deprecated during the Yoga cycle
        parser.add_argument(
            '--identity', '-i',
            metavar='<keyfile>',
            help=argparse.SUPPRESS,
        )
        # Deprecated during the Yoga cycle
        parser.add_argument(
            '--option', '-o',
            metavar='<config-options>',
            help=argparse.SUPPRESS,
        )
        ip_group = parser.add_mutually_exclusive_group()
        ip_group.add_argument(
            '-4',
            dest='ipv4',
            action='store_true',
            default=False,
            help=_('Use only IPv4 addresses'),
        )
        ip_group.add_argument(
            '-6',
            dest='ipv6',
            action='store_true',
            default=False,
            help=_('Use only IPv6 addresses'),
        )
        type_group = parser.add_mutually_exclusive_group()
        type_group.add_argument(
            '--public',
            dest='address_type',
            action='store_const',
            const='public',
            default='public',
            help=_('Use public IP address'),
        )
        type_group.add_argument(
            '--private',
            dest='address_type',
            action='store_const',
            const='private',
            default='public',
            help=_('Use private IP address'),
        )
        type_group.add_argument(
            '--address-type',
            metavar='<address-type>',
            dest='address_type',
            default='public',
            help=_('Use other IP address (public, private, etc)'),
        )
        # Deprecated during the Yoga cycle
        parser.add_argument(
            '-v',
            dest='verbose',
            action='store_true',
            default=False,
            help=argparse.SUPPRESS,
        )
        parser.add_argument(
            'ssh_args',
            nargs='*',
            metavar='-- <standard ssh args>',
            help=(
                'Any argument or option that ssh allows. '
                'Use -- once between openstackclient args and SSH args.'
            ),
        )
        return parser

    def take_action(self, parsed_args):

        compute_client = self.app.client_manager.compute

        server = utils.find_resource(
            compute_client.servers,
            parsed_args.server,
        )

        # first, handle the deprecated options
        if any((
            parsed_args.port,
            parsed_args.identity,
            parsed_args.option,
            parsed_args.login,
            parsed_args.verbose,
        )):
            msg = _(
                'The ssh options have been deprecated. The ssh equivalent '
                'options can be used instead as arguments after "--" on '
                'the command line.'
            )
            self.log.warning(msg)

        ip_address_family = [4, 6]
        if parsed_args.ipv4:
            ip_address_family = [4]
        if parsed_args.ipv6:
            ip_address_family = [6]

        args = parsed_args.ssh_args[:]

        if parsed_args.port:
            args.extend(['-p', str(parsed_args.port)])

        if parsed_args.identity:
            args.extend(['-i', parsed_args.identity])

        if parsed_args.option:
            args.extend(['-o', parsed_args.option])

        if parsed_args.login:
            login = parsed_args.login
            args.extend(['-l', login])
        elif '-l' not in args:
            login = self.app.client_manager.auth_ref.username
            args.extend(['-l', login])

        if parsed_args.verbose:
            args.append('-v')

        ip_address = _get_ip_address(
            server.addresses,
            parsed_args.address_type,
            ip_address_family,
        )

        cmd = ' '.join(['ssh', ip_address] + args)
        LOG.debug("ssh command: {cmd}".format(cmd=cmd))
        os.system(cmd)


class StartServer(command.Command):
    _description = _("Start server(s)")

    def get_parser(self, prog_name):
        parser = super().get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            nargs="+",
            help=_('Server(s) to start (name or ID)'),
        )
        parser.add_argument(
            '--all-projects',
            action='store_true',
            default=boolenv('ALL_PROJECTS'),
            help=_(
                'Start server(s) in another project by name (admin only)'
                '(can be specified using the ALL_PROJECTS envvar)'
            ),
        )
        return parser

    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.sdk_connection.compute
        for server in parsed_args.server:
            try:
                server_id = compute_client.find_server(
                    name=server,
                    details=False,
                    all_projects=parsed_args.all_projects,
                    ignore_missing=False,
                ).id
            except sdk_exceptions.HttpException as exc:
                if exc.status_code == 403:
                    msg = _("Policy doesn't allow passing all-projects")
                    raise exceptions.Forbidden(msg)

            compute_client.start_server(server_id)


class StopServer(command.Command):
    _description = _("Stop server(s)")

    def get_parser(self, prog_name):
        parser = super().get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            nargs="+",
            help=_('Server(s) to stop (name or ID)'),
        )
        parser.add_argument(
            '--all-projects',
            action='store_true',
            default=boolenv('ALL_PROJECTS'),
            help=_(
                'Stop server(s) in another project by name (admin only)'
                '(can be specified using the ALL_PROJECTS envvar)'
            ),
        )
        return parser

    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.sdk_connection.compute
        for server in parsed_args.server:
            try:
                server_id = compute_client.find_server(
                    name=server,
                    details=False,
                    all_projects=parsed_args.all_projects,
                    ignore_missing=False,
                ).id
            except sdk_exceptions.HttpException as exc:
                if exc.status_code == 403:
                    msg = _("Policy doesn't allow passing all-projects")
                    raise exceptions.Forbidden(msg)

            compute_client.stop_server(server_id)


class SuspendServer(command.Command):
    _description = _("Suspend server(s)")

    def get_parser(self, prog_name):
        parser = super(SuspendServer, self).get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            nargs='+',
            help=_('Server(s) to suspend (name or ID)'),
        )
        return parser

    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.sdk_connection.compute
        for server in parsed_args.server:
            server_id = compute_client.find_server(
                server,
                ignore_missing=False,
            ).id
            compute_client.suspend_server(server_id)


class UnlockServer(command.Command):
    _description = _("Unlock server(s)")

    def get_parser(self, prog_name):
        parser = super().get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            nargs='+',
            help=_('Server(s) to unlock (name or ID)'),
        )
        return parser

    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.sdk_connection.compute
        for server in parsed_args.server:
            server_id = compute_client.find_server(
                server,
                ignore_missing=False,
            ).id
            compute_client.unlock_server(server_id)


class UnpauseServer(command.Command):
    _description = _("Unpause server(s)")

    def get_parser(self, prog_name):
        parser = super(UnpauseServer, self).get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            nargs='+',
            help=_('Server(s) to unpause (name or ID)'),
        )
        return parser

    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.sdk_connection.compute
        for server in parsed_args.server:
            server_id = compute_client.find_server(
                server,
                ignore_missing=False,
            ).id
            compute_client.unpause_server(server_id)


class UnrescueServer(command.Command):
    _description = _("Restore server from rescue mode")

    def get_parser(self, prog_name):
        parser = super(UnrescueServer, self).get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            help=_('Server (name or ID)'),
        )
        return parser

    def take_action(self, parsed_args):

        compute_client = self.app.client_manager.compute
        utils.find_resource(
            compute_client.servers,
            parsed_args.server,
        ).unrescue()


class UnsetServer(command.Command):
    _description = _("Unset server properties and tags")

    def get_parser(self, prog_name):
        parser = super(UnsetServer, self).get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            help=_('Server (name or ID)'),
        )
        parser.add_argument(
            '--property',
            metavar='<key>',
            action='append',
            default=[],
            dest='properties',
            help=_('Property key to remove from server '
                   '(repeat option to remove multiple values)'),
        )
        parser.add_argument(
            '--description',
            dest='description',
            action='store_true',
            help=_('Unset server description (supported by '
                   '--os-compute-api-version 2.19 or above)'),
        )
        parser.add_argument(
            '--tag',
            metavar='<tag>',
            action='append',
            default=[],
            dest='tags',
            help=_(
                'Tag to remove from the server. '
                'Specify multiple times to remove multiple tags. '
                '(supported by --os-compute-api-version 2.26 or above)'
            ),
        )
        return parser

    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.compute
        server = utils.find_resource(
            compute_client.servers,
            parsed_args.server,
        )

        if parsed_args.properties:
            compute_client.servers.delete_meta(server, parsed_args.properties)

        if parsed_args.description:
            if compute_client.api_version < api_versions.APIVersion("2.19"):
                msg = _("Description is not supported for "
                        "--os-compute-api-version less than 2.19")
                raise exceptions.CommandError(msg)
            compute_client.servers.update(
                server,
                description="",
            )

        if parsed_args.tags:
            if compute_client.api_version < api_versions.APIVersion('2.26'):
                msg = _(
                    '--os-compute-api-version 2.26 or greater is required to '
                    'support the --tag option'
                )
                raise exceptions.CommandError(msg)

            for tag in parsed_args.tags:
                compute_client.servers.delete_tag(server, tag=tag)


class UnshelveServer(command.Command):
    _description = _("Unshelve server(s)")

    def get_parser(self, prog_name):
        parser = super(UnshelveServer, self).get_parser(prog_name)
        parser.add_argument(
            'server',
            metavar='<server>',
            nargs='+',
            help=_('Server(s) to unshelve (name or ID)'),
        )
        group = parser.add_mutually_exclusive_group()
        group.add_argument(
            '--availability-zone',
            default=None,
            help=_('Name of the availability zone in which to unshelve a '
                   'SHELVED_OFFLOADED server (supported by '
                   '--os-compute-api-version 2.77 or above)'),
        )
        group.add_argument(
            '--no-availability-zone',
            action='store_true',
            default=False,
            help=_('Unpin the availability zone of a SHELVED_OFFLOADED '
                   'server. Server will be unshelved on a host without '
                   'availability zone constraint (supported by '
                   '--os-compute-api-version 2.91 or above)'),
        )
        parser.add_argument(
            '--host',
            default=None,
            help=_('Name of the destination host in which to unshelve a '
                   'SHELVED_OFFLOADED server (supported by '
                   '--os-compute-api-version 2.91 or above)'),
        )
        parser.add_argument(
            '--wait',
            action='store_true',
            default=False,
            help=_('Wait for unshelve operation to complete'),
        )
        return parser

    def take_action(self, parsed_args):

        def _show_progress(progress):
            if progress:
                self.app.stdout.write('\rProgress: %s' % progress)
                self.app.stdout.flush()

        compute_client = self.app.client_manager.compute
        kwargs = {}

        if parsed_args.availability_zone:
            if compute_client.api_version < api_versions.APIVersion('2.77'):
                msg = _(
                    '--os-compute-api-version 2.77 or greater is required '
                    'to support the --availability-zone option'
                )
                raise exceptions.CommandError(msg)

            kwargs['availability_zone'] = parsed_args.availability_zone

        if parsed_args.host:
            if compute_client.api_version < api_versions.APIVersion('2.91'):
                msg = _(
                    '--os-compute-api-version 2.91 or greater is required '
                    'to support the --host option'
                )
                raise exceptions.CommandError(msg)

            kwargs['host'] = parsed_args.host

        if parsed_args.no_availability_zone:
            if compute_client.api_version < api_versions.APIVersion('2.91'):
                msg = _(
                    '--os-compute-api-version 2.91 or greater is required '
                    'to support the --no-availability-zone option'
                )
                raise exceptions.CommandError(msg)

            kwargs['availability_zone'] = None

        for server in parsed_args.server:
            server_obj = utils.find_resource(
                compute_client.servers,
                server,
            )

            if server_obj.status.lower() not in (
                'shelved', 'shelved_offloaded',
            ):
                continue

            server_obj.unshelve(**kwargs)

            if parsed_args.wait:
                if not utils.wait_for_status(
                    compute_client.servers.get, server_obj.id,
                    success_status=('active', 'shutoff'),
                    callback=_show_progress,
                ):
                    LOG.error(_('Error unshelving server %s'), server_obj.id)
                    self.app.stdout.write(
                        _('Error unshelving server: %s\n') % server_obj.id)
                    raise SystemExit