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
|
# Copyright (c) 2013-2014 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import argparse
import copy
import os
import sys
import time
import warnings
import six
from cinderclient import api_versions
from cinderclient import base
from cinderclient import exceptions
from cinderclient import utils
from cinderclient.v3 import availability_zones
from oslo_utils import strutils
def _poll_for_status(poll_fn, obj_id, action, final_ok_states,
poll_period=5, show_progress=True):
"""Blocks while an action occurs. Periodically shows progress."""
def print_progress(progress):
if show_progress:
msg = ('\rInstance %(action)s... %(progress)s%% complete'
% dict(action=action, progress=progress))
else:
msg = '\rInstance %(action)s...' % dict(action=action)
sys.stdout.write(msg)
sys.stdout.flush()
print()
while True:
obj = poll_fn(obj_id)
status = obj.status.lower()
progress = getattr(obj, 'progress', None) or 0
if status in final_ok_states:
print_progress(100)
print("\nFinished")
break
elif status == "error":
print("\nError %(action)s instance" % {'action': action})
break
else:
print_progress(progress)
time.sleep(poll_period)
def _find_volume_snapshot(cs, snapshot):
"""Gets a volume snapshot by name or ID."""
return utils.find_resource(cs.volume_snapshots, snapshot)
def _find_vtype(cs, vtype):
"""Gets a volume type by name or ID."""
return utils.find_resource(cs.volume_types, vtype)
def _find_gtype(cs, gtype):
"""Gets a group type by name or ID."""
return utils.find_resource(cs.group_types, gtype)
def _find_backup(cs, backup):
"""Gets a backup by name or ID."""
return utils.find_resource(cs.backups, backup)
def _find_consistencygroup(cs, consistencygroup):
"""Gets a consistencygroup by name or ID."""
return utils.find_resource(cs.consistencygroups, consistencygroup)
def _find_group(cs, group):
"""Gets a group by name or ID."""
return utils.find_resource(cs.groups, group)
def _find_cgsnapshot(cs, cgsnapshot):
"""Gets a cgsnapshot by name or ID."""
return utils.find_resource(cs.cgsnapshots, cgsnapshot)
def _find_group_snapshot(cs, group_snapshot):
"""Gets a group_snapshot by name or ID."""
return utils.find_resource(cs.group_snapshots, group_snapshot)
def _find_transfer(cs, transfer):
"""Gets a transfer by name or ID."""
return utils.find_resource(cs.transfers, transfer)
def _find_qos_specs(cs, qos_specs):
"""Gets a qos specs by ID."""
return utils.find_resource(cs.qos_specs, qos_specs)
def _find_message(cs, message):
"""Gets a message by ID."""
return utils.find_resource(cs.messages, message)
def _print_volume_snapshot(snapshot):
utils.print_dict(snapshot._info)
def _print_volume_image(image):
utils.print_dict(image[1]['os-volume_upload_image'])
def _translate_keys(collection, convert):
for item in collection:
keys = item.__dict__
for from_key, to_key in convert:
if from_key in keys and to_key not in keys:
setattr(item, to_key, item._info[from_key])
def _translate_volume_keys(collection):
convert = [('volumeType', 'volume_type'),
('os-vol-tenant-attr:tenant_id', 'tenant_id')]
_translate_keys(collection, convert)
def _translate_volume_snapshot_keys(collection):
convert = [('volumeId', 'volume_id')]
_translate_keys(collection, convert)
def _translate_availability_zone_keys(collection):
convert = [('zoneName', 'name'), ('zoneState', 'status')]
_translate_keys(collection, convert)
def _extract_metadata(args):
metadata = {}
for metadatum in args.metadata:
# unset doesn't require a val, so we have the if/else
if '=' in metadatum:
(key, value) = metadatum.split('=', 1)
else:
key = metadatum
value = None
metadata[key] = value
return metadata
@utils.arg('--all-tenants',
dest='all_tenants',
metavar='<0|1>',
nargs='?',
type=int,
const=1,
default=0,
help='Shows details for all tenants. Admin only.')
@utils.arg('--all_tenants',
nargs='?',
type=int,
const=1,
help=argparse.SUPPRESS)
@utils.arg('--name',
metavar='<name>',
default=None,
help='Filters results by a name. Default=None.')
@utils.arg('--display-name',
help=argparse.SUPPRESS)
@utils.arg('--status',
metavar='<status>',
default=None,
help='Filters results by a status. Default=None.')
@utils.arg('--bootable',
metavar='<True|true|False|false>',
const=True,
nargs='?',
choices=['True', 'true', 'False', 'false'],
help='Filters results by bootable status. Default=None.')
@utils.arg('--migration_status',
metavar='<migration_status>',
default=None,
help='Filters results by a migration status. Default=None. '
'Admin only.')
@utils.arg('--metadata',
type=str,
nargs='*',
metavar='<key=value>',
default=None,
help='Filters results by a metadata key and value pair. '
'Default=None.')
@utils.arg('--marker',
metavar='<marker>',
default=None,
help='Begin returning volumes that appear later in the volume '
'list than that represented by this volume id. '
'Default=None.')
@utils.arg('--limit',
metavar='<limit>',
default=None,
help='Maximum number of volumes to return. Default=None.')
@utils.arg('--fields',
default=None,
metavar='<fields>',
help='Comma-separated list of fields to display. '
'Use the show command to see which fields are available. '
'Unavailable/non-existent fields will be ignored. '
'Default=None.')
@utils.arg('--sort_key',
metavar='<sort_key>',
default=None,
help=argparse.SUPPRESS)
@utils.arg('--sort_dir',
metavar='<sort_dir>',
default=None,
help=argparse.SUPPRESS)
@utils.arg('--sort',
metavar='<key>[:<direction>]',
default=None,
help=(('Comma-separated list of sort keys and directions in the '
'form of <key>[:<asc|desc>]. '
'Valid keys: %s. '
'Default=None.') % ', '.join(base.SORT_KEY_VALUES)))
@utils.arg('--tenant',
type=str,
dest='tenant',
nargs='?',
metavar='<tenant>',
help='Display information from single tenant (Admin only).')
@utils.service_type('volumev3')
def do_list(cs, args):
"""Lists all volumes."""
# NOTE(thingee): Backwards-compatibility with v1 args
if args.display_name is not None:
args.name = args.display_name
all_tenants = 1 if args.tenant else \
int(os.environ.get("ALL_TENANTS", args.all_tenants))
search_opts = {
'all_tenants': all_tenants,
'project_id': args.tenant,
'name': args.name,
'status': args.status,
'bootable': args.bootable,
'migration_status': args.migration_status,
'metadata': _extract_metadata(args) if args.metadata else None,
}
# If unavailable/non-existent fields are specified, these fields will
# be removed from key_list at the print_list() during key validation.
field_titles = []
if args.fields:
for field_title in args.fields.split(','):
field_titles.append(field_title)
# --sort_key and --sort_dir deprecated in kilo and is not supported
# with --sort
if args.sort and (args.sort_key or args.sort_dir):
raise exceptions.CommandError(
'The --sort_key and --sort_dir arguments are deprecated and are '
'not supported with --sort.')
volumes = cs.volumes.list(search_opts=search_opts, marker=args.marker,
limit=args.limit, sort_key=args.sort_key,
sort_dir=args.sort_dir, sort=args.sort)
_translate_volume_keys(volumes)
# Create a list of servers to which the volume is attached
for vol in volumes:
servers = [s.get('server_id') for s in vol.attachments]
setattr(vol, 'attached_to', ','.join(map(str, servers)))
if field_titles:
key_list = ['ID'] + field_titles
else:
key_list = ['ID', 'Status', 'Name', 'Size', 'Volume Type',
'Bootable', 'Attached to']
# If all_tenants is specified, print
# Tenant ID as well.
if search_opts['all_tenants']:
key_list.insert(1, 'Tenant ID')
if args.sort_key or args.sort_dir or args.sort:
sortby_index = None
else:
sortby_index = 0
utils.print_list(volumes, key_list, exclude_unavailable=True,
sortby_index=sortby_index)
@utils.arg('volume',
metavar='<volume>',
help='Name or ID of volume.')
@utils.service_type('volumev3')
def do_show(cs, args):
"""Shows volume details."""
info = dict()
volume = utils.find_volume(cs, args.volume)
info.update(volume._info)
info.pop('links', None)
utils.print_dict(info,
formatters=['metadata', 'volume_image_metadata'])
class CheckSizeArgForCreate(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
if ((args.snapshot_id or args.source_volid or args.source_replica)
is None and values is None):
parser.error('Size is a required parameter if snapshot '
'or source volume is not specified.')
setattr(args, self.dest, values)
@utils.service_type('volumev3')
@utils.arg('size',
metavar='<size>',
nargs='?',
type=int,
action=CheckSizeArgForCreate,
help='Size of volume, in GiBs. (Required unless '
'snapshot-id/source-volid is specified).')
@utils.arg('--consisgroup-id',
metavar='<consistencygroup-id>',
default=None,
help='ID of a consistency group where the new volume belongs to. '
'Default=None.')
@utils.arg('--group-id',
metavar='<group-id>',
default=None,
help='ID of a group where the new volume belongs to. '
'Default=None.',
start_version='3.13')
@utils.arg('--snapshot-id',
metavar='<snapshot-id>',
default=None,
help='Creates volume from snapshot ID. Default=None.')
@utils.arg('--snapshot_id',
help=argparse.SUPPRESS)
@utils.arg('--source-volid',
metavar='<source-volid>',
default=None,
help='Creates volume from volume ID. Default=None.')
@utils.arg('--source_volid',
help=argparse.SUPPRESS)
@utils.arg('--source-replica',
metavar='<source-replica>',
default=None,
help='Creates volume from replicated volume ID. Default=None.')
@utils.arg('--image-id',
metavar='<image-id>',
default=None,
help='Creates volume from image ID. Default=None.')
@utils.arg('--image_id',
help=argparse.SUPPRESS)
@utils.arg('--image',
metavar='<image>',
default=None,
help='Creates a volume from image (ID or name). Default=None.')
@utils.arg('--image_ref',
help=argparse.SUPPRESS)
@utils.arg('--name',
metavar='<name>',
default=None,
help='Volume name. Default=None.')
@utils.arg('--display-name',
help=argparse.SUPPRESS)
@utils.arg('--display_name',
help=argparse.SUPPRESS)
@utils.arg('--description',
metavar='<description>',
default=None,
help='Volume description. Default=None.')
@utils.arg('--display-description',
help=argparse.SUPPRESS)
@utils.arg('--display_description',
help=argparse.SUPPRESS)
@utils.arg('--volume-type',
metavar='<volume-type>',
default=None,
help='Volume type. Default=None.')
@utils.arg('--volume_type',
help=argparse.SUPPRESS)
@utils.arg('--availability-zone',
metavar='<availability-zone>',
default=None,
help='Availability zone for volume. Default=None.')
@utils.arg('--availability_zone',
help=argparse.SUPPRESS)
@utils.arg('--metadata',
type=str,
nargs='*',
metavar='<key=value>',
default=None,
help='Metadata key and value pairs. Default=None.')
@utils.arg('--hint',
metavar='<key=value>',
dest='scheduler_hints',
action='append',
default=[],
help='Scheduler hint, like in nova.')
@utils.arg('--allow-multiattach',
dest='multiattach',
action="store_true",
help=('Allow volume to be attached more than once.'
' Default=False'),
default=False)
def do_create(cs, args):
"""Creates a volume."""
# NOTE(thingee): Backwards-compatibility with v1 args
if args.display_name is not None:
args.name = args.display_name
if args.display_description is not None:
args.description = args.display_description
volume_metadata = None
if args.metadata is not None:
volume_metadata = _extract_metadata(args)
# NOTE(N.S.): take this piece from novaclient
hints = {}
if args.scheduler_hints:
for hint in args.scheduler_hints:
key, _sep, value = hint.partition('=')
# NOTE(vish): multiple copies of same hint will
# result in a list of values
if key in hints:
if isinstance(hints[key], six.string_types):
hints[key] = [hints[key]]
hints[key] += [value]
else:
hints[key] = value
# NOTE(N.S.): end of taken piece
# Keep backward compatibility with image_id, favoring explicit ID
image_ref = args.image_id or args.image or args.image_ref
try:
group_id = args.group_id
except AttributeError:
group_id = None
volume = cs.volumes.create(args.size,
args.consisgroup_id,
group_id,
args.snapshot_id,
args.source_volid,
args.name,
args.description,
args.volume_type,
availability_zone=args.availability_zone,
imageRef=image_ref,
metadata=volume_metadata,
scheduler_hints=hints,
source_replica=args.source_replica,
multiattach=args.multiattach)
info = dict()
volume = cs.volumes.get(volume.id)
info.update(volume._info)
info.pop('links', None)
utils.print_dict(info)
@utils.arg('--cascade',
action='store_true',
default=False,
help='Remove any snapshots along with volume. Default=False.')
@utils.arg('volume',
metavar='<volume>', nargs='+',
help='Name or ID of volume or volumes to delete.')
@utils.service_type('volumev3')
def do_delete(cs, args):
"""Removes one or more volumes."""
failure_count = 0
for volume in args.volume:
try:
utils.find_volume(cs, volume).delete(cascade=args.cascade)
print("Request to delete volume %s has been accepted." % (volume))
except Exception as e:
failure_count += 1
print("Delete for volume %s failed: %s" % (volume, e))
if failure_count == len(args.volume):
raise exceptions.CommandError("Unable to delete any of the specified "
"volumes.")
@utils.arg('volume',
metavar='<volume>', nargs='+',
help='Name or ID of volume or volumes to delete.')
@utils.service_type('volumev3')
def do_force_delete(cs, args):
"""Attempts force-delete of volume, regardless of state."""
failure_count = 0
for volume in args.volume:
try:
utils.find_volume(cs, volume).force_delete()
except Exception as e:
failure_count += 1
print("Delete for volume %s failed: %s" % (volume, e))
if failure_count == len(args.volume):
raise exceptions.CommandError("Unable to force delete any of the "
"specified volumes.")
@utils.arg('volume', metavar='<volume>', nargs='+',
help='Name or ID of volume to modify.')
@utils.arg('--state', metavar='<state>', default=None,
help=('The state to assign to the volume. Valid values are '
'"available", "error", "creating", "deleting", "in-use", '
'"attaching", "detaching", "error_deleting" and '
'"maintenance". '
'NOTE: This command simply changes the state of the '
'Volume in the DataBase with no regard to actual status, '
'exercise caution when using. Default=None, that means the '
'state is unchanged.'))
@utils.arg('--attach-status', metavar='<attach-status>', default=None,
help=('The attach status to assign to the volume in the DataBase, '
'with no regard to the actual status. Valid values are '
'"attached" and "detached". Default=None, that means the '
'status is unchanged.'))
@utils.arg('--reset-migration-status',
action='store_true',
help=('Clears the migration status of the volume in the DataBase '
'that indicates the volume is source or destination of '
'volume migration, with no regard to the actual status.'))
@utils.service_type('volumev3')
def do_reset_state(cs, args):
"""Explicitly updates the volume state in the Cinder database.
Note that this does not affect whether the volume is actually attached to
the Nova compute host or instance and can result in an unusable volume.
Being a database change only, this has no impact on the true state of the
volume and may not match the actual state. This can render a volume
unusable in the case of change to the 'available' state.
"""
failure_flag = False
migration_status = 'none' if args.reset_migration_status else None
if not (args.state or args.attach_status or migration_status):
# Nothing specified, default to resetting state
args.state = 'available'
for volume in args.volume:
try:
utils.find_volume(cs, volume).reset_state(args.state,
args.attach_status,
migration_status)
except Exception as e:
failure_flag = True
msg = "Reset state for volume %s failed: %s" % (volume, e)
print(msg)
if failure_flag:
msg = "Unable to reset the state for the specified volume(s)."
raise exceptions.CommandError(msg)
@utils.arg('volume',
metavar='<volume>',
help='Name or ID of volume to rename.')
@utils.arg('name',
nargs='?',
metavar='<name>',
help='New name for volume.')
@utils.arg('--description', metavar='<description>',
help='Volume description. Default=None.',
default=None)
@utils.arg('--display-description',
help=argparse.SUPPRESS)
@utils.arg('--display_description',
help=argparse.SUPPRESS)
@utils.service_type('volumev3')
def do_rename(cs, args):
"""Renames a volume."""
kwargs = {}
if args.name is not None:
kwargs['name'] = args.name
if args.display_description is not None:
kwargs['description'] = args.display_description
elif args.description is not None:
kwargs['description'] = args.description
if not any(kwargs):
msg = 'Must supply either name or description.'
raise exceptions.ClientException(code=1, message=msg)
utils.find_volume(cs, args.volume).update(**kwargs)
@utils.arg('volume',
metavar='<volume>',
help='Name or ID of volume for which to update metadata.')
@utils.arg('action',
metavar='<action>',
choices=['set', 'unset'],
help='The action. Valid values are "set" or "unset."')
@utils.arg('metadata',
metavar='<key=value>',
nargs='+',
default=[],
end_version='3.14',
help='Metadata key and value pair to set or unset. '
'For unset, specify only the key.')
@utils.arg('metadata',
metavar='<key=value>',
nargs='+',
default=[],
start_version='3.15',
help='Metadata key and value pair to set or unset. '
'For unset, specify only the key(s): <key key>')
@utils.service_type('volumev3')
def do_metadata(cs, args):
"""Sets or deletes volume metadata."""
volume = utils.find_volume(cs, args.volume)
metadata = _extract_metadata(args)
if args.action == 'set':
cs.volumes.set_metadata(volume, metadata)
elif args.action == 'unset':
# NOTE(zul): Make sure py2/py3 sorting is the same
cs.volumes.delete_metadata(volume, sorted(metadata.keys(),
reverse=True))
@utils.arg('volume',
metavar='<volume>',
help='Name or ID of volume for which to update metadata.')
@utils.arg('action',
metavar='<action>',
choices=['set', 'unset'],
help="The action. Valid values are 'set' or 'unset.'")
@utils.arg('metadata',
metavar='<key=value>',
nargs='+',
default=[],
help='Metadata key and value pair to set or unset. '
'For unset, specify only the key.')
@utils.service_type('volumev3')
def do_image_metadata(cs, args):
"""Sets or deletes volume image metadata."""
volume = utils.find_volume(cs, args.volume)
metadata = _extract_metadata(args)
if args.action == 'set':
cs.volumes.set_image_metadata(volume, metadata)
elif args.action == 'unset':
cs.volumes.delete_image_metadata(volume, sorted(metadata.keys(),
reverse=True))
@utils.arg('--all-tenants',
dest='all_tenants',
metavar='<0|1>',
nargs='?',
type=int,
const=1,
default=0,
help='Shows details for all tenants. Admin only.')
@utils.arg('--all_tenants',
nargs='?',
type=int,
const=1,
help=argparse.SUPPRESS)
@utils.arg('--name',
metavar='<name>',
default=None,
help='Filters results by a name. Default=None.')
@utils.arg('--display-name',
help=argparse.SUPPRESS)
@utils.arg('--display_name',
help=argparse.SUPPRESS)
@utils.arg('--status',
metavar='<status>',
default=None,
help='Filters results by a status. Default=None.')
@utils.arg('--volume-id',
metavar='<volume-id>',
default=None,
help='Filters results by a volume ID. Default=None.')
@utils.arg('--volume_id',
help=argparse.SUPPRESS)
@utils.arg('--marker',
metavar='<marker>',
default=None,
help='Begin returning snapshots that appear later in the snapshot '
'list than that represented by this id. '
'Default=None.')
@utils.arg('--limit',
metavar='<limit>',
default=None,
help='Maximum number of snapshots to return. Default=None.')
@utils.arg('--sort',
metavar='<key>[:<direction>]',
default=None,
help=(('Comma-separated list of sort keys and directions in the '
'form of <key>[:<asc|desc>]. '
'Valid keys: %s. '
'Default=None.') % ', '.join(base.SORT_KEY_VALUES)))
@utils.arg('--tenant',
type=str,
dest='tenant',
nargs='?',
metavar='<tenant>',
help='Display information from single tenant (Admin only).')
@utils.service_type('volumev3')
def do_snapshot_list(cs, args):
"""Lists all snapshots."""
all_tenants = (1 if args.tenant else
int(os.environ.get("ALL_TENANTS", args.all_tenants)))
if args.display_name is not None:
args.name = args.display_name
search_opts = {
'all_tenants': all_tenants,
'display_name': args.name,
'status': args.status,
'volume_id': args.volume_id,
'project_id': args.tenant,
}
snapshots = cs.volume_snapshots.list(search_opts=search_opts,
marker=args.marker,
limit=args.limit,
sort=args.sort)
_translate_volume_snapshot_keys(snapshots)
if args.sort:
sortby_index = None
else:
sortby_index = 0
utils.print_list(snapshots,
['ID', 'Volume ID', 'Status', 'Name', 'Size'],
sortby_index=sortby_index)
@utils.arg('snapshot',
metavar='<snapshot>',
help='Name or ID of snapshot.')
@utils.service_type('volumev3')
def do_snapshot_show(cs, args):
"""Shows snapshot details."""
snapshot = _find_volume_snapshot(cs, args.snapshot)
_print_volume_snapshot(snapshot)
@utils.arg('volume',
metavar='<volume>',
help='Name or ID of volume to snapshot.')
@utils.arg('--force',
metavar='<True|False>',
const=True,
nargs='?',
default=False,
help='Allows or disallows snapshot of '
'a volume when the volume is attached to an instance. '
'If set to True, ignores the current status of the '
'volume when attempting to snapshot it rather '
'than forcing it to be available. '
'Default=False.')
@utils.arg('--name',
metavar='<name>',
default=None,
help='Snapshot name. Default=None.')
@utils.arg('--display-name',
help=argparse.SUPPRESS)
@utils.arg('--display_name',
help=argparse.SUPPRESS)
@utils.arg('--description',
metavar='<description>',
default=None,
help='Snapshot description. Default=None.')
@utils.arg('--display-description',
help=argparse.SUPPRESS)
@utils.arg('--display_description',
help=argparse.SUPPRESS)
@utils.arg('--metadata',
type=str,
nargs='*',
metavar='<key=value>',
default=None,
help='Snapshot metadata key and value pairs. Default=None.')
@utils.service_type('volumev3')
def do_snapshot_create(cs, args):
"""Creates a snapshot."""
if args.display_name is not None:
args.name = args.display_name
if args.display_description is not None:
args.description = args.display_description
snapshot_metadata = None
if args.metadata is not None:
snapshot_metadata = _extract_metadata(args)
volume = utils.find_volume(cs, args.volume)
snapshot = cs.volume_snapshots.create(volume.id,
args.force,
args.name,
args.description,
metadata=snapshot_metadata)
_print_volume_snapshot(snapshot)
@utils.arg('snapshot',
metavar='<snapshot>', nargs='+',
help='Name or ID of the snapshot(s) to delete.')
@utils.arg('--force',
action="store_true",
help='Allows deleting snapshot of a volume '
'when its status is other than "available" or "error". '
'Default=False.')
@utils.service_type('volumev3')
def do_snapshot_delete(cs, args):
"""Removes one or more snapshots."""
failure_count = 0
for snapshot in args.snapshot:
try:
_find_volume_snapshot(cs, snapshot).delete(args.force)
except Exception as e:
failure_count += 1
print("Delete for snapshot %s failed: %s" % (snapshot, e))
if failure_count == len(args.snapshot):
raise exceptions.CommandError("Unable to delete any of the specified "
"snapshots.")
@utils.arg('snapshot', metavar='<snapshot>',
help='Name or ID of snapshot.')
@utils.arg('name', nargs='?', metavar='<name>',
help='New name for snapshot.')
@utils.arg('--description', metavar='<description>',
default=None,
help='Snapshot description. Default=None.')
@utils.arg('--display-description',
help=argparse.SUPPRESS)
@utils.arg('--display_description',
help=argparse.SUPPRESS)
@utils.service_type('volumev3')
def do_snapshot_rename(cs, args):
"""Renames a snapshot."""
kwargs = {}
if args.name is not None:
kwargs['name'] = args.name
if args.description is not None:
kwargs['description'] = args.description
elif args.display_description is not None:
kwargs['description'] = args.display_description
if not any(kwargs):
msg = 'Must supply either name or description.'
raise exceptions.ClientException(code=1, message=msg)
_find_volume_snapshot(cs, args.snapshot).update(**kwargs)
@utils.arg('snapshot', metavar='<snapshot>', nargs='+',
help='Name or ID of snapshot to modify.')
@utils.arg('--state', metavar='<state>',
default='available',
help=('The state to assign to the snapshot. Valid values are '
'"available", "error", "creating", "deleting", and '
'"error_deleting". NOTE: This command simply changes '
'the state of the Snapshot in the DataBase with no regard '
'to actual status, exercise caution when using. '
'Default=available.'))
@utils.service_type('volumev3')
def do_snapshot_reset_state(cs, args):
"""Explicitly updates the snapshot state."""
failure_count = 0
single = (len(args.snapshot) == 1)
for snapshot in args.snapshot:
try:
_find_volume_snapshot(cs, snapshot).reset_state(args.state)
except Exception as e:
failure_count += 1
msg = "Reset state for snapshot %s failed: %s" % (snapshot, e)
if not single:
print(msg)
if failure_count == len(args.snapshot):
if not single:
msg = ("Unable to reset the state for any of the specified "
"snapshots.")
raise exceptions.CommandError(msg)
def _print_volume_type_list(vtypes):
utils.print_list(vtypes, ['ID', 'Name', 'Description', 'Is_Public'])
def _print_group_type_list(gtypes):
utils.print_list(gtypes, ['ID', 'Name', 'Description'])
@utils.service_type('volumev3')
def do_type_list(cs, args):
"""Lists available 'volume types'. (Admin only will see private types)"""
vtypes = cs.volume_types.list()
_print_volume_type_list(vtypes)
@utils.service_type('volumev3')
@api_versions.wraps('3.11')
def do_group_type_list(cs, args):
"""Lists available 'group types'. (Admin only will see private types)"""
gtypes = cs.group_types.list()
_print_group_type_list(gtypes)
@utils.service_type('volumev3')
def do_type_default(cs, args):
"""List the default volume type."""
vtype = cs.volume_types.default()
_print_volume_type_list([vtype])
@utils.service_type('volumev3')
@api_versions.wraps('3.11')
def do_group_type_default(cs, args):
"""List the default group type."""
gtype = cs.group_types.default()
_print_group_type_list([gtype])
@utils.arg('volume_type',
metavar='<volume_type>',
help='Name or ID of the volume type.')
@utils.service_type('volumev3')
def do_type_show(cs, args):
"""Show volume type details."""
vtype = _find_vtype(cs, args.volume_type)
info = dict()
info.update(vtype._info)
info.pop('links', None)
utils.print_dict(info, formatters=['extra_specs'])
@utils.service_type('volumev3')
@api_versions.wraps('3.11')
@utils.arg('group_type',
metavar='<group_type>',
help='Name or ID of the group type.')
def do_group_type_show(cs, args):
"""Show group type details."""
gtype = _find_gtype(cs, args.group_type)
info = dict()
info.update(gtype._info)
info.pop('links', None)
utils.print_dict(info, formatters=['group_specs'])
@utils.arg('id',
metavar='<id>',
help='ID of the volume type.')
@utils.arg('--name',
metavar='<name>',
help='Name of the volume type.')
@utils.arg('--description',
metavar='<description>',
help='Description of the volume type.')
@utils.arg('--is-public',
metavar='<is-public>',
help='Make type accessible to the public or not.')
@utils.service_type('volumev3')
def do_type_update(cs, args):
"""Updates volume type name, description, and/or is_public."""
is_public = strutils.bool_from_string(args.is_public, strict=True)
vtype = cs.volume_types.update(args.id, args.name, args.description,
is_public)
_print_volume_type_list([vtype])
@utils.service_type('volumev3')
@api_versions.wraps('3.11')
@utils.arg('id',
metavar='<id>',
help='ID of the group type.')
@utils.arg('--name',
metavar='<name>',
help='Name of the group type.')
@utils.arg('--description',
metavar='<description>',
help='Description of the group type.')
@utils.arg('--is-public',
metavar='<is-public>',
help='Make type accessible to the public or not.')
def do_group_type_update(cs, args):
"""Updates group type name, description, and/or is_public."""
is_public = strutils.bool_from_string(args.is_public)
gtype = cs.group_types.update(args.id, args.name, args.description,
is_public)
_print_group_type_list([gtype])
@utils.service_type('volumev3')
def do_extra_specs_list(cs, args):
"""Lists current volume types and extra specs."""
vtypes = cs.volume_types.list()
utils.print_list(vtypes, ['ID', 'Name', 'extra_specs'])
@utils.service_type('volumev3')
@api_versions.wraps('3.11')
def do_group_specs_list(cs, args):
"""Lists current group types and specs."""
gtypes = cs.group_types.list()
utils.print_list(gtypes, ['ID', 'Name', 'group_specs'])
@utils.arg('name',
metavar='<name>',
help='Name of new volume type.')
@utils.arg('--description',
metavar='<description>',
help='Description of new volume type.')
@utils.arg('--is-public',
metavar='<is-public>',
default=True,
help='Make type accessible to the public (default true).')
@utils.service_type('volumev3')
def do_type_create(cs, args):
"""Creates a volume type."""
is_public = strutils.bool_from_string(args.is_public, strict=True)
vtype = cs.volume_types.create(args.name, args.description, is_public)
_print_volume_type_list([vtype])
@utils.service_type('volumev3')
@api_versions.wraps('3.11')
@utils.arg('name',
metavar='<name>',
help='Name of new group type.')
@utils.arg('--description',
metavar='<description>',
help='Description of new group type.')
@utils.arg('--is-public',
metavar='<is-public>',
default=True,
help='Make type accessible to the public (default true).')
def do_group_type_create(cs, args):
"""Creates a group type."""
is_public = strutils.bool_from_string(args.is_public)
gtype = cs.group_types.create(args.name, args.description, is_public)
_print_group_type_list([gtype])
@utils.arg('vol_type',
metavar='<vol_type>', nargs='+',
help='Name or ID of volume type or types to delete.')
@utils.service_type('volumev3')
def do_type_delete(cs, args):
"""Deletes volume type or types."""
failure_count = 0
for vol_type in args.vol_type:
try:
vtype = _find_volume_type(cs, vol_type)
cs.volume_types.delete(vtype)
print("Request to delete volume type %s has been accepted."
% (vol_type))
except Exception as e:
failure_count += 1
print("Delete for volume type %s failed: %s" % (vol_type, e))
if failure_count == len(args.vol_type):
raise exceptions.CommandError("Unable to delete any of the "
"specified types.")
@utils.service_type('volumev3')
@api_versions.wraps('3.11')
@utils.arg('group_type',
metavar='<group_type>', nargs='+',
help='Name or ID of group type or types to delete.')
def do_group_type_delete(cs, args):
"""Deletes group type or types."""
failure_count = 0
for group_type in args.group_type:
try:
gtype = _find_group_type(cs, group_type)
cs.group_types.delete(gtype)
print("Request to delete group type %s has been accepted."
% (group_type))
except Exception as e:
failure_count += 1
print("Delete for group type %s failed: %s" % (group_type, e))
if failure_count == len(args.group_type):
raise exceptions.CommandError("Unable to delete any of the "
"specified types.")
@utils.arg('vtype',
metavar='<vtype>',
help='Name or ID of volume type.')
@utils.arg('action',
metavar='<action>',
choices=['set', 'unset'],
help='The action. Valid values are "set" or "unset."')
@utils.arg('metadata',
metavar='<key=value>',
nargs='+',
default=[],
help='The extra specs key and value pair to set or unset. '
'For unset, specify only the key.')
@utils.service_type('volumev3')
def do_type_key(cs, args):
"""Sets or unsets extra_spec for a volume type."""
vtype = _find_volume_type(cs, args.vtype)
keypair = _extract_metadata(args)
if args.action == 'set':
vtype.set_keys(keypair)
elif args.action == 'unset':
vtype.unset_keys(list(keypair))
@utils.service_type('volumev3')
@api_versions.wraps('3.11')
@utils.arg('gtype',
metavar='<gtype>',
help='Name or ID of group type.')
@utils.arg('action',
metavar='<action>',
choices=['set', 'unset'],
help='The action. Valid values are "set" or "unset."')
@utils.arg('metadata',
metavar='<key=value>',
nargs='+',
default=[],
help='The group specs key and value pair to set or unset. '
'For unset, specify only the key.')
def do_group_type_key(cs, args):
"""Sets or unsets group_spec for a group type."""
gtype = _find_group_type(cs, args.gtype)
keypair = _extract_metadata(args)
if args.action == 'set':
gtype.set_keys(keypair)
elif args.action == 'unset':
gtype.unset_keys(list(keypair))
@utils.arg('--volume-type', metavar='<volume_type>', required=True,
help='Filter results by volume type name or ID.')
@utils.service_type('volumev3')
def do_type_access_list(cs, args):
"""Print access information about the given volume type."""
volume_type = _find_volume_type(cs, args.volume_type)
if volume_type.is_public:
raise exceptions.CommandError("Failed to get access list "
"for public volume type.")
access_list = cs.volume_type_access.list(volume_type)
columns = ['Volume_type_ID', 'Project_ID']
utils.print_list(access_list, columns)
@utils.arg('--volume-type', metavar='<volume_type>', required=True,
help='Volume type name or ID to add access for the given project.')
@utils.arg('--project-id', metavar='<project_id>', required=True,
help='Project ID to add volume type access for.')
@utils.service_type('volumev3')
def do_type_access_add(cs, args):
"""Adds volume type access for the given project."""
vtype = _find_volume_type(cs, args.volume_type)
cs.volume_type_access.add_project_access(vtype, args.project_id)
@utils.arg('--volume-type', metavar='<volume_type>', required=True,
help=('Volume type name or ID to remove access '
'for the given project.'))
@utils.arg('--project-id', metavar='<project_id>', required=True,
help='Project ID to remove volume type access for.')
@utils.service_type('volumev3')
def do_type_access_remove(cs, args):
"""Removes volume type access for the given project."""
vtype = _find_volume_type(cs, args.volume_type)
cs.volume_type_access.remove_project_access(
vtype, args.project_id)
@utils.service_type('volumev3')
def do_endpoints(cs, args):
"""Discovers endpoints registered by authentication service."""
warnings.warn(
"``cinder endpoints`` is deprecated, use ``openstack catalog list`` "
"instead. The ``cinder endpoints`` command may be removed in the P "
"release or next major release of cinderclient (v2.0.0 or greater).")
catalog = cs.client.service_catalog.catalog
for e in catalog:
utils.print_dict(e['endpoints'][0], e['name'])
@utils.service_type('volumev3')
def do_credentials(cs, args):
"""Shows user credentials returned from auth."""
catalog = cs.client.service_catalog.catalog
# formatters defines field to be converted from unicode to string
utils.print_dict(catalog['user'], "User Credentials",
formatters=['domain', 'roles'])
utils.print_dict(catalog['token'], "Token",
formatters=['audit_ids', 'tenant'])
_quota_resources = ['volumes', 'snapshots', 'gigabytes',
'backups', 'backup_gigabytes',
'consistencygroups', 'per_volume_gigabytes',
'groups', ]
_quota_infos = ['Type', 'In_use', 'Reserved', 'Limit']
def _quota_show(quotas):
quota_dict = {}
for resource in quotas._info:
good_name = False
for name in _quota_resources:
if resource.startswith(name):
good_name = True
if not good_name:
continue
quota_dict[resource] = getattr(quotas, resource, None)
utils.print_dict(quota_dict)
def _quota_usage_show(quotas):
quota_list = []
for resource in quotas._info.keys():
good_name = False
for name in _quota_resources:
if resource.startswith(name):
good_name = True
if not good_name:
continue
quota_info = getattr(quotas, resource, None)
quota_info['Type'] = resource
quota_info = dict((k.capitalize(), v) for k, v in quota_info.items())
quota_list.append(quota_info)
utils.print_list(quota_list, _quota_infos)
def _quota_update(manager, identifier, args):
updates = {}
for resource in _quota_resources:
val = getattr(args, resource, None)
if val is not None:
if args.volume_type:
resource = resource + '_%s' % args.volume_type
updates[resource] = val
if updates:
_quota_show(manager.update(identifier, **updates))
@utils.arg('tenant',
metavar='<tenant_id>',
help='ID of tenant for which to list quotas.')
@utils.service_type('volumev3')
def do_quota_show(cs, args):
"""Lists quotas for a tenant."""
_quota_show(cs.quotas.get(args.tenant))
@utils.arg('tenant', metavar='<tenant_id>',
help='ID of tenant for which to list quota usage.')
@utils.service_type('volumev3')
def do_quota_usage(cs, args):
"""Lists quota usage for a tenant."""
_quota_usage_show(cs.quotas.get(args.tenant, usage=True))
@utils.arg('tenant',
metavar='<tenant_id>',
help='ID of tenant for which to list quota defaults.')
@utils.service_type('volumev3')
def do_quota_defaults(cs, args):
"""Lists default quotas for a tenant."""
_quota_show(cs.quotas.defaults(args.tenant))
@utils.arg('tenant',
metavar='<tenant_id>',
help='ID of tenant for which to set quotas.')
@utils.arg('--volumes',
metavar='<volumes>',
type=int, default=None,
help='The new "volumes" quota value. Default=None.')
@utils.arg('--snapshots',
metavar='<snapshots>',
type=int, default=None,
help='The new "snapshots" quota value. Default=None.')
@utils.arg('--gigabytes',
metavar='<gigabytes>',
type=int, default=None,
help='The new "gigabytes" quota value. Default=None.')
@utils.arg('--backups',
metavar='<backups>',
type=int, default=None,
help='The new "backups" quota value. Default=None.')
@utils.arg('--backup-gigabytes',
metavar='<backup_gigabytes>',
type=int, default=None,
help='The new "backup_gigabytes" quota value. Default=None.')
@utils.arg('--consistencygroups',
metavar='<consistencygroups>',
type=int, default=None,
help='The new "consistencygroups" quota value. Default=None.')
@utils.arg('--groups',
metavar='<groups>',
type=int, default=None,
help='The new "groups" quota value. Default=None.',
start_version='3.13')
@utils.arg('--volume-type',
metavar='<volume_type_name>',
default=None,
help='Volume type. Default=None.')
@utils.arg('--per-volume-gigabytes',
metavar='<per_volume_gigabytes>',
type=int, default=None,
help='Set max volume size limit. Default=None.')
@utils.service_type('volumev3')
def do_quota_update(cs, args):
"""Updates quotas for a tenant."""
_quota_update(cs.quotas, args.tenant, args)
@utils.arg('tenant', metavar='<tenant_id>',
help='UUID of tenant to delete the quotas for.')
@utils.service_type('volumev3')
def do_quota_delete(cs, args):
"""Delete the quotas for a tenant."""
cs.quotas.delete(args.tenant)
@utils.arg('class_name',
metavar='<class>',
help='Name of quota class for which to list quotas.')
@utils.service_type('volumev3')
def do_quota_class_show(cs, args):
"""Lists quotas for a quota class."""
_quota_show(cs.quota_classes.get(args.class_name))
@utils.arg('class_name',
metavar='<class_name>',
help='Name of quota class for which to set quotas.')
@utils.arg('--volumes',
metavar='<volumes>',
type=int, default=None,
help='The new "volumes" quota value. Default=None.')
@utils.arg('--snapshots',
metavar='<snapshots>',
type=int, default=None,
help='The new "snapshots" quota value. Default=None.')
@utils.arg('--gigabytes',
metavar='<gigabytes>',
type=int, default=None,
help='The new "gigabytes" quota value. Default=None.')
@utils.arg('--volume-type',
metavar='<volume_type_name>',
default=None,
help='Volume type. Default=None.')
@utils.service_type('volumev3')
def do_quota_class_update(cs, args):
"""Updates quotas for a quota class."""
_quota_update(cs.quota_classes, args.class_name, args)
@utils.arg('tenant',
metavar='<tenant_id>',
nargs='?',
default=None,
help='Display information for a single tenant (Admin only).')
@utils.service_type('volumev3')
def do_absolute_limits(cs, args):
"""Lists absolute limits for a user."""
limits = cs.limits.get(args.tenant).absolute
columns = ['Name', 'Value']
utils.print_list(limits, columns)
@utils.arg('tenant',
metavar='<tenant_id>',
nargs='?',
default=None,
help='Display information for a single tenant (Admin only).')
@utils.service_type('volumev3')
def do_rate_limits(cs, args):
"""Lists rate limits for a user."""
limits = cs.limits.get(args.tenant).rate
columns = ['Verb', 'URI', 'Value', 'Remain', 'Unit', 'Next_Available']
utils.print_list(limits, columns)
def _find_volume_type(cs, vtype):
"""Gets a volume type by name or ID."""
return utils.find_resource(cs.volume_types, vtype)
def _find_group_type(cs, gtype):
"""Gets a group type by name or ID."""
return utils.find_resource(cs.group_types, gtype)
@utils.arg('volume',
metavar='<volume>',
help='Name or ID of volume to snapshot.')
@utils.arg('--force',
metavar='<True|False>',
const=True,
nargs='?',
default=False,
help='Enables or disables upload of '
'a volume that is attached to an instance. '
'Default=False. '
'This option may not be supported by your cloud.')
@utils.arg('--container-format',
metavar='<container-format>',
default='bare',
help='Container format type. '
'Default is bare.')
@utils.arg('--container_format',
help=argparse.SUPPRESS)
@utils.arg('--disk-format',
metavar='<disk-format>',
default='raw',
help='Disk format type. '
'Default is raw.')
@utils.arg('--disk_format',
help=argparse.SUPPRESS)
@utils.arg('image_name',
metavar='<image-name>',
help='The new image name.')
@utils.arg('--image_name',
help=argparse.SUPPRESS)
@utils.arg('--visibility',
metavar='<public|private>',
help='Set image visibility to either public or private. '
'Default=private.',
default='private',
start_version='3.1')
@utils.arg('--protected',
metavar='<True|False>',
help='Prevents image from being deleted. Default=False.',
default=False,
start_version='3.1')
@utils.service_type('volumev3')
def do_upload_to_image(cs, args):
"""Uploads volume to Image Service as an image."""
volume = utils.find_volume(cs, args.volume)
if cs.api_version >= api_versions.APIVersion("3.1"):
_print_volume_image(volume.upload_to_image(args.force,
args.image_name,
args.container_format,
args.disk_format,
args.visibility,
args.protected))
else:
_print_volume_image(volume.upload_to_image(args.force,
args.image_name,
args.container_format,
args.disk_format))
@utils.arg('volume', metavar='<volume>', help='ID of volume to migrate.')
@utils.arg('host', metavar='<host>', help='Destination host. Takes the form: '
'host@backend-name#pool')
@utils.arg('--force-host-copy', metavar='<True|False>',
choices=['True', 'False'],
required=False,
const=True,
nargs='?',
default=False,
help='Enables or disables generic host-based '
'force-migration, which bypasses driver '
'optimizations. Default=False.')
@utils.arg('--lock-volume', metavar='<True|False>',
choices=['True', 'False'],
required=False,
const=True,
nargs='?',
default=False,
help='Enables or disables the termination of volume migration '
'caused by other commands. This option applies to the '
'available volume. True means it locks the volume '
'state and does not allow the migration to be aborted. The '
'volume status will be in maintenance during the '
'migration. False means it allows the volume migration '
'to be aborted. The volume status is still in the original '
'status. Default=False.')
@utils.service_type('volumev3')
def do_migrate(cs, args):
"""Migrates volume to a new host."""
volume = utils.find_volume(cs, args.volume)
try:
volume.migrate_volume(args.host, args.force_host_copy,
args.lock_volume)
print("Request to migrate volume %s has been accepted." % (volume.id))
except Exception as e:
print("Migration for volume %s failed: %s." % (volume.id,
six.text_type(e)))
@utils.arg('volume', metavar='<volume>',
help='Name or ID of volume for which to modify type.')
@utils.arg('new_type', metavar='<volume-type>', help='New volume type.')
@utils.arg('--migration-policy', metavar='<never|on-demand>', required=False,
choices=['never', 'on-demand'], default='never',
help='Migration policy during retype of volume.')
@utils.service_type('volumev3')
def do_retype(cs, args):
"""Changes the volume type for a volume."""
volume = utils.find_volume(cs, args.volume)
volume.retype(args.new_type, args.migration_policy)
@utils.arg('volume', metavar='<volume>',
help='Name or ID of volume to backup.')
@utils.arg('--container', metavar='<container>',
default=None,
help='Backup container name. Default=None.')
@utils.arg('--display-name',
help=argparse.SUPPRESS)
@utils.arg('--name', metavar='<name>',
default=None,
help='Backup name. Default=None.')
@utils.arg('--display-description',
help=argparse.SUPPRESS)
@utils.arg('--description',
metavar='<description>',
default=None,
help='Backup description. Default=None.')
@utils.arg('--incremental',
action='store_true',
help='Incremental backup. Default=False.',
default=False)
@utils.arg('--force',
action='store_true',
help='Allows or disallows backup of a volume '
'when the volume is attached to an instance. '
'If set to True, backs up the volume whether '
'its status is "available" or "in-use". The backup '
'of an "in-use" volume means your data is crash '
'consistent. Default=False.',
default=False)
@utils.arg('--snapshot-id',
metavar='<snapshot-id>',
default=None,
help='ID of snapshot to backup. Default=None.')
@utils.service_type('volumev3')
def do_backup_create(cs, args):
"""Creates a volume backup."""
if args.display_name is not None:
args.name = args.display_name
if args.display_description is not None:
args.description = args.display_description
volume = utils.find_volume(cs, args.volume)
backup = cs.backups.create(volume.id,
args.container,
args.name,
args.description,
args.incremental,
args.force,
args.snapshot_id)
info = {"volume_id": volume.id}
info.update(backup._info)
if 'links' in info:
info.pop('links')
utils.print_dict(info)
@utils.arg('backup', metavar='<backup>', help='Name or ID of backup.')
@utils.service_type('volumev3')
def do_backup_show(cs, args):
"""Shows backup details."""
backup = _find_backup(cs, args.backup)
info = dict()
info.update(backup._info)
info.pop('links', None)
utils.print_dict(info)
@utils.arg('--all-tenants',
metavar='<all_tenants>',
nargs='?',
type=int,
const=1,
default=0,
help='Shows details for all tenants. Admin only.')
@utils.arg('--all_tenants',
nargs='?',
type=int,
const=1,
help=argparse.SUPPRESS)
@utils.arg('--name',
metavar='<name>',
default=None,
help='Filters results by a name. Default=None.')
@utils.arg('--status',
metavar='<status>',
default=None,
help='Filters results by a status. Default=None.')
@utils.arg('--volume-id',
metavar='<volume-id>',
default=None,
help='Filters results by a volume ID. Default=None.')
@utils.arg('--volume_id',
help=argparse.SUPPRESS)
@utils.arg('--marker',
metavar='<marker>',
default=None,
help='Begin returning backups that appear later in the backup '
'list than that represented by this id. '
'Default=None.')
@utils.arg('--limit',
metavar='<limit>',
default=None,
help='Maximum number of backups to return. Default=None.')
@utils.arg('--sort',
metavar='<key>[:<direction>]',
default=None,
help=(('Comma-separated list of sort keys and directions in the '
'form of <key>[:<asc|desc>]. '
'Valid keys: %s. '
'Default=None.') % ', '.join(base.SORT_KEY_VALUES)))
@utils.service_type('volumev3')
def do_backup_list(cs, args):
"""Lists all backups."""
search_opts = {
'all_tenants': args.all_tenants,
'name': args.name,
'status': args.status,
'volume_id': args.volume_id,
}
backups = cs.backups.list(search_opts=search_opts,
marker=args.marker,
limit=args.limit,
sort=args.sort)
_translate_volume_snapshot_keys(backups)
columns = ['ID', 'Volume ID', 'Status', 'Name', 'Size', 'Object Count',
'Container']
if args.sort:
sortby_index = None
else:
sortby_index = 0
utils.print_list(backups, columns, sortby_index=sortby_index)
@utils.arg('--force',
action="store_true",
help='Allows deleting backup of a volume '
'when its status is other than "available" or "error". '
'Default=False.')
@utils.arg('backup', metavar='<backup>', nargs='+',
help='Name or ID of backup(s) to delete.')
@utils.service_type('volumev3')
def do_backup_delete(cs, args):
"""Removes one or more backups."""
failure_count = 0
for backup in args.backup:
try:
_find_backup(cs, backup).delete(args.force)
print("Request to delete backup %s has been accepted." % (backup))
except Exception as e:
failure_count += 1
print("Delete for backup %s failed: %s" % (backup, e))
if failure_count == len(args.backup):
raise exceptions.CommandError("Unable to delete any of the specified "
"backups.")
@utils.arg('backup', metavar='<backup>',
help='Name or ID of backup to restore.')
@utils.arg('--volume-id', metavar='<volume>',
default=None,
help=argparse.SUPPRESS)
@utils.arg('--volume', metavar='<volume>',
default=None,
help='Name or ID of existing volume to which to restore. '
'This is mutually exclusive with --name and takes priority. '
'Default=None.')
@utils.arg('--name', metavar='<name>',
default=None,
help='Use the name for new volume creation to restore. '
'This is mutually exclusive with --volume (or the deprecated '
'--volume-id) and --volume (or --volume-id) takes priority. '
'Default=None.')
@utils.service_type('volumev3')
def do_backup_restore(cs, args):
"""Restores a backup."""
vol = args.volume or args.volume_id
if vol:
volume_id = utils.find_volume(cs, vol).id
if args.name:
args.name = None
print('Mutually exclusive options are specified simultaneously: '
'"--volume (or the deprecated --volume-id) and --name". '
'The --volume (or --volume-id) option takes priority.')
else:
volume_id = None
backup = _find_backup(cs, args.backup)
restore = cs.restores.restore(backup.id, volume_id, args.name)
info = {"backup_id": backup.id}
info.update(restore._info)
info.pop('links', None)
utils.print_dict(info)
@utils.arg('backup', metavar='<backup>',
help='ID of the backup to export.')
@utils.service_type('volumev3')
def do_backup_export(cs, args):
"""Export backup metadata record."""
info = cs.backups.export_record(args.backup)
utils.print_dict(info)
@utils.arg('backup_service', metavar='<backup_service>',
help='Backup service to use for importing the backup.')
@utils.arg('backup_url', metavar='<backup_url>',
help='Backup URL for importing the backup metadata.')
@utils.service_type('volumev3')
def do_backup_import(cs, args):
"""Import backup metadata record."""
info = cs.backups.import_record(args.backup_service, args.backup_url)
info.pop('links', None)
utils.print_dict(info)
@utils.arg('backup', metavar='<backup>', nargs='+',
help='Name or ID of the backup to modify.')
@utils.arg('--state', metavar='<state>',
default='available',
help='The state to assign to the backup. Valid values are '
'"available", "error". Default=available.')
@utils.service_type('volumev3')
def do_backup_reset_state(cs, args):
"""Explicitly updates the backup state."""
failure_count = 0
single = (len(args.backup) == 1)
for backup in args.backup:
try:
_find_backup(cs, backup).reset_state(args.state)
except Exception as e:
failure_count += 1
msg = "Reset state for backup %s failed: %s" % (backup, e)
if not single:
print(msg)
if failure_count == len(args.backup):
if not single:
msg = ("Unable to reset the state for any of the specified "
"backups.")
raise exceptions.CommandError(msg)
@utils.service_type('volumev3')
@api_versions.wraps('3.9')
@utils.arg('backup', metavar='<backup>',
help='Name or ID of backup to rename.')
@utils.arg('--name', nargs='?', metavar='<name>',
help='New name for backup.')
@utils.arg('--description', metavar='<description>',
help='Backup description. Default=None.')
def do_backup_update(cs, args):
"""Renames a backup."""
kwargs = {}
if args.name is not None:
kwargs['name'] = args.name
if args.description is not None:
kwargs['description'] = args.description
if not kwargs:
msg = 'Must supply either name or description.'
raise exceptions.ClientException(code=1, message=msg)
_find_backup(cs, args.backup).update(**kwargs)
@utils.arg('volume', metavar='<volume>',
help='Name or ID of volume to transfer.')
@utils.arg('--name',
metavar='<name>',
default=None,
help='Transfer name. Default=None.')
@utils.arg('--display-name',
help=argparse.SUPPRESS)
@utils.service_type('volumev3')
def do_transfer_create(cs, args):
"""Creates a volume transfer."""
if args.display_name is not None:
args.name = args.display_name
volume = utils.find_volume(cs, args.volume)
transfer = cs.transfers.create(volume.id,
args.name)
info = dict()
info.update(transfer._info)
info.pop('links', None)
utils.print_dict(info)
@utils.service_type('volumev3')
@api_versions.wraps('3.7')
@utils.arg('--name', metavar='<name>', default=None,
help='Filter by cluster name, without backend will list all '
'clustered services from the same cluster. Default=None.')
@utils.arg('--binary', metavar='<binary>', default=None,
help='Cluster binary. Default=None.')
@utils.arg('--is-up', metavar='<True|true|False|false>', default=None,
choices=('True', 'true', 'False', 'false'),
help='Filter by up/dow status. Default=None.')
@utils.arg('--disabled', metavar='<True|true|False|false>', default=None,
choices=('True', 'true', 'False', 'false'),
help='Filter by disabled status. Default=None.')
@utils.arg('--num-hosts', metavar='<num-hosts>', default=None,
help='Filter by number of hosts in the cluster.')
@utils.arg('--num-down-hosts', metavar='<num-down-hosts>', default=None,
help='Filter by number of hosts that are down.')
@utils.arg('--detailed', dest='detailed', default=False,
help='Get detailed clustered service information (Default=False).',
action='store_true')
def do_cluster_list(cs, args):
"""Lists clustered services with optional filtering."""
clusters = cs.clusters.list(name=args.name, binary=args.binary,
is_up=args.is_up, disabled=args.disabled,
num_hosts=args.num_hosts,
num_down_hosts=args.num_down_hosts,
detailed=args.detailed)
columns = ['Name', 'Binary', 'State', 'Status']
if args.detailed:
columns.extend(('Num Hosts', 'Num Down Hosts', 'Last Heartbeat',
'Disabled Reason', 'Created At', 'Updated at'))
utils.print_list(clusters, columns)
@utils.service_type('volumev3')
@api_versions.wraps('3.7')
@utils.arg('binary', metavar='<binary>', nargs='?', default='cinder-volume',
help='Binary to filter by. Default: cinder-volume.')
@utils.arg('name', metavar='<cluster-name>',
help='Name of the clustered service to show.')
def do_cluster_show(cs, args):
"""Show detailed information on a clustered service."""
cluster = cs.clusters.show(args.name, args.binary)
utils.print_dict(cluster.to_dict())
@utils.service_type('volumev3')
@api_versions.wraps('3.7')
@utils.arg('binary', metavar='<binary>', nargs='?', default='cinder-volume',
help='Binary to filter by. Default: cinder-volume.')
@utils.arg('name', metavar='<cluster-name>',
help='Name of the clustered services to update.')
def do_cluster_enable(cs, args):
"""Enables clustered services."""
cluster = cs.clusters.update(args.name, args.binary, disabled=False)
utils.print_dict(cluster.to_dict())
@utils.service_type('volumev3')
@api_versions.wraps('3.7')
@utils.arg('binary', metavar='<binary>', nargs='?', default='cinder-volume',
help='Binary to filter by. Default: cinder-volume.')
@utils.arg('name', metavar='<cluster-name>',
help='Name of the clustered services to update.')
@utils.arg('--reason', metavar='<reason>', default=None,
help='Reason for disabling clustered service.')
def do_cluster_disable(cs, args):
"""Disables clustered services."""
cluster = cs.clusters.update(args.name, args.binary, disabled=True,
disabled_reason=args.reason)
utils.print_dict(cluster.to_dict())
@utils.arg('transfer', metavar='<transfer>',
help='Name or ID of transfer to delete.')
@utils.service_type('volumev3')
def do_transfer_delete(cs, args):
"""Undoes a transfer."""
transfer = _find_transfer(cs, args.transfer)
transfer.delete()
@utils.arg('transfer', metavar='<transfer>',
help='ID of transfer to accept.')
@utils.arg('auth_key', metavar='<auth_key>',
help='Authentication key of transfer to accept.')
@utils.service_type('volumev3')
def do_transfer_accept(cs, args):
"""Accepts a volume transfer."""
transfer = cs.transfers.accept(args.transfer, args.auth_key)
info = dict()
info.update(transfer._info)
info.pop('links', None)
utils.print_dict(info)
@utils.arg('--all-tenants',
dest='all_tenants',
metavar='<0|1>',
nargs='?',
type=int,
const=1,
default=0,
help='Shows details for all tenants. Admin only.')
@utils.arg('--all_tenants',
nargs='?',
type=int,
const=1,
help=argparse.SUPPRESS)
@utils.service_type('volumev3')
def do_transfer_list(cs, args):
"""Lists all transfers."""
all_tenants = int(os.environ.get("ALL_TENANTS", args.all_tenants))
search_opts = {
'all_tenants': all_tenants,
}
transfers = cs.transfers.list(search_opts=search_opts)
columns = ['ID', 'Volume ID', 'Name']
utils.print_list(transfers, columns)
@utils.arg('transfer', metavar='<transfer>',
help='Name or ID of transfer to accept.')
@utils.service_type('volumev3')
def do_transfer_show(cs, args):
"""Shows transfer details."""
transfer = _find_transfer(cs, args.transfer)
info = dict()
info.update(transfer._info)
info.pop('links', None)
utils.print_dict(info)
@utils.arg('volume', metavar='<volume>',
help='Name or ID of volume to extend.')
@utils.arg('new_size',
metavar='<new_size>',
type=int,
help='New size of volume, in GiBs.')
@utils.service_type('volumev3')
def do_extend(cs, args):
"""Attempts to extend size of an existing volume."""
volume = utils.find_volume(cs, args.volume)
cs.volumes.extend(volume, args.new_size)
@utils.arg('--host', metavar='<hostname>', default=None,
help='Host name. Default=None.')
@utils.arg('--binary', metavar='<binary>', default=None,
help='Service binary. Default=None.')
@utils.arg('--withreplication',
metavar='<True|False>',
const=True,
nargs='?',
default=False,
help='Enables or disables display of '
'Replication info for c-vol services. Default=False.')
@utils.service_type('volumev3')
def do_service_list(cs, args):
"""Lists all services. Filter by host and service binary."""
replication = strutils.bool_from_string(args.withreplication,
strict=True)
result = cs.services.list(host=args.host, binary=args.binary)
columns = ["Binary", "Host", "Zone", "Status", "State", "Updated_at"]
if cs.api_version.matches('3.7'):
columns.append('Cluster')
if replication:
columns.extend(["Replication Status", "Active Backend ID", "Frozen"])
# NOTE(jay-lau-513): we check if the response has disabled_reason
# so as not to add the column when the extended ext is not enabled.
if result and hasattr(result[0], 'disabled_reason'):
columns.append("Disabled Reason")
utils.print_list(result, columns)
@utils.arg('host', metavar='<hostname>', help='Host name.')
@utils.arg('binary', metavar='<binary>', help='Service binary.')
@utils.service_type('volumev3')
def do_service_enable(cs, args):
"""Enables the service."""
result = cs.services.enable(args.host, args.binary)
columns = ["Host", "Binary", "Status"]
utils.print_list([result], columns)
@utils.arg('host', metavar='<hostname>', help='Host name.')
@utils.arg('binary', metavar='<binary>', help='Service binary.')
@utils.arg('--reason', metavar='<reason>',
help='Reason for disabling service.')
@utils.service_type('volumev3')
def do_service_disable(cs, args):
"""Disables the service."""
columns = ["Host", "Binary", "Status"]
if args.reason:
columns.append('Disabled Reason')
result = cs.services.disable_log_reason(args.host, args.binary,
args.reason)
else:
result = cs.services.disable(args.host, args.binary)
utils.print_list([result], columns)
@utils.service_type('volumev3')
def _treeizeAvailabilityZone(zone):
"""Builds a tree view for availability zones."""
AvailabilityZone = availability_zones.AvailabilityZone
az = AvailabilityZone(zone.manager,
copy.deepcopy(zone._info), zone._loaded)
result = []
# Zone tree view item
az.zoneName = zone.zoneName
az.zoneState = ('available'
if zone.zoneState['available'] else 'not available')
az._info['zoneName'] = az.zoneName
az._info['zoneState'] = az.zoneState
result.append(az)
if getattr(zone, "hosts", None) and zone.hosts is not None:
for (host, services) in zone.hosts.items():
# Host tree view item
az = AvailabilityZone(zone.manager,
copy.deepcopy(zone._info), zone._loaded)
az.zoneName = '|- %s' % host
az.zoneState = ''
az._info['zoneName'] = az.zoneName
az._info['zoneState'] = az.zoneState
result.append(az)
for (svc, state) in services.items():
# Service tree view item
az = AvailabilityZone(zone.manager,
copy.deepcopy(zone._info), zone._loaded)
az.zoneName = '| |- %s' % svc
az.zoneState = '%s %s %s' % (
'enabled' if state['active'] else 'disabled',
':-)' if state['available'] else 'XXX',
state['updated_at'])
az._info['zoneName'] = az.zoneName
az._info['zoneState'] = az.zoneState
result.append(az)
return result
@utils.service_type('volumev3')
def do_availability_zone_list(cs, _args):
"""Lists all availability zones."""
try:
availability_zones = cs.availability_zones.list()
except exceptions.Forbidden as e: # policy doesn't allow probably
try:
availability_zones = cs.availability_zones.list(detailed=False)
except Exception:
raise e
result = []
for zone in availability_zones:
result += _treeizeAvailabilityZone(zone)
_translate_availability_zone_keys(result)
utils.print_list(result, ['Name', 'Status'])
def _print_volume_encryption_type_list(encryption_types):
"""
Lists volume encryption types.
:param encryption_types: a list of :class: VolumeEncryptionType instances
"""
utils.print_list(encryption_types, ['Volume Type ID', 'Provider',
'Cipher', 'Key Size',
'Control Location'])
@utils.service_type('volumev3')
def do_encryption_type_list(cs, args):
"""Shows encryption type details for volume types. Admin only."""
result = cs.volume_encryption_types.list()
utils.print_list(result, ['Volume Type ID', 'Provider', 'Cipher',
'Key Size', 'Control Location'])
@utils.arg('volume_type',
metavar='<volume_type>',
type=str,
help='Name or ID of volume type.')
@utils.service_type('volumev3')
def do_encryption_type_show(cs, args):
"""Shows encryption type details for a volume type. Admin only."""
volume_type = _find_volume_type(cs, args.volume_type)
result = cs.volume_encryption_types.get(volume_type)
# Display result or an empty table if no result
if hasattr(result, 'volume_type_id'):
_print_volume_encryption_type_list([result])
else:
_print_volume_encryption_type_list([])
@utils.arg('volume_type',
metavar='<volume_type>',
type=str,
help='Name or ID of volume type.')
@utils.arg('provider',
metavar='<provider>',
type=str,
help='The class that provides encryption support. '
'For example, LuksEncryptor.')
@utils.arg('--cipher',
metavar='<cipher>',
type=str,
required=False,
default=None,
help='The encryption algorithm or mode. '
'For example, aes-xts-plain64. Default=None.')
@utils.arg('--key_size',
metavar='<key_size>',
type=int,
required=False,
default=None,
help='Size of encryption key, in bits. '
'For example, 128 or 256. Default=None.')
@utils.arg('--control_location',
metavar='<control_location>',
choices=['front-end', 'back-end'],
type=str,
required=False,
default='front-end',
help='Notional service where encryption is performed. '
'Valid values are "front-end" or "back-end." '
'For example, front-end=Nova. Default is "front-end."')
@utils.service_type('volumev3')
def do_encryption_type_create(cs, args):
"""Creates encryption type for a volume type. Admin only."""
volume_type = _find_volume_type(cs, args.volume_type)
body = {
'provider': args.provider,
'cipher': args.cipher,
'key_size': args.key_size,
'control_location': args.control_location
}
result = cs.volume_encryption_types.create(volume_type, body)
_print_volume_encryption_type_list([result])
@utils.arg('volume_type',
metavar='<volume-type>',
type=str,
help="Name or ID of the volume type")
@utils.arg('--provider',
metavar='<provider>',
type=str,
required=False,
default=argparse.SUPPRESS,
help="Class providing encryption support (e.g. LuksEncryptor) "
"(Optional)")
@utils.arg('--cipher',
metavar='<cipher>',
type=str,
nargs='?',
required=False,
default=argparse.SUPPRESS,
const=None,
help="Encryption algorithm/mode to use (e.g., aes-xts-plain64). "
"Provide parameter without value to set to provider default. "
"(Optional)")
@utils.arg('--key-size',
dest='key_size',
metavar='<key-size>',
type=int,
nargs='?',
required=False,
default=argparse.SUPPRESS,
const=None,
help="Size of the encryption key, in bits (e.g., 128, 256). "
"Provide parameter without value to set to provider default. "
"(Optional)")
@utils.arg('--control-location',
dest='control_location',
metavar='<control-location>',
choices=['front-end', 'back-end'],
type=str,
required=False,
default=argparse.SUPPRESS,
help="Notional service where encryption is performed (e.g., "
"front-end=Nova). Values: 'front-end', 'back-end' (Optional)")
@utils.service_type('volumev3')
def do_encryption_type_update(cs, args):
"""Update encryption type information for a volume type (Admin Only)."""
volume_type = _find_volume_type(cs, args.volume_type)
# An argument should only be pulled if the user specified the parameter.
body = {}
for attr in ['provider', 'cipher', 'key_size', 'control_location']:
if hasattr(args, attr):
body[attr] = getattr(args, attr)
cs.volume_encryption_types.update(volume_type, body)
result = cs.volume_encryption_types.get(volume_type)
_print_volume_encryption_type_list([result])
@utils.arg('volume_type',
metavar='<volume_type>',
type=str,
help='Name or ID of volume type.')
@utils.service_type('volumev3')
def do_encryption_type_delete(cs, args):
"""Deletes encryption type for a volume type. Admin only."""
volume_type = _find_volume_type(cs, args.volume_type)
cs.volume_encryption_types.delete(volume_type)
def _print_qos_specs(qos_specs):
# formatters defines field to be converted from unicode to string
utils.print_dict(qos_specs._info, formatters=['specs'])
def _print_qos_specs_list(q_specs):
utils.print_list(q_specs, ['ID', 'Name', 'Consumer', 'specs'])
def _print_qos_specs_and_associations_list(q_specs):
utils.print_list(q_specs, ['ID', 'Name', 'Consumer', 'specs'])
def _print_associations_list(associations):
utils.print_list(associations, ['Association_Type', 'Name', 'ID'])
@utils.arg('name',
metavar='<name>',
help='Name of new QoS specifications.')
@utils.arg('metadata',
metavar='<key=value>',
nargs='+',
default=[],
help='QoS specifications.')
@utils.service_type('volumev3')
def do_qos_create(cs, args):
"""Creates a qos specs."""
keypair = None
if args.metadata is not None:
keypair = _extract_metadata(args)
qos_specs = cs.qos_specs.create(args.name, keypair)
_print_qos_specs(qos_specs)
@utils.service_type('volumev3')
def do_qos_list(cs, args):
"""Lists qos specs."""
qos_specs = cs.qos_specs.list()
_print_qos_specs_list(qos_specs)
@utils.arg('qos_specs', metavar='<qos_specs>',
help='ID of QoS specifications to show.')
@utils.service_type('volumev3')
def do_qos_show(cs, args):
"""Shows qos specs details."""
qos_specs = _find_qos_specs(cs, args.qos_specs)
_print_qos_specs(qos_specs)
@utils.arg('qos_specs', metavar='<qos_specs>',
help='ID of QoS specifications to delete.')
@utils.arg('--force',
metavar='<True|False>',
const=True,
nargs='?',
default=False,
help='Enables or disables deletion of in-use '
'QoS specifications. Default=False.')
@utils.service_type('volumev3')
def do_qos_delete(cs, args):
"""Deletes a specified qos specs."""
force = strutils.bool_from_string(args.force,
strict=True)
qos_specs = _find_qos_specs(cs, args.qos_specs)
cs.qos_specs.delete(qos_specs, force)
@utils.arg('qos_specs', metavar='<qos_specs>',
help='ID of QoS specifications.')
@utils.arg('vol_type_id', metavar='<volume_type_id>',
help='ID of volume type with which to associate '
'QoS specifications.')
@utils.service_type('volumev3')
def do_qos_associate(cs, args):
"""Associates qos specs with specified volume type."""
cs.qos_specs.associate(args.qos_specs, args.vol_type_id)
@utils.arg('qos_specs', metavar='<qos_specs>',
help='ID of QoS specifications.')
@utils.arg('vol_type_id', metavar='<volume_type_id>',
help='ID of volume type with which to associate '
'QoS specifications.')
@utils.service_type('volumev3')
def do_qos_disassociate(cs, args):
"""Disassociates qos specs from specified volume type."""
cs.qos_specs.disassociate(args.qos_specs, args.vol_type_id)
@utils.arg('qos_specs', metavar='<qos_specs>',
help='ID of QoS specifications on which to operate.')
@utils.service_type('volumev3')
def do_qos_disassociate_all(cs, args):
"""Disassociates qos specs from all its associations."""
cs.qos_specs.disassociate_all(args.qos_specs)
@utils.arg('qos_specs', metavar='<qos_specs>',
help='ID of QoS specifications.')
@utils.arg('action',
metavar='<action>',
choices=['set', 'unset'],
help='The action. Valid values are "set" or "unset."')
@utils.arg('metadata', metavar='key=value',
nargs='+',
default=[],
help='Metadata key and value pair to set or unset. '
'For unset, specify only the key.')
@utils.service_type('volumev3')
def do_qos_key(cs, args):
"""Sets or unsets specifications for a qos spec."""
keypair = _extract_metadata(args)
if args.action == 'set':
cs.qos_specs.set_keys(args.qos_specs, keypair)
elif args.action == 'unset':
cs.qos_specs.unset_keys(args.qos_specs, list(keypair))
@utils.arg('qos_specs', metavar='<qos_specs>',
help='ID of QoS specifications.')
@utils.service_type('volumev3')
def do_qos_get_association(cs, args):
"""Lists all associations for specified qos specs."""
associations = cs.qos_specs.get_associations(args.qos_specs)
_print_associations_list(associations)
@utils.arg('snapshot',
metavar='<snapshot>',
help='ID of snapshot for which to update metadata.')
@utils.arg('action',
metavar='<action>',
choices=['set', 'unset'],
help='The action. Valid values are "set" or "unset."')
@utils.arg('metadata',
metavar='<key=value>',
nargs='+',
default=[],
help='Metadata key and value pair to set or unset. '
'For unset, specify only the key.')
@utils.service_type('volumev3')
def do_snapshot_metadata(cs, args):
"""Sets or deletes snapshot metadata."""
snapshot = _find_volume_snapshot(cs, args.snapshot)
metadata = _extract_metadata(args)
if args.action == 'set':
metadata = snapshot.set_metadata(metadata)
utils.print_dict(metadata._info)
elif args.action == 'unset':
snapshot.delete_metadata(list(metadata.keys()))
@utils.arg('snapshot', metavar='<snapshot>',
help='ID of snapshot.')
@utils.service_type('volumev3')
def do_snapshot_metadata_show(cs, args):
"""Shows snapshot metadata."""
snapshot = _find_volume_snapshot(cs, args.snapshot)
utils.print_dict(snapshot._info['metadata'], 'Metadata-property')
@utils.arg('volume', metavar='<volume>',
help='ID of volume.')
@utils.service_type('volumev3')
def do_metadata_show(cs, args):
"""Shows volume metadata."""
volume = utils.find_volume(cs, args.volume)
utils.print_dict(volume._info['metadata'], 'Metadata-property')
@utils.arg('volume', metavar='<volume>',
help='ID of volume.')
@utils.service_type('volumev3')
def do_image_metadata_show(cs, args):
"""Shows volume image metadata."""
volume = utils.find_volume(cs, args.volume)
resp, body = volume.show_image_metadata(volume)
utils.print_dict(body['metadata'], 'Metadata-property')
@utils.arg('volume',
metavar='<volume>',
help='ID of volume for which to update metadata.')
@utils.arg('metadata',
metavar='<key=value>',
nargs='+',
default=[],
help='Metadata key and value pair or pairs to update.')
@utils.service_type('volumev3')
def do_metadata_update_all(cs, args):
"""Updates volume metadata."""
volume = utils.find_volume(cs, args.volume)
metadata = _extract_metadata(args)
metadata = volume.update_all_metadata(metadata)
utils.print_dict(metadata['metadata'], 'Metadata-property')
@utils.arg('snapshot',
metavar='<snapshot>',
help='ID of snapshot for which to update metadata.')
@utils.arg('metadata',
metavar='<key=value>',
nargs='+',
default=[],
help='Metadata key and value pair to update.')
@utils.service_type('volumev3')
def do_snapshot_metadata_update_all(cs, args):
"""Updates snapshot metadata."""
snapshot = _find_volume_snapshot(cs, args.snapshot)
metadata = _extract_metadata(args)
metadata = snapshot.update_all_metadata(metadata)
utils.print_dict(metadata)
@utils.arg('volume', metavar='<volume>', help='ID of volume to update.')
@utils.arg('read_only',
metavar='<True|true|False|false>',
choices=['True', 'true', 'False', 'false'],
help='Enables or disables update of volume to '
'read-only access mode.')
@utils.service_type('volumev3')
def do_readonly_mode_update(cs, args):
"""Updates volume read-only access-mode flag."""
volume = utils.find_volume(cs, args.volume)
cs.volumes.update_readonly_flag(volume,
strutils.bool_from_string(args.read_only,
strict=True))
@utils.arg('volume', metavar='<volume>', help='ID of the volume to update.')
@utils.arg('bootable',
metavar='<True|true|False|false>',
choices=['True', 'true', 'False', 'false'],
help='Flag to indicate whether volume is bootable.')
@utils.service_type('volumev3')
def do_set_bootable(cs, args):
"""Update bootable status of a volume."""
volume = utils.find_volume(cs, args.volume)
cs.volumes.set_bootable(volume,
strutils.bool_from_string(args.bootable,
strict=True))
@utils.arg('host',
metavar='<host>',
help='Cinder host on which the existing volume resides; '
'takes the form: host@backend-name#pool')
@utils.arg('identifier',
metavar='<identifier>',
help='Name or other Identifier for existing volume')
@utils.arg('--id-type',
metavar='<id-type>',
default='source-name',
help='Type of backend device identifier provided, '
'typically source-name or source-id (Default=source-name)')
@utils.arg('--name',
metavar='<name>',
help='Volume name (Default=None)')
@utils.arg('--description',
metavar='<description>',
help='Volume description (Default=None)')
@utils.arg('--volume-type',
metavar='<volume-type>',
help='Volume type (Default=None)')
@utils.arg('--availability-zone',
metavar='<availability-zone>',
help='Availability zone for volume (Default=None)')
@utils.arg('--metadata',
type=str,
nargs='*',
metavar='<key=value>',
help='Metadata key=value pairs (Default=None)')
@utils.arg('--bootable',
action='store_true',
help='Specifies that the newly created volume should be'
' marked as bootable')
@utils.service_type('volumev3')
def do_manage(cs, args):
"""Manage an existing volume."""
volume_metadata = None
if args.metadata is not None:
volume_metadata = _extract_metadata(args)
# Build a dictionary of key/value pairs to pass to the API.
ref_dict = {args.id_type: args.identifier}
# The recommended way to specify an existing volume is by ID or name, and
# have the Cinder driver look for 'source-name' or 'source-id' elements in
# the ref structure. To make things easier for the user, we have special
# --source-name and --source-id CLI options that add the appropriate
# element to the ref structure.
#
# Note how argparse converts hyphens to underscores. We use hyphens in the
# dictionary so that it is consistent with what the user specified on the
# CLI.
if hasattr(args, 'source_name') and args.source_name is not None:
ref_dict['source-name'] = args.source_name
if hasattr(args, 'source_id') and args.source_id is not None:
ref_dict['source-id'] = args.source_id
volume = cs.volumes.manage(host=args.host,
ref=ref_dict,
name=args.name,
description=args.description,
volume_type=args.volume_type,
availability_zone=args.availability_zone,
metadata=volume_metadata,
bootable=args.bootable)
info = {}
volume = cs.volumes.get(volume.id)
info.update(volume._info)
info.pop('links', None)
utils.print_dict(info)
@utils.service_type('volumev3')
@api_versions.wraps('3.8')
@utils.arg('host',
metavar='<host>',
help='Cinder host on which to list manageable volumes; '
'takes the form: host@backend-name#pool')
@utils.arg('--detailed',
metavar='<detailed>',
default=True,
help='Returned detailed information (default true).')
@utils.arg('--marker',
metavar='<marker>',
default=None,
help='Begin returning volumes that appear later in the volume '
'list than that represented by this volume id. '
'Default=None.')
@utils.arg('--limit',
metavar='<limit>',
default=None,
help='Maximum number of volumes to return. Default=None.')
@utils.arg('--offset',
metavar='<offset>',
default=None,
help='Number of volumes to skip after marker. Default=None.')
@utils.arg('--sort',
metavar='<key>[:<direction>]',
default=None,
help=(('Comma-separated list of sort keys and directions in the '
'form of <key>[:<asc|desc>]. '
'Valid keys: %s. '
'Default=None.') % ', '.join(base.SORT_KEY_VALUES)))
def do_manageable_list(cs, args):
"""Lists all manageable volumes."""
detailed = strutils.bool_from_string(args.detailed)
volumes = cs.volumes.list_manageable(host=args.host, detailed=detailed,
marker=args.marker, limit=args.limit,
offset=args.offset, sort=args.sort)
columns = ['reference', 'size', 'safe_to_manage']
if detailed:
columns.extend(['reason_not_safe', 'cinder_id', 'extra_info'])
utils.print_list(volumes, columns, sortby_index=None)
@utils.arg('volume', metavar='<volume>',
help='Name or ID of the volume to unmanage.')
@utils.service_type('volumev3')
def do_unmanage(cs, args):
"""Stop managing a volume."""
volume = utils.find_volume(cs, args.volume)
cs.volumes.unmanage(volume.id)
@utils.arg('volume', metavar='<volume>',
help='Name or ID of the volume to promote. '
'The volume should have the replica volume created with '
'source-replica argument.')
@utils.service_type('volumev3')
def do_replication_promote(cs, args):
"""Promote a secondary volume to primary for a relationship."""
volume = utils.find_volume(cs, args.volume)
cs.volumes.promote(volume.id)
@utils.arg('volume', metavar='<volume>',
help='Name or ID of the volume to reenable replication. '
'The replication-status of the volume should be inactive.')
@utils.service_type('volumev3')
def do_replication_reenable(cs, args):
"""Sync the secondary volume with primary for a relationship."""
volume = utils.find_volume(cs, args.volume)
cs.volumes.reenable(volume.id)
@utils.arg('--all-tenants',
dest='all_tenants',
metavar='<0|1>',
nargs='?',
type=int,
const=1,
default=0,
help='Shows details for all tenants. Admin only.')
@utils.service_type('volumev3')
def do_consisgroup_list(cs, args):
"""Lists all consistencygroups."""
consistencygroups = cs.consistencygroups.list()
columns = ['ID', 'Status', 'Name']
utils.print_list(consistencygroups, columns)
@utils.service_type('volumev3')
@api_versions.wraps('3.13')
@utils.arg('--all-tenants',
dest='all_tenants',
metavar='<0|1>',
nargs='?',
type=int,
const=1,
default=0,
help='Shows details for all tenants. Admin only.')
def do_group_list(cs, args):
"""Lists all groups."""
groups = cs.groups.list()
columns = ['ID', 'Status', 'Name']
utils.print_list(groups, columns)
@utils.service_type('volumev3')
@utils.arg('consistencygroup',
metavar='<consistencygroup>',
help='Name or ID of a consistency group.')
def do_consisgroup_show(cs, args):
"""Shows details of a consistency group."""
info = dict()
consistencygroup = _find_consistencygroup(cs, args.consistencygroup)
info.update(consistencygroup._info)
info.pop('links', None)
utils.print_dict(info)
@utils.arg('group',
metavar='<group>',
help='Name or ID of a group.')
@utils.service_type('volumev3')
def do_group_show(cs, args):
"""Shows details of a group."""
info = dict()
group = _find_group(cs, args.group)
info.update(group._info)
info.pop('links', None)
utils.print_dict(info)
@utils.arg('volumetypes',
metavar='<volume-types>',
help='Volume types.')
@utils.arg('--name',
metavar='<name>',
help='Name of a consistency group.')
@utils.arg('--description',
metavar='<description>',
default=None,
help='Description of a consistency group. Default=None.')
@utils.arg('--availability-zone',
metavar='<availability-zone>',
default=None,
help='Availability zone for volume. Default=None.')
@utils.service_type('volumev3')
def do_consisgroup_create(cs, args):
"""Creates a consistency group."""
consistencygroup = cs.consistencygroups.create(
args.volumetypes,
args.name,
args.description,
availability_zone=args.availability_zone)
info = dict()
consistencygroup = cs.consistencygroups.get(consistencygroup.id)
info.update(consistencygroup._info)
info.pop('links', None)
utils.print_dict(info)
@utils.service_type('volumev3')
@api_versions.wraps('3.13')
@utils.arg('grouptype',
metavar='<group-type>',
help='Group type.')
@utils.arg('volumetypes',
metavar='<volume-types>',
help='Comma-separated list of volume types.')
@utils.arg('--name',
metavar='<name>',
help='Name of a group.')
@utils.arg('--description',
metavar='<description>',
default=None,
help='Description of a group. Default=None.')
@utils.arg('--availability-zone',
metavar='<availability-zone>',
default=None,
help='Availability zone for group. Default=None.')
def do_group_create(cs, args):
"""Creates a group."""
group = cs.groups.create(
args.grouptype,
args.volumetypes,
args.name,
args.description,
availability_zone=args.availability_zone)
info = dict()
group = cs.groups.get(group.id)
info.update(group._info)
info.pop('links', None)
utils.print_dict(info)
@utils.arg('--cgsnapshot',
metavar='<cgsnapshot>',
help='Name or ID of a cgsnapshot. Default=None.')
@utils.arg('--source-cg',
metavar='<source-cg>',
help='Name or ID of a source CG. Default=None.')
@utils.arg('--name',
metavar='<name>',
help='Name of a consistency group. Default=None.')
@utils.arg('--description',
metavar='<description>',
help='Description of a consistency group. Default=None.')
@utils.service_type('volumev3')
def do_consisgroup_create_from_src(cs, args):
"""Creates a consistency group from a cgsnapshot or a source CG."""
if not args.cgsnapshot and not args.source_cg:
msg = ('Cannot create consistency group because neither '
'cgsnapshot nor source CG is provided.')
raise exceptions.ClientException(code=1, message=msg)
if args.cgsnapshot and args.source_cg:
msg = ('Cannot create consistency group because both '
'cgsnapshot and source CG are provided.')
raise exceptions.ClientException(code=1, message=msg)
cgsnapshot = None
if args.cgsnapshot:
cgsnapshot = _find_cgsnapshot(cs, args.cgsnapshot)
source_cg = None
if args.source_cg:
source_cg = _find_consistencygroup(cs, args.source_cg)
info = cs.consistencygroups.create_from_src(
cgsnapshot.id if cgsnapshot else None,
source_cg.id if source_cg else None,
args.name,
args.description)
info.pop('links', None)
utils.print_dict(info)
@utils.service_type('volumev3')
@api_versions.wraps('3.14')
@utils.arg('--group-snapshot',
metavar='<group-snapshot>',
help='Name or ID of a group snapshot. Default=None.')
@utils.arg('--source-group',
metavar='<source-group>',
help='Name or ID of a source group. Default=None.')
@utils.arg('--name',
metavar='<name>',
help='Name of a group. Default=None.')
@utils.arg('--description',
metavar='<description>',
help='Description of a group. Default=None.')
def do_group_create_from_src(cs, args):
"""Creates a group from a group snapshot or a source group."""
if not args.group_snapshot and not args.source_group:
msg = ('Cannot create group because neither '
'group snapshot nor source group is provided.')
raise exceptions.ClientException(code=1, message=msg)
if args.group_snapshot and args.source_group:
msg = ('Cannot create group because both '
'group snapshot and source group are provided.')
raise exceptions.ClientException(code=1, message=msg)
group_snapshot = None
if args.group_snapshot:
group_snapshot = _find_group_snapshot(cs, args.group_snapshot)
source_group = None
if args.source_group:
source_group = _find_group(cs, args.source_group)
info = cs.groups.create_from_src(
group_snapshot.id if group_snapshot else None,
source_group.id if source_group else None,
args.name,
args.description)
info.pop('links', None)
utils.print_dict(info)
@utils.arg('consistencygroup',
metavar='<consistencygroup>', nargs='+',
help='Name or ID of one or more consistency groups '
'to be deleted.')
@utils.arg('--force',
action='store_true',
default=False,
help='Allows or disallows consistency groups '
'to be deleted. If the consistency group is empty, '
'it can be deleted without the force flag. '
'If the consistency group is not empty, the force '
'flag is required for it to be deleted.')
@utils.service_type('volumev3')
def do_consisgroup_delete(cs, args):
"""Removes one or more consistency groups."""
failure_count = 0
for consistencygroup in args.consistencygroup:
try:
_find_consistencygroup(cs, consistencygroup).delete(args.force)
except Exception as e:
failure_count += 1
print("Delete for consistency group %s failed: %s" %
(consistencygroup, e))
if failure_count == len(args.consistencygroup):
raise exceptions.CommandError("Unable to delete any of the specified "
"consistency groups.")
@utils.service_type('volumev3')
@api_versions.wraps('3.13')
@utils.arg('group',
metavar='<group>', nargs='+',
help='Name or ID of one or more groups '
'to be deleted.')
@utils.arg('--delete-volumes',
action='store_true',
default=False,
help='Allows or disallows groups to be deleted '
'if they are not empty. If the group is empty, '
'it can be deleted without the delete-volumes flag. '
'If the group is not empty, the delete-volumes '
'flag is required for it to be deleted. If True, '
'all volumes in the group will also be deleted.')
def do_group_delete(cs, args):
"""Removes one or more groups."""
failure_count = 0
for group in args.group:
try:
_find_group(cs, group).delete(args.delete_volumes)
except Exception as e:
failure_count += 1
print("Delete for group %s failed: %s" %
(group, e))
if failure_count == len(args.group):
raise exceptions.CommandError("Unable to delete any of the specified "
"groups.")
@utils.arg('consistencygroup',
metavar='<consistencygroup>',
help='Name or ID of a consistency group.')
@utils.arg('--name', metavar='<name>',
help='New name for consistency group. Default=None.')
@utils.arg('--description', metavar='<description>',
help='New description for consistency group. Default=None.')
@utils.arg('--add-volumes',
metavar='<uuid1,uuid2,......>',
help='UUID of one or more volumes '
'to be added to the consistency group, '
'separated by commas. Default=None.')
@utils.arg('--remove-volumes',
metavar='<uuid3,uuid4,......>',
help='UUID of one or more volumes '
'to be removed from the consistency group, '
'separated by commas. Default=None.')
@utils.service_type('volumev3')
def do_consisgroup_update(cs, args):
"""Updates a consistencygroup."""
kwargs = {}
if args.name is not None:
kwargs['name'] = args.name
if args.description is not None:
kwargs['description'] = args.description
if args.add_volumes is not None:
kwargs['add_volumes'] = args.add_volumes
if args.remove_volumes is not None:
kwargs['remove_volumes'] = args.remove_volumes
if not kwargs:
msg = ('At least one of the following args must be supplied: '
'name, description, add-volumes, remove-volumes.')
raise exceptions.ClientException(code=1, message=msg)
_find_consistencygroup(cs, args.consistencygroup).update(**kwargs)
@utils.service_type('volumev3')
@api_versions.wraps('3.13')
@utils.arg('group',
metavar='<group>',
help='Name or ID of a group.')
@utils.arg('--name', metavar='<name>',
help='New name for group. Default=None.')
@utils.arg('--description', metavar='<description>',
help='New description for group. Default=None.')
@utils.arg('--add-volumes',
metavar='<uuid1,uuid2,......>',
help='UUID of one or more volumes '
'to be added to the group, '
'separated by commas. Default=None.')
@utils.arg('--remove-volumes',
metavar='<uuid3,uuid4,......>',
help='UUID of one or more volumes '
'to be removed from the group, '
'separated by commas. Default=None.')
def do_group_update(cs, args):
"""Updates a group."""
kwargs = {}
if args.name is not None:
kwargs['name'] = args.name
if args.description is not None:
kwargs['description'] = args.description
if args.add_volumes is not None:
kwargs['add_volumes'] = args.add_volumes
if args.remove_volumes is not None:
kwargs['remove_volumes'] = args.remove_volumes
if not kwargs:
msg = ('At least one of the following args must be supplied: '
'name, description, add-volumes, remove-volumes.')
raise exceptions.ClientException(code=1, message=msg)
_find_group(cs, args.group).update(**kwargs)
@utils.arg('--all-tenants',
dest='all_tenants',
metavar='<0|1>',
nargs='?',
type=int,
const=1,
default=0,
help='Shows details for all tenants. Admin only.')
@utils.arg('--status',
metavar='<status>',
default=None,
help='Filters results by a status. Default=None.')
@utils.arg('--consistencygroup-id',
metavar='<consistencygroup_id>',
default=None,
help='Filters results by a consistency group ID. Default=None.')
@utils.service_type('volumev3')
def do_cgsnapshot_list(cs, args):
"""Lists all cgsnapshots."""
all_tenants = int(os.environ.get("ALL_TENANTS", args.all_tenants))
search_opts = {
'all_tenants': all_tenants,
'status': args.status,
'consistencygroup_id': args.consistencygroup_id,
}
cgsnapshots = cs.cgsnapshots.list(search_opts=search_opts)
columns = ['ID', 'Status', 'Name']
utils.print_list(cgsnapshots, columns)
@utils.service_type('volumev3')
@api_versions.wraps('3.14')
@utils.arg('--all-tenants',
dest='all_tenants',
metavar='<0|1>',
nargs='?',
type=int,
const=1,
default=0,
help='Shows details for all tenants. Admin only.')
@utils.arg('--status',
metavar='<status>',
default=None,
help='Filters results by a status. Default=None.')
@utils.arg('--group-id',
metavar='<group_id>',
default=None,
help='Filters results by a group ID. Default=None.')
def do_group_snapshot_list(cs, args):
"""Lists all group snapshots."""
all_tenants = int(os.environ.get("ALL_TENANTS", args.all_tenants))
search_opts = {
'all_tenants': all_tenants,
'status': args.status,
'group_id': args.group_id,
}
group_snapshots = cs.group_snapshots.list(search_opts=search_opts)
columns = ['ID', 'Status', 'Name']
utils.print_list(group_snapshots, columns)
@utils.arg('cgsnapshot',
metavar='<cgsnapshot>',
help='Name or ID of cgsnapshot.')
@utils.service_type('volumev3')
def do_cgsnapshot_show(cs, args):
"""Shows cgsnapshot details."""
info = dict()
cgsnapshot = _find_cgsnapshot(cs, args.cgsnapshot)
info.update(cgsnapshot._info)
info.pop('links', None)
utils.print_dict(info)
@utils.service_type('volumev3')
@api_versions.wraps('3.14')
@utils.arg('group_snapshot',
metavar='<group_snapshot>',
help='Name or ID of group snapshot.')
def do_group_snapshot_show(cs, args):
"""Shows group snapshot details."""
info = dict()
group_snapshot = _find_group_snapshot(cs, args.group_snapshot)
info.update(group_snapshot._info)
info.pop('links', None)
utils.print_dict(info)
@utils.arg('consistencygroup',
metavar='<consistencygroup>',
help='Name or ID of a consistency group.')
@utils.arg('--name',
metavar='<name>',
default=None,
help='Cgsnapshot name. Default=None.')
@utils.arg('--description',
metavar='<description>',
default=None,
help='Cgsnapshot description. Default=None.')
@utils.service_type('volumev3')
def do_cgsnapshot_create(cs, args):
"""Creates a cgsnapshot."""
consistencygroup = _find_consistencygroup(cs, args.consistencygroup)
cgsnapshot = cs.cgsnapshots.create(
consistencygroup.id,
args.name,
args.description)
info = dict()
cgsnapshot = cs.cgsnapshots.get(cgsnapshot.id)
info.update(cgsnapshot._info)
info.pop('links', None)
utils.print_dict(info)
@utils.service_type('volumev3')
@api_versions.wraps('3.14')
@utils.arg('group',
metavar='<group>',
help='Name or ID of a group.')
@utils.arg('--name',
metavar='<name>',
default=None,
help='Group snapshot name. Default=None.')
@utils.arg('--description',
metavar='<description>',
default=None,
help='Group snapshot description. Default=None.')
def do_group_snapshot_create(cs, args):
"""Creates a group snapshot."""
group = _find_group(cs, args.group)
group_snapshot = cs.group_snapshots.create(
group.id,
args.name,
args.description)
info = dict()
group_snapshot = cs.group_snapshots.get(group_snapshot.id)
info.update(group_snapshot._info)
info.pop('links', None)
utils.print_dict(info)
@utils.arg('cgsnapshot',
metavar='<cgsnapshot>', nargs='+',
help='Name or ID of one or more cgsnapshots to be deleted.')
@utils.service_type('volumev3')
def do_cgsnapshot_delete(cs, args):
"""Removes one or more cgsnapshots."""
failure_count = 0
for cgsnapshot in args.cgsnapshot:
try:
_find_cgsnapshot(cs, cgsnapshot).delete()
except Exception as e:
failure_count += 1
print("Delete for cgsnapshot %s failed: %s" % (cgsnapshot, e))
if failure_count == len(args.cgsnapshot):
raise exceptions.CommandError("Unable to delete any of the specified "
"cgsnapshots.")
@utils.service_type('volumev3')
@api_versions.wraps('3.14')
@utils.arg('group_snapshot',
metavar='<group_snapshot>', nargs='+',
help='Name or ID of one or more group snapshots to be deleted.')
def do_group_snapshot_delete(cs, args):
"""Removes one or more group snapshots."""
failure_count = 0
for group_snapshot in args.group_snapshot:
try:
_find_group_snapshot(cs, group_snapshot).delete()
except Exception as e:
failure_count += 1
print("Delete for group snapshot %s failed: %s" %
(group_snapshot, e))
if failure_count == len(args.group_snapshot):
raise exceptions.CommandError("Unable to delete any of the specified "
"group snapshots.")
@utils.arg('--detail',
action='store_true',
help='Show detailed information about pools.')
@utils.service_type('volumev3')
def do_get_pools(cs, args):
"""Show pool information for backends. Admin only."""
pools = cs.volumes.get_pools(args.detail)
infos = dict()
infos.update(pools._info)
for info in infos['pools']:
backend = dict()
backend['name'] = info['name']
if args.detail:
backend.update(info['capabilities'])
utils.print_dict(backend)
@utils.arg('host',
metavar='<host>',
help='Cinder host to show backend volume stats and properties; '
'takes the form: host@backend-name')
@utils.service_type('volumev3')
def do_get_capabilities(cs, args):
"""Show backend volume stats and properties. Admin only."""
capabilities = cs.capabilities.get(args.host)
infos = dict()
infos.update(capabilities._info)
prop = infos.pop('properties', None)
utils.print_dict(infos, "Volume stats")
utils.print_dict(prop, "Backend properties")
@utils.arg('volume',
metavar='<volume>',
help='Cinder volume already exists in volume backend')
@utils.arg('identifier',
metavar='<identifier>',
help='Name or other Identifier for existing snapshot')
@utils.arg('--id-type',
metavar='<id-type>',
default='source-name',
help='Type of backend device identifier provided, '
'typically source-name or source-id (Default=source-name)')
@utils.arg('--name',
metavar='<name>',
help='Snapshot name (Default=None)')
@utils.arg('--description',
metavar='<description>',
help='Snapshot description (Default=None)')
@utils.arg('--metadata',
type=str,
nargs='*',
metavar='<key=value>',
help='Metadata key=value pairs (Default=None)')
@utils.service_type('volumev3')
def do_snapshot_manage(cs, args):
"""Manage an existing snapshot."""
snapshot_metadata = None
if args.metadata is not None:
snapshot_metadata = _extract_metadata(args)
# Build a dictionary of key/value pairs to pass to the API.
ref_dict = {args.id_type: args.identifier}
if hasattr(args, 'source_name') and args.source_name is not None:
ref_dict['source-name'] = args.source_name
if hasattr(args, 'source_id') and args.source_id is not None:
ref_dict['source-id'] = args.source_id
volume = utils.find_volume(cs, args.volume)
snapshot = cs.volume_snapshots.manage(volume_id=volume.id,
ref=ref_dict,
name=args.name,
description=args.description,
metadata=snapshot_metadata)
info = {}
snapshot = cs.volume_snapshots.get(snapshot.id)
info.update(snapshot._info)
info.pop('links', None)
utils.print_dict(info)
@utils.service_type('volumev3')
@api_versions.wraps('3.8')
@utils.arg('host',
metavar='<host>',
help='Cinder host on which to list manageable snapshots; '
'takes the form: host@backend-name#pool')
@utils.arg('--detailed',
metavar='<detailed>',
default=True,
help='Returned detailed information (default true).')
@utils.arg('--marker',
metavar='<marker>',
default=None,
help='Begin returning volumes that appear later in the volume '
'list than that represented by this volume id. '
'Default=None.')
@utils.arg('--limit',
metavar='<limit>',
default=None,
help='Maximum number of volumes to return. Default=None.')
@utils.arg('--offset',
metavar='<offset>',
default=None,
help='Number of volumes to skip after marker. Default=None.')
@utils.arg('--sort',
metavar='<key>[:<direction>]',
default=None,
help=(('Comma-separated list of sort keys and directions in the '
'form of <key>[:<asc|desc>]. '
'Valid keys: %s. '
'Default=None.') % ', '.join(base.SORT_KEY_VALUES)))
def do_snapshot_manageable_list(cs, args):
"""Lists all manageable snapshots."""
detailed = strutils.bool_from_string(args.detailed)
snapshots = cs.volume_snapshots.list_manageable(host=args.host,
detailed=detailed,
marker=args.marker,
limit=args.limit,
offset=args.offset,
sort=args.sort)
columns = ['reference', 'size', 'safe_to_manage', 'source_reference']
if detailed:
columns.extend(['reason_not_safe', 'cinder_id', 'extra_info'])
utils.print_list(snapshots, columns, sortby_index=None)
@utils.arg('snapshot', metavar='<snapshot>',
help='Name or ID of the snapshot to unmanage.')
@utils.service_type('volumev3')
def do_snapshot_unmanage(cs, args):
"""Stop managing a snapshot."""
snapshot = _find_volume_snapshot(cs, args.snapshot)
cs.volume_snapshots.unmanage(snapshot.id)
@utils.arg('host', metavar='<hostname>', help='Host name.')
@utils.service_type('volumev3')
def do_freeze_host(cs, args):
"""Freeze and disable the specified cinder-volume host."""
cs.services.freeze_host(args.host)
@utils.arg('host', metavar='<hostname>', help='Host name.')
@utils.service_type('volumev3')
def do_thaw_host(cs, args):
"""Thaw and enable the specified cinder-volume host."""
cs.services.thaw_host(args.host)
@utils.service_type('volumev3')
@utils.arg('host', metavar='<hostname>', help='Host name.')
@utils.arg('--backend_id',
metavar='<backend-id>',
help='ID of backend to failover to (Default=None)')
def do_failover_host(cs, args):
"""Failover a replicating cinder-volume host."""
cs.services.failover_host(args.host, args.backend_id)
@utils.service_type('volumev3')
@api_versions.wraps("3.0")
def do_api_version(cs, args):
"""Display the server API version information."""
columns = ['ID', 'Status', 'Version', 'Min_version']
response = cs.services.server_api_version()
utils.print_list(response, columns)
@utils.service_type('volumev3')
@api_versions.wraps("3.3")
@utils.arg('--marker',
metavar='<marker>',
default=None,
start_version='3.5',
help='Begin returning message that appear later in the message '
'list than that represented by this id. '
'Default=None.')
@utils.arg('--limit',
metavar='<limit>',
default=None,
start_version='3.5',
help='Maximum number of messages to return. Default=None.')
@utils.arg('--sort',
metavar='<key>[:<direction>]',
default=None,
start_version='3.5',
help=(('Comma-separated list of sort keys and directions in the '
'form of <key>[:<asc|desc>]. '
'Valid keys: %s. '
'Default=None.') % ', '.join(base.SORT_KEY_VALUES)))
@utils.arg('--resource_uuid',
metavar='<resource_uuid>',
default=None,
help='Filters results by a resource uuid. Default=None.')
@utils.arg('--resource_type',
metavar='<type>',
default=None,
help='Filters results by a resource type. Default=None.')
@utils.arg('--event_id',
metavar='<id>',
default=None,
help='Filters results by event id. Default=None.')
@utils.arg('--request_id',
metavar='<request_id>',
default=None,
help='Filters results by request id. Default=None.')
@utils.arg('--level',
metavar='<level>',
default=None,
help='Filters results by the message level. Default=None.')
def do_message_list(cs, args):
"""Lists all messages."""
search_opts = {
'resource_uuid': args.resource_uuid,
'event_id': args.event_id,
'request_id': args.request_id,
}
if args.resource_type:
search_opts['resource_type'] = args.resource_type.upper()
if args.level:
search_opts['message_level'] = args.level.upper()
marker = args.marker if hasattr(args, 'marker') else None
limit = args.limit if hasattr(args, 'limit') else None
sort = args.sort if hasattr(args, 'sort') else None
messages = cs.messages.list(search_opts=search_opts,
marker=marker,
limit=limit,
sort=sort)
columns = ['ID', 'Resource Type', 'Resource UUID', 'Event ID',
'User Message']
if sort:
sortby_index = None
else:
sortby_index = 0
utils.print_list(messages, columns, sortby_index=sortby_index)
@utils.service_type('volumev3')
@api_versions.wraps("3.3")
@utils.arg('message',
metavar='<message>',
help='ID of message.')
def do_message_show(cs, args):
"""Shows message details."""
info = dict()
message = _find_message(cs, args.message)
info.update(message._info)
info.pop('links', None)
utils.print_dict(info)
@utils.service_type('volumev3')
@api_versions.wraps("3.3")
@utils.arg('message',
metavar='<message>', nargs='+',
help='ID of one or more message to be deleted.')
def do_message_delete(cs, args):
"""Removes one or more messages."""
failure_count = 0
for message in args.message:
try:
_find_message(cs, message).delete()
except Exception as e:
failure_count += 1
print("Delete for message %s failed: %s" % (message, e))
if failure_count == len(args.message):
raise exceptions.CommandError("Unable to delete any of the specified "
"messages.")
|