1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593
|
# Licensed under the Apache License, Version 3.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.
import base64
import collections
import copy
import datetime
import functools
import hashlib
import ipaddress
import iso8601
import json
import jsonpatch
import operator
import os_client_config.defaults
import six
import threading
import time
import warnings
import dogpile.cache
import munch
import requestsexceptions
from six.moves import urllib
import keystoneauth1.exceptions
import keystoneauth1.session
import os
import os_client_config
import shade
from shade import _adapter
from shade import exc
from shade._heat import event_utils
from shade._heat import template_utils
from shade import _log
from shade import _legacy_clients
from shade import _normalize
from shade import meta
from shade import task_manager
from shade import _utils
OBJECT_MD5_KEY = 'x-object-meta-x-shade-md5'
OBJECT_SHA256_KEY = 'x-object-meta-x-shade-sha256'
OBJECT_AUTOCREATE_KEY = 'x-object-meta-x-shade-autocreated'
OBJECT_AUTOCREATE_CONTAINER = 'images'
IMAGE_MD5_KEY = 'owner_specified.shade.md5'
IMAGE_SHA256_KEY = 'owner_specified.shade.sha256'
IMAGE_OBJECT_KEY = 'owner_specified.shade.object'
# Rackspace returns this for intermittent import errors
IMAGE_ERROR_396 = "Image cannot be imported. Error code: '396'"
DEFAULT_OBJECT_SEGMENT_SIZE = 1073741824 # 1GB
# This halves the current default for Swift
DEFAULT_MAX_FILE_SIZE = (5 * 1024 * 1024 * 1024 + 2) / 2
DEFAULT_SERVER_AGE = 5
DEFAULT_PORT_AGE = 5
DEFAULT_FLOAT_AGE = 5
_OCC_DOC_URL = "https://docs.openstack.org/os-client-config/latest/"
OBJECT_CONTAINER_ACLS = {
'public': '.r:*,.rlistings',
'private': '',
}
def _no_pending_volumes(volumes):
"""If there are any volumes not in a steady state, don't cache"""
for volume in volumes:
if volume['status'] not in ('available', 'error', 'in-use'):
return False
return True
def _no_pending_images(images):
"""If there are any images not in a steady state, don't cache"""
for image in images:
if image.status not in ('active', 'deleted', 'killed'):
return False
return True
def _no_pending_stacks(stacks):
"""If there are any stacks not in a steady state, don't cache"""
for stack in stacks:
status = stack['stack_status']
if '_COMPLETE' not in status and '_FAILED' not in status:
return False
return True
class OpenStackCloud(
_normalize.Normalizer,
_legacy_clients.LegacyClientFactoryMixin):
"""Represent a connection to an OpenStack Cloud.
OpenStackCloud is the entry point for all cloud operations, regardless
of which OpenStack service those operations may ultimately come from.
The operations on an OpenStackCloud are resource oriented rather than
REST API operation oriented. For instance, one will request a Floating IP
and that Floating IP will be actualized either via neutron or via nova
depending on how this particular cloud has decided to arrange itself.
:param TaskManager manager: Optional task manager to use for running
OpenStack API tasks. Unless you're doing
rate limiting client side, you almost
certainly don't need this. (optional)
:param bool log_inner_exceptions: Ignored. Exists for backwards compat.
:param bool strict: Only return documented attributes for each resource
as per the shade Data Model contract. (Default False)
:param app_name: Name of the application to be appended to the user-agent
string. Optional, defaults to None.
:param app_version: Version of the application to be appended to the
user-agent string. Optional, defaults to None.
:param CloudConfig cloud_config: Cloud config object from os-client-config
In the future, this will be the only way
to pass in cloud configuration, but is
being phased in currently.
"""
def __init__(
self,
cloud_config=None,
manager=None, log_inner_exceptions=False,
strict=False,
app_name=None,
app_version=None,
use_direct_get=False,
**kwargs):
self.log = _log.setup_logging('shade')
if not cloud_config:
config = os_client_config.OpenStackConfig(
app_name=app_name, app_version=app_version)
cloud_config = config.get_one_cloud(**kwargs)
self.name = cloud_config.name
self.auth = cloud_config.get_auth_args()
self.region_name = cloud_config.region_name
self.default_interface = cloud_config.get_interface()
self.private = cloud_config.config.get('private', False)
self.api_timeout = cloud_config.config['api_timeout']
self.image_api_use_tasks = cloud_config.config['image_api_use_tasks']
self.secgroup_source = cloud_config.config['secgroup_source']
self.force_ipv4 = cloud_config.force_ipv4
self.strict_mode = strict
# TODO(mordred) When os-client-config adds a "get_client_settings()"
# method to CloudConfig - remove this.
self._extra_config = cloud_config._openstack_config.get_extra_config(
'shade', {
'get_flavor_extra_specs': True,
})
if manager is not None:
self.manager = manager
else:
self.manager = task_manager.TaskManager(
name=':'.join([self.name, self.region_name]), client=self)
self._external_ipv4_names = cloud_config.get_external_ipv4_networks()
self._internal_ipv4_names = cloud_config.get_internal_ipv4_networks()
self._external_ipv6_names = cloud_config.get_external_ipv6_networks()
self._internal_ipv6_names = cloud_config.get_internal_ipv6_networks()
self._nat_destination = cloud_config.get_nat_destination()
self._default_network = cloud_config.get_default_network()
self._floating_ip_source = cloud_config.config.get(
'floating_ip_source')
if self._floating_ip_source:
if self._floating_ip_source.lower() == 'none':
self._floating_ip_source = None
else:
self._floating_ip_source = self._floating_ip_source.lower()
self._use_external_network = cloud_config.config.get(
'use_external_network', True)
self._use_internal_network = cloud_config.config.get(
'use_internal_network', True)
# Work around older TaskManager objects that don't have submit_task
if not hasattr(self.manager, 'submit_task'):
self.manager.submit_task = self.manager.submitTask
(self.verify, self.cert) = cloud_config.get_requests_verify_args()
# Turn off urllib3 warnings about insecure certs if we have
# explicitly configured requests to tell it we do not want
# cert verification
if not self.verify:
self.log.debug(
"Turning off Insecure SSL warnings since verify=False")
category = requestsexceptions.InsecureRequestWarning
if category:
# InsecureRequestWarning references a Warning class or is None
warnings.filterwarnings('ignore', category=category)
self._disable_warnings = {}
self.use_direct_get = use_direct_get
self._servers = None
self._servers_time = 0
self._servers_lock = threading.Lock()
self._ports = None
self._ports_time = 0
self._ports_lock = threading.Lock()
self._floating_ips = None
self._floating_ips_time = 0
self._floating_ips_lock = threading.Lock()
self._floating_network_by_router = None
self._floating_network_by_router_run = False
self._floating_network_by_router_lock = threading.Lock()
self._networks_lock = threading.Lock()
self._reset_network_caches()
cache_expiration_time = int(cloud_config.get_cache_expiration_time())
cache_class = cloud_config.get_cache_class()
cache_arguments = cloud_config.get_cache_arguments()
self._resource_caches = {}
if cache_class != 'dogpile.cache.null':
self.cache_enabled = True
self._cache = self._make_cache(
cache_class, cache_expiration_time, cache_arguments)
expirations = cloud_config.get_cache_expiration()
for expire_key in expirations.keys():
# Only build caches for things we have list operations for
if getattr(
self, 'list_{0}'.format(expire_key), None):
self._resource_caches[expire_key] = self._make_cache(
cache_class, expirations[expire_key], cache_arguments)
self._SERVER_AGE = DEFAULT_SERVER_AGE
self._PORT_AGE = DEFAULT_PORT_AGE
self._FLOAT_AGE = DEFAULT_FLOAT_AGE
else:
self.cache_enabled = False
def _fake_invalidate(unused):
pass
class _FakeCache(object):
def invalidate(self):
pass
# Don't cache list_servers if we're not caching things.
# Replace this with a more specific cache configuration
# soon.
self._SERVER_AGE = 0
self._PORT_AGE = 0
self._FLOAT_AGE = 0
self._cache = _FakeCache()
# Undecorate cache decorated methods. Otherwise the call stacks
# wind up being stupidly long and hard to debug
for method in _utils._decorated_methods:
meth_obj = getattr(self, method, None)
if not meth_obj:
continue
if (hasattr(meth_obj, 'invalidate')
and hasattr(meth_obj, 'func')):
new_func = functools.partial(meth_obj.func, self)
new_func.invalidate = _fake_invalidate
setattr(self, method, new_func)
# If server expiration time is set explicitly, use that. Otherwise
# fall back to whatever it was before
self._SERVER_AGE = cloud_config.get_cache_resource_expiration(
'server', self._SERVER_AGE)
self._PORT_AGE = cloud_config.get_cache_resource_expiration(
'port', self._PORT_AGE)
self._FLOAT_AGE = cloud_config.get_cache_resource_expiration(
'floating_ip', self._FLOAT_AGE)
self._container_cache = dict()
self._file_hash_cache = dict()
self._keystone_session = None
self._legacy_clients = {}
self._raw_clients = {}
self._local_ipv6 = (
_utils.localhost_supports_ipv6() if not self.force_ipv4 else False)
self.cloud_config = cloud_config
def connect_as(self, **kwargs):
"""Make a new OpenStackCloud object with new auth context.
Take the existing settings from the current cloud and construct a new
OpenStackCloud object with some of the auth settings overridden. This
is useful for getting an object to perform tasks with as another user,
or in the context of a different project.
.. code-block:: python
cloud = shade.openstack_cloud(cloud='example')
# Work normally
servers = cloud.list_servers()
cloud2 = cloud.connect_as(username='different-user', password='')
# Work as different-user
servers = cloud2.list_servers()
:param kwargs: keyword arguments can contain anything that would
normally go in an auth dict. They will override the same
settings from the parent cloud as appropriate. Entries
that do not want to be overridden can be ommitted.
"""
if self.cloud_config._openstack_config:
config = self.cloud_config._openstack_config
else:
config = os_client_config.OpenStackConfig(
app_name=self.cloud_config._app_name,
app_version=self.cloud_config._app_version,
load_yaml_config=False)
params = copy.deepcopy(self.cloud_config.config)
# Remove profile from current cloud so that overridding works
params.pop('profile', None)
# Utility function to help with the stripping below.
def pop_keys(params, auth, name_key, id_key):
if name_key in auth or id_key in auth:
params['auth'].pop(name_key, None)
params['auth'].pop(id_key, None)
# If there are user, project or domain settings in the incoming auth
# dict, strip out both id and name so that a user can say:
# cloud.connect_as(project_name='foo')
# and have that work with clouds that have a project_id set in their
# config.
for prefix in ('user', 'project'):
if prefix == 'user':
name_key = 'username'
else:
name_key = 'project_name'
id_key = '{prefix}_id'.format(prefix=prefix)
pop_keys(params, kwargs, name_key, id_key)
id_key = '{prefix}_domain_id'.format(prefix=prefix)
name_key = '{prefix}_domain_name'.format(prefix=prefix)
pop_keys(params, kwargs, name_key, id_key)
for key, value in kwargs.items():
params['auth'][key] = value
# Closure to pass to OpenStackConfig to ensure the new cloud shares
# the Session with the current cloud. This will ensure that version
# discovery cache will be re-used.
def session_constructor(*args, **kwargs):
# We need to pass our current keystone session to the Session
# Constructor, otherwise the new auth plugin doesn't get used.
return keystoneauth1.session.Session(session=self.keystone_session)
cloud_config = config.get_one_cloud(
session_constructor=session_constructor,
**params)
# Override the cloud name so that logging/location work right
if hasattr(cloud_config, '_name'):
cloud_config._name = self.name
else:
cloud_config.name = self.name
cloud_config.config['profile'] = self.name
# Use self.__class__ so that OperatorCloud will return an OperatorCloud
# instance. This should also help passthrough from sdk work better when
# we have it.
return self.__class__(cloud_config=cloud_config)
def connect_as_project(self, project):
"""Make a new OpenStackCloud object with a new project.
Take the existing settings from the current cloud and construct a new
OpenStackCloud object with the project settings overridden. This
is useful for getting an object to perform tasks with as another user,
or in the context of a different project.
.. code-block:: python
cloud = shade.openstack_cloud(cloud='example')
# Work normally
servers = cloud.list_servers()
cloud2 = cloud.connect_as_project('different-project')
# Work in different-project
servers = cloud2.list_servers()
:param project: Either a project name or a project dict as returned by
`list_projects`.
"""
auth = {}
if isinstance(project, dict):
auth['project_id'] = project.get('id')
auth['project_name'] = project.get('name')
if project.get('domain_id'):
auth['project_domain_id'] = project['domain_id']
else:
auth['project_name'] = project
return self.connect_as(**auth)
def _make_cache(self, cache_class, expiration_time, arguments):
return dogpile.cache.make_region(
function_key_generator=self._make_cache_key
).configure(
cache_class,
expiration_time=expiration_time,
arguments=arguments)
def _make_cache_key(self, namespace, fn):
fname = fn.__name__
if namespace is None:
name_key = self.name
else:
name_key = '%s:%s' % (self.name, namespace)
def generate_key(*args, **kwargs):
arg_key = ','.join(args)
kw_keys = sorted(kwargs.keys())
kwargs_key = ','.join(
['%s:%s' % (k, kwargs[k]) for k in kw_keys if k != 'cache'])
ans = "_".join(
[str(name_key), fname, arg_key, kwargs_key])
return ans
return generate_key
def _get_cache(self, resource_name):
if resource_name and resource_name in self._resource_caches:
return self._resource_caches[resource_name]
else:
return self._cache
def _get_client(
self, service_key, client_class=None, interface_key=None,
pass_version_arg=True, **kwargs):
try:
client = self.cloud_config.get_legacy_client(
service_key=service_key, client_class=client_class,
interface_key=interface_key, pass_version_arg=pass_version_arg,
**kwargs)
except Exception:
self.log.debug(
"Couldn't construct %(service)s object",
{'service': service_key}, exc_info=True)
raise
if client is None:
raise exc.OpenStackCloudException(
"Failed to instantiate {service} client."
" This could mean that your credentials are wrong.".format(
service=service_key))
return client
def _get_major_version_id(self, version):
if isinstance(version, int):
return version
elif isinstance(version, six.string_types + (tuple,)):
return int(version[0])
return version
def _get_versioned_client(
self, service_type, min_version=None, max_version=None):
config_version = self.cloud_config.get_api_version(service_type)
config_major = self._get_major_version_id(config_version)
max_major = self._get_major_version_id(max_version)
min_major = self._get_major_version_id(min_version)
# NOTE(mordred) The shade logic for versions is slightly different
# than the ksa Adapter constructor logic. shade knows the versions
# it knows, and uses them when it detects them. However, if a user
# requests a version, and it's not found, and a different one shade
# does know about it found, that's a warning in shade.
if config_version:
if min_major and config_major < min_major:
raise exc.OpenStackCloudException(
"Version {config_version} requested for {service_type}"
" but shade understands a minimum of {min_version}".format(
config_version=config_version,
service_type=service_type,
min_version=min_version))
elif max_major and config_major > max_major:
raise exc.OpenStackCloudException(
"Version {config_version} requested for {service_type}"
" but shade understands a maximum of {max_version}".format(
config_version=config_version,
service_type=service_type,
max_version=max_version))
request_min_version = config_version
request_max_version = '{version}.latest'.format(
version=config_major)
adapter = _adapter.ShadeAdapter(
session=self.keystone_session,
manager=self.manager,
service_type=self.cloud_config.get_service_type(service_type),
service_name=self.cloud_config.get_service_name(service_type),
interface=self.cloud_config.get_interface(service_type),
endpoint_override=self.cloud_config.get_endpoint(service_type),
region_name=self.cloud_config.region,
min_version=request_min_version,
max_version=request_max_version,
shade_logger=self.log)
if adapter.get_endpoint():
return adapter
adapter = _adapter.ShadeAdapter(
session=self.keystone_session,
manager=self.manager,
service_type=self.cloud_config.get_service_type(service_type),
service_name=self.cloud_config.get_service_name(service_type),
interface=self.cloud_config.get_interface(service_type),
endpoint_override=self.cloud_config.get_endpoint(service_type),
region_name=self.cloud_config.region,
min_version=min_version,
max_version=max_version,
shade_logger=self.log)
# data.api_version can be None if no version was detected, such
# as with neutron
api_version = adapter.get_api_major_version(
endpoint_override=self.cloud_config.get_endpoint(service_type))
api_major = self._get_major_version_id(api_version)
# If we detect a different version that was configured, warn the user.
# shade still knows what to do - but if the user gave us an explicit
# version and we couldn't find it, they may want to investigate.
if api_version and (api_major != config_major):
warning_msg = (
'{service_type} is configured for {config_version}'
' but only {api_version} is available. shade is happy'
' with this version, but if you were trying to force an'
' override, that did not happen. You may want to check'
' your cloud, or remove the version specification from'
' your config.'.format(
service_type=service_type,
config_version=config_version,
api_version='.'.join([str(f) for f in api_version])))
self.log.debug(warning_msg)
warnings.warn(warning_msg)
return adapter
def _get_raw_client(
self, service_type, api_version=None, endpoint_override=None):
return _adapter.ShadeAdapter(
session=self.keystone_session,
manager=self.manager,
service_type=self.cloud_config.get_service_type(service_type),
service_name=self.cloud_config.get_service_name(service_type),
interface=self.cloud_config.get_interface(service_type),
endpoint_override=self.cloud_config.get_endpoint(
service_type) or endpoint_override,
region_name=self.cloud_config.region,
shade_logger=self.log)
def _is_client_version(self, client, version):
client_name = '_{client}_client'.format(client=client)
client = getattr(self, client_name)
return client._version_matches(version)
@property
def _application_catalog_client(self):
if 'application-catalog' not in self._raw_clients:
self._raw_clients['application-catalog'] = self._get_raw_client(
'application-catalog')
return self._raw_clients['application-catalog']
@property
def _baremetal_client(self):
if 'baremetal' not in self._raw_clients:
client = self._get_raw_client('baremetal')
# Do this to force version discovery. We need to do that, because
# the endpoint-override trick we do for neutron because
# ironicclient just appends a /v1 won't work and will break
# keystoneauth - because ironic's versioned discovery endpoint
# is non-compliant and doesn't return an actual version dict.
client = self._get_versioned_client(
'baremetal', min_version=1, max_version='1.latest')
self._raw_clients['baremetal'] = client
return self._raw_clients['baremetal']
@property
def _container_infra_client(self):
if 'container-infra' not in self._raw_clients:
self._raw_clients['container-infra'] = self._get_raw_client(
'container-infra')
return self._raw_clients['container-infra']
@property
def _compute_client(self):
# TODO(mordred) Deal with microversions
if 'compute' not in self._raw_clients:
self._raw_clients['compute'] = self._get_raw_client('compute')
return self._raw_clients['compute']
@property
def _database_client(self):
if 'database' not in self._raw_clients:
self._raw_clients['database'] = self._get_raw_client('database')
return self._raw_clients['database']
@property
def _dns_client(self):
if 'dns' not in self._raw_clients:
dns_client = self._get_versioned_client(
'dns', min_version=2, max_version='2.latest')
self._raw_clients['dns'] = dns_client
return self._raw_clients['dns']
@property
def _identity_client(self):
if 'identity' not in self._raw_clients:
self._raw_clients['identity'] = self._get_versioned_client(
'identity', min_version=2, max_version='3.latest')
return self._raw_clients['identity']
@property
def _raw_image_client(self):
if 'raw-image' not in self._raw_clients:
image_client = self._get_raw_client('image')
self._raw_clients['raw-image'] = image_client
return self._raw_clients['raw-image']
@property
def _image_client(self):
if 'image' not in self._raw_clients:
self._raw_clients['image'] = self._get_versioned_client(
'image', min_version=1, max_version='2.latest')
return self._raw_clients['image']
@property
def _network_client(self):
if 'network' not in self._raw_clients:
client = self._get_raw_client('network')
# TODO(mordred) I don't care if this is what neutronclient does,
# fix this.
# Don't bother with version discovery - there is only one version
# of neutron. This is what neutronclient does, fwiw.
endpoint = client.get_endpoint()
if not endpoint.rstrip().rsplit('/')[1] == 'v2.0':
if not endpoint.endswith('/'):
endpoint += '/'
endpoint = urllib.parse.urljoin(
endpoint, 'v2.0')
client.endpoint_override = endpoint
self._raw_clients['network'] = client
return self._raw_clients['network']
@property
def _object_store_client(self):
if 'object-store' not in self._raw_clients:
raw_client = self._get_raw_client('object-store')
self._raw_clients['object-store'] = raw_client
return self._raw_clients['object-store']
@property
def _orchestration_client(self):
if 'orchestration' not in self._raw_clients:
raw_client = self._get_raw_client('orchestration')
self._raw_clients['orchestration'] = raw_client
return self._raw_clients['orchestration']
@property
def _volume_client(self):
if 'volume' not in self._raw_clients:
self._raw_clients['volume'] = self._get_raw_client('volume')
return self._raw_clients['volume']
def pprint(self, resource):
"""Wrapper aroud pprint that groks munch objects"""
# import late since this is a utility function
import pprint
new_resource = _utils._dictify_resource(resource)
pprint.pprint(new_resource)
def pformat(self, resource):
"""Wrapper aroud pformat that groks munch objects"""
# import late since this is a utility function
import pprint
new_resource = _utils._dictify_resource(resource)
return pprint.pformat(new_resource)
@property
def keystone_session(self):
if self._keystone_session is None:
try:
self._keystone_session = self.cloud_config.get_session()
if hasattr(self._keystone_session, 'additional_user_agent'):
self._keystone_session.additional_user_agent.append(
('shade', shade.__version__))
except Exception as e:
raise exc.OpenStackCloudException(
"Error authenticating to keystone: %s " % str(e))
return self._keystone_session
@property
def _keystone_catalog(self):
return self.keystone_session.auth.get_access(
self.keystone_session).service_catalog
@property
def service_catalog(self):
return self._keystone_catalog.catalog
def endpoint_for(self, service_type, interface='public'):
return self._keystone_catalog.url_for(
service_type=service_type, interface=interface)
@property
def auth_token(self):
# Keystone's session will reuse a token if it is still valid.
# We don't need to track validity here, just get_token() each time.
return self.keystone_session.get_token()
@property
def current_user_id(self):
"""Get the id of the currently logged-in user from the token."""
return self.keystone_session.auth.get_access(
self.keystone_session).user_id
@property
def current_project_id(self):
"""Get the current project ID.
Returns the project_id of the current token scope. None means that
the token is domain scoped or unscoped.
:raises keystoneauth1.exceptions.auth.AuthorizationFailure:
if a new token fetch fails.
:raises keystoneauth1.exceptions.auth_plugins.MissingAuthPlugin:
if a plugin is not available.
"""
return self.keystone_session.get_project_id()
@property
def current_project(self):
"""Return a ``munch.Munch`` describing the current project"""
return self._get_project_info()
def _get_project_info(self, project_id=None):
project_info = munch.Munch(
id=project_id,
name=None,
domain_id=None,
domain_name=None,
)
if not project_id or project_id == self.current_project_id:
# If we don't have a project_id parameter, it means a user is
# directly asking what the current state is.
# Alternately, if we have one, that means we're calling this
# from within a normalize function, which means the object has
# a project_id associated with it. If the project_id matches
# the project_id of our current token, that means we can supplement
# the info with human readable info about names if we have them.
# If they don't match, that means we're an admin who has pulled
# an object from a different project, so adding info from the
# current token would be wrong.
auth_args = self.cloud_config.config.get('auth', {})
project_info['id'] = self.current_project_id
project_info['name'] = auth_args.get('project_name')
project_info['domain_id'] = auth_args.get('project_domain_id')
project_info['domain_name'] = auth_args.get('project_domain_name')
return project_info
@property
def current_location(self):
"""Return a ``munch.Munch`` explaining the current cloud location."""
return self._get_current_location()
def _get_current_location(self, project_id=None, zone=None):
return munch.Munch(
cloud=self.name,
region_name=self.region_name,
zone=zone,
project=self._get_project_info(project_id),
)
def _get_identity_location(self):
'''Identity resources do not exist inside of projects.'''
return munch.Munch(
cloud=self.name,
region_name=None,
zone=None,
project=munch.Munch(
id=None,
name=None,
domain_id=None,
domain_name=None))
def _get_project_id_param_dict(self, name_or_id):
if name_or_id:
project = self.get_project(name_or_id)
if not project:
return {}
if self._is_client_version('identity', 3):
return {'default_project_id': project['id']}
else:
return {'tenant_id': project['id']}
else:
return {}
def _get_domain_id_param_dict(self, domain_id):
"""Get a useable domain."""
# Keystone v3 requires domains for user and project creation. v2 does
# not. However, keystone v2 does not allow user creation by non-admin
# users, so we can throw an error to the user that does not need to
# mention api versions
if self._is_client_version('identity', 3):
if not domain_id:
raise exc.OpenStackCloudException(
"User or project creation requires an explicit"
" domain_id argument.")
else:
return {'domain_id': domain_id}
else:
return {}
def _get_identity_params(self, domain_id=None, project=None):
"""Get the domain and project/tenant parameters if needed.
keystone v2 and v3 are divergent enough that we need to pass or not
pass project or tenant_id or domain or nothing in a sane manner.
"""
ret = {}
ret.update(self._get_domain_id_param_dict(domain_id))
ret.update(self._get_project_id_param_dict(project))
return ret
def range_search(self, data, filters):
"""Perform integer range searches across a list of dictionaries.
Given a list of dictionaries, search across the list using the given
dictionary keys and a range of integer values for each key. Only
dictionaries that match ALL search filters across the entire original
data set will be returned.
It is not a requirement that each dictionary contain the key used
for searching. Those without the key will be considered non-matching.
The range values must be string values and is either a set of digits
representing an integer for matching, or a range operator followed by
a set of digits representing an integer for matching. If a range
operator is not given, exact value matching will be used. Valid
operators are one of: <,>,<=,>=
:param list data: List of dictionaries to be searched.
:param filters: Dict describing the one or more range searches to
perform. If more than one search is given, the result will be the
members of the original data set that match ALL searches. An
example of filtering by multiple ranges::
{"vcpus": "<=5", "ram": "<=2048", "disk": "1"}
:returns: A list subset of the original data set.
:raises: OpenStackCloudException on invalid range expressions.
"""
filtered = []
for key, range_value in filters.items():
# We always want to operate on the full data set so that
# calculations for minimum and maximum are correct.
results = _utils.range_filter(data, key, range_value)
if not filtered:
# First set of results
filtered = results
else:
# The combination of all searches should be the intersection of
# all result sets from each search. So adjust the current set
# of filtered data by computing its intersection with the
# latest result set.
filtered = [r for r in results for f in filtered if r == f]
return filtered
def _get_and_munchify(self, key, data):
"""Wrapper around meta.get_and_munchify.
Some of the methods expect a `meta` attribute to be passed in as
part of the method signature. In those methods the meta param is
overriding the meta module making the call to meta.get_and_munchify
to fail.
"""
return meta.get_and_munchify(key, data)
@_utils.cache_on_arguments()
def list_projects(self, domain_id=None, name_or_id=None, filters=None):
"""List projects.
With no parameters, returns a full listing of all visible projects.
:param domain_id: domain ID to scope the searched projects.
:param name_or_id: project name or ID.
:param filters: a dict containing additional filters to use
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: a list of ``munch.Munch`` containing the projects
:raises: ``OpenStackCloudException``: if something goes wrong during
the OpenStack API call.
"""
kwargs = dict(
filters=filters,
domain_id=domain_id)
if self._is_client_version('identity', 3):
kwargs['obj_name'] = 'project'
pushdown, filters = _normalize._split_filters(**kwargs)
try:
if self._is_client_version('identity', 3):
key = 'projects'
else:
key = 'tenants'
data = self._identity_client.get(
'/{endpoint}'.format(endpoint=key), params=pushdown)
projects = self._normalize_projects(
self._get_and_munchify(key, data))
except Exception as e:
self.log.debug("Failed to list projects", exc_info=True)
raise exc.OpenStackCloudException(str(e))
return _utils._filter_list(projects, name_or_id, filters)
def search_projects(self, name_or_id=None, filters=None, domain_id=None):
'''Backwards compatibility method for search_projects
search_projects originally had a parameter list that was name_or_id,
filters and list had domain_id first. This method exists in this form
to allow code written with positional parameter to still work. But
really, use keyword arguments.
'''
return self.list_projects(
domain_id=domain_id, name_or_id=name_or_id, filters=filters)
def get_project(self, name_or_id, filters=None, domain_id=None):
"""Get exactly one project.
:param name_or_id: project name or ID.
:param filters: a dict containing additional filters to use.
:param domain_id: domain ID (identity v3 only).
:returns: a list of ``munch.Munch`` containing the project description.
:raises: ``OpenStackCloudException``: if something goes wrong during
the OpenStack API call.
"""
return _utils._get_entity(self, 'project', name_or_id, filters,
domain_id=domain_id)
@_utils.valid_kwargs('description')
def update_project(self, name_or_id, enabled=None, domain_id=None,
**kwargs):
with _utils.shade_exceptions(
"Error in updating project {project}".format(
project=name_or_id)):
proj = self.get_project(name_or_id, domain_id=domain_id)
if not proj:
raise exc.OpenStackCloudException(
"Project %s not found." % name_or_id)
if enabled is not None:
kwargs.update({'enabled': enabled})
# NOTE(samueldmq): Current code only allow updates of description
# or enabled fields.
if self._is_client_version('identity', 3):
data = self._identity_client.patch(
'/projects/' + proj['id'], json={'project': kwargs})
project = self._get_and_munchify('project', data)
else:
data = self._identity_client.post(
'/tenants/' + proj['id'], json={'tenant': kwargs})
project = self._get_and_munchify('tenant', data)
project = self._normalize_project(project)
self.list_projects.invalidate(self)
return project
def create_project(
self, name, description=None, domain_id=None, enabled=True):
"""Create a project."""
with _utils.shade_exceptions(
"Error in creating project {project}".format(project=name)):
project_ref = self._get_domain_id_param_dict(domain_id)
project_ref.update({'name': name,
'description': description,
'enabled': enabled})
endpoint, key = ('tenants', 'tenant')
if self._is_client_version('identity', 3):
endpoint, key = ('projects', 'project')
data = self._identity_client.post(
'/{endpoint}'.format(endpoint=endpoint),
json={key: project_ref})
project = self._normalize_project(
self._get_and_munchify(key, data))
self.list_projects.invalidate(self)
return project
def delete_project(self, name_or_id, domain_id=None):
"""Delete a project.
:param string name_or_id: Project name or ID.
:param string domain_id: Domain ID containing the project(identity v3
only).
:returns: True if delete succeeded, False if the project was not found.
:raises: ``OpenStackCloudException`` if something goes wrong during
the OpenStack API call
"""
with _utils.shade_exceptions(
"Error in deleting project {project}".format(
project=name_or_id)):
project = self.get_project(name_or_id, domain_id=domain_id)
if project is None:
self.log.debug(
"Project %s not found for deleting", name_or_id)
return False
if self._is_client_version('identity', 3):
self._identity_client.delete('/projects/' + project['id'])
else:
self._identity_client.delete('/tenants/' + project['id'])
return True
@_utils.valid_kwargs('domain_id')
@_utils.cache_on_arguments()
def list_users(self, **kwargs):
"""List users.
:param domain_id: Domain ID. (v3)
:returns: a list of ``munch.Munch`` containing the user description.
:raises: ``OpenStackCloudException``: if something goes wrong during
the OpenStack API call.
"""
data = self._identity_client.get('/users', params=kwargs)
return _utils.normalize_users(
self._get_and_munchify('users', data))
@_utils.valid_kwargs('domain_id')
def search_users(self, name_or_id=None, filters=None, **kwargs):
"""Search users.
:param string name_or_id: user name or ID.
:param domain_id: Domain ID. (v3)
:param filters: a dict containing additional filters to use.
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: a list of ``munch.Munch`` containing the users
:raises: ``OpenStackCloudException``: if something goes wrong during
the OpenStack API call.
"""
users = self.list_users(**kwargs)
return _utils._filter_list(users, name_or_id, filters)
@_utils.valid_kwargs('domain_id')
def get_user(self, name_or_id, filters=None, **kwargs):
"""Get exactly one user.
:param string name_or_id: user name or ID.
:param domain_id: Domain ID. (v3)
:param filters: a dict containing additional filters to use.
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: a single ``munch.Munch`` containing the user description.
:raises: ``OpenStackCloudException``: if something goes wrong during
the OpenStack API call.
"""
return _utils._get_entity(self, 'user', name_or_id, filters, **kwargs)
def get_user_by_id(self, user_id, normalize=True):
"""Get a user by ID.
:param string user_id: user ID
:param bool normalize: Flag to control dict normalization
:returns: a single ``munch.Munch`` containing the user description
"""
data = self._identity_client.get(
'/users/{user}'.format(user=user_id),
error_message="Error getting user with ID {user_id}".format(
user_id=user_id))
user = self._get_and_munchify('user', data)
if user and normalize:
user = _utils.normalize_users(user)
return user
# NOTE(Shrews): Keystone v2 supports updating only name, email and enabled.
@_utils.valid_kwargs('name', 'email', 'enabled', 'domain_id', 'password',
'description', 'default_project')
def update_user(self, name_or_id, **kwargs):
self.list_users.invalidate(self)
user_kwargs = {}
if 'domain_id' in kwargs and kwargs['domain_id']:
user_kwargs['domain_id'] = kwargs['domain_id']
user = self.get_user(name_or_id, **user_kwargs)
# TODO(mordred) When this changes to REST, force interface=admin
# in the adapter call if it's an admin force call (and figure out how
# to make that disctinction)
if self._is_client_version('identity', 2):
# Do not pass v3 args to a v2 keystone.
kwargs.pop('domain_id', None)
kwargs.pop('description', None)
kwargs.pop('default_project', None)
password = kwargs.pop('password', None)
if password is not None:
with _utils.shade_exceptions(
"Error updating password for {user}".format(
user=name_or_id)):
error_msg = "Error updating password for user {}".format(
name_or_id)
data = self._identity_client.put(
'/users/{u}/OS-KSADM/password'.format(u=user['id']),
json={'user': {'password': password}},
error_message=error_msg)
# Identity v2.0 implements PUT. v3 PATCH. Both work as PATCH.
data = self._identity_client.put(
'/users/{user}'.format(user=user['id']), json={'user': kwargs},
error_message="Error in updating user {}".format(name_or_id))
else:
# NOTE(samueldmq): now this is a REST call and domain_id is dropped
# if None. keystoneclient drops keys with None values.
if 'domain_id' in kwargs and kwargs['domain_id'] is None:
del kwargs['domain_id']
data = self._identity_client.patch(
'/users/{user}'.format(user=user['id']), json={'user': kwargs},
error_message="Error in updating user {}".format(name_or_id))
user = self._get_and_munchify('user', data)
self.list_users.invalidate(self)
return _utils.normalize_users([user])[0]
def create_user(
self, name, password=None, email=None, default_project=None,
enabled=True, domain_id=None, description=None):
"""Create a user."""
params = self._get_identity_params(domain_id, default_project)
params.update({'name': name, 'password': password, 'email': email,
'enabled': enabled})
if self._is_client_version('identity', 3):
params['description'] = description
elif description is not None:
self.log.info(
"description parameter is not supported on Keystone v2")
error_msg = "Error in creating user {user}".format(user=name)
data = self._identity_client.post('/users', json={'user': params},
error_message=error_msg)
user = self._get_and_munchify('user', data)
self.list_users.invalidate(self)
return _utils.normalize_users([user])[0]
@_utils.valid_kwargs('domain_id')
def delete_user(self, name_or_id, **kwargs):
# TODO(mordred) Why are we invalidating at the TOP?
self.list_users.invalidate(self)
user = self.get_user(name_or_id, **kwargs)
if not user:
self.log.debug(
"User {0} not found for deleting".format(name_or_id))
return False
# TODO(mordred) Extra GET only needed to support keystoneclient.
# Can be removed as a follow-on.
user = self.get_user_by_id(user['id'], normalize=False)
self._identity_client.delete(
'/users/{user}'.format(user=user['id']),
error_message="Error in deleting user {user}".format(
user=name_or_id))
self.list_users.invalidate(self)
return True
def _get_user_and_group(self, user_name_or_id, group_name_or_id):
user = self.get_user(user_name_or_id)
if not user:
raise exc.OpenStackCloudException(
'User {user} not found'.format(user=user_name_or_id))
group = self.get_group(group_name_or_id)
if not group:
raise exc.OpenStackCloudException(
'Group {user} not found'.format(user=group_name_or_id))
return (user, group)
def add_user_to_group(self, name_or_id, group_name_or_id):
"""Add a user to a group.
:param string name_or_id: User name or ID
:param string group_name_or_id: Group name or ID
:raises: ``OpenStackCloudException`` if something goes wrong during
the OpenStack API call
"""
user, group = self._get_user_and_group(name_or_id, group_name_or_id)
error_msg = "Error adding user {user} to group {group}".format(
user=name_or_id, group=group_name_or_id)
self._identity_client.put(
'/groups/{g}/users/{u}'.format(g=group['id'], u=user['id']),
error_message=error_msg)
def is_user_in_group(self, name_or_id, group_name_or_id):
"""Check to see if a user is in a group.
:param string name_or_id: User name or ID
:param string group_name_or_id: Group name or ID
:returns: True if user is in the group, False otherwise
:raises: ``OpenStackCloudException`` if something goes wrong during
the OpenStack API call
"""
user, group = self._get_user_and_group(name_or_id, group_name_or_id)
try:
self._identity_client.head(
'/groups/{g}/users/{u}'.format(g=group['id'], u=user['id']))
return True
except exc.OpenStackCloudURINotFound:
# NOTE(samueldmq): knowing this URI exists, let's interpret this as
# user not found in group rather than URI not found.
return False
def remove_user_from_group(self, name_or_id, group_name_or_id):
"""Remove a user from a group.
:param string name_or_id: User name or ID
:param string group_name_or_id: Group name or ID
:raises: ``OpenStackCloudException`` if something goes wrong during
the OpenStack API call
"""
user, group = self._get_user_and_group(name_or_id, group_name_or_id)
error_msg = "Error removing user {user} from group {group}".format(
user=name_or_id, group=group_name_or_id)
self._identity_client.delete(
'/groups/{g}/users/{u}'.format(g=group['id'], u=user['id']),
error_message=error_msg)
def get_template_contents(
self, template_file=None, template_url=None,
template_object=None, files=None):
try:
return template_utils.get_template_contents(
template_file=template_file, template_url=template_url,
template_object=template_object, files=files)
except Exception as e:
raise exc.OpenStackCloudException(
"Error in processing template files: %s" % str(e))
def create_stack(
self, name, tags=None,
template_file=None, template_url=None,
template_object=None, files=None,
rollback=True,
wait=False, timeout=3600,
environment_files=None,
**parameters):
"""Create a stack.
:param string name: Name of the stack.
:param tags: List of tag(s) of the stack. (optional)
:param string template_file: Path to the template.
:param string template_url: URL of template.
:param string template_object: URL to retrieve template object.
:param dict files: dict of additional file content to include.
:param boolean rollback: Enable rollback on create failure.
:param boolean wait: Whether to wait for the create to finish.
:param int timeout: Stack create timeout in seconds. None will use
the server default.
:param list environment_files: Paths to environment files to apply.
Other arguments will be passed as stack parameters which will take
precedence over any parameters specified in the environments.
Only one of template_file, template_url, template_object should be
specified.
:returns: a dict containing the stack description
:raises: ``OpenStackCloudException`` if something goes wrong during
the OpenStack API call
"""
if timeout:
timeout = timeout // 60
envfiles, env = template_utils.process_multiple_environments_and_files(
env_paths=environment_files)
tpl_files, template = template_utils.get_template_contents(
template_file=template_file,
template_url=template_url,
template_object=template_object,
files=files)
params = dict(
stack_name=name,
tags=tags,
disable_rollback=not rollback,
parameters=parameters,
template=template,
files=dict(list(tpl_files.items()) + list(envfiles.items())),
environment=env,
timeout_mins=timeout,
)
self._orchestration_client.post('/stacks', json=params)
if wait:
event_utils.poll_for_events(self, stack_name=name,
action='CREATE')
return self.get_stack(name)
def update_stack(
self, name_or_id,
template_file=None, template_url=None,
template_object=None, files=None,
rollback=True,
wait=False, timeout=3600,
environment_files=None,
**parameters):
"""Update a stack.
:param string name_or_id: Name or ID of the stack to update.
:param string template_file: Path to the template.
:param string template_url: URL of template.
:param string template_object: URL to retrieve template object.
:param dict files: dict of additional file content to include.
:param boolean rollback: Enable rollback on update failure.
:param boolean wait: Whether to wait for the delete to finish.
:param int timeout: Stack update timeout in seconds. None will use
the server default.
:param list environment_files: Paths to environment files to apply.
Other arguments will be passed as stack parameters which will take
precedence over any parameters specified in the environments.
Only one of template_file, template_url, template_object should be
specified.
:returns: a dict containing the stack description
:raises: ``OpenStackCloudException`` if something goes wrong during
the OpenStack API calls
"""
if timeout:
timeout = timeout // 60
envfiles, env = template_utils.process_multiple_environments_and_files(
env_paths=environment_files)
tpl_files, template = template_utils.get_template_contents(
template_file=template_file,
template_url=template_url,
template_object=template_object,
files=files)
params = dict(
disable_rollback=not rollback,
parameters=parameters,
template=template,
files=dict(list(tpl_files.items()) + list(envfiles.items())),
environment=env,
timeout_mins=timeout,
)
if wait:
# find the last event to use as the marker
events = event_utils.get_events(
self, name_or_id, event_args={'sort_dir': 'desc', 'limit': 1})
marker = events[0].id if events else None
self._orchestration_client.put(
'/stacks/{name_or_id}'.format(name_or_id=name_or_id), json=params)
if wait:
event_utils.poll_for_events(self,
name_or_id,
action='UPDATE',
marker=marker)
return self.get_stack(name_or_id)
def delete_stack(self, name_or_id, wait=False):
"""Delete a stack
:param string name_or_id: Stack name or ID.
:param boolean wait: Whether to wait for the delete to finish
:returns: True if delete succeeded, False if the stack was not found.
:raises: ``OpenStackCloudException`` if something goes wrong during
the OpenStack API call
"""
stack = self.get_stack(name_or_id, resolve_outputs=False)
if stack is None:
self.log.debug("Stack %s not found for deleting", name_or_id)
return False
if wait:
# find the last event to use as the marker
events = event_utils.get_events(
self, name_or_id, event_args={'sort_dir': 'desc', 'limit': 1})
marker = events[0].id if events else None
self._orchestration_client.delete(
'/stacks/{id}'.format(id=stack['id']))
if wait:
try:
event_utils.poll_for_events(self,
stack_name=name_or_id,
action='DELETE',
marker=marker)
except exc.OpenStackCloudHTTPError:
pass
stack = self.get_stack(name_or_id, resolve_outputs=False)
if stack and stack['stack_status'] == 'DELETE_FAILED':
raise exc.OpenStackCloudException(
"Failed to delete stack {id}: {reason}".format(
id=name_or_id, reason=stack['stack_status_reason']))
return True
def get_name(self):
return self.name
def get_region(self):
return self.region_name
def get_flavor_name(self, flavor_id):
flavor = self.get_flavor(flavor_id, get_extra=False)
if flavor:
return flavor['name']
return None
def get_flavor_by_ram(self, ram, include=None, get_extra=True):
"""Get a flavor based on amount of RAM available.
Finds the flavor with the least amount of RAM that is at least
as much as the specified amount. If `include` is given, further
filter based on matching flavor name.
:param int ram: Minimum amount of RAM.
:param string include: If given, will return a flavor whose name
contains this string as a substring.
"""
flavors = self.list_flavors(get_extra=get_extra)
for flavor in sorted(flavors, key=operator.itemgetter('ram')):
if (flavor['ram'] >= ram and
(not include or include in flavor['name'])):
return flavor
raise exc.OpenStackCloudException(
"Could not find a flavor with {ram} and '{include}'".format(
ram=ram, include=include))
def get_session_endpoint(self, service_key):
try:
return self.cloud_config.get_session_endpoint(service_key)
except keystoneauth1.exceptions.catalog.EndpointNotFound as e:
self.log.debug(
"Endpoint not found in %s cloud: %s", self.name, str(e))
endpoint = None
except exc.OpenStackCloudException:
raise
except Exception as e:
raise exc.OpenStackCloudException(
"Error getting {service} endpoint on {cloud}:{region}:"
" {error}".format(
service=service_key,
cloud=self.name,
region=self.region_name,
error=str(e)))
return endpoint
def has_service(self, service_key):
if not self.cloud_config.config.get('has_%s' % service_key, True):
# TODO(mordred) add a stamp here so that we only report this once
if not (service_key in self._disable_warnings
and self._disable_warnings[service_key]):
self.log.debug(
"Disabling %(service_key)s entry in catalog"
" per config", {'service_key': service_key})
self._disable_warnings[service_key] = True
return False
try:
endpoint = self.get_session_endpoint(service_key)
except exc.OpenStackCloudException:
return False
if endpoint:
return True
else:
return False
@_utils.cache_on_arguments()
def _nova_extensions(self):
extensions = set()
data = self._compute_client.get(
'/extensions',
error_message="Error fetching extension list for nova")
for extension in self._get_and_munchify('extensions', data):
extensions.add(extension['alias'])
return extensions
def _has_nova_extension(self, extension_name):
return extension_name in self._nova_extensions()
def search_keypairs(self, name_or_id=None, filters=None):
keypairs = self.list_keypairs()
return _utils._filter_list(keypairs, name_or_id, filters)
@_utils.cache_on_arguments()
def _neutron_extensions(self):
extensions = set()
data = self._network_client.get(
'/extensions.json',
error_message="Error fetching extension list for neutron")
for extension in self._get_and_munchify('extensions', data):
extensions.add(extension['alias'])
return extensions
def _has_neutron_extension(self, extension_alias):
return extension_alias in self._neutron_extensions()
def search_networks(self, name_or_id=None, filters=None):
"""Search networks
:param name_or_id: Name or ID of the desired network.
:param filters: a dict containing additional filters to use. e.g.
{'router:external': True}
:returns: a list of ``munch.Munch`` containing the network description.
:raises: ``OpenStackCloudException`` if something goes wrong during the
OpenStack API call.
"""
networks = self.list_networks(filters)
return _utils._filter_list(networks, name_or_id, filters)
def search_routers(self, name_or_id=None, filters=None):
"""Search routers
:param name_or_id: Name or ID of the desired router.
:param filters: a dict containing additional filters to use. e.g.
{'admin_state_up': True}
:returns: a list of ``munch.Munch`` containing the router description.
:raises: ``OpenStackCloudException`` if something goes wrong during the
OpenStack API call.
"""
routers = self.list_routers(filters)
return _utils._filter_list(routers, name_or_id, filters)
def search_subnets(self, name_or_id=None, filters=None):
"""Search subnets
:param name_or_id: Name or ID of the desired subnet.
:param filters: a dict containing additional filters to use. e.g.
{'enable_dhcp': True}
:returns: a list of ``munch.Munch`` containing the subnet description.
:raises: ``OpenStackCloudException`` if something goes wrong during the
OpenStack API call.
"""
subnets = self.list_subnets(filters)
return _utils._filter_list(subnets, name_or_id, filters)
def search_ports(self, name_or_id=None, filters=None):
"""Search ports
:param name_or_id: Name or ID of the desired port.
:param filters: a dict containing additional filters to use. e.g.
{'device_id': '2711c67a-b4a7-43dd-ace7-6187b791c3f0'}
:returns: a list of ``munch.Munch`` containing the port description.
:raises: ``OpenStackCloudException`` if something goes wrong during the
OpenStack API call.
"""
# If port caching is enabled, do not push the filter down to
# neutron; get all the ports (potentially from the cache) and
# filter locally.
if self._PORT_AGE:
pushdown_filters = None
else:
pushdown_filters = filters
ports = self.list_ports(pushdown_filters)
return _utils._filter_list(ports, name_or_id, filters)
def search_qos_policies(self, name_or_id=None, filters=None):
"""Search QoS policies
:param name_or_id: Name or ID of the desired policy.
:param filters: a dict containing additional filters to use. e.g.
{'shared': True}
:returns: a list of ``munch.Munch`` containing the network description.
:raises: ``OpenStackCloudException`` if something goes wrong during the
OpenStack API call.
"""
policies = self.list_qos_policies(filters)
return _utils._filter_list(policies, name_or_id, filters)
def search_volumes(self, name_or_id=None, filters=None):
volumes = self.list_volumes()
return _utils._filter_list(
volumes, name_or_id, filters)
def search_volume_snapshots(self, name_or_id=None, filters=None):
volumesnapshots = self.list_volume_snapshots()
return _utils._filter_list(
volumesnapshots, name_or_id, filters)
def search_volume_backups(self, name_or_id=None, filters=None):
volume_backups = self.list_volume_backups()
return _utils._filter_list(
volume_backups, name_or_id, filters)
def search_volume_types(
self, name_or_id=None, filters=None, get_extra=True):
volume_types = self.list_volume_types(get_extra=get_extra)
return _utils._filter_list(volume_types, name_or_id, filters)
def search_flavors(self, name_or_id=None, filters=None, get_extra=True):
flavors = self.list_flavors(get_extra=get_extra)
return _utils._filter_list(flavors, name_or_id, filters)
def search_security_groups(self, name_or_id=None, filters=None):
# `filters` could be a dict or a jmespath (str)
groups = self.list_security_groups(
filters=filters if isinstance(filters, dict) else None
)
return _utils._filter_list(groups, name_or_id, filters)
def search_servers(
self, name_or_id=None, filters=None, detailed=False,
all_projects=False, bare=False):
servers = self.list_servers(
detailed=detailed, all_projects=all_projects, bare=bare)
return _utils._filter_list(servers, name_or_id, filters)
def search_server_groups(self, name_or_id=None, filters=None):
"""Seach server groups.
:param name: server group name or ID.
:param filters: a dict containing additional filters to use.
:returns: a list of dicts containing the server groups
:raises: ``OpenStackCloudException``: if something goes wrong during
the OpenStack API call.
"""
server_groups = self.list_server_groups()
return _utils._filter_list(server_groups, name_or_id, filters)
def search_images(self, name_or_id=None, filters=None):
images = self.list_images()
return _utils._filter_list(images, name_or_id, filters)
def search_floating_ip_pools(self, name=None, filters=None):
pools = self.list_floating_ip_pools()
return _utils._filter_list(pools, name, filters)
# With Neutron, there are some cases in which full server side filtering is
# not possible (e.g. nested attributes or list of objects) so we also need
# to use the client-side filtering
# The same goes for all neutron-related search/get methods!
def search_floating_ips(self, id=None, filters=None):
# `filters` could be a jmespath expression which Neutron server doesn't
# understand, obviously.
if self._use_neutron_floating() and isinstance(filters, dict):
filter_keys = ['router_id', 'status', 'tenant_id', 'project_id',
'revision_number', 'description',
'floating_network_id', 'fixed_ip_address',
'floating_ip_address', 'port_id', 'sort_dir',
'sort_key', 'tags', 'tags-any', 'not-tags',
'not-tags-any', 'fields']
neutron_filters = {k: v for k, v in filters.items()
if k in filter_keys}
kwargs = {'filters': neutron_filters}
else:
kwargs = {}
floating_ips = self.list_floating_ips(**kwargs)
return _utils._filter_list(floating_ips, id, filters)
def search_stacks(self, name_or_id=None, filters=None):
"""Search stacks.
:param name_or_id: Name or ID of the desired stack.
:param filters: a dict containing additional filters to use. e.g.
{'stack_status': 'CREATE_COMPLETE'}
:returns: a list of ``munch.Munch`` containing the stack description.
:raises: ``OpenStackCloudException`` if something goes wrong during the
OpenStack API call.
"""
stacks = self.list_stacks()
return _utils._filter_list(stacks, name_or_id, filters)
def list_keypairs(self):
"""List all available keypairs.
:returns: A list of ``munch.Munch`` containing keypair info.
"""
data = self._compute_client.get(
'/os-keypairs',
error_message="Error fetching keypair list")
return self._normalize_keypairs([
k['keypair'] for k in self._get_and_munchify('keypairs', data)])
def list_networks(self, filters=None):
"""List all available networks.
:param filters: (optional) dict of filter conditions to push down
:returns: A list of ``munch.Munch`` containing network info.
"""
# Translate None from search interface to empty {} for kwargs below
if not filters:
filters = {}
data = self._network_client.get("/networks.json", params=filters)
return self._get_and_munchify('networks', data)
def list_routers(self, filters=None):
"""List all available routers.
:param filters: (optional) dict of filter conditions to push down
:returns: A list of router ``munch.Munch``.
"""
# Translate None from search interface to empty {} for kwargs below
if not filters:
filters = {}
data = self._network_client.get(
"/routers.json", params=filters,
error_message="Error fetching router list")
return self._get_and_munchify('routers', data)
def list_subnets(self, filters=None):
"""List all available subnets.
:param filters: (optional) dict of filter conditions to push down
:returns: A list of subnet ``munch.Munch``.
"""
# Translate None from search interface to empty {} for kwargs below
if not filters:
filters = {}
data = self._network_client.get("/subnets.json", params=filters)
return self._get_and_munchify('subnets', data)
def list_ports(self, filters=None):
"""List all available ports.
:param filters: (optional) dict of filter conditions to push down
:returns: A list of port ``munch.Munch``.
"""
# If pushdown filters are specified and we do not have batched caching
# enabled, bypass local caching and push down the filters.
if filters and self._PORT_AGE == 0:
return self._list_ports(filters)
# Translate None from search interface to empty {} for kwargs below
filters = {}
if (time.time() - self._ports_time) >= self._PORT_AGE:
# Since we're using cached data anyway, we don't need to
# have more than one thread actually submit the list
# ports task. Let the first one submit it while holding
# a lock, and the non-blocking acquire method will cause
# subsequent threads to just skip this and use the old
# data until it succeeds.
# Initially when we never got data, block to retrieve some data.
first_run = self._ports is None
if self._ports_lock.acquire(first_run):
try:
if not (first_run and self._ports is not None):
self._ports = self._list_ports(filters)
self._ports_time = time.time()
finally:
self._ports_lock.release()
return self._ports
def _list_ports(self, filters):
data = self._network_client.get(
"/ports.json", params=filters,
error_message="Error fetching port list")
return self._get_and_munchify('ports', data)
def list_qos_rule_types(self, filters=None):
"""List all available QoS rule types.
:param filters: (optional) dict of filter conditions to push down
:returns: A list of rule types ``munch.Munch``.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud')
# Translate None from search interface to empty {} for kwargs below
if not filters:
filters = {}
data = self._network_client.get(
"/qos/rule-types.json", params=filters,
error_message="Error fetching QoS rule types list")
return self._get_and_munchify('rule_types', data)
def get_qos_rule_type_details(self, rule_type, filters=None):
"""Get a QoS rule type details by rule type name.
:param string rule_type: Name of the QoS rule type.
:returns: A rule type details ``munch.Munch`` or None if
no matching rule type is found.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud')
if not self._has_neutron_extension('qos-rule-type-details'):
raise exc.OpenStackCloudUnavailableExtension(
'qos-rule-type-details extension is not available '
'on target cloud')
data = self._network_client.get(
"/qos/rule-types/{rule_type}.json".format(rule_type=rule_type),
error_message="Error fetching QoS details of {rule_type} "
"rule type".format(rule_type=rule_type))
return self._get_and_munchify('rule_type', data)
def list_qos_policies(self, filters=None):
"""List all available QoS policies.
:param filters: (optional) dict of filter conditions to push down
:returns: A list of policies ``munch.Munch``.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud')
# Translate None from search interface to empty {} for kwargs below
if not filters:
filters = {}
data = self._network_client.get(
"/qos/policies.json", params=filters,
error_message="Error fetching QoS policies list")
return self._get_and_munchify('policies', data)
@_utils.cache_on_arguments(should_cache_fn=_no_pending_volumes)
def list_volumes(self, cache=True):
"""List all available volumes.
:returns: A list of volume ``munch.Munch``.
"""
def _list(data):
volumes.extend(data.get('volumes', []))
endpoint = None
for l in data.get('volumes_links', []):
if 'rel' in l and 'next' == l['rel']:
endpoint = l['href']
break
if endpoint:
try:
_list(self._volume_client.get(endpoint))
except exc.OpenStackCloudURINotFound:
# Catch and re-raise here because we are making recursive
# calls and we just have context for the log here
self.log.debug(
"While listing volumes, could not find next link"
" {link}.".format(link=data))
raise
if not cache:
warnings.warn('cache argument to list_volumes is deprecated. Use '
'invalidate instead.')
# Fetching paginated volumes can fails for several reasons, if
# something goes wrong we'll have to start fetching volumes from
# scratch
attempts = 5
for _ in range(attempts):
volumes = []
data = self._volume_client.get('/volumes/detail')
if 'volumes_links' not in data:
# no pagination needed
volumes.extend(data.get('volumes', []))
break
try:
_list(data)
break
except exc.OpenStackCloudURINotFound:
pass
else:
self.log.debug(
"List volumes failed to retrieve all volumes after"
" {attempts} attempts. Returning what we found.".format(
attempts=attempts))
# list volumes didn't complete succesfully so just return what
# we found
return self._normalize_volumes(
self._get_and_munchify(key=None, data=volumes))
@_utils.cache_on_arguments()
def list_volume_types(self, get_extra=True):
"""List all available volume types.
:returns: A list of volume ``munch.Munch``.
"""
data = self._volume_client.get(
'/types',
params=dict(is_public='None'),
error_message='Error fetching volume_type list')
return self._normalize_volume_types(
self._get_and_munchify('volume_types', data))
@_utils.cache_on_arguments()
def list_availability_zone_names(self, unavailable=False):
"""List names of availability zones.
:param bool unavailable: Whether or not to include unavailable zones
in the output. Defaults to False.
:returns: A list of availability zone names, or an empty list if the
list could not be fetched.
"""
try:
data = self._compute_client.get('/os-availability-zone')
except exc.OpenStackCloudHTTPError:
self.log.debug(
"Availability zone list could not be fetched",
exc_info=True)
return []
zones = self._get_and_munchify('availabilityZoneInfo', data)
ret = []
for zone in zones:
if zone['zoneState']['available'] or unavailable:
ret.append(zone['zoneName'])
return ret
@_utils.cache_on_arguments()
def list_flavors(self, get_extra=None):
"""List all available flavors.
:param get_extra: Whether or not to fetch extra specs for each flavor.
Defaults to True. Default behavior value can be
overridden in clouds.yaml by setting
shade.get_extra_specs to False.
:returns: A list of flavor ``munch.Munch``.
"""
if get_extra is None:
get_extra = self._extra_config['get_flavor_extra_specs']
data = self._compute_client.get(
'/flavors/detail', params=dict(is_public='None'),
error_message="Error fetching flavor list")
flavors = self._normalize_flavors(
self._get_and_munchify('flavors', data))
for flavor in flavors:
if not flavor.extra_specs and get_extra:
endpoint = "/flavors/{id}/os-extra_specs".format(
id=flavor.id)
try:
data = self._compute_client.get(
endpoint,
error_message="Error fetching flavor extra specs")
flavor.extra_specs = self._get_and_munchify(
'extra_specs', data)
except exc.OpenStackCloudHTTPError as e:
flavor.extra_specs = {}
self.log.debug(
'Fetching extra specs for flavor failed:'
' %(msg)s', {'msg': str(e)})
return flavors
@_utils.cache_on_arguments(should_cache_fn=_no_pending_stacks)
def list_stacks(self):
"""List all stacks.
:returns: a list of ``munch.Munch`` containing the stack description.
:raises: ``OpenStackCloudException`` if something goes wrong during the
OpenStack API call.
"""
data = self._orchestration_client.get(
'/stacks', error_message="Error fetching stack list")
return self._normalize_stacks(
self._get_and_munchify('stacks', data))
def list_server_security_groups(self, server):
"""List all security groups associated with the given server.
:returns: A list of security group ``munch.Munch``.
"""
# Don't even try if we're a cloud that doesn't have them
if not self._has_secgroups():
return []
data = self._compute_client.get(
'/servers/{server_id}/os-security-groups'.format(
server_id=server['id']))
return self._normalize_secgroups(
self._get_and_munchify('security_groups', data))
def _get_server_security_groups(self, server, security_groups):
if not self._has_secgroups():
raise exc.OpenStackCloudUnavailableFeature(
"Unavailable feature: security groups"
)
if not isinstance(server, dict):
server = self.get_server(server, bare=True)
if server is None:
self.log.debug('Server %s not found', server)
return None, None
if not isinstance(security_groups, (list, tuple)):
security_groups = [security_groups]
sec_group_objs = []
for sg in security_groups:
if not isinstance(sg, dict):
sg = self.get_security_group(sg)
if sg is None:
self.log.debug('Security group %s not found for adding',
sg)
return None, None
sec_group_objs.append(sg)
return server, sec_group_objs
def add_server_security_groups(self, server, security_groups):
"""Add security groups to a server.
Add existing security groups to an existing server. If the security
groups are already present on the server this will continue unaffected.
:returns: False if server or security groups are undefined, True
otherwise.
:raises: ``OpenStackCloudException``, on operation error.
"""
server, security_groups = self._get_server_security_groups(
server, security_groups)
if not (server and security_groups):
return False
for sg in security_groups:
self._compute_client.post(
'/servers/%s/action' % server['id'],
json={'addSecurityGroup': {'name': sg.name}})
return True
def remove_server_security_groups(self, server, security_groups):
"""Remove security groups from a server
Remove existing security groups from an existing server. If the
security groups are not present on the server this will continue
unaffected.
:returns: False if server or security groups are undefined, True
otherwise.
:raises: ``OpenStackCloudException``, on operation error.
"""
server, security_groups = self._get_server_security_groups(
server, security_groups)
if not (server and security_groups):
return False
ret = True
for sg in security_groups:
try:
self._compute_client.post(
'/servers/%s/action' % server['id'],
json={'removeSecurityGroup': {'name': sg.name}})
except exc.OpenStackCloudURINotFound:
# NOTE(jamielennox): Is this ok? If we remove something that
# isn't present should we just conclude job done or is that an
# error? Nova returns ok if you try to add a group twice.
self.log.debug(
"The security group %s was not present on server %s so "
"no action was performed", sg.name, server.name)
ret = False
return ret
def list_security_groups(self, filters=None):
"""List all available security groups.
:param filters: (optional) dict of filter conditions to push down
:returns: A list of security group ``munch.Munch``.
"""
# Security groups not supported
if not self._has_secgroups():
raise exc.OpenStackCloudUnavailableFeature(
"Unavailable feature: security groups"
)
if not filters:
filters = {}
data = []
# Handle neutron security groups
if self._use_neutron_secgroups():
# Neutron returns dicts, so no need to convert objects here.
data = self._network_client.get(
'/security-groups.json', params=filters,
error_message="Error fetching security group list")
return self._get_and_munchify('security_groups', data)
# Handle nova security groups
else:
data = self._compute_client.get(
'/os-security-groups', params=filters)
return self._normalize_secgroups(
self._get_and_munchify('security_groups', data))
def iter_servers(self, detailed=False,
all_projects=False, bare=False,
filters=None):
"""Iterate over all available servers.
:param detailed: Whether or not to add detailed additional information.
Defaults to False.
:param all_projects: Whether to list servers from all projects or just
the current auth scoped project.
:param bare: Whether to skip adding any additional information to the
server record. Defaults to False, meaning the addresses
dict will be populated as needed from neutron. Setting
to True implies detailed = False.
:param filters: Additional query parameters passed to the API server.
:yields: Lists of server ``munch.Munch`` (one list per each chunk).
"""
for servers in self._iter_servers(detailed=detailed,
all_projects=all_projects,
bare=bare, filters=filters):
yield servers
def list_servers(self, detailed=False, all_projects=False, bare=False,
filters=None):
"""List all available servers.
:param detailed: Whether or not to add detailed additional information.
Defaults to False.
:param all_projects: Whether to list servers from all projects or just
the current auth scoped project.
:param bare: Whether to skip adding any additional information to the
server record. Defaults to False, meaning the addresses
dict will be populated as needed from neutron. Setting
to True implies detailed = False.
:param filters: Additional query parameters passed to the API server.
:returns: A list of server ``munch.Munch``.
"""
if (time.time() - self._servers_time) >= self._SERVER_AGE:
# Since we're using cached data anyway, we don't need to
# have more than one thread actually submit the list
# servers task. Let the first one submit it while holding
# a lock, and the non-blocking acquire method will cause
# subsequent threads to just skip this and use the old
# data until it succeeds.
# Initially when we never got data, block to retrieve some data.
first_run = self._servers is None
if self._servers_lock.acquire(first_run):
try:
if not (first_run and self._servers is not None):
servers = []
for chunk in self._iter_servers(
detailed=detailed, all_projects=all_projects,
bare=bare, filters=filters):
servers.extend(chunk)
self._servers = servers
self._servers_time = time.time()
finally:
self._servers_lock.release()
return self._servers
def _iter_servers(self, detailed=False,
all_projects=False, bare=False,
filters=None):
error_msg = "Error fetching server list on {cloud}:{region}:".format(
cloud=self.name,
region=self.region_name)
params = filters or {}
if all_projects:
params['all_tenants'] = True
data = self._compute_client.get(
'/servers/detail', params=params, error_message=error_msg)
while 'servers_links' in data:
servers = self._normalize_servers(
self._get_and_munchify('servers', data))
yield [
self._expand_server(server, detailed, bare)
for server in servers
]
parse_result = urllib.parse.urlparse(
data['servers_links'][0]['href'])
pagination_params = dict(
urllib.parse.parse_qsl(parse_result.query))
params.update(pagination_params)
data = self._compute_client.get(
'/servers/detail', params=params, error_message=error_msg)
servers = self._normalize_servers(
self._get_and_munchify('servers', data))
yield [
self._expand_server(server, detailed, bare)
for server in servers
]
def list_server_groups(self):
"""List all available server groups.
:returns: A list of server group dicts.
"""
data = self._compute_client.get(
'/os-server-groups',
error_message="Error fetching server group list")
return self._get_and_munchify('server_groups', data)
def get_compute_limits(self, name_or_id=None):
""" Get compute limits for a project
:param name_or_id: (optional) project name or ID to get limits for
if different from the current project
:raises: OpenStackCloudException if it's not a valid project
:returns: Munch object with the limits
"""
params = {}
project_id = None
error_msg = "Failed to get limits"
if name_or_id:
proj = self.get_project(name_or_id)
if not proj:
raise exc.OpenStackCloudException("project does not exist")
project_id = proj.id
params['tenant_id'] = project_id
error_msg = "{msg} for the project: {project} ".format(
msg=error_msg, project=name_or_id)
data = self._compute_client.get('/limits', params=params)
limits = self._get_and_munchify('limits', data)
return self._normalize_compute_limits(limits, project_id=project_id)
@_utils.cache_on_arguments(should_cache_fn=_no_pending_images)
def list_images(self, filter_deleted=True, show_all=False):
"""Get available images.
:param filter_deleted: Control whether deleted images are returned.
:param show_all: Show all images, including images that are shared
but not accepted. (By default in glance v2 shared image that
have not been accepted are not shown) show_all will override the
value of filter_deleted to False.
:returns: A list of glance images.
"""
if show_all:
filter_deleted = False
# First, try to actually get images from glance, it's more efficient
images = []
params = {}
image_list = []
try:
if self._is_client_version('image', 2):
endpoint = '/images'
if show_all:
params['member_status'] = 'all'
else:
endpoint = '/images/detail'
response = self._image_client.get(endpoint, params=params)
except keystoneauth1.exceptions.catalog.EndpointNotFound:
# We didn't have glance, let's try nova
# If this doesn't work - we just let the exception propagate
response = self._compute_client.get('/images/detail')
while 'next' in response:
image_list.extend(meta.obj_list_to_munch(response['images']))
endpoint = response['next']
# next links from glance have the version prefix. If the catalog
# has a versioned endpoint, then we can't append the next link to
# it. Strip the absolute prefix (/v1/ or /v2/ to turn it into
# a proper relative link.
if endpoint.startswith('/v'):
endpoint = endpoint[4:]
response = self._image_client.get(endpoint)
if 'images' in response:
image_list.extend(meta.obj_list_to_munch(response['images']))
else:
image_list.extend(response)
for image in image_list:
# The cloud might return DELETED for invalid images.
# While that's cute and all, that's an implementation detail.
if not filter_deleted:
images.append(image)
elif image.status.lower() != 'deleted':
images.append(image)
return self._normalize_images(images)
def list_floating_ip_pools(self):
"""List all available floating IP pools.
NOTE: This function supports the nova-net view of the world. nova-net
has been deprecated, so it's highly recommended to switch to using
neutron. `get_external_ipv4_floating_networks` is what you should
almost certainly be using.
:returns: A list of floating IP pool ``munch.Munch``.
"""
if not self._has_nova_extension('os-floating-ip-pools'):
raise exc.OpenStackCloudUnavailableExtension(
'Floating IP pools extension is not available on target cloud')
data = self._compute_client.get(
'os-floating-ip-pools',
error_message="Error fetching floating IP pool list")
pools = self._get_and_munchify('floating_ip_pools', data)
return [{'name': p['name']} for p in pools]
def _list_floating_ips(self, filters=None):
if self._use_neutron_floating():
try:
return self._normalize_floating_ips(
self._neutron_list_floating_ips(filters))
except exc.OpenStackCloudURINotFound as e:
# Nova-network don't support server-side floating ips
# filtering, so it's safer to return and empty list than
# to fallback to Nova which may return more results that
# expected.
if filters:
self.log.error(
"Neutron returned NotFound for floating IPs, which"
" means this cloud doesn't have neutron floating ips."
" shade can't fallback to trying Nova since nova"
" doesn't support server-side filtering when listing"
" floating ips and filters were given. If you do not"
" think shade should be attempting to list floating"
" ips on neutron, it is possible to control the"
" behavior by setting floating_ip_source to 'nova' or"
" None for cloud: %(cloud)s. If you are not already"
" using clouds.yaml to configure settings for your"
" cloud(s), and you want to configure this setting,"
" you will need a clouds.yaml file. For more"
" information, please see %(doc_url)s", {
'cloud': self.name,
'doc_url': _OCC_DOC_URL,
}
)
# We can't fallback to nova because we push-down filters.
# We got a 404 which means neutron doesn't exist. If the
# user
return []
self.log.debug(
"Something went wrong talking to neutron API: "
"'%(msg)s'. Trying with Nova.", {'msg': str(e)})
# Fall-through, trying with Nova
else:
if filters:
raise ValueError(
"Nova-network don't support server-side floating ips "
"filtering. Use the search_floatting_ips method instead"
)
floating_ips = self._nova_list_floating_ips()
return self._normalize_floating_ips(floating_ips)
def list_floating_ips(self, filters=None):
"""List all available floating IPs.
:param filters: (optional) dict of filter conditions to push down
:returns: A list of floating IP ``munch.Munch``.
"""
# If pushdown filters are specified and we do not have batched caching
# enabled, bypass local caching and push down the filters.
if filters and self._FLOAT_AGE == 0:
return self._list_floating_ips(filters)
if (time.time() - self._floating_ips_time) >= self._FLOAT_AGE:
# Since we're using cached data anyway, we don't need to
# have more than one thread actually submit the list
# floating ips task. Let the first one submit it while holding
# a lock, and the non-blocking acquire method will cause
# subsequent threads to just skip this and use the old
# data until it succeeds.
# Initially when we never got data, block to retrieve some data.
first_run = self._floating_ips is None
if self._floating_ips_lock.acquire(first_run):
try:
if not (first_run and self._floating_ips is not None):
self._floating_ips = self._list_floating_ips()
self._floating_ips_time = time.time()
finally:
self._floating_ips_lock.release()
return self._floating_ips
def _neutron_list_floating_ips(self, filters=None):
if not filters:
filters = {}
data = self._network_client.get('/floatingips.json', params=filters)
return self._get_and_munchify('floatingips', data)
def _nova_list_floating_ips(self):
try:
data = self._compute_client.get('/os-floating-ips')
except exc.OpenStackCloudURINotFound:
return []
return self._get_and_munchify('floating_ips', data)
def use_external_network(self):
return self._use_external_network
def use_internal_network(self):
return self._use_internal_network
def _reset_network_caches(self):
# Variables to prevent us from going through the network finding
# logic again if we've done it once. This is different from just
# the cached value, since "None" is a valid value to find.
with self._networks_lock:
self._external_ipv4_networks = []
self._external_ipv4_floating_networks = []
self._internal_ipv4_networks = []
self._external_ipv6_networks = []
self._internal_ipv6_networks = []
self._nat_destination_network = None
self._default_network_network = None
self._network_list_stamp = False
def _set_interesting_networks(self):
external_ipv4_networks = []
external_ipv4_floating_networks = []
internal_ipv4_networks = []
external_ipv6_networks = []
internal_ipv6_networks = []
nat_destination = None
default_network = None
all_subnets = None
# Filter locally because we have an or condition
try:
# TODO(mordred): Rackspace exposes neutron but it does not
# work. I think that overriding what the service catalog
# reports should be a thing os-client-config should handle
# in a vendor profile - but for now it does not. That means
# this search_networks can just totally fail. If it does
# though, that's fine, clearly the neutron introspection is
# not going to work.
all_networks = self.list_networks()
except exc.OpenStackCloudException:
self._network_list_stamp = True
return
for network in all_networks:
# External IPv4 networks
if (network['name'] in self._external_ipv4_names
or network['id'] in self._external_ipv4_names):
external_ipv4_networks.append(network)
elif ((('router:external' in network
and network['router:external']) or
network.get('provider:physical_network')) and
network['name'] not in self._internal_ipv4_names and
network['id'] not in self._internal_ipv4_names):
external_ipv4_networks.append(network)
# External Floating IPv4 networks
if ('router:external' in network and network['router:external']):
external_ipv4_floating_networks.append(network)
# Internal networks
if (network['name'] in self._internal_ipv4_names
or network['id'] in self._internal_ipv4_names):
internal_ipv4_networks.append(network)
elif (not network.get('router:external', False) and
not network.get('provider:physical_network') and
network['name'] not in self._external_ipv4_names and
network['id'] not in self._external_ipv4_names):
internal_ipv4_networks.append(network)
# External networks
if (network['name'] in self._external_ipv6_names
or network['id'] in self._external_ipv6_names):
external_ipv6_networks.append(network)
elif (network.get('router:external') and
network['name'] not in self._internal_ipv6_names and
network['id'] not in self._internal_ipv6_names):
external_ipv6_networks.append(network)
# Internal networks
if (network['name'] in self._internal_ipv6_names
or network['id'] in self._internal_ipv6_names):
internal_ipv6_networks.append(network)
elif (not network.get('router:external', False) and
network['name'] not in self._external_ipv6_names and
network['id'] not in self._external_ipv6_names):
internal_ipv6_networks.append(network)
# NAT Destination
if self._nat_destination in (
network['name'], network['id']):
if nat_destination:
raise exc.OpenStackCloudException(
'Multiple networks were found matching'
' {nat_net} which is the network configured'
' to be the NAT destination. Please check your'
' cloud resources. It is probably a good idea'
' to configure this network by ID rather than'
' by name.'.format(
nat_net=self._nat_destination))
nat_destination = network
elif self._nat_destination is None:
# TODO(mordred) need a config value for floating
# ips for this cloud so that we can skip this
# No configured nat destination, we have to figured
# it out.
if all_subnets is None:
try:
all_subnets = self.list_subnets()
except exc.OpenStackCloudException:
# Thanks Rackspace broken neutron
all_subnets = []
for subnet in all_subnets:
# TODO(mordred) trap for detecting more than
# one network with a gateway_ip without a config
if ('gateway_ip' in subnet and subnet['gateway_ip']
and network['id'] == subnet['network_id']):
nat_destination = network
break
# Default network
if self._default_network in (
network['name'], network['id']):
if default_network:
raise exc.OpenStackCloudException(
'Multiple networks were found matching'
' {default_net} which is the network'
' configured to be the default interface'
' network. Please check your cloud resources.'
' It is probably a good idea'
' to configure this network by ID rather than'
' by name.'.format(
default_net=self._default_network))
default_network = network
# Validate config vs. reality
for net_name in self._external_ipv4_names:
if net_name not in [net['name'] for net in external_ipv4_networks]:
raise exc.OpenStackCloudException(
"Networks: {network} was provided for external IPv4"
" access and those networks could not be found".format(
network=net_name))
for net_name in self._internal_ipv4_names:
if net_name not in [net['name'] for net in internal_ipv4_networks]:
raise exc.OpenStackCloudException(
"Networks: {network} was provided for internal IPv4"
" access and those networks could not be found".format(
network=net_name))
for net_name in self._external_ipv6_names:
if net_name not in [net['name'] for net in external_ipv6_networks]:
raise exc.OpenStackCloudException(
"Networks: {network} was provided for external IPv6"
" access and those networks could not be found".format(
network=net_name))
for net_name in self._internal_ipv6_names:
if net_name not in [net['name'] for net in internal_ipv6_networks]:
raise exc.OpenStackCloudException(
"Networks: {network} was provided for internal IPv6"
" access and those networks could not be found".format(
network=net_name))
if self._nat_destination and not nat_destination:
raise exc.OpenStackCloudException(
'Network {network} was configured to be the'
' destination for inbound NAT but it could not be'
' found'.format(
network=self._nat_destination))
if self._default_network and not default_network:
raise exc.OpenStackCloudException(
'Network {network} was configured to be the'
' default network interface but it could not be'
' found'.format(
network=self._default_network))
self._external_ipv4_networks = external_ipv4_networks
self._external_ipv4_floating_networks = external_ipv4_floating_networks
self._internal_ipv4_networks = internal_ipv4_networks
self._external_ipv6_networks = external_ipv6_networks
self._internal_ipv6_networks = internal_ipv6_networks
self._nat_destination_network = nat_destination
self._default_network_network = default_network
def _find_interesting_networks(self):
if self._networks_lock.acquire():
try:
if self._network_list_stamp:
return
if (not self._use_external_network
and not self._use_internal_network):
# Both have been flagged as skip - don't do a list
return
if not self.has_service('network'):
return
self._set_interesting_networks()
self._network_list_stamp = True
finally:
self._networks_lock.release()
def get_nat_destination(self):
"""Return the network that is configured to be the NAT destination.
:returns: A network dict if one is found
"""
self._find_interesting_networks()
return self._nat_destination_network
def get_default_network(self):
"""Return the network that is configured to be the default interface.
:returns: A network dict if one is found
"""
self._find_interesting_networks()
return self._default_network_network
def get_external_networks(self):
"""Return the networks that are configured to route northbound.
This should be avoided in favor of the specific ipv4/ipv6 method,
but is here for backwards compatibility.
:returns: A list of network ``munch.Munch`` if one is found
"""
self._find_interesting_networks()
return list(
set(self._external_ipv4_networks) |
set(self._external_ipv6_networks))
def get_internal_networks(self):
"""Return the networks that are configured to not route northbound.
This should be avoided in favor of the specific ipv4/ipv6 method,
but is here for backwards compatibility.
:returns: A list of network ``munch.Munch`` if one is found
"""
self._find_interesting_networks()
return list(
set(self._internal_ipv4_networks) |
set(self._internal_ipv6_networks))
def get_external_ipv4_networks(self):
"""Return the networks that are configured to route northbound.
:returns: A list of network ``munch.Munch`` if one is found
"""
self._find_interesting_networks()
return self._external_ipv4_networks
def get_external_ipv4_floating_networks(self):
"""Return the networks that are configured to route northbound.
:returns: A list of network ``munch.Munch`` if one is found
"""
self._find_interesting_networks()
return self._external_ipv4_floating_networks
def get_internal_ipv4_networks(self):
"""Return the networks that are configured to not route northbound.
:returns: A list of network ``munch.Munch`` if one is found
"""
self._find_interesting_networks()
return self._internal_ipv4_networks
def get_external_ipv6_networks(self):
"""Return the networks that are configured to route northbound.
:returns: A list of network ``munch.Munch`` if one is found
"""
self._find_interesting_networks()
return self._external_ipv6_networks
def get_internal_ipv6_networks(self):
"""Return the networks that are configured to not route northbound.
:returns: A list of network ``munch.Munch`` if one is found
"""
self._find_interesting_networks()
return self._internal_ipv6_networks
def _has_floating_ips(self):
if not self._floating_ip_source:
return False
else:
return self._floating_ip_source in ('nova', 'neutron')
def _use_neutron_floating(self):
return (self.has_service('network')
and self._floating_ip_source == 'neutron')
def _has_secgroups(self):
if not self.secgroup_source:
return False
else:
return self.secgroup_source.lower() in ('nova', 'neutron')
def _use_neutron_secgroups(self):
return (self.has_service('network')
and self.secgroup_source == 'neutron')
def get_keypair(self, name_or_id, filters=None):
"""Get a keypair by name or ID.
:param name_or_id: Name or ID of the keypair.
:param filters:
A dictionary of meta data to use for further filtering. Elements
of this dictionary may, themselves, be dictionaries. Example::
{
'last_name': 'Smith',
'other': {
'gender': 'Female'
}
}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A keypair ``munch.Munch`` or None if no matching keypair is
found.
"""
return _utils._get_entity(self, 'keypair', name_or_id, filters)
def get_network(self, name_or_id, filters=None):
"""Get a network by name or ID.
:param name_or_id: Name or ID of the network.
:param filters:
A dictionary of meta data to use for further filtering. Elements
of this dictionary may, themselves, be dictionaries. Example::
{
'last_name': 'Smith',
'other': {
'gender': 'Female'
}
}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A network ``munch.Munch`` or None if no matching network is
found.
"""
return _utils._get_entity(self, 'network', name_or_id, filters)
def get_network_by_id(self, id):
""" Get a network by ID
:param id: ID of the network.
:returns: A network ``munch.Munch``.
"""
data = self._network_client.get(
'/networks/{id}'.format(id=id),
error_message="Error getting network with ID {id}".format(id=id)
)
network = self._get_and_munchify('network', data)
return network
def get_router(self, name_or_id, filters=None):
"""Get a router by name or ID.
:param name_or_id: Name or ID of the router.
:param filters:
A dictionary of meta data to use for further filtering. Elements
of this dictionary may, themselves, be dictionaries. Example::
{
'last_name': 'Smith',
'other': {
'gender': 'Female'
}
}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A router ``munch.Munch`` or None if no matching router is
found.
"""
return _utils._get_entity(self, 'router', name_or_id, filters)
def get_subnet(self, name_or_id, filters=None):
"""Get a subnet by name or ID.
:param name_or_id: Name or ID of the subnet.
:param filters:
A dictionary of meta data to use for further filtering. Elements
of this dictionary may, themselves, be dictionaries. Example::
{
'last_name': 'Smith',
'other': {
'gender': 'Female'
}
}
:returns: A subnet ``munch.Munch`` or None if no matching subnet is
found.
"""
return _utils._get_entity(self, 'subnet', name_or_id, filters)
def get_subnet_by_id(self, id):
""" Get a subnet by ID
:param id: ID of the subnet.
:returns: A subnet ``munch.Munch``.
"""
data = self._network_client.get(
'/subnets/{id}'.format(id=id),
error_message="Error getting subnet with ID {id}".format(id=id)
)
subnet = self._get_and_munchify('subnet', data)
return subnet
def get_port(self, name_or_id, filters=None):
"""Get a port by name or ID.
:param name_or_id: Name or ID of the port.
:param filters:
A dictionary of meta data to use for further filtering. Elements
of this dictionary may, themselves, be dictionaries. Example::
{
'last_name': 'Smith',
'other': {
'gender': 'Female'
}
}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A port ``munch.Munch`` or None if no matching port is found.
"""
return _utils._get_entity(self, 'port', name_or_id, filters)
def get_port_by_id(self, id):
""" Get a port by ID
:param id: ID of the port.
:returns: A port ``munch.Munch``.
"""
data = self._network_client.get(
'/ports/{id}'.format(id=id),
error_message="Error getting port with ID {id}".format(id=id)
)
port = self._get_and_munchify('port', data)
return port
def get_qos_policy(self, name_or_id, filters=None):
"""Get a QoS policy by name or ID.
:param name_or_id: Name or ID of the policy.
:param filters:
A dictionary of meta data to use for further filtering. Elements
of this dictionary may, themselves, be dictionaries. Example::
{
'last_name': 'Smith',
'other': {
'gender': 'Female'
}
}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A policy ``munch.Munch`` or None if no matching network is
found.
"""
return _utils._get_entity(
self, 'qos_policie', name_or_id, filters)
def get_volume(self, name_or_id, filters=None):
"""Get a volume by name or ID.
:param name_or_id: Name or ID of the volume.
:param filters:
A dictionary of meta data to use for further filtering. Elements
of this dictionary may, themselves, be dictionaries. Example::
{
'last_name': 'Smith',
'other': {
'gender': 'Female'
}
}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A volume ``munch.Munch`` or None if no matching volume is
found.
"""
return _utils._get_entity(self, 'volume', name_or_id, filters)
def get_volume_by_id(self, id):
""" Get a volume by ID
:param id: ID of the volume.
:returns: A volume ``munch.Munch``.
"""
data = self._volume_client.get(
'/volumes/{id}'.format(id=id),
error_message="Error getting volume with ID {id}".format(id=id)
)
volume = self._normalize_volume(
self._get_and_munchify('volume', data))
return volume
def get_volume_type(self, name_or_id, filters=None):
"""Get a volume type by name or ID.
:param name_or_id: Name or ID of the volume.
:param filters:
A dictionary of meta data to use for further filtering. Elements
of this dictionary may, themselves, be dictionaries. Example::
{
'last_name': 'Smith',
'other': {
'gender': 'Female'
}
}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A volume ``munch.Munch`` or None if no matching volume is
found.
"""
return _utils._get_entity(
self, 'volume_type', name_or_id, filters)
def get_flavor(self, name_or_id, filters=None, get_extra=True):
"""Get a flavor by name or ID.
:param name_or_id: Name or ID of the flavor.
:param filters:
A dictionary of meta data to use for further filtering. Elements
of this dictionary may, themselves, be dictionaries. Example::
{
'last_name': 'Smith',
'other': {
'gender': 'Female'
}
}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:param get_extra:
Whether or not the list_flavors call should get the extra flavor
specs.
:returns: A flavor ``munch.Munch`` or None if no matching flavor is
found.
"""
search_func = functools.partial(
self.search_flavors, get_extra=get_extra)
return _utils._get_entity(self, search_func, name_or_id, filters)
def get_flavor_by_id(self, id, get_extra=True):
""" Get a flavor by ID
:param id: ID of the flavor.
:param get_extra:
Whether or not the list_flavors call should get the extra flavor
specs.
:returns: A flavor ``munch.Munch``.
"""
data = self._compute_client.get(
'/flavors/{id}'.format(id=id),
error_message="Error getting flavor with ID {id}".format(id=id)
)
flavor = self._normalize_flavor(
self._get_and_munchify('flavor', data))
if get_extra is None:
get_extra = self._extra_config['get_flavor_extra_specs']
if not flavor.extra_specs and get_extra:
endpoint = "/flavors/{id}/os-extra_specs".format(
id=flavor.id)
try:
data = self._compute_client.get(
endpoint,
error_message="Error fetching flavor extra specs")
flavor.extra_specs = self._get_and_munchify(
'extra_specs', data)
except exc.OpenStackCloudHTTPError as e:
flavor.extra_specs = {}
self.log.debug(
'Fetching extra specs for flavor failed:'
' %(msg)s', {'msg': str(e)})
return flavor
def get_security_group(self, name_or_id, filters=None):
"""Get a security group by name or ID.
:param name_or_id: Name or ID of the security group.
:param filters:
A dictionary of meta data to use for further filtering. Elements
of this dictionary may, themselves, be dictionaries. Example::
{
'last_name': 'Smith',
'other': {
'gender': 'Female'
}
}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A security group ``munch.Munch`` or None if no matching
security group is found.
"""
return _utils._get_entity(
self, 'security_group', name_or_id, filters)
def get_security_group_by_id(self, id):
""" Get a security group by ID
:param id: ID of the security group.
:returns: A security group ``munch.Munch``.
"""
if not self._has_secgroups():
raise exc.OpenStackCloudUnavailableFeature(
"Unavailable feature: security groups"
)
error_message = ("Error getting security group with"
" ID {id}".format(id=id))
if self._use_neutron_secgroups():
data = self._network_client.get(
'/security-groups/{id}'.format(id=id),
error_message=error_message)
else:
data = self._compute_client.get(
'/os-security-groups/{id}'.format(id=id),
error_message=error_message)
return self._normalize_secgroup(
self._get_and_munchify('security_group', data))
def get_server_console(self, server, length=None):
"""Get the console log for a server.
:param server: The server to fetch the console log for. Can be either
a server dict or the Name or ID of the server.
:param int length: The number of lines you would like to retrieve from
the end of the log. (optional, defaults to all)
:returns: A string containing the text of the console log or an
empty string if the cloud does not support console logs.
:raises: OpenStackCloudException if an invalid server argument is given
or if something else unforseen happens
"""
if not isinstance(server, dict):
server = self.get_server(server, bare=True)
if not server:
raise exc.OpenStackCloudException(
"Console log requested for invalid server")
try:
return self._get_server_console_output(server['id'], length)
except exc.OpenStackCloudBadRequest:
return ""
def _get_server_console_output(self, server_id, length=None):
data = self._compute_client.post(
'/servers/{server_id}/action'.format(server_id=server_id),
json={'os-getConsoleOutput': {'length': length}})
return self._get_and_munchify('output', data)
def get_server(
self, name_or_id=None, filters=None, detailed=False, bare=False,
all_projects=False):
"""Get a server by name or ID.
:param name_or_id: Name or ID of the server.
:param filters:
A dictionary of meta data to use for further filtering. Elements
of this dictionary may, themselves, be dictionaries. Example::
{
'last_name': 'Smith',
'other': {
'gender': 'Female'
}
}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:param detailed: Whether or not to add detailed additional information.
Defaults to False.
:param bare: Whether to skip adding any additional information to the
server record. Defaults to False, meaning the addresses
dict will be populated as needed from neutron. Setting
to True implies detailed = False.
:param all_projects: Whether to get server from all projects or just
the current auth scoped project.
:returns: A server ``munch.Munch`` or None if no matching server is
found.
"""
if self.use_direct_get:
searchfunc = functools.partial(self.get_server_by_id, bare=True)
else:
searchfunc = functools.partial(self.search_servers,
detailed=detailed, bare=True,
all_projects=all_projects)
server = _utils._get_entity(self, searchfunc, name_or_id, filters)
return self._expand_server(server, detailed, bare)
def _expand_server(self, server, detailed, bare):
if bare or not server:
return server
elif detailed:
return meta.get_hostvars_from_server(self, server)
else:
return meta.add_server_interfaces(self, server)
def get_server_by_id(
self, id=None, detailed=False, bare=False, all_projects=False):
"""Get a server by ID.
:param id: ID of the server.
:param detailed: Whether or not to add detailed additional information.
Defaults to False.
:param bare: Whether to skip adding any additional information to the
server record. Defaults to False, meaning the addresses
dict will be populated as needed from neutron. Setting
to True implies detailed = False.
:param all_projects: Whether to get server from all projects or just
the current auth scoped project.
:returns: A server ``munch.Munch`` or None if no matching server is
found.
"""
params = {}
if all_projects:
params['all_tenants'] = True
data = self._compute_client.get(
'/servers/{id}'.format(id=id), params=params)
server = self._get_and_munchify('server', data)
return self._expand_server(
self._normalize_server(server), detailed=detailed, bare=bare)
def get_server_group(self, name_or_id=None, filters=None):
"""Get a server group by name or ID.
:param name_or_id: Name or ID of the server group.
:param filters:
A dictionary of meta data to use for further filtering. Elements
of this dictionary may, themselves, be dictionaries. Example::
{
'policy': 'affinity',
}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A server groups dict or None if no matching server group
is found.
"""
return _utils._get_entity(self, 'server_group', name_or_id,
filters)
def get_image(self, name_or_id, filters=None):
"""Get an image by name or ID.
:param name_or_id: Name or ID of the image.
:param filters:
A dictionary of meta data to use for further filtering. Elements
of this dictionary may, themselves, be dictionaries. Example::
{
'last_name': 'Smith',
'other': {
'gender': 'Female'
}
}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: An image ``munch.Munch`` or None if no matching image
is found
"""
return _utils._get_entity(self, 'image', name_or_id, filters)
def get_image_by_id(self, id):
""" Get a image by ID
:param id: ID of the image.
:returns: An image ``munch.Munch``.
"""
data = self._image_client.get(
'/images/{id}'.format(id=id),
error_message="Error getting image with ID {id}".format(id=id)
)
key = 'image' if 'image' in data else None
image = self._normalize_image(
self._get_and_munchify(key, data))
return image
def download_image(
self, name_or_id, output_path=None, output_file=None,
chunk_size=1024):
"""Download an image by name or ID
:param str name_or_id: Name or ID of the image.
:param output_path: the output path to write the image to. Either this
or output_file must be specified
:param output_file: a file object (or file-like object) to write the
image data to. Only write() will be called on this object. Either
this or output_path must be specified
:param int chunk_size: size in bytes to read from the wire and buffer
at one time. Defaults to 1024
:raises: OpenStackCloudException in the event download_image is called
without exactly one of either output_path or output_file
:raises: OpenStackCloudResourceNotFound if no images are found matching
the name or ID provided
"""
if output_path is None and output_file is None:
raise exc.OpenStackCloudException(
'No output specified, an output path'
' or file object is necessary to '
'write the image data to')
elif output_path is not None and output_file is not None:
raise exc.OpenStackCloudException(
'Both an output path and file object'
' were provided, however only one '
'can be used at once')
image = self.search_images(name_or_id)
if len(image) == 0:
raise exc.OpenStackCloudResourceNotFound(
"No images with name or ID %s were found" % name_or_id, None)
if self._is_client_version('image', 2):
endpoint = '/images/{id}/file'.format(id=image[0]['id'])
else:
endpoint = '/images/{id}'.format(id=image[0]['id'])
response = self._image_client.get(endpoint, stream=True)
with _utils.shade_exceptions("Unable to download image"):
if output_path:
with open(output_path, 'wb') as fd:
for chunk in response.iter_content(chunk_size=chunk_size):
fd.write(chunk)
return
elif output_file:
for chunk in response.iter_content(chunk_size=chunk_size):
output_file.write(chunk)
return
def get_floating_ip(self, id, filters=None):
"""Get a floating IP by ID
:param id: ID of the floating IP.
:param filters:
A dictionary of meta data to use for further filtering. Elements
of this dictionary may, themselves, be dictionaries. Example::
{
'last_name': 'Smith',
'other': {
'gender': 'Female'
}
}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A floating IP ``munch.Munch`` or None if no matching floating
IP is found.
"""
return _utils._get_entity(self, 'floating_ip', id, filters)
def get_floating_ip_by_id(self, id):
""" Get a floating ip by ID
:param id: ID of the floating ip.
:returns: A floating ip ``munch.Munch``.
"""
error_message = "Error getting floating ip with ID {id}".format(id=id)
if self._use_neutron_floating():
data = self._network_client.get(
'/floatingips/{id}'.format(id=id),
error_message=error_message)
return self._normalize_floating_ip(
self._get_and_munchify('floatingip', data))
else:
data = self._compute_client.get(
'/os-floating-ips/{id}'.format(id=id),
error_message=error_message)
return self._normalize_floating_ip(
self._get_and_munchify('floating_ip', data))
def get_stack(self, name_or_id, filters=None, resolve_outputs=True):
"""Get exactly one stack.
:param name_or_id: Name or ID of the desired stack.
:param filters: a dict containing additional filters to use. e.g.
{'stack_status': 'CREATE_COMPLETE'}
:param resolve_outputs: If True, then outputs for this
stack will be resolved
:returns: a ``munch.Munch`` containing the stack description
:raises: ``OpenStackCloudException`` if something goes wrong during the
OpenStack API call or if multiple matches are found.
"""
def _search_one_stack(name_or_id=None, filters=None):
# stack names are mandatory and enforced unique in the project
# so a StackGet can always be used for name or ID.
try:
url = '/stacks/{name_or_id}'.format(name_or_id=name_or_id)
if not resolve_outputs:
url = '{url}?resolve_outputs=False'.format(url=url)
data = self._orchestration_client.get(
url,
error_message="Error fetching stack")
stack = self._get_and_munchify('stack', data)
# Treat DELETE_COMPLETE stacks as a NotFound
if stack['stack_status'] == 'DELETE_COMPLETE':
return []
except exc.OpenStackCloudURINotFound:
return []
stack = self._normalize_stack(stack)
return _utils._filter_list([stack], name_or_id, filters)
return _utils._get_entity(
self, _search_one_stack, name_or_id, filters)
def create_keypair(self, name, public_key=None):
"""Create a new keypair.
:param name: Name of the keypair being created.
:param public_key: Public key for the new keypair.
:raises: OpenStackCloudException on operation error.
"""
keypair = {
'name': name,
}
if public_key:
keypair['public_key'] = public_key
data = self._compute_client.post(
'/os-keypairs',
json={'keypair': keypair},
error_message="Unable to create keypair {name}".format(name=name))
return self._normalize_keypair(
self._get_and_munchify('keypair', data))
def delete_keypair(self, name):
"""Delete a keypair.
:param name: Name of the keypair to delete.
:returns: True if delete succeeded, False otherwise.
:raises: OpenStackCloudException on operation error.
"""
try:
self._compute_client.delete('/os-keypairs/{name}'.format(
name=name))
except exc.OpenStackCloudURINotFound:
self.log.debug("Keypair %s not found for deleting", name)
return False
return True
def create_network(self, name, shared=False, admin_state_up=True,
external=False, provider=None, project_id=None,
availability_zone_hints=None,
port_security_enabled=None,
mtu_size=None):
"""Create a network.
:param string name: Name of the network being created.
:param bool shared: Set the network as shared.
:param bool admin_state_up: Set the network administrative state to up.
:param bool external: Whether this network is externally accessible.
:param dict provider: A dict of network provider options. Example::
{ 'network_type': 'vlan', 'segmentation_id': 'vlan1' }
:param string project_id: Specify the project ID this network
will be created on (admin-only).
:param list availability_zone_hints: A list of availability zone hints.
:param bool port_security_enabled: Enable / Disable port security
:param int mtu_size: maximum transmission unit value to address
fragmentation. Minimum value is 68 for IPv4, and 1280 for IPv6.
:returns: The network object.
:raises: OpenStackCloudException on operation error.
"""
network = {
'name': name,
'admin_state_up': admin_state_up,
}
if shared:
network['shared'] = shared
if project_id is not None:
network['tenant_id'] = project_id
if availability_zone_hints is not None:
if not isinstance(availability_zone_hints, list):
raise exc.OpenStackCloudException(
"Parameter 'availability_zone_hints' must be a list")
if not self._has_neutron_extension('network_availability_zone'):
raise exc.OpenStackCloudUnavailableExtension(
'network_availability_zone extension is not available on '
'target cloud')
network['availability_zone_hints'] = availability_zone_hints
if provider:
if not isinstance(provider, dict):
raise exc.OpenStackCloudException(
"Parameter 'provider' must be a dict")
# Only pass what we know
for attr in ('physical_network', 'network_type',
'segmentation_id'):
if attr in provider:
arg = "provider:" + attr
network[arg] = provider[attr]
# Do not send 'router:external' unless it is explicitly
# set since sending it *might* cause "Forbidden" errors in
# some situations. It defaults to False in the client, anyway.
if external:
network['router:external'] = True
if port_security_enabled is not None:
if not isinstance(port_security_enabled, bool):
raise exc.OpenStackCloudException(
"Parameter 'port_security_enabled' must be a bool")
network['port_security_enabled'] = port_security_enabled
if mtu_size:
if not isinstance(mtu_size, int):
raise exc.OpenStackCloudException(
"Parameter 'mtu_size' must be an integer.")
if not mtu_size >= 68:
raise exc.OpenStackCloudException(
"Parameter 'mtu_size' must be greater than 67.")
network['mtu'] = mtu_size
data = self._network_client.post("/networks.json",
json={'network': network})
# Reset cache so the new network is picked up
self._reset_network_caches()
return self._get_and_munchify('network', data)
def delete_network(self, name_or_id):
"""Delete a network.
:param name_or_id: Name or ID of the network being deleted.
:returns: True if delete succeeded, False otherwise.
:raises: OpenStackCloudException on operation error.
"""
network = self.get_network(name_or_id)
if not network:
self.log.debug("Network %s not found for deleting", name_or_id)
return False
self._network_client.delete(
"/networks/{network_id}.json".format(network_id=network['id']))
# Reset cache so the deleted network is removed
self._reset_network_caches()
return True
@_utils.valid_kwargs("name", "description", "shared", "default",
"project_id")
def create_qos_policy(self, **kwargs):
"""Create a QoS policy.
:param string name: Name of the QoS policy being created.
:param string description: Description of created QoS policy.
:param bool shared: Set the QoS policy as shared.
:param bool default: Set the QoS policy as default for project.
:param string project_id: Specify the project ID this QoS policy
will be created on (admin-only).
:returns: The QoS policy object.
:raises: OpenStackCloudException on operation error.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud')
default = kwargs.pop("default", None)
if default is not None:
if self._has_neutron_extension('qos-default'):
kwargs['is_default'] = default
else:
self.log.debug("'qos-default' extension is not available on "
"target cloud")
data = self._network_client.post("/qos/policies.json",
json={'policy': kwargs})
return self._get_and_munchify('policy', data)
@_utils.valid_kwargs("name", "description", "shared", "default",
"project_id")
def update_qos_policy(self, name_or_id, **kwargs):
"""Update an existing QoS policy.
:param string name_or_id:
Name or ID of the QoS policy to update.
:param string policy_name:
The new name of the QoS policy.
:param string description:
The new description of the QoS policy.
:param bool shared:
If True, the QoS policy will be set as shared.
:param bool default:
If True, the QoS policy will be set as default for project.
:returns: The updated QoS policy object.
:raises: OpenStackCloudException on operation error.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud')
default = kwargs.pop("default", None)
if default is not None:
if self._has_neutron_extension('qos-default'):
kwargs['is_default'] = default
else:
self.log.debug("'qos-default' extension is not available on "
"target cloud")
if not kwargs:
self.log.debug("No QoS policy data to update")
return
curr_policy = self.get_qos_policy(name_or_id)
if not curr_policy:
raise exc.OpenStackCloudException(
"QoS policy %s not found." % name_or_id)
data = self._network_client.put(
"/qos/policies/{policy_id}.json".format(
policy_id=curr_policy['id']),
json={'policy': kwargs})
return self._get_and_munchify('policy', data)
def delete_qos_policy(self, name_or_id):
"""Delete a QoS policy.
:param name_or_id: Name or ID of the policy being deleted.
:returns: True if delete succeeded, False otherwise.
:raises: OpenStackCloudException on operation error.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud')
policy = self.get_qos_policy(name_or_id)
if not policy:
self.log.debug("QoS policy %s not found for deleting", name_or_id)
return False
self._network_client.delete(
"/qos/policies/{policy_id}.json".format(policy_id=policy['id']))
return True
def search_qos_bandwidth_limit_rules(self, policy_name_or_id, rule_id=None,
filters=None):
"""Search QoS bandwidth limit rules
:param string policy_name_or_id: Name or ID of the QoS policy to which
rules should be associated.
:param string rule_id: ID of searched rule.
:param filters: a dict containing additional filters to use. e.g.
{'max_kbps': 1000}
:returns: a list of ``munch.Munch`` containing the bandwidth limit
rule descriptions.
:raises: ``OpenStackCloudException`` if something goes wrong during the
OpenStack API call.
"""
rules = self.list_qos_bandwidth_limit_rules(policy_name_or_id, filters)
return _utils._filter_list(rules, rule_id, filters)
def list_qos_bandwidth_limit_rules(self, policy_name_or_id, filters=None):
"""List all available QoS bandwith limit rules.
:param string policy_name_or_id: Name or ID of the QoS policy from
from rules should be listed.
:param filters: (optional) dict of filter conditions to push down
:returns: A list of ``munch.Munch`` containing rule info.
:raises: ``OpenStackCloudResourceNotFound`` if QoS policy will not be
found.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud')
policy = self.get_qos_policy(policy_name_or_id)
if not policy:
raise exc.OpenStackCloudResourceNotFound(
"QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id))
# Translate None from search interface to empty {} for kwargs below
if not filters:
filters = {}
data = self._network_client.get(
"/qos/policies/{policy_id}/bandwidth_limit_rules.json".format(
policy_id=policy['id']),
params=filters,
error_message="Error fetching QoS bandwith limit rules from "
"{policy}".format(policy=policy['id']))
return self._get_and_munchify('bandwidth_limit_rules', data)
def get_qos_bandwidth_limit_rule(self, policy_name_or_id, rule_id):
"""Get a QoS bandwidth limit rule by name or ID.
:param string policy_name_or_id: Name or ID of the QoS policy to which
rule should be associated.
:param rule_id: ID of the rule.
:returns: A bandwidth limit rule ``munch.Munch`` or None if
no matching rule is found.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud')
policy = self.get_qos_policy(policy_name_or_id)
if not policy:
raise exc.OpenStackCloudResourceNotFound(
"QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id))
data = self._network_client.get(
"/qos/policies/{policy_id}/bandwidth_limit_rules/{rule_id}.json".
format(policy_id=policy['id'], rule_id=rule_id),
error_message="Error fetching QoS bandwith limit rule {rule_id} "
"from {policy}".format(rule_id=rule_id,
policy=policy['id']))
return self._get_and_munchify('bandwidth_limit_rule', data)
@_utils.valid_kwargs("max_burst_kbps", "direction")
def create_qos_bandwidth_limit_rule(self, policy_name_or_id, max_kbps,
**kwargs):
"""Create a QoS bandwidth limit rule.
:param string policy_name_or_id: Name or ID of the QoS policy to which
rule should be associated.
:param int max_kbps: Maximum bandwidth limit value
(in kilobits per second).
:param int max_burst_kbps: Maximum burst value (in kilobits).
:param string direction: Ingress or egress.
The direction in which the traffic will be limited.
:returns: The QoS bandwidth limit rule.
:raises: OpenStackCloudException on operation error.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud')
policy = self.get_qos_policy(policy_name_or_id)
if not policy:
raise exc.OpenStackCloudResourceNotFound(
"QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id))
if kwargs.get("direction") is not None:
if not self._has_neutron_extension('qos-bw-limit-direction'):
kwargs.pop("direction")
self.log.debug(
"'qos-bw-limit-direction' extension is not available on "
"target cloud")
kwargs['max_kbps'] = max_kbps
data = self._network_client.post(
"/qos/policies/{policy_id}/bandwidth_limit_rules".format(
policy_id=policy['id']),
json={'bandwidth_limit_rule': kwargs})
return self._get_and_munchify('bandwidth_limit_rule', data)
@_utils.valid_kwargs("max_kbps", "max_burst_kbps", "direction")
def update_qos_bandwidth_limit_rule(self, policy_name_or_id, rule_id,
**kwargs):
"""Update a QoS bandwidth limit rule.
:param string policy_name_or_id: Name or ID of the QoS policy to which
rule is associated.
:param string rule_id: ID of rule to update.
:param int max_kbps: Maximum bandwidth limit value
(in kilobits per second).
:param int max_burst_kbps: Maximum burst value (in kilobits).
:param string direction: Ingress or egress.
The direction in which the traffic will be limited.
:returns: The updated QoS bandwidth limit rule.
:raises: OpenStackCloudException on operation error.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud')
policy = self.get_qos_policy(policy_name_or_id)
if not policy:
raise exc.OpenStackCloudResourceNotFound(
"QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id))
if kwargs.get("direction") is not None:
if not self._has_neutron_extension('qos-bw-limit-direction'):
kwargs.pop("direction")
self.log.debug(
"'qos-bw-limit-direction' extension is not available on "
"target cloud")
if not kwargs:
self.log.debug("No QoS bandwidth limit rule data to update")
return
curr_rule = self.get_qos_bandwidth_limit_rule(
policy_name_or_id, rule_id)
if not curr_rule:
raise exc.OpenStackCloudException(
"QoS bandwidth_limit_rule {rule_id} not found in policy "
"{policy_id}".format(rule_id=rule_id,
policy_id=policy['id']))
data = self._network_client.put(
"/qos/policies/{policy_id}/bandwidth_limit_rules/{rule_id}.json".
format(policy_id=policy['id'], rule_id=rule_id),
json={'bandwidth_limit_rule': kwargs})
return self._get_and_munchify('bandwidth_limit_rule', data)
def delete_qos_bandwidth_limit_rule(self, policy_name_or_id, rule_id):
"""Delete a QoS bandwidth limit rule.
:param string policy_name_or_id: Name or ID of the QoS policy to which
rule is associated.
:param string rule_id: ID of rule to update.
:raises: OpenStackCloudException on operation error.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud')
policy = self.get_qos_policy(policy_name_or_id)
if not policy:
raise exc.OpenStackCloudResourceNotFound(
"QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id))
try:
self._network_client.delete(
"/qos/policies/{policy}/bandwidth_limit_rules/{rule}.json".
format(policy=policy['id'], rule=rule_id))
except exc.OpenStackCloudURINotFound:
self.log.debug(
"QoS bandwidth limit rule {rule_id} not found in policy "
"{policy_id}. Ignoring.".format(rule_id=rule_id,
policy_id=policy['id']))
return False
return True
def search_qos_dscp_marking_rules(self, policy_name_or_id, rule_id=None,
filters=None):
"""Search QoS DSCP marking rules
:param string policy_name_or_id: Name or ID of the QoS policy to which
rules should be associated.
:param string rule_id: ID of searched rule.
:param filters: a dict containing additional filters to use. e.g.
{'dscp_mark': 32}
:returns: a list of ``munch.Munch`` containing the dscp marking
rule descriptions.
:raises: ``OpenStackCloudException`` if something goes wrong during the
OpenStack API call.
"""
rules = self.list_qos_dscp_marking_rules(policy_name_or_id, filters)
return _utils._filter_list(rules, rule_id, filters)
def list_qos_dscp_marking_rules(self, policy_name_or_id, filters=None):
"""List all available QoS DSCP marking rules.
:param string policy_name_or_id: Name or ID of the QoS policy from
from rules should be listed.
:param filters: (optional) dict of filter conditions to push down
:returns: A list of ``munch.Munch`` containing rule info.
:raises: ``OpenStackCloudResourceNotFound`` if QoS policy will not be
found.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud')
policy = self.get_qos_policy(policy_name_or_id)
if not policy:
raise exc.OpenStackCloudResourceNotFound(
"QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id))
# Translate None from search interface to empty {} for kwargs below
if not filters:
filters = {}
data = self._network_client.get(
"/qos/policies/{policy_id}/dscp_marking_rules.json".format(
policy_id=policy['id']),
params=filters,
error_message="Error fetching QoS DSCP marking rules from "
"{policy}".format(policy=policy['id']))
return meta.get_and_munchify('dscp_marking_rules', data)
def get_qos_dscp_marking_rule(self, policy_name_or_id, rule_id):
"""Get a QoS DSCP marking rule by name or ID.
:param string policy_name_or_id: Name or ID of the QoS policy to which
rule should be associated.
:param rule_id: ID of the rule.
:returns: A bandwidth limit rule ``munch.Munch`` or None if
no matching rule is found.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud')
policy = self.get_qos_policy(policy_name_or_id)
if not policy:
raise exc.OpenStackCloudResourceNotFound(
"QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id))
data = self._network_client.get(
"/qos/policies/{policy_id}/dscp_marking_rules/{rule_id}.json".
format(policy_id=policy['id'], rule_id=rule_id),
error_message="Error fetching QoS DSCP marking rule {rule_id} "
"from {policy}".format(rule_id=rule_id,
policy=policy['id']))
return meta.get_and_munchify('dscp_marking_rule', data)
def create_qos_dscp_marking_rule(self, policy_name_or_id, dscp_mark):
"""Create a QoS DSCP marking rule.
:param string policy_name_or_id: Name or ID of the QoS policy to which
rule should be associated.
:param int dscp_mark: DSCP mark value
:returns: The QoS DSCP marking rule.
:raises: OpenStackCloudException on operation error.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud')
policy = self.get_qos_policy(policy_name_or_id)
if not policy:
raise exc.OpenStackCloudResourceNotFound(
"QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id))
body = {
'dscp_mark': dscp_mark
}
data = self._network_client.post(
"/qos/policies/{policy_id}/dscp_marking_rules".format(
policy_id=policy['id']),
json={'dscp_marking_rule': body})
return meta.get_and_munchify('dscp_marking_rule', data)
@_utils.valid_kwargs("dscp_mark")
def update_qos_dscp_marking_rule(self, policy_name_or_id, rule_id,
**kwargs):
"""Update a QoS DSCP marking rule.
:param string policy_name_or_id: Name or ID of the QoS policy to which
rule is associated.
:param string rule_id: ID of rule to update.
:param int dscp_mark: DSCP mark value
:returns: The updated QoS bandwidth limit rule.
:raises: OpenStackCloudException on operation error.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud')
policy = self.get_qos_policy(policy_name_or_id)
if not policy:
raise exc.OpenStackCloudResourceNotFound(
"QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id))
if not kwargs:
self.log.debug("No QoS DSCP marking rule data to update")
return
curr_rule = self.get_qos_dscp_marking_rule(
policy_name_or_id, rule_id)
if not curr_rule:
raise exc.OpenStackCloudException(
"QoS dscp_marking_rule {rule_id} not found in policy "
"{policy_id}".format(rule_id=rule_id,
policy_id=policy['id']))
data = self._network_client.put(
"/qos/policies/{policy_id}/dscp_marking_rules/{rule_id}.json".
format(policy_id=policy['id'], rule_id=rule_id),
json={'dscp_marking_rule': kwargs})
return meta.get_and_munchify('dscp_marking_rule', data)
def delete_qos_dscp_marking_rule(self, policy_name_or_id, rule_id):
"""Delete a QoS DSCP marking rule.
:param string policy_name_or_id: Name or ID of the QoS policy to which
rule is associated.
:param string rule_id: ID of rule to update.
:raises: OpenStackCloudException on operation error.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud')
policy = self.get_qos_policy(policy_name_or_id)
if not policy:
raise exc.OpenStackCloudResourceNotFound(
"QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id))
try:
self._network_client.delete(
"/qos/policies/{policy}/dscp_marking_rules/{rule}.json".
format(policy=policy['id'], rule=rule_id))
except exc.OpenStackCloudURINotFound:
self.log.debug(
"QoS DSCP marking rule {rule_id} not found in policy "
"{policy_id}. Ignoring.".format(rule_id=rule_id,
policy_id=policy['id']))
return False
return True
def search_qos_minimum_bandwidth_rules(self, policy_name_or_id,
rule_id=None, filters=None):
"""Search QoS minimum bandwidth rules
:param string policy_name_or_id: Name or ID of the QoS policy to which
rules should be associated.
:param string rule_id: ID of searched rule.
:param filters: a dict containing additional filters to use. e.g.
{'min_kbps': 1000}
:returns: a list of ``munch.Munch`` containing the bandwidth limit
rule descriptions.
:raises: ``OpenStackCloudException`` if something goes wrong during the
OpenStack API call.
"""
rules = self.list_qos_minimum_bandwidth_rules(
policy_name_or_id, filters)
return _utils._filter_list(rules, rule_id, filters)
def list_qos_minimum_bandwidth_rules(self, policy_name_or_id,
filters=None):
"""List all available QoS minimum bandwith rules.
:param string policy_name_or_id: Name or ID of the QoS policy from
from rules should be listed.
:param filters: (optional) dict of filter conditions to push down
:returns: A list of ``munch.Munch`` containing rule info.
:raises: ``OpenStackCloudResourceNotFound`` if QoS policy will not be
found.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud')
policy = self.get_qos_policy(policy_name_or_id)
if not policy:
raise exc.OpenStackCloudResourceNotFound(
"QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id))
# Translate None from search interface to empty {} for kwargs below
if not filters:
filters = {}
data = self._network_client.get(
"/qos/policies/{policy_id}/minimum_bandwidth_rules.json".format(
policy_id=policy['id']),
params=filters,
error_message="Error fetching QoS minimum bandwith rules from "
"{policy}".format(policy=policy['id']))
return self._get_and_munchify('minimum_bandwidth_rules', data)
def get_qos_minimum_bandwidth_rule(self, policy_name_or_id, rule_id):
"""Get a QoS minimum bandwidth rule by name or ID.
:param string policy_name_or_id: Name or ID of the QoS policy to which
rule should be associated.
:param rule_id: ID of the rule.
:returns: A bandwidth limit rule ``munch.Munch`` or None if
no matching rule is found.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud')
policy = self.get_qos_policy(policy_name_or_id)
if not policy:
raise exc.OpenStackCloudResourceNotFound(
"QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id))
data = self._network_client.get(
"/qos/policies/{policy_id}/minimum_bandwidth_rules/{rule_id}.json".
format(policy_id=policy['id'], rule_id=rule_id),
error_message="Error fetching QoS minimum_bandwith rule {rule_id} "
"from {policy}".format(rule_id=rule_id,
policy=policy['id']))
return self._get_and_munchify('minimum_bandwidth_rule', data)
@_utils.valid_kwargs("direction")
def create_qos_minimum_bandwidth_rule(self, policy_name_or_id, min_kbps,
**kwargs):
"""Create a QoS minimum bandwidth limit rule.
:param string policy_name_or_id: Name or ID of the QoS policy to which
rule should be associated.
:param int min_kbps: Minimum bandwidth value (in kilobits per second).
:param string direction: Ingress or egress.
The direction in which the traffic will be available.
:returns: The QoS minimum bandwidth rule.
:raises: OpenStackCloudException on operation error.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud')
policy = self.get_qos_policy(policy_name_or_id)
if not policy:
raise exc.OpenStackCloudResourceNotFound(
"QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id))
kwargs['min_kbps'] = min_kbps
data = self._network_client.post(
"/qos/policies/{policy_id}/minimum_bandwidth_rules".format(
policy_id=policy['id']),
json={'minimum_bandwidth_rule': kwargs})
return self._get_and_munchify('minimum_bandwidth_rule', data)
@_utils.valid_kwargs("min_kbps", "direction")
def update_qos_minimum_bandwidth_rule(self, policy_name_or_id, rule_id,
**kwargs):
"""Update a QoS minimum bandwidth rule.
:param string policy_name_or_id: Name or ID of the QoS policy to which
rule is associated.
:param string rule_id: ID of rule to update.
:param int min_kbps: Minimum bandwidth value (in kilobits per second).
:param string direction: Ingress or egress.
The direction in which the traffic will be available.
:returns: The updated QoS minimum bandwidth rule.
:raises: OpenStackCloudException on operation error.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud')
policy = self.get_qos_policy(policy_name_or_id)
if not policy:
raise exc.OpenStackCloudResourceNotFound(
"QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id))
if not kwargs:
self.log.debug("No QoS minimum bandwidth rule data to update")
return
curr_rule = self.get_qos_minimum_bandwidth_rule(
policy_name_or_id, rule_id)
if not curr_rule:
raise exc.OpenStackCloudException(
"QoS minimum_bandwidth_rule {rule_id} not found in policy "
"{policy_id}".format(rule_id=rule_id,
policy_id=policy['id']))
data = self._network_client.put(
"/qos/policies/{policy_id}/minimum_bandwidth_rules/{rule_id}.json".
format(policy_id=policy['id'], rule_id=rule_id),
json={'minimum_bandwidth_rule': kwargs})
return self._get_and_munchify('minimum_bandwidth_rule', data)
def delete_qos_minimum_bandwidth_rule(self, policy_name_or_id, rule_id):
"""Delete a QoS minimum bandwidth rule.
:param string policy_name_or_id: Name or ID of the QoS policy to which
rule is associated.
:param string rule_id: ID of rule to delete.
:raises: OpenStackCloudException on operation error.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud')
policy = self.get_qos_policy(policy_name_or_id)
if not policy:
raise exc.OpenStackCloudResourceNotFound(
"QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id))
try:
self._network_client.delete(
"/qos/policies/{policy}/minimum_bandwidth_rules/{rule}.json".
format(policy=policy['id'], rule=rule_id))
except exc.OpenStackCloudURINotFound:
self.log.debug(
"QoS minimum bandwidth rule {rule_id} not found in policy "
"{policy_id}. Ignoring.".format(rule_id=rule_id,
policy_id=policy['id']))
return False
return True
def _build_external_gateway_info(self, ext_gateway_net_id, enable_snat,
ext_fixed_ips):
info = {}
if ext_gateway_net_id:
info['network_id'] = ext_gateway_net_id
# Only send enable_snat if it is explicitly set.
if enable_snat is not None:
info['enable_snat'] = enable_snat
if ext_fixed_ips:
info['external_fixed_ips'] = ext_fixed_ips
if info:
return info
return None
def add_router_interface(self, router, subnet_id=None, port_id=None):
"""Attach a subnet to an internal router interface.
Either a subnet ID or port ID must be specified for the internal
interface. Supplying both will result in an error.
:param dict router: The dict object of the router being changed
:param string subnet_id: The ID of the subnet to use for the interface
:param string port_id: The ID of the port to use for the interface
:returns: A ``munch.Munch`` with the router ID (ID),
subnet ID (subnet_id), port ID (port_id) and tenant ID
(tenant_id).
:raises: OpenStackCloudException on operation error.
"""
json_body = {}
if subnet_id:
json_body['subnet_id'] = subnet_id
if port_id:
json_body['port_id'] = port_id
return self._network_client.put(
"/routers/{router_id}/add_router_interface.json".format(
router_id=router['id']),
json=json_body,
error_message="Error attaching interface to router {0}".format(
router['id']))
def remove_router_interface(self, router, subnet_id=None, port_id=None):
"""Detach a subnet from an internal router interface.
At least one of subnet_id or port_id must be supplied.
If you specify both subnet and port ID, the subnet ID must
correspond to the subnet ID of the first IP address on the port
specified by the port ID. Otherwise an error occurs.
:param dict router: The dict object of the router being changed
:param string subnet_id: The ID of the subnet to use for the interface
:param string port_id: The ID of the port to use for the interface
:returns: None on success
:raises: OpenStackCloudException on operation error.
"""
json_body = {}
if subnet_id:
json_body['subnet_id'] = subnet_id
if port_id:
json_body['port_id'] = port_id
if not json_body:
raise ValueError(
"At least one of subnet_id or port_id must be supplied.")
self._network_client.put(
"/routers/{router_id}/remove_router_interface.json".format(
router_id=router['id']),
json=json_body,
error_message="Error detaching interface from router {0}".format(
router['id']))
def list_router_interfaces(self, router, interface_type=None):
"""List all interfaces for a router.
:param dict router: A router dict object.
:param string interface_type: One of None, "internal", or "external".
Controls whether all, internal interfaces or external interfaces
are returned.
:returns: A list of port ``munch.Munch`` objects.
"""
# Find only router interface and gateway ports, ignore L3 HA ports etc.
router_interfaces = self.search_ports(filters={
'device_id': router['id'],
'device_owner': 'network:router_interface'}
) + self.search_ports(filters={
'device_id': router['id'],
'device_owner': 'network:router_interface_distributed'}
) + self.search_ports(filters={
'device_id': router['id'],
'device_owner': 'network:ha_router_replicated_interface'})
router_gateways = self.search_ports(filters={
'device_id': router['id'],
'device_owner': 'network:router_gateway'})
ports = router_interfaces + router_gateways
if interface_type:
if interface_type == 'internal':
return router_interfaces
if interface_type == 'external':
return router_gateways
return ports
def create_router(self, name=None, admin_state_up=True,
ext_gateway_net_id=None, enable_snat=None,
ext_fixed_ips=None, project_id=None,
availability_zone_hints=None):
"""Create a logical router.
:param string name: The router name.
:param bool admin_state_up: The administrative state of the router.
:param string ext_gateway_net_id: Network ID for the external gateway.
:param bool enable_snat: Enable Source NAT (SNAT) attribute.
:param list ext_fixed_ips:
List of dictionaries of desired IP and/or subnet on the
external network. Example::
[
{
"subnet_id": "8ca37218-28ff-41cb-9b10-039601ea7e6b",
"ip_address": "192.168.10.2"
}
]
:param string project_id: Project ID for the router.
:param list availability_zone_hints: A list of availability zone hints.
:returns: The router object.
:raises: OpenStackCloudException on operation error.
"""
router = {
'admin_state_up': admin_state_up
}
if project_id is not None:
router['tenant_id'] = project_id
if name:
router['name'] = name
ext_gw_info = self._build_external_gateway_info(
ext_gateway_net_id, enable_snat, ext_fixed_ips
)
if ext_gw_info:
router['external_gateway_info'] = ext_gw_info
if availability_zone_hints is not None:
if not isinstance(availability_zone_hints, list):
raise exc.OpenStackCloudException(
"Parameter 'availability_zone_hints' must be a list")
if not self._has_neutron_extension('router_availability_zone'):
raise exc.OpenStackCloudUnavailableExtension(
'router_availability_zone extension is not available on '
'target cloud')
router['availability_zone_hints'] = availability_zone_hints
data = self._network_client.post(
"/routers.json", json={"router": router},
error_message="Error creating router {0}".format(name))
return self._get_and_munchify('router', data)
def update_router(self, name_or_id, name=None, admin_state_up=None,
ext_gateway_net_id=None, enable_snat=None,
ext_fixed_ips=None, routes=None):
"""Update an existing logical router.
:param string name_or_id: The name or UUID of the router to update.
:param string name: The new router name.
:param bool admin_state_up: The administrative state of the router.
:param string ext_gateway_net_id:
The network ID for the external gateway.
:param bool enable_snat: Enable Source NAT (SNAT) attribute.
:param list ext_fixed_ips:
List of dictionaries of desired IP and/or subnet on the
external network. Example::
[
{
"subnet_id": "8ca37218-28ff-41cb-9b10-039601ea7e6b",
"ip_address": "192.168.10.2"
}
]
:param list routes:
A list of dictionaries with destination and nexthop parameters.
Example::
[
{
"destination": "179.24.1.0/24",
"nexthop": "172.24.3.99"
}
]
:returns: The router object.
:raises: OpenStackCloudException on operation error.
"""
router = {}
if name:
router['name'] = name
if admin_state_up is not None:
router['admin_state_up'] = admin_state_up
ext_gw_info = self._build_external_gateway_info(
ext_gateway_net_id, enable_snat, ext_fixed_ips
)
if ext_gw_info:
router['external_gateway_info'] = ext_gw_info
if routes:
if self._has_neutron_extension('extraroute'):
router['routes'] = routes
else:
self.log.warn(
'extra routes extension is not available on target cloud')
if not router:
self.log.debug("No router data to update")
return
curr_router = self.get_router(name_or_id)
if not curr_router:
raise exc.OpenStackCloudException(
"Router %s not found." % name_or_id)
data = self._network_client.put(
"/routers/{router_id}.json".format(router_id=curr_router['id']),
json={"router": router},
error_message="Error updating router {0}".format(name_or_id))
return self._get_and_munchify('router', data)
def delete_router(self, name_or_id):
"""Delete a logical router.
If a name, instead of a unique UUID, is supplied, it is possible
that we could find more than one matching router since names are
not required to be unique. An error will be raised in this case.
:param name_or_id: Name or ID of the router being deleted.
:returns: True if delete succeeded, False otherwise.
:raises: OpenStackCloudException on operation error.
"""
router = self.get_router(name_or_id)
if not router:
self.log.debug("Router %s not found for deleting", name_or_id)
return False
self._network_client.delete(
"/routers/{router_id}.json".format(router_id=router['id']),
error_message="Error deleting router {0}".format(name_or_id))
return True
def get_image_exclude(self, name_or_id, exclude):
for image in self.search_images(name_or_id):
if exclude:
if exclude not in image.name:
return image
else:
return image
return None
def get_image_name(self, image_id, exclude=None):
image = self.get_image_exclude(image_id, exclude)
if image:
return image.name
return None
def get_image_id(self, image_name, exclude=None):
image = self.get_image_exclude(image_name, exclude)
if image:
return image.id
return None
def create_image_snapshot(
self, name, server, wait=False, timeout=3600, **metadata):
"""Create an image by snapshotting an existing server.
..note::
On most clouds this is a cold snapshot - meaning that the server
in question will be shutdown before taking the snapshot. It is
possible that it's a live snapshot - but there is no way to know
as a user, so caveat emptor.
:param name: Name of the image to be created
:param server: Server name or ID or dict representing the server
to be snapshotted
:param wait: If true, waits for image to be created.
:param timeout: Seconds to wait for image creation. None is forever.
:param metadata: Metadata to give newly-created image entity
:returns: A ``munch.Munch`` of the Image object
:raises: OpenStackCloudException if there are problems uploading
"""
if not isinstance(server, dict):
server_obj = self.get_server(server, bare=True)
if not server_obj:
raise exc.OpenStackCloudException(
"Server {server} could not be found and therefore"
" could not be snapshotted.".format(server=server))
server = server_obj
response = self._compute_client.post(
'/servers/{server_id}/action'.format(server_id=server['id']),
json={
"createImage": {
"name": name,
"metadata": metadata,
}
})
# You won't believe it - wait, who am I kidding - of course you will!
# Nova returns the URL of the image created in the Location
# header of the response. (what?) But, even better, the URL it responds
# with has a very good chance of being wrong (it is built from
# nova.conf values that point to internal API servers in any cloud
# large enough to have both public and internal endpoints.
# However, nobody has ever noticed this because novaclient doesn't
# actually use that URL - it extracts the id from the end of
# the url, then returns the id. This leads us to question:
# a) why Nova is going to return a value in a header
# b) why it's going to return data that probably broken
# c) indeed the very nature of the fabric of reality
# Although it fills us with existential dread, we have no choice but
# to follow suit like a lemming being forced over a cliff by evil
# producers from Disney.
# TODO(mordred) Update this to consume json microversion when it is
# available.
# blueprint:remove-create-image-location-header-response
image_id = response.headers['Location'].rsplit('/', 1)[1]
self.list_images.invalidate(self)
image = self.get_image(image_id)
if not wait:
return image
return self.wait_for_image(image, timeout=timeout)
def wait_for_image(self, image, timeout=3600):
image_id = image['id']
for count in _utils._iterate_timeout(
timeout, "Timeout waiting for image to snapshot"):
self.list_images.invalidate(self)
image = self.get_image(image_id)
if not image:
continue
if image['status'] == 'active':
return image
elif image['status'] == 'error':
raise exc.OpenStackCloudException(
'Image {image} hit error state'.format(image=image_id))
def delete_image(
self, name_or_id, wait=False, timeout=3600, delete_objects=True):
"""Delete an existing image.
:param name_or_id: Name of the image to be deleted.
:param wait: If True, waits for image to be deleted.
:param timeout: Seconds to wait for image deletion. None is forever.
:param delete_objects: If True, also deletes uploaded swift objects.
:returns: True if delete succeeded, False otherwise.
:raises: OpenStackCloudException if there are problems deleting.
"""
image = self.get_image(name_or_id)
if not image:
return False
self._image_client.delete(
'/images/{id}'.format(id=image.id),
error_message="Error in deleting image")
self.list_images.invalidate(self)
# Task API means an image was uploaded to swift
if self.image_api_use_tasks and IMAGE_OBJECT_KEY in image:
(container, objname) = image[IMAGE_OBJECT_KEY].split('/', 1)
self.delete_object(container=container, name=objname)
if wait:
for count in _utils._iterate_timeout(
timeout,
"Timeout waiting for the image to be deleted."):
self._get_cache(None).invalidate()
if self.get_image(image.id) is None:
break
return True
def _get_name_and_filename(self, name):
# See if name points to an existing file
if os.path.exists(name):
# Neat. Easy enough
return (os.path.splitext(os.path.basename(name))[0], name)
# Try appending the disk format
name_with_ext = '.'.join((
name, self.cloud_config.config['image_format']))
if os.path.exists(name_with_ext):
return (os.path.basename(name), name_with_ext)
raise exc.OpenStackCloudException(
'No filename parameter was given to create_image,'
' and {name} was not the path to an existing file.'
' Please provide either a path to an existing file'
' or a name and a filename'.format(name=name))
def _hashes_up_to_date(self, md5, sha256, md5_key, sha256_key):
'''Compare md5 and sha256 hashes for being up to date
md5 and sha256 are the current values.
md5_key and sha256_key are the previous values.
'''
up_to_date = False
if md5 and md5_key == md5:
up_to_date = True
if sha256 and sha256_key == sha256:
up_to_date = True
if md5 and md5_key != md5:
up_to_date = False
if sha256 and sha256_key != sha256:
up_to_date = False
return up_to_date
def create_image(
self, name, filename=None, container=OBJECT_AUTOCREATE_CONTAINER,
md5=None, sha256=None,
disk_format=None, container_format=None,
disable_vendor_agent=True,
wait=False, timeout=3600,
allow_duplicates=False, meta=None, volume=None, **kwargs):
"""Upload an image.
:param str name: Name of the image to create. If it is a pathname
of an image, the name will be constructed from the
extensionless basename of the path.
:param str filename: The path to the file to upload, if needed.
(optional, defaults to None)
:param str container: Name of the container in swift where images
should be uploaded for import if the cloud
requires such a thing. (optiona, defaults to
'images')
:param str md5: md5 sum of the image file. If not given, an md5 will
be calculated.
:param str sha256: sha256 sum of the image file. If not given, an md5
will be calculated.
:param str disk_format: The disk format the image is in. (optional,
defaults to the os-client-config config value
for this cloud)
:param str container_format: The container format the image is in.
(optional, defaults to the
os-client-config config value for this
cloud)
:param bool disable_vendor_agent: Whether or not to append metadata
flags to the image to inform the
cloud in question to not expect a
vendor agent to be runing.
(optional, defaults to True)
:param bool wait: If true, waits for image to be created. Defaults to
true - however, be aware that one of the upload
methods is always synchronous.
:param timeout: Seconds to wait for image creation. None is forever.
:param allow_duplicates: If true, skips checks that enforce unique
image name. (optional, defaults to False)
:param meta: A dict of key/value pairs to use for metadata that
bypasses automatic type conversion.
:param volume: Name or ID or volume object of a volume to create an
image from. Mutually exclusive with (optional, defaults
to None)
Additional kwargs will be passed to the image creation as additional
metadata for the image and will have all values converted to string
except for min_disk, min_ram, size and virtual_size which will be
converted to int.
If you are sure you have all of your data types correct or have an
advanced need to be explicit, use meta. If you are just a normal
consumer, using kwargs is likely the right choice.
If a value is in meta and kwargs, meta wins.
:returns: A ``munch.Munch`` of the Image object
:raises: OpenStackCloudException if there are problems uploading
"""
if not meta:
meta = {}
if not disk_format:
disk_format = self.cloud_config.config['image_format']
if not container_format:
# https://docs.openstack.org/image-guide/image-formats.html
container_format = 'bare'
if volume:
if 'id' in volume:
volume_id = volume['id']
else:
volume_obj = self.get_volume(volume)
if not volume_obj:
raise exc.OpenStackCloudException(
"Volume {volume} given to create_image could"
" not be foud".format(volume=volume))
volume_id = volume_obj['id']
return self._upload_image_from_volume(
name=name, volume_id=volume_id,
allow_duplicates=allow_duplicates,
container_format=container_format, disk_format=disk_format,
wait=wait, timeout=timeout)
# If there is no filename, see if name is actually the filename
if not filename:
name, filename = self._get_name_and_filename(name)
if not (md5 or sha256):
(md5, sha256) = self._get_file_hashes(filename)
if allow_duplicates:
current_image = None
else:
current_image = self.get_image(name)
if current_image:
md5_key = current_image.get(IMAGE_MD5_KEY, '')
sha256_key = current_image.get(IMAGE_SHA256_KEY, '')
up_to_date = self._hashes_up_to_date(
md5=md5, sha256=sha256,
md5_key=md5_key, sha256_key=sha256_key)
if up_to_date:
self.log.debug(
"image %(name)s exists and is up to date",
{'name': name})
return current_image
kwargs[IMAGE_MD5_KEY] = md5 or ''
kwargs[IMAGE_SHA256_KEY] = sha256 or ''
kwargs[IMAGE_OBJECT_KEY] = '/'.join([container, name])
if disable_vendor_agent:
kwargs.update(self.cloud_config.config['disable_vendor_agent'])
# We can never have nice things. Glance v1 took "is_public" as a
# boolean. Glance v2 takes "visibility". If the user gives us
# is_public, we know what they mean. If they give us visibility, they
# know that they mean.
if self._is_client_version('image', 2):
if 'is_public' in kwargs:
is_public = kwargs.pop('is_public')
if is_public:
kwargs['visibility'] = 'public'
else:
kwargs['visibility'] = 'private'
try:
# This makes me want to die inside
if self.image_api_use_tasks:
return self._upload_image_task(
name, filename, container,
current_image=current_image,
wait=wait, timeout=timeout,
md5=md5, sha256=sha256,
meta=meta, **kwargs)
else:
# If a user used the v1 calling format, they will have
# passed a dict called properties along
properties = kwargs.pop('properties', {})
kwargs.update(properties)
image_kwargs = dict(properties=kwargs)
if disk_format:
image_kwargs['disk_format'] = disk_format
if container_format:
image_kwargs['container_format'] = container_format
return self._upload_image_put(
name, filename, meta=meta,
wait=wait, timeout=timeout,
**image_kwargs)
except exc.OpenStackCloudException:
self.log.debug("Image creation failed", exc_info=True)
raise
except Exception as e:
raise exc.OpenStackCloudException(
"Image creation failed: {message}".format(message=str(e)))
def _make_v2_image_params(self, meta, properties):
ret = {}
for k, v in iter(properties.items()):
if k in ('min_disk', 'min_ram', 'size', 'virtual_size'):
ret[k] = int(v)
elif k == 'protected':
ret[k] = v
else:
if v is None:
ret[k] = None
else:
ret[k] = str(v)
ret.update(meta)
return ret
def _upload_image_from_volume(
self, name, volume_id, allow_duplicates,
container_format, disk_format, wait, timeout):
data = self._volume_client.post(
'/volumes/{id}/action'.format(id=volume_id),
json={
'os-volume_upload_image': {
'force': allow_duplicates,
'image_name': name,
'container_format': container_format,
'disk_format': disk_format}})
response = self._get_and_munchify('os-volume_upload_image', data)
if not wait:
return self.get_image(response['image_id'])
try:
for count in _utils._iterate_timeout(
timeout,
"Timeout waiting for the image to finish."):
image_obj = self.get_image(response['image_id'])
if image_obj and image_obj.status not in ('queued', 'saving'):
return image_obj
except exc.OpenStackCloudTimeout:
self.log.debug(
"Timeout waiting for image to become ready. Deleting.")
self.delete_image(response['image_id'], wait=True)
raise
def _upload_image_put_v2(self, name, image_data, meta, **image_kwargs):
properties = image_kwargs.pop('properties', {})
image_kwargs.update(self._make_v2_image_params(meta, properties))
image_kwargs['name'] = name
data = self._image_client.post('/images', json=image_kwargs)
image = self._get_and_munchify(key=None, data=data)
try:
self._image_client.put(
'/images/{id}/file'.format(id=image.id),
headers={'Content-Type': 'application/octet-stream'},
data=image_data)
except Exception:
self.log.debug("Deleting failed upload of image %s", name)
try:
self._image_client.delete(
'/images/{id}'.format(id=image.id))
except exc.OpenStackCloudHTTPError:
# We're just trying to clean up - if it doesn't work - shrug
self.log.debug(
"Failed deleting image after we failed uploading it.",
exc_info=True)
raise
return image
def _upload_image_put_v1(
self, name, image_data, meta, **image_kwargs):
image_kwargs['properties'].update(meta)
image_kwargs['name'] = name
image = self._get_and_munchify(
'image',
self._image_client.post('/images', json=image_kwargs))
checksum = image_kwargs['properties'].get(IMAGE_MD5_KEY, '')
try:
# Let us all take a brief moment to be grateful that this
# is not actually how OpenStack APIs work anymore
headers = {
'x-glance-registry-purge-props': 'false',
}
if checksum:
headers['x-image-meta-checksum'] = checksum
image = self._get_and_munchify(
'image',
self._image_client.put(
'/images/{id}'.format(id=image.id),
headers=headers, data=image_data))
except exc.OpenStackCloudHTTPError:
self.log.debug("Deleting failed upload of image %s", name)
try:
self._image_client.delete(
'/images/{id}'.format(id=image.id))
except exc.OpenStackCloudHTTPError:
# We're just trying to clean up - if it doesn't work - shrug
self.log.debug(
"Failed deleting image after we failed uploading it.",
exc_info=True)
raise
return self._normalize_image(image)
def _upload_image_put(
self, name, filename, meta, wait, timeout, **image_kwargs):
image_data = open(filename, 'rb')
# Because reasons and crying bunnies
if self._is_client_version('image', 2):
image = self._upload_image_put_v2(
name, image_data, meta, **image_kwargs)
else:
image = self._upload_image_put_v1(
name, image_data, meta, **image_kwargs)
self._get_cache(None).invalidate()
if not wait:
return image
try:
for count in _utils._iterate_timeout(
timeout,
"Timeout waiting for the image to finish."):
image_obj = self.get_image(image.id)
if image_obj and image_obj.status not in ('queued', 'saving'):
return image_obj
except exc.OpenStackCloudTimeout:
self.log.debug(
"Timeout waiting for image to become ready. Deleting.")
self.delete_image(image.id, wait=True)
raise
def _upload_image_task(
self, name, filename, container, current_image,
wait, timeout, meta, md5=None, sha256=None, **image_kwargs):
parameters = image_kwargs.pop('parameters', {})
image_kwargs.update(parameters)
self.create_object(
container, name, filename,
md5=md5, sha256=sha256,
metadata={OBJECT_AUTOCREATE_KEY: 'true'},
**{'content-type': 'application/octet-stream'})
if not current_image:
current_image = self.get_image(name)
# TODO(mordred): Can we do something similar to what nodepool does
# using glance properties to not delete then upload but instead make a
# new "good" image and then mark the old one as "bad"
task_args = dict(
type='import', input=dict(
import_from='{container}/{name}'.format(
container=container, name=name),
image_properties=dict(name=name)))
data = self._image_client.post('/tasks', json=task_args)
glance_task = self._get_and_munchify(key=None, data=data)
self.list_images.invalidate(self)
if wait:
start = time.time()
image_id = None
for count in _utils._iterate_timeout(
timeout,
"Timeout waiting for the image to import."):
try:
if image_id is None:
status = self._image_client.get(
'/tasks/{id}'.format(id=glance_task.id))
except exc.OpenStackCloudHTTPError as e:
if e.response.status_code == 503:
# Clear the exception so that it doesn't linger
# and get reported as an Inner Exception later
_utils._exc_clear()
# Intermittent failure - catch and try again
continue
raise
if status['status'] == 'success':
image_id = status['result']['image_id']
try:
image = self.get_image(image_id)
except exc.OpenStackCloudHTTPError as e:
if e.response.status_code == 503:
# Clear the exception so that it doesn't linger
# and get reported as an Inner Exception later
_utils._exc_clear()
# Intermittent failure - catch and try again
continue
raise
if image is None:
continue
self.update_image_properties(
image=image, meta=meta, **image_kwargs)
self.log.debug(
"Image Task %s imported %s in %s",
glance_task.id, image_id, (time.time() - start))
# Clean up after ourselves. The object we created is not
# needed after the import is done.
self.delete_object(container, name)
return self.get_image(image_id)
elif status['status'] == 'failure':
if status['message'] == IMAGE_ERROR_396:
glance_task = self._image_client.post(
'/tasks', data=task_args)
self.list_images.invalidate(self)
else:
# Clean up after ourselves. The image did not import
# and this isn't a 'just retry' error - glance didn't
# like the content. So we don't want to keep it for
# next time.
self.delete_object(container, name)
raise exc.OpenStackCloudException(
"Image creation failed: {message}".format(
message=status['message']),
extra_data=status)
else:
return glance_task
def update_image_properties(
self, image=None, name_or_id=None, meta=None, **properties):
if image is None:
image = self.get_image(name_or_id)
if not meta:
meta = {}
img_props = {}
for k, v in iter(properties.items()):
if v and k in ['ramdisk', 'kernel']:
v = self.get_image_id(v)
k = '{0}_id'.format(k)
img_props[k] = v
# This makes me want to die inside
if self._is_client_version('image', 2):
return self._update_image_properties_v2(image, meta, img_props)
else:
return self._update_image_properties_v1(image, meta, img_props)
def _update_image_properties_v2(self, image, meta, properties):
img_props = image.properties.copy()
for k, v in iter(self._make_v2_image_params(meta, properties).items()):
if image.get(k, None) != v:
img_props[k] = v
if not img_props:
return False
headers = {
'Content-Type': 'application/openstack-images-v2.1-json-patch'}
patch = sorted(list(jsonpatch.JsonPatch.from_diff(
image.properties, img_props)), key=operator.itemgetter('value'))
# No need to fire an API call if there is an empty patch
if patch:
self._image_client.patch(
'/images/{id}'.format(id=image.id),
headers=headers,
data=json.dumps(patch))
self.list_images.invalidate(self)
return True
def _update_image_properties_v1(self, image, meta, properties):
properties.update(meta)
img_props = {}
for k, v in iter(properties.items()):
if image.properties.get(k, None) != v:
img_props['x-image-meta-{key}'.format(key=k)] = v
if not img_props:
return False
self._image_client.put(
'/images/{id}'.format(image.id), headers=img_props)
self.list_images.invalidate(self)
return True
def create_volume(
self, size,
wait=True, timeout=None, image=None, bootable=None, **kwargs):
"""Create a volume.
:param size: Size, in GB of the volume to create.
:param name: (optional) Name for the volume.
:param description: (optional) Name for the volume.
:param wait: If true, waits for volume to be created.
:param timeout: Seconds to wait for volume creation. None is forever.
:param image: (optional) Image name, ID or object from which to create
the volume
:param bootable: (optional) Make this volume bootable. If set, wait
will also be set to true.
:param kwargs: Keyword arguments as expected for cinder client.
:returns: The created volume object.
:raises: OpenStackCloudTimeout if wait time exceeded.
:raises: OpenStackCloudException on operation error.
"""
if bootable is not None:
wait = True
if image:
image_obj = self.get_image(image)
if not image_obj:
raise exc.OpenStackCloudException(
"Image {image} was requested as the basis for a new"
" volume, but was not found on the cloud".format(
image=image))
kwargs['imageRef'] = image_obj['id']
kwargs = self._get_volume_kwargs(kwargs)
kwargs['size'] = size
payload = dict(volume=kwargs)
if 'scheduler_hints' in kwargs:
payload['OS-SCH-HNT:scheduler_hints'] = kwargs.pop(
'scheduler_hints', None)
data = self._volume_client.post(
'/volumes',
json=dict(payload),
error_message='Error in creating volume')
volume = self._get_and_munchify('volume', data)
self.list_volumes.invalidate(self)
if volume['status'] == 'error':
raise exc.OpenStackCloudException("Error in creating volume")
if wait:
vol_id = volume['id']
for count in _utils._iterate_timeout(
timeout,
"Timeout waiting for the volume to be available."):
volume = self.get_volume(vol_id)
if not volume:
continue
if volume['status'] == 'available':
if bootable is not None:
self.set_volume_bootable(volume, bootable=bootable)
# no need to re-fetch to update the flag, just set it.
volume['bootable'] = bootable
return volume
if volume['status'] == 'error':
raise exc.OpenStackCloudException(
"Error in creating volume")
return self._normalize_volume(volume)
def set_volume_bootable(self, name_or_id, bootable=True):
"""Set a volume's bootable flag.
:param name_or_id: Name, unique ID of the volume or a volume dict.
:param bool bootable: Whether the volume should be bootable.
(Defaults to True)
:raises: OpenStackCloudTimeout if wait time exceeded.
:raises: OpenStackCloudException on operation error.
"""
volume = self.get_volume(name_or_id)
if not volume:
raise exc.OpenStackCloudException(
"Volume {name_or_id} does not exist".format(
name_or_id=name_or_id))
self._volume_client.post(
'volumes/{id}/action'.format(id=volume['id']),
json={'os-set_bootable': {'bootable': bootable}},
error_message="Error setting bootable on volume {volume}".format(
volume=volume['id'])
)
def delete_volume(self, name_or_id=None, wait=True, timeout=None,
force=False):
"""Delete a volume.
:param name_or_id: Name or unique ID of the volume.
:param wait: If true, waits for volume to be deleted.
:param timeout: Seconds to wait for volume deletion. None is forever.
:param force: Force delete volume even if the volume is in deleting
or error_deleting state.
:raises: OpenStackCloudTimeout if wait time exceeded.
:raises: OpenStackCloudException on operation error.
"""
self.list_volumes.invalidate(self)
volume = self.get_volume(name_or_id)
if not volume:
self.log.debug(
"Volume %(name_or_id)s does not exist",
{'name_or_id': name_or_id},
exc_info=True)
return False
with _utils.shade_exceptions("Error in deleting volume"):
try:
if force:
self._volume_client.post(
'volumes/{id}/action'.format(id=volume['id']),
json={'os-force_delete': None})
else:
self._volume_client.delete(
'volumes/{id}'.format(id=volume['id']))
except exc.OpenStackCloudURINotFound:
self.log.debug(
"Volume {id} not found when deleting. Ignoring.".format(
id=volume['id']))
return False
self.list_volumes.invalidate(self)
if wait:
for count in _utils._iterate_timeout(
timeout,
"Timeout waiting for the volume to be deleted."):
if not self.get_volume(volume['id']):
break
return True
def get_volumes(self, server, cache=True):
volumes = []
for volume in self.list_volumes(cache=cache):
for attach in volume['attachments']:
if attach['server_id'] == server['id']:
volumes.append(volume)
return volumes
def get_volume_limits(self, name_or_id=None):
""" Get volume limits for a project
:param name_or_id: (optional) project name or ID to get limits for
if different from the current project
:raises: OpenStackCloudException if it's not a valid project
:returns: Munch object with the limits
"""
params = {}
project_id = None
error_msg = "Failed to get limits"
if name_or_id:
proj = self.get_project(name_or_id)
if not proj:
raise exc.OpenStackCloudException("project does not exist")
project_id = proj.id
params['tenant_id'] = project_id
error_msg = "{msg} for the project: {project} ".format(
msg=error_msg, project=name_or_id)
data = self._volume_client.get('/limits', params=params)
limits = self._get_and_munchify('limits', data)
return limits
def get_volume_id(self, name_or_id):
volume = self.get_volume(name_or_id)
if volume:
return volume['id']
return None
def volume_exists(self, name_or_id):
return self.get_volume(name_or_id) is not None
def get_volume_attach_device(self, volume, server_id):
"""Return the device name a volume is attached to for a server.
This can also be used to verify if a volume is attached to
a particular server.
:param volume: Volume dict
:param server_id: ID of server to check
:returns: Device name if attached, None if volume is not attached.
"""
for attach in volume['attachments']:
if server_id == attach['server_id']:
return attach['device']
return None
def detach_volume(self, server, volume, wait=True, timeout=None):
"""Detach a volume from a server.
:param server: The server dict to detach from.
:param volume: The volume dict to detach.
:param wait: If true, waits for volume to be detached.
:param timeout: Seconds to wait for volume detachment. None is forever.
:raises: OpenStackCloudTimeout if wait time exceeded.
:raises: OpenStackCloudException on operation error.
"""
self._compute_client.delete(
'/servers/{server_id}/os-volume_attachments/{volume_id}'.format(
server_id=server['id'], volume_id=volume['id']),
error_message=(
"Error detaching volume {volume} from server {server}".format(
volume=volume['id'], server=server['id'])))
if wait:
for count in _utils._iterate_timeout(
timeout,
"Timeout waiting for volume %s to detach." % volume['id']):
try:
vol = self.get_volume(volume['id'])
except Exception:
self.log.debug(
"Error getting volume info %s", volume['id'],
exc_info=True)
continue
if vol['status'] == 'available':
return
if vol['status'] == 'error':
raise exc.OpenStackCloudException(
"Error in detaching volume %s" % volume['id']
)
def attach_volume(self, server, volume, device=None,
wait=True, timeout=None):
"""Attach a volume to a server.
This will attach a volume, described by the passed in volume
dict (as returned by get_volume()), to the server described by
the passed in server dict (as returned by get_server()) on the
named device on the server.
If the volume is already attached to the server, or generally not
available, then an exception is raised. To re-attach to a server,
but under a different device, the user must detach it first.
:param server: The server dict to attach to.
:param volume: The volume dict to attach.
:param device: The device name where the volume will attach.
:param wait: If true, waits for volume to be attached.
:param timeout: Seconds to wait for volume attachment. None is forever.
:returns: a volume attachment object.
:raises: OpenStackCloudTimeout if wait time exceeded.
:raises: OpenStackCloudException on operation error.
"""
dev = self.get_volume_attach_device(volume, server['id'])
if dev:
raise exc.OpenStackCloudException(
"Volume %s already attached to server %s on device %s"
% (volume['id'], server['id'], dev)
)
if volume['status'] != 'available':
raise exc.OpenStackCloudException(
"Volume %s is not available. Status is '%s'"
% (volume['id'], volume['status'])
)
payload = {'volumeId': volume['id']}
if device:
payload['device'] = device
data = self._compute_client.post(
'/servers/{server_id}/os-volume_attachments'.format(
server_id=server['id']),
json=dict(volumeAttachment=payload),
error_message="Error attaching volume {volume_id} to server "
"{server_id}".format(volume_id=volume['id'],
server_id=server['id']))
if wait:
for count in _utils._iterate_timeout(
timeout,
"Timeout waiting for volume %s to attach." % volume['id']):
try:
self.list_volumes.invalidate(self)
vol = self.get_volume(volume['id'])
except Exception:
self.log.debug(
"Error getting volume info %s", volume['id'],
exc_info=True)
continue
if self.get_volume_attach_device(vol, server['id']):
break
# TODO(Shrews) check to see if a volume can be in error status
# and also attached. If so, we should move this
# above the get_volume_attach_device call
if vol['status'] == 'error':
raise exc.OpenStackCloudException(
"Error in attaching volume %s" % volume['id']
)
return self._normalize_volume_attachment(
self._get_and_munchify('volumeAttachment', data))
def _get_volume_kwargs(self, kwargs):
name = kwargs.pop('name', kwargs.pop('display_name', None))
description = kwargs.pop('description',
kwargs.pop('display_description', None))
if name:
if self._is_client_version('volume', 2):
kwargs['name'] = name
else:
kwargs['display_name'] = name
if description:
if self._is_client_version('volume', 2):
kwargs['description'] = description
else:
kwargs['display_description'] = description
return kwargs
@_utils.valid_kwargs('name', 'display_name',
'description', 'display_description')
def create_volume_snapshot(self, volume_id, force=False,
wait=True, timeout=None, **kwargs):
"""Create a volume.
:param volume_id: the ID of the volume to snapshot.
:param force: If set to True the snapshot will be created even if the
volume is attached to an instance, if False it will not
:param name: name of the snapshot, one will be generated if one is
not provided
:param description: description of the snapshot, one will be generated
if one is not provided
:param wait: If true, waits for volume snapshot to be created.
:param timeout: Seconds to wait for volume snapshot creation. None is
forever.
:returns: The created volume object.
:raises: OpenStackCloudTimeout if wait time exceeded.
:raises: OpenStackCloudException on operation error.
"""
kwargs = self._get_volume_kwargs(kwargs)
payload = {'volume_id': volume_id, 'force': force}
payload.update(kwargs)
data = self._volume_client.post(
'/snapshots',
json=dict(snapshot=payload),
error_message="Error creating snapshot of volume "
"{volume_id}".format(volume_id=volume_id))
snapshot = self._get_and_munchify('snapshot', data)
if wait:
snapshot_id = snapshot['id']
for count in _utils._iterate_timeout(
timeout,
"Timeout waiting for the volume snapshot to be available."
):
snapshot = self.get_volume_snapshot_by_id(snapshot_id)
if snapshot['status'] == 'available':
break
if snapshot['status'] == 'error':
raise exc.OpenStackCloudException(
"Error in creating volume snapshot")
# TODO(mordred) need to normalize snapshots. We were normalizing them
# as volumes, which is an error. They need to be normalized as
# volume snapshots, which are completely different objects
return snapshot
def get_volume_snapshot_by_id(self, snapshot_id):
"""Takes a snapshot_id and gets a dict of the snapshot
that maches that ID.
Note: This is more efficient than get_volume_snapshot.
param: snapshot_id: ID of the volume snapshot.
"""
data = self._volume_client.get(
'/snapshots/{snapshot_id}'.format(snapshot_id=snapshot_id),
error_message="Error getting snapshot "
"{snapshot_id}".format(snapshot_id=snapshot_id))
return self._normalize_volume(
self._get_and_munchify('snapshot', data))
def get_volume_snapshot(self, name_or_id, filters=None):
"""Get a volume by name or ID.
:param name_or_id: Name or ID of the volume snapshot.
:param filters:
A dictionary of meta data to use for further filtering. Elements
of this dictionary may, themselves, be dictionaries. Example::
{
'last_name': 'Smith',
'other': {
'gender': 'Female'
}
}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A volume ``munch.Munch`` or None if no matching volume is
found.
"""
return _utils._get_entity(self, 'volume_snapshot', name_or_id,
filters)
def create_volume_backup(self, volume_id, name=None, description=None,
force=False, wait=True, timeout=None):
"""Create a volume backup.
:param volume_id: the ID of the volume to backup.
:param name: name of the backup, one will be generated if one is
not provided
:param description: description of the backup, one will be generated
if one is not provided
:param force: If set to True the backup will be created even if the
volume is attached to an instance, if False it will not
:param wait: If true, waits for volume backup to be created.
:param timeout: Seconds to wait for volume backup creation. None is
forever.
:returns: The created volume backup object.
:raises: OpenStackCloudTimeout if wait time exceeded.
:raises: OpenStackCloudException on operation error.
"""
payload = {
'name': name,
'volume_id': volume_id,
'description': description,
'force': force,
}
data = self._volume_client.post(
'/backups', json=dict(backup=payload),
error_message="Error creating backup of volume "
"{volume_id}".format(volume_id=volume_id))
backup = self._get_and_munchify('backup', data)
if wait:
backup_id = backup['id']
msg = ("Timeout waiting for the volume backup {} to be "
"available".format(backup_id))
for _ in _utils._iterate_timeout(timeout, msg):
backup = self.get_volume_backup(backup_id)
if backup['status'] == 'available':
break
if backup['status'] == 'error':
raise exc.OpenStackCloudException(
"Error in creating volume backup {id}".format(
id=backup_id))
return backup
def get_volume_backup(self, name_or_id, filters=None):
"""Get a volume backup by name or ID.
:returns: A backup ``munch.Munch`` or None if no matching backup is
found.
"""
return _utils._get_entity(self, 'volume_backup', name_or_id,
filters)
def list_volume_snapshots(self, detailed=True, search_opts=None):
"""List all volume snapshots.
:returns: A list of volume snapshots ``munch.Munch``.
"""
endpoint = '/snapshots/detail' if detailed else '/snapshots'
data = self._volume_client.get(
endpoint,
params=search_opts,
error_message="Error getting a list of snapshots")
return self._get_and_munchify('snapshots', data)
def list_volume_backups(self, detailed=True, search_opts=None):
"""
List all volume backups.
:param bool detailed: Also list details for each entry
:param dict search_opts: Search options
A dictionary of meta data to use for further filtering. Example::
{
'name': 'my-volume-backup',
'status': 'available',
'volume_id': 'e126044c-7b4c-43be-a32a-c9cbbc9ddb56',
'all_tenants': 1
}
:returns: A list of volume backups ``munch.Munch``.
"""
endpoint = '/backups/detail' if detailed else '/backups'
data = self._volume_client.get(
endpoint, params=search_opts,
error_message="Error getting a list of backups")
return self._get_and_munchify('backups', data)
def delete_volume_backup(self, name_or_id=None, force=False, wait=False,
timeout=None):
"""Delete a volume backup.
:param name_or_id: Name or unique ID of the volume backup.
:param force: Allow delete in state other than error or available.
:param wait: If true, waits for volume backup to be deleted.
:param timeout: Seconds to wait for volume backup deletion. None is
forever.
:raises: OpenStackCloudTimeout if wait time exceeded.
:raises: OpenStackCloudException on operation error.
"""
volume_backup = self.get_volume_backup(name_or_id)
if not volume_backup:
return False
msg = "Error in deleting volume backup"
if force:
self._volume_client.post(
'/backups/{backup_id}/action'.format(
backup_id=volume_backup['id']),
json={'os-force_delete': None},
error_message=msg)
else:
self._volume_client.delete(
'/backups/{backup_id}'.format(
backup_id=volume_backup['id']),
error_message=msg)
if wait:
msg = "Timeout waiting for the volume backup to be deleted."
for count in _utils._iterate_timeout(timeout, msg):
if not self.get_volume_backup(volume_backup['id']):
break
return True
def delete_volume_snapshot(self, name_or_id=None, wait=False,
timeout=None):
"""Delete a volume snapshot.
:param name_or_id: Name or unique ID of the volume snapshot.
:param wait: If true, waits for volume snapshot to be deleted.
:param timeout: Seconds to wait for volume snapshot deletion. None is
forever.
:raises: OpenStackCloudTimeout if wait time exceeded.
:raises: OpenStackCloudException on operation error.
"""
volumesnapshot = self.get_volume_snapshot(name_or_id)
if not volumesnapshot:
return False
self._volume_client.delete(
'/snapshots/{snapshot_id}'.format(
snapshot_id=volumesnapshot['id']),
error_message="Error in deleting volume snapshot")
if wait:
for count in _utils._iterate_timeout(
timeout,
"Timeout waiting for the volume snapshot to be deleted."):
if not self.get_volume_snapshot(volumesnapshot['id']):
break
return True
def get_server_id(self, name_or_id):
server = self.get_server(name_or_id, bare=True)
if server:
return server['id']
return None
def get_server_private_ip(self, server):
return meta.get_server_private_ip(server, self)
def get_server_public_ip(self, server):
return meta.get_server_external_ipv4(self, server)
def get_server_meta(self, server):
# TODO(mordred) remove once ansible has moved to Inventory interface
server_vars = meta.get_hostvars_from_server(self, server)
groups = meta.get_groups_from_server(self, server, server_vars)
return dict(server_vars=server_vars, groups=groups)
def get_openstack_vars(self, server):
return meta.get_hostvars_from_server(self, server)
def _expand_server_vars(self, server):
# Used by nodepool
# TODO(mordred) remove after these make it into what we
# actually want the API to be.
return meta.expand_server_vars(self, server)
def _find_floating_network_by_router(self):
"""Find the network providing floating ips by looking at routers."""
if self._floating_network_by_router_lock.acquire(
not self._floating_network_by_router_run):
if self._floating_network_by_router_run:
self._floating_network_by_router_lock.release()
return self._floating_network_by_router
try:
for router in self.list_routers():
if router['admin_state_up']:
network_id = router.get(
'external_gateway_info', {}).get('network_id')
if network_id:
self._floating_network_by_router = network_id
finally:
self._floating_network_by_router_run = True
self._floating_network_by_router_lock.release()
return self._floating_network_by_router
def available_floating_ip(self, network=None, server=None):
"""Get a floating IP from a network or a pool.
Return the first available floating IP or allocate a new one.
:param network: Name or ID of the network.
:param server: Server the IP is for if known
:returns: a (normalized) structure with a floating IP address
description.
"""
if self._use_neutron_floating():
try:
f_ips = self._normalize_floating_ips(
self._neutron_available_floating_ips(
network=network, server=server))
return f_ips[0]
except exc.OpenStackCloudURINotFound as e:
self.log.debug(
"Something went wrong talking to neutron API: "
"'%(msg)s'. Trying with Nova.", {'msg': str(e)})
# Fall-through, trying with Nova
f_ips = self._normalize_floating_ips(
self._nova_available_floating_ips(pool=network)
)
return f_ips[0]
def _get_floating_network_id(self):
# Get first existing external IPv4 network
networks = self.get_external_ipv4_floating_networks()
if networks:
floating_network_id = networks[0]['id']
else:
floating_network = self._find_floating_network_by_router()
if floating_network:
floating_network_id = floating_network
else:
raise exc.OpenStackCloudResourceNotFound(
"unable to find an external network")
return floating_network_id
def _neutron_available_floating_ips(
self, network=None, project_id=None, server=None):
"""Get a floating IP from a network.
Return a list of available floating IPs or allocate a new one and
return it in a list of 1 element.
:param network: A single network name or ID, or a list of them.
:param server: (server) Server the Floating IP is for
:returns: a list of floating IP addresses.
:raises: ``OpenStackCloudResourceNotFound``, if an external network
that meets the specified criteria cannot be found.
"""
if project_id is None:
# Make sure we are only listing floatingIPs allocated the current
# tenant. This is the default behaviour of Nova
project_id = self.current_project_id
if network:
if isinstance(network, six.string_types):
network = [network]
# Use given list to get first matching external network
floating_network_id = None
for net in network:
for ext_net in self.get_external_ipv4_floating_networks():
if net in (ext_net['name'], ext_net['id']):
floating_network_id = ext_net['id']
break
if floating_network_id:
break
if floating_network_id is None:
raise exc.OpenStackCloudResourceNotFound(
"unable to find external network {net}".format(
net=network)
)
else:
floating_network_id = self._get_floating_network_id()
filters = {
'port': None,
'network': floating_network_id,
'location': {'project': {'id': project_id}},
}
floating_ips = self._list_floating_ips()
available_ips = _utils._filter_list(
floating_ips, name_or_id=None, filters=filters)
if available_ips:
return available_ips
# No available IP found or we didn't try
# allocate a new Floating IP
f_ip = self._neutron_create_floating_ip(
network_id=floating_network_id, server=server)
return [f_ip]
def _nova_available_floating_ips(self, pool=None):
"""Get available floating IPs from a floating IP pool.
Return a list of available floating IPs or allocate a new one and
return it in a list of 1 element.
:param pool: Nova floating IP pool name.
:returns: a list of floating IP addresses.
:raises: ``OpenStackCloudResourceNotFound``, if a floating IP pool
is not specified and cannot be found.
"""
with _utils.shade_exceptions(
"Unable to create floating IP in pool {pool}".format(
pool=pool)):
if pool is None:
pools = self.list_floating_ip_pools()
if not pools:
raise exc.OpenStackCloudResourceNotFound(
"unable to find a floating ip pool")
pool = pools[0]['name']
filters = {
'instance_id': None,
'pool': pool
}
floating_ips = self._nova_list_floating_ips()
available_ips = _utils._filter_list(
floating_ips, name_or_id=None, filters=filters)
if available_ips:
return available_ips
# No available IP found or we did not try.
# Allocate a new Floating IP
f_ip = self._nova_create_floating_ip(pool=pool)
return [f_ip]
def create_floating_ip(self, network=None, server=None,
fixed_address=None, nat_destination=None,
port=None, wait=False, timeout=60):
"""Allocate a new floating IP from a network or a pool.
:param network: Name or ID of the network
that the floating IP should come from.
:param server: (optional) Server dict for the server to create
the IP for and to which it should be attached.
:param fixed_address: (optional) Fixed IP to attach the floating
ip to.
:param nat_destination: (optional) Name or ID of the network
that the fixed IP to attach the floating
IP to should be on.
:param port: (optional) The port ID that the floating IP should be
attached to. Specifying a port conflicts
with specifying a server, fixed_address or
nat_destination.
:param wait: (optional) Whether to wait for the IP to be active.
Defaults to False. Only applies if a server is
provided.
:param timeout: (optional) How long to wait for the IP to be active.
Defaults to 60. Only applies if a server is
provided.
:returns: a floating IP address
:raises: ``OpenStackCloudException``, on operation error.
"""
if self._use_neutron_floating():
try:
return self._neutron_create_floating_ip(
network_name_or_id=network, server=server,
fixed_address=fixed_address,
nat_destination=nat_destination,
port=port,
wait=wait, timeout=timeout)
except exc.OpenStackCloudURINotFound as e:
self.log.debug(
"Something went wrong talking to neutron API: "
"'%(msg)s'. Trying with Nova.", {'msg': str(e)})
# Fall-through, trying with Nova
if port:
raise exc.OpenStackCloudException(
"This cloud uses nova-network which does not support"
" arbitrary floating-ip/port mappings. Please nudge"
" your cloud provider to upgrade the networking stack"
" to neutron, or alternately provide the server,"
" fixed_address and nat_destination arguments as appropriate")
# Else, we are using Nova network
f_ips = self._normalize_floating_ips(
[self._nova_create_floating_ip(pool=network)])
return f_ips[0]
def _submit_create_fip(self, kwargs):
# Split into a method to aid in test mocking
data = self._network_client.post(
"/floatingips.json", json={"floatingip": kwargs})
return self._normalize_floating_ip(
self._get_and_munchify('floatingip', data))
def _neutron_create_floating_ip(
self, network_name_or_id=None, server=None,
fixed_address=None, nat_destination=None,
port=None,
wait=False, timeout=60, network_id=None):
if not network_id:
if network_name_or_id:
network = self.get_network(network_name_or_id)
if not network:
raise exc.OpenStackCloudResourceNotFound(
"unable to find network for floating ips with ID "
"{0}".format(network_name_or_id))
network_id = network['id']
else:
network_id = self._get_floating_network_id()
kwargs = {
'floating_network_id': network_id,
}
if not port:
if server:
(port_obj, fixed_ip_address) = self._nat_destination_port(
server, fixed_address=fixed_address,
nat_destination=nat_destination)
if port_obj:
port = port_obj['id']
if fixed_ip_address:
kwargs['fixed_ip_address'] = fixed_ip_address
if port:
kwargs['port_id'] = port
fip = self._submit_create_fip(kwargs)
fip_id = fip['id']
if port:
# The FIP is only going to become active in this context
# when we've attached it to something, which only occurs
# if we've provided a port as a parameter
if wait:
try:
for count in _utils._iterate_timeout(
timeout,
"Timeout waiting for the floating IP"
" to be ACTIVE",
wait=self._FLOAT_AGE):
fip = self.get_floating_ip(fip_id)
if fip and fip['status'] == 'ACTIVE':
break
except exc.OpenStackCloudTimeout:
self.log.error(
"Timed out on floating ip %(fip)s becoming active."
" Deleting", {'fip': fip_id})
try:
self.delete_floating_ip(fip_id)
except Exception as e:
self.log.error(
"FIP LEAK: Attempted to delete floating ip "
"%(fip)s but received %(exc)s exception: "
"%(err)s", {'fip': fip_id, 'exc': e.__class__,
'err': str(e)})
raise
if fip['port_id'] != port:
if server:
raise exc.OpenStackCloudException(
"Attempted to create FIP on port {port} for server"
" {server} but FIP has port {port_id}".format(
port=port, port_id=fip['port_id'],
server=server['id']))
else:
raise exc.OpenStackCloudException(
"Attempted to create FIP on port {port}"
" but something went wrong".format(port=port))
return fip
def _nova_create_floating_ip(self, pool=None):
with _utils.shade_exceptions(
"Unable to create floating IP in pool {pool}".format(
pool=pool)):
if pool is None:
pools = self.list_floating_ip_pools()
if not pools:
raise exc.OpenStackCloudResourceNotFound(
"unable to find a floating ip pool")
pool = pools[0]['name']
data = self._compute_client.post(
'/os-floating-ips', json=dict(pool=pool))
pool_ip = self._get_and_munchify('floating_ip', data)
# TODO(mordred) Remove this - it's just for compat
data = self._compute_client.get('/os-floating-ips/{id}'.format(
id=pool_ip['id']))
return self._get_and_munchify('floating_ip', data)
def delete_floating_ip(self, floating_ip_id, retry=1):
"""Deallocate a floating IP from a project.
:param floating_ip_id: a floating IP address ID.
:param retry: number of times to retry. Optional, defaults to 1,
which is in addition to the initial delete call.
A value of 0 will also cause no checking of results to
occur.
:returns: True if the IP address has been deleted, False if the IP
address was not found.
:raises: ``OpenStackCloudException``, on operation error.
"""
for count in range(0, max(0, retry) + 1):
result = self._delete_floating_ip(floating_ip_id)
if (retry == 0) or not result:
return result
# Wait for the cached floating ip list to be regenerated
if self._FLOAT_AGE:
time.sleep(self._FLOAT_AGE)
# neutron sometimes returns success when deleting a floating
# ip. That's awesome. SO - verify that the delete actually
# worked. Some clouds will set the status to DOWN rather than
# deleting the IP immediately. This is, of course, a bit absurd.
f_ip = self.get_floating_ip(id=floating_ip_id)
if not f_ip or f_ip['status'] == 'DOWN':
return True
raise exc.OpenStackCloudException(
"Attempted to delete Floating IP {ip} with ID {id} a total of"
" {retry} times. Although the cloud did not indicate any errors"
" the floating ip is still in existence. Aborting further"
" operations.".format(
id=floating_ip_id, ip=f_ip['floating_ip_address'],
retry=retry + 1))
def _delete_floating_ip(self, floating_ip_id):
if self._use_neutron_floating():
try:
return self._neutron_delete_floating_ip(floating_ip_id)
except exc.OpenStackCloudURINotFound as e:
self.log.debug(
"Something went wrong talking to neutron API: "
"'%(msg)s'. Trying with Nova.", {'msg': str(e)})
return self._nova_delete_floating_ip(floating_ip_id)
def _neutron_delete_floating_ip(self, floating_ip_id):
try:
self._network_client.delete(
"/floatingips/{fip_id}.json".format(fip_id=floating_ip_id),
error_message="unable to delete floating IP")
except exc.OpenStackCloudResourceNotFound:
return False
except Exception as e:
raise exc.OpenStackCloudException(
"Unable to delete floating IP ID {fip_id}: {msg}".format(
fip_id=floating_ip_id, msg=str(e)))
return True
def _nova_delete_floating_ip(self, floating_ip_id):
try:
self._compute_client.delete(
'/os-floating-ips/{id}'.format(id=floating_ip_id),
error_message='Unable to delete floating IP {fip_id}'.format(
fip_id=floating_ip_id))
except exc.OpenStackCloudURINotFound:
return False
return True
def delete_unattached_floating_ips(self, retry=1):
"""Safely delete unattached floating ips.
If the cloud can safely purge any unattached floating ips without
race conditions, do so.
Safely here means a specific thing. It means that you are not running
this while another process that might do a two step create/attach
is running. You can safely run this method while another process
is creating servers and attaching floating IPs to them if either that
process is using add_auto_ip from shade, or is creating the floating
IPs by passing in a server to the create_floating_ip call.
:param retry: number of times to retry. Optional, defaults to 1,
which is in addition to the initial delete call.
A value of 0 will also cause no checking of results to
occur.
:returns: True if Floating IPs have been deleted, False if not
:raises: ``OpenStackCloudException``, on operation error.
"""
processed = []
if self._use_neutron_floating():
for ip in self.list_floating_ips():
if not ip['attached']:
processed.append(self.delete_floating_ip(
floating_ip_id=ip['id'], retry=retry))
return all(processed) if processed else False
def _attach_ip_to_server(
self, server, floating_ip,
fixed_address=None, wait=False,
timeout=60, skip_attach=False, nat_destination=None):
"""Attach a floating IP to a server.
:param server: Server dict
:param floating_ip: Floating IP dict to attach
:param fixed_address: (optional) fixed address to which attach the
floating IP to.
:param wait: (optional) Wait for the address to appear as assigned
to the server. Defaults to False.
:param timeout: (optional) Seconds to wait, defaults to 60.
See the ``wait`` parameter.
:param skip_attach: (optional) Skip the actual attach and just do
the wait. Defaults to False.
:param nat_destination: The fixed network the server's port for the
FIP to attach to will come from.
:returns: The server ``munch.Munch``
:raises: OpenStackCloudException, on operation error.
"""
# Short circuit if we're asking to attach an IP that's already
# attached
ext_ip = meta.get_server_ip(server, ext_tag='floating', public=True)
if ext_ip == floating_ip['floating_ip_address']:
return server
if self._use_neutron_floating():
if not skip_attach:
try:
self._neutron_attach_ip_to_server(
server=server, floating_ip=floating_ip,
fixed_address=fixed_address,
nat_destination=nat_destination)
except exc.OpenStackCloudURINotFound as e:
self.log.debug(
"Something went wrong talking to neutron API: "
"'%(msg)s'. Trying with Nova.", {'msg': str(e)})
# Fall-through, trying with Nova
else:
# Nova network
self._nova_attach_ip_to_server(
server_id=server['id'], floating_ip_id=floating_ip['id'],
fixed_address=fixed_address)
if wait:
# Wait for the address to be assigned to the server
server_id = server['id']
for _ in _utils._iterate_timeout(
timeout,
"Timeout waiting for the floating IP to be attached.",
wait=self._SERVER_AGE):
server = self.get_server(server_id)
ext_ip = meta.get_server_ip(
server, ext_tag='floating', public=True)
if ext_ip == floating_ip['floating_ip_address']:
return server
return server
def _nat_destination_port(
self, server, fixed_address=None, nat_destination=None):
"""Returns server port that is on a nat_destination network
Find a port attached to the server which is on a network which
has a subnet which can be the destination of NAT. Such a network
is referred to in shade as a "nat_destination" network. So this
then is a function which returns a port on such a network that is
associated with the given server.
:param server: Server dict.
:param fixed_address: Fixed ip address of the port
:param nat_destination: Name or ID of the network of the port.
"""
# If we are caching port lists, we may not find the port for
# our server if the list is old. Try for at least 2 cache
# periods if that is the case.
if self._PORT_AGE:
timeout = self._PORT_AGE * 2
else:
timeout = None
for count in _utils._iterate_timeout(
timeout,
"Timeout waiting for port to show up in list",
wait=self._PORT_AGE):
try:
port_filter = {'device_id': server['id']}
ports = self.search_ports(filters=port_filter)
break
except exc.OpenStackCloudTimeout:
ports = None
if not ports:
return (None, None)
port = None
if not fixed_address:
if len(ports) > 1:
if nat_destination:
nat_network = self.get_network(nat_destination)
if not nat_network:
raise exc.OpenStackCloudException(
'NAT Destination {nat_destination} was configured'
' but not found on the cloud. Please check your'
' config and your cloud and try again.'.format(
nat_destination=nat_destination))
else:
nat_network = self.get_nat_destination()
if not nat_network:
raise exc.OpenStackCloudException(
'Multiple ports were found for server {server}'
' but none of the networks are a valid NAT'
' destination, so it is impossible to add a'
' floating IP. If you have a network that is a valid'
' destination for NAT and we could not find it,'
' please file a bug. But also configure the'
' nat_destination property of the networks list in'
' your clouds.yaml file. If you do not have a'
' clouds.yaml file, please make one - your setup'
' is complicated.'.format(server=server['id']))
maybe_ports = []
for maybe_port in ports:
if maybe_port['network_id'] == nat_network['id']:
maybe_ports.append(maybe_port)
if not maybe_ports:
raise exc.OpenStackCloudException(
'No port on server {server} was found matching'
' your NAT destination network {dest}. Please '
' check your config'.format(
server=server['id'], dest=nat_network['name']))
ports = maybe_ports
# Select the most recent available IPv4 address
# To do this, sort the ports in reverse order by the created_at
# field which is a string containing an ISO DateTime (which
# thankfully sort properly) This way the most recent port created,
# if there are more than one, will be the arbitrary port we
# select.
for port in sorted(
ports,
key=lambda p: p.get('created_at', 0),
reverse=True):
for address in port.get('fixed_ips', list()):
try:
ip = ipaddress.ip_address(address['ip_address'])
except Exception:
continue
if ip.version == 4:
fixed_address = address['ip_address']
return port, fixed_address
raise exc.OpenStackCloudException(
"unable to find a free fixed IPv4 address for server "
"{0}".format(server['id']))
# unfortunately a port can have more than one fixed IP:
# we can't use the search_ports filtering for fixed_address as
# they are contained in a list. e.g.
#
# "fixed_ips": [
# {
# "subnet_id": "008ba151-0b8c-4a67-98b5-0d2b87666062",
# "ip_address": "172.24.4.2"
# }
# ]
#
# Search fixed_address
for p in ports:
for fixed_ip in p['fixed_ips']:
if fixed_address == fixed_ip['ip_address']:
return (p, fixed_address)
return (None, None)
def _neutron_attach_ip_to_server(
self, server, floating_ip, fixed_address=None,
nat_destination=None):
# Find an available port
(port, fixed_address) = self._nat_destination_port(
server, fixed_address=fixed_address,
nat_destination=nat_destination)
if not port:
raise exc.OpenStackCloudException(
"unable to find a port for server {0}".format(
server['id']))
floating_ip_args = {'port_id': port['id']}
if fixed_address is not None:
floating_ip_args['fixed_ip_address'] = fixed_address
return self._network_client.put(
"/floatingips/{fip_id}.json".format(fip_id=floating_ip['id']),
json={'floatingip': floating_ip_args},
error_message=("Error attaching IP {ip} to "
"server {server_id}".format(
ip=floating_ip['id'],
server_id=server['id'])))
def _nova_attach_ip_to_server(self, server_id, floating_ip_id,
fixed_address=None):
f_ip = self.get_floating_ip(
id=floating_ip_id)
if f_ip is None:
raise exc.OpenStackCloudException(
"unable to find floating IP {0}".format(floating_ip_id))
error_message = "Error attaching IP {ip} to instance {id}".format(
ip=floating_ip_id, id=server_id)
body = {
'address': f_ip['floating_ip_address']
}
if fixed_address:
body['fixed_address'] = fixed_address
return self._compute_client.post(
'/servers/{server_id}/action'.format(server_id=server_id),
json=dict(addFloatingIp=body),
error_message=error_message)
def detach_ip_from_server(self, server_id, floating_ip_id):
"""Detach a floating IP from a server.
:param server_id: ID of a server.
:param floating_ip_id: Id of the floating IP to detach.
:returns: True if the IP has been detached, or False if the IP wasn't
attached to any server.
:raises: ``OpenStackCloudException``, on operation error.
"""
if self._use_neutron_floating():
try:
return self._neutron_detach_ip_from_server(
server_id=server_id, floating_ip_id=floating_ip_id)
except exc.OpenStackCloudURINotFound as e:
self.log.debug(
"Something went wrong talking to neutron API: "
"'%(msg)s'. Trying with Nova.", {'msg': str(e)})
# Fall-through, trying with Nova
# Nova network
self._nova_detach_ip_from_server(
server_id=server_id, floating_ip_id=floating_ip_id)
def _neutron_detach_ip_from_server(self, server_id, floating_ip_id):
f_ip = self.get_floating_ip(id=floating_ip_id)
if f_ip is None or not f_ip['attached']:
return False
self._network_client.put(
"/floatingips/{fip_id}.json".format(fip_id=floating_ip_id),
json={"floatingip": {"port_id": None}},
error_message=("Error detaching IP {ip} from "
"server {server_id}".format(
ip=floating_ip_id, server_id=server_id)))
return True
def _nova_detach_ip_from_server(self, server_id, floating_ip_id):
f_ip = self.get_floating_ip(id=floating_ip_id)
if f_ip is None:
raise exc.OpenStackCloudException(
"unable to find floating IP {0}".format(floating_ip_id))
error_message = "Error detaching IP {ip} from instance {id}".format(
ip=floating_ip_id, id=server_id)
return self._compute_client.post(
'/servers/{server_id}/action'.format(server_id=server_id),
json=dict(removeFloatingIp=dict(
address=f_ip['floating_ip_address'])),
error_message=error_message)
return True
def _add_ip_from_pool(
self, server, network, fixed_address=None, reuse=True,
wait=False, timeout=60, nat_destination=None):
"""Add a floating IP to a server from a given pool
This method reuses available IPs, when possible, or allocate new IPs
to the current tenant.
The floating IP is attached to the given fixed address or to the
first server port/fixed address
:param server: Server dict
:param network: Name or ID of the network.
:param fixed_address: a fixed address
:param reuse: Try to reuse existing ips. Defaults to True.
:param wait: (optional) Wait for the address to appear as assigned
to the server. Defaults to False.
:param timeout: (optional) Seconds to wait, defaults to 60.
See the ``wait`` parameter.
:param nat_destination: (optional) the name of the network of the
port to associate with the floating ip.
:returns: the updated server ``munch.Munch``
"""
if reuse:
f_ip = self.available_floating_ip(network=network)
else:
start_time = time.time()
f_ip = self.create_floating_ip(
server=server,
network=network, nat_destination=nat_destination,
wait=wait, timeout=timeout)
timeout = timeout - (time.time() - start_time)
# Wait for cache invalidation time so that we don't try
# to attach the FIP a second time below
time.sleep(self._SERVER_AGE)
server = self.get_server(server.id)
# We run attach as a second call rather than in the create call
# because there are code flows where we will not have an attached
# FIP yet. However, even if it was attached in the create, we run
# the attach function below to get back the server dict refreshed
# with the FIP information.
return self._attach_ip_to_server(
server=server, floating_ip=f_ip, fixed_address=fixed_address,
wait=wait, timeout=timeout, nat_destination=nat_destination)
def add_ip_list(
self, server, ips, wait=False, timeout=60,
fixed_address=None):
"""Attach a list of IPs to a server.
:param server: a server object
:param ips: list of floating IP addresses or a single address
:param wait: (optional) Wait for the address to appear as assigned
to the server. Defaults to False.
:param timeout: (optional) Seconds to wait, defaults to 60.
See the ``wait`` parameter.
:param fixed_address: (optional) Fixed address of the server to
attach the IP to
:returns: The updated server ``munch.Munch``
:raises: ``OpenStackCloudException``, on operation error.
"""
if type(ips) == list:
ip = ips[0]
else:
ip = ips
f_ip = self.get_floating_ip(
id=None, filters={'floating_ip_address': ip})
return self._attach_ip_to_server(
server=server, floating_ip=f_ip, wait=wait, timeout=timeout,
fixed_address=fixed_address)
def add_auto_ip(self, server, wait=False, timeout=60, reuse=True):
"""Add a floating IP to a server.
This method is intended for basic usage. For advanced network
architecture (e.g. multiple external networks or servers with multiple
interfaces), use other floating IP methods.
This method can reuse available IPs, or allocate new IPs to the current
project.
:param server: a server dictionary.
:param reuse: Whether or not to attempt to reuse IPs, defaults
to True.
:param wait: (optional) Wait for the address to appear as assigned
to the server. Defaults to False.
:param timeout: (optional) Seconds to wait, defaults to 60.
See the ``wait`` parameter.
:param reuse: Try to reuse existing ips. Defaults to True.
:returns: Floating IP address attached to server.
"""
server = self._add_auto_ip(
server, wait=wait, timeout=timeout, reuse=reuse)
return server['interface_ip'] or None
def _add_auto_ip(self, server, wait=False, timeout=60, reuse=True):
skip_attach = False
created = False
if reuse:
f_ip = self.available_floating_ip()
else:
start_time = time.time()
f_ip = self.create_floating_ip(
server=server, wait=wait, timeout=timeout)
timeout = timeout - (time.time() - start_time)
if server:
# This gets passed in for both nova and neutron
# but is only meaningful for the neutron logic branch
skip_attach = True
created = True
try:
# We run attach as a second call rather than in the create call
# because there are code flows where we will not have an attached
# FIP yet. However, even if it was attached in the create, we run
# the attach function below to get back the server dict refreshed
# with the FIP information.
return self._attach_ip_to_server(
server=server, floating_ip=f_ip, wait=wait, timeout=timeout,
skip_attach=skip_attach)
except exc.OpenStackCloudTimeout:
if self._use_neutron_floating() and created:
# We are here because we created an IP on the port
# It failed. Delete so as not to leak an unmanaged
# resource
self.log.error(
"Timeout waiting for floating IP to become"
" active. Floating IP %(ip)s:%(id)s was created for"
" server %(server)s but is being deleted due to"
" activation failure.", {
'ip': f_ip['floating_ip_address'],
'id': f_ip['id'],
'server': server['id']})
try:
self.delete_floating_ip(f_ip['id'])
except Exception as e:
self.log.error(
"FIP LEAK: Attempted to delete floating ip "
"%(fip)s but received %(exc)s exception: %(err)s",
{'fip': f_ip['id'], 'exc': e.__class__, 'err': str(e)})
raise e
raise
def add_ips_to_server(
self, server, auto_ip=True, ips=None, ip_pool=None,
wait=False, timeout=60, reuse=True, fixed_address=None,
nat_destination=None):
if ip_pool:
server = self._add_ip_from_pool(
server, ip_pool, reuse=reuse, wait=wait, timeout=timeout,
fixed_address=fixed_address, nat_destination=nat_destination)
elif ips:
server = self.add_ip_list(
server, ips, wait=wait, timeout=timeout,
fixed_address=fixed_address)
elif auto_ip:
if self._needs_floating_ip(server, nat_destination):
server = self._add_auto_ip(
server, wait=wait, timeout=timeout, reuse=reuse)
return server
def _needs_floating_ip(self, server, nat_destination):
"""Figure out if auto_ip should add a floating ip to this server.
If the server has a public_v4 it does not need a floating ip.
If the server does not have a private_v4 it does not need a
floating ip.
If self.private then the server does not need a floating ip.
If the cloud runs nova, and the server has a private_v4 and not
a public_v4, then the server needs a floating ip.
If the server has a private_v4 and no public_v4 and the cloud has
a network from which floating IPs come that is connected via a
router to the network from which the private_v4 address came,
then the server needs a floating ip.
If the server has a private_v4 and no public_v4 and the cloud
does not have a network from which floating ips come, or it has
one but that network is not connected to the network from which
the server's private_v4 address came via a router, then the
server does not need a floating ip.
"""
if not self._has_floating_ips():
return False
if server['public_v4']:
return False
if not server['private_v4']:
return False
if self.private:
return False
if not self.has_service('network'):
return True
# No floating ip network - no FIPs
try:
self._get_floating_network_id()
except exc.OpenStackCloudException:
return False
(port_obj, fixed_ip_address) = self._nat_destination_port(
server, nat_destination=nat_destination)
if not port_obj or not fixed_ip_address:
return False
return True
def _get_boot_from_volume_kwargs(
self, image, boot_from_volume, boot_volume, volume_size,
terminate_volume, volumes, kwargs):
"""Return block device mappings
:param image: Image dict, name or id to boot with.
"""
# TODO(mordred) We're only testing this in functional tests. We need
# to add unit tests for this too.
if boot_volume or boot_from_volume or volumes:
kwargs.setdefault('block_device_mapping_v2', [])
else:
return kwargs
# If we have boot_from_volume but no root volume, then we're
# booting an image from volume
if boot_volume:
volume = self.get_volume(boot_volume)
if not volume:
raise exc.OpenStackCloudException(
'Volume {boot_volume} is not a valid volume'
' in {cloud}:{region}'.format(
boot_volume=boot_volume,
cloud=self.name, region=self.region_name))
block_mapping = {
'boot_index': '0',
'delete_on_termination': terminate_volume,
'destination_type': 'volume',
'uuid': volume['id'],
'source_type': 'volume',
}
kwargs['block_device_mapping_v2'].append(block_mapping)
kwargs['imageRef'] = ''
elif boot_from_volume:
if isinstance(image, dict):
image_obj = image
else:
image_obj = self.get_image(image)
if not image_obj:
raise exc.OpenStackCloudException(
'Image {image} is not a valid image in'
' {cloud}:{region}'.format(
image=image,
cloud=self.name, region=self.region_name))
block_mapping = {
'boot_index': '0',
'delete_on_termination': terminate_volume,
'destination_type': 'volume',
'uuid': image_obj['id'],
'source_type': 'image',
'volume_size': volume_size,
}
kwargs['imageRef'] = ''
kwargs['block_device_mapping_v2'].append(block_mapping)
if volumes and kwargs['imageRef']:
# If we're attaching volumes on boot but booting from an image,
# we need to specify that in the BDM.
block_mapping = {
u'boot_index': 0,
u'delete_on_termination': True,
u'destination_type': u'local',
u'source_type': u'image',
u'uuid': kwargs['imageRef'],
}
kwargs['block_device_mapping_v2'].append(block_mapping)
for volume in volumes:
volume_obj = self.get_volume(volume)
if not volume_obj:
raise exc.OpenStackCloudException(
'Volume {volume} is not a valid volume'
' in {cloud}:{region}'.format(
volume=volume,
cloud=self.name, region=self.region_name))
block_mapping = {
'boot_index': '-1',
'delete_on_termination': False,
'destination_type': 'volume',
'uuid': volume_obj['id'],
'source_type': 'volume',
}
kwargs['block_device_mapping_v2'].append(block_mapping)
if boot_volume or boot_from_volume or volumes:
self.list_volumes.invalidate(self)
return kwargs
def _encode_server_userdata(self, userdata):
if hasattr(userdata, 'read'):
userdata = userdata.read()
if not isinstance(userdata, six.binary_type):
# If the userdata passed in is bytes, just send it unmodified
if not isinstance(userdata, six.string_types):
raise TypeError("%s can't be encoded" % type(userdata))
# If it's not bytes, make it bytes
userdata = userdata.encode('utf-8', 'strict')
# Once we have base64 bytes, make them into a utf-8 string for REST
return base64.b64encode(userdata).decode('utf-8')
@_utils.valid_kwargs(
'meta', 'files', 'userdata',
'reservation_id', 'return_raw', 'min_count',
'max_count', 'security_groups', 'key_name',
'availability_zone', 'block_device_mapping',
'block_device_mapping_v2', 'nics', 'scheduler_hints',
'config_drive', 'admin_pass', 'disk_config')
def create_server(
self, name, image=None, flavor=None,
auto_ip=True, ips=None, ip_pool=None,
root_volume=None, terminate_volume=False,
wait=False, timeout=180, reuse_ips=True,
network=None, boot_from_volume=False, volume_size='50',
boot_volume=None, volumes=None, nat_destination=None,
group=None,
**kwargs):
"""Create a virtual server instance.
:param name: Something to name the server.
:param image: Image dict, name or ID to boot with. image is required
unless boot_volume is given.
:param flavor: Flavor dict, name or ID to boot onto.
:param auto_ip: Whether to take actions to find a routable IP for
the server. (defaults to True)
:param ips: List of IPs to attach to the server (defaults to None)
:param ip_pool: Name of the network or floating IP pool to get an
address from. (defaults to None)
:param root_volume: Name or ID of a volume to boot from
(defaults to None - deprecated, use boot_volume)
:param boot_volume: Name or ID of a volume to boot from
(defaults to None)
:param terminate_volume: If booting from a volume, whether it should
be deleted when the server is destroyed.
(defaults to False)
:param volumes: (optional) A list of volumes to attach to the server
:param meta: (optional) A dict of arbitrary key/value metadata to
store for this server. Both keys and values must be
<=255 characters.
:param files: (optional, deprecated) A dict of files to overwrite
on the server upon boot. Keys are file names (i.e.
``/etc/passwd``) and values
are the file contents (either as a string or as a
file-like object). A maximum of five entries is allowed,
and each file must be 10k or less.
:param reservation_id: a UUID for the set of servers being requested.
:param min_count: (optional extension) The minimum number of
servers to launch.
:param max_count: (optional extension) The maximum number of
servers to launch.
:param security_groups: A list of security group names
:param userdata: user data to pass to be exposed by the metadata
server this can be a file type object as well or a
string.
:param key_name: (optional extension) name of previously created
keypair to inject into the instance.
:param availability_zone: Name of the availability zone for instance
placement.
:param block_device_mapping: (optional) A dict of block
device mappings for this server.
:param block_device_mapping_v2: (optional) A dict of block
device mappings for this server.
:param nics: (optional extension) an ordered list of nics to be
added to this server, with information about
connected networks, fixed IPs, port etc.
:param scheduler_hints: (optional extension) arbitrary key-value pairs
specified by the client to help boot an instance
:param config_drive: (optional extension) value for config drive
either boolean, or volume-id
:param disk_config: (optional extension) control how the disk is
partitioned when the server is created. possible
values are 'AUTO' or 'MANUAL'.
:param admin_pass: (optional extension) add a user supplied admin
password.
:param wait: (optional) Wait for the address to appear as assigned
to the server. Defaults to False.
:param timeout: (optional) Seconds to wait, defaults to 60.
See the ``wait`` parameter.
:param reuse_ips: (optional) Whether to attempt to reuse pre-existing
floating ips should a floating IP be
needed (defaults to True)
:param network: (optional) Network dict or name or ID to attach the
server to. Mutually exclusive with the nics parameter.
Can also be be a list of network names or IDs or
network dicts.
:param boot_from_volume: Whether to boot from volume. 'boot_volume'
implies True, but boot_from_volume=True with
no boot_volume is valid and will create a
volume from the image and use that.
:param volume_size: When booting an image from volume, how big should
the created volume be? Defaults to 50.
:param nat_destination: Which network should a created floating IP
be attached to, if it's not possible to
infer from the cloud's configuration.
(Optional, defaults to None)
:param group: ServerGroup dict, name or id to boot the server in.
If a group is provided in both scheduler_hints and in
the group param, the group param will win.
(Optional, defaults to None)
:returns: A ``munch.Munch`` representing the created server.
:raises: OpenStackCloudException on operation error.
"""
# TODO(shade) Image is optional but flavor is not - yet flavor comes
# after image in the argument list. Doh.
if not flavor:
raise TypeError(
"create_server() missing 1 required argument: 'flavor'")
if not image and not boot_volume:
raise TypeError(
"create_server() requires either 'image' or 'boot_volume'")
# TODO(mordred) Add support for description starting in 2.19
security_groups = kwargs.get('security_groups', [])
if security_groups and not isinstance(kwargs['security_groups'], list):
security_groups = [security_groups]
if security_groups:
kwargs['security_groups'] = []
for sec_group in security_groups:
kwargs['security_groups'].append(dict(name=sec_group))
if 'userdata' in kwargs:
user_data = kwargs.pop('userdata')
if user_data:
kwargs['user_data'] = self._encode_server_userdata(user_data)
for (desired, given) in (
('OS-DCF:diskConfig', 'disk_config'),
('config_drive', 'config_drive'),
('key_name', 'key_name'),
('metadata', 'meta'),
('adminPass', 'admin_pass')):
value = kwargs.pop(given, None)
if value:
kwargs[desired] = value
hints = kwargs.pop('scheduler_hints', {})
if group:
group_obj = self.get_server_group(group)
if not group_obj:
raise exc.OpenStackCloudException(
"Server Group {group} was requested but was not found"
" on the cloud".format(group=group))
hints['group'] = group_obj['id']
kwargs.setdefault('max_count', kwargs.get('max_count', 1))
kwargs.setdefault('min_count', kwargs.get('min_count', 1))
if 'nics' in kwargs and not isinstance(kwargs['nics'], list):
if isinstance(kwargs['nics'], dict):
# Be nice and help the user out
kwargs['nics'] = [kwargs['nics']]
else:
raise exc.OpenStackCloudException(
'nics parameter to create_server takes a list of dicts.'
' Got: {nics}'.format(nics=kwargs['nics']))
if network and ('nics' not in kwargs or not kwargs['nics']):
nics = []
if not isinstance(network, list):
network = [network]
for net_name in network:
if isinstance(net_name, dict) and 'id' in net_name:
network_obj = net_name
else:
network_obj = self.get_network(name_or_id=net_name)
if not network_obj:
raise exc.OpenStackCloudException(
'Network {network} is not a valid network in'
' {cloud}:{region}'.format(
network=network,
cloud=self.name, region=self.region_name))
nics.append({'net-id': network_obj['id']})
kwargs['nics'] = nics
if not network and ('nics' not in kwargs or not kwargs['nics']):
default_network = self.get_default_network()
if default_network:
kwargs['nics'] = [{'net-id': default_network['id']}]
networks = []
for nic in kwargs.pop('nics', []):
net = {}
if 'net-id' in nic:
# TODO(mordred) Make sure this is in uuid format
net['uuid'] = nic.pop('net-id')
# If there's a net-id, ignore net-name
nic.pop('net-name', None)
elif 'net-name' in nic:
nic_net = self.get_network(nic['net-name'])
if not nic_net:
raise exc.OpenStackCloudException(
"Requested network {net} could not be found.".format(
net=nic['net-name']))
net['uuid'] = nic_net['id']
for ip_key in ('v4-fixed-ip', 'v6-fixed-ip', 'fixed_ip'):
fixed_ip = nic.pop(ip_key, None)
if fixed_ip and net.get('fixed_ip'):
raise exc.OpenStackCloudException(
"Only one of v4-fixed-ip, v6-fixed-ip or fixed_ip"
" may be given")
if fixed_ip:
net['fixed_ip'] = fixed_ip
# TODO(mordred) Add support for tag if server supports microversion
# 2.32-2.36 or >= 2.42
for key in ('port', 'port-id'):
if key in nic:
net['port'] = nic.pop(key)
if nic:
raise exc.OpenStackCloudException(
"Additional unsupported keys given for server network"
" creation: {keys}".format(keys=nic.keys()))
networks.append(net)
if networks:
kwargs['networks'] = networks
if image:
if isinstance(image, dict):
kwargs['imageRef'] = image['id']
else:
kwargs['imageRef'] = self.get_image(image).id
if isinstance(flavor, dict):
kwargs['flavorRef'] = flavor['id']
else:
kwargs['flavorRef'] = self.get_flavor(flavor, get_extra=False).id
if volumes is None:
volumes = []
# nova cli calls this boot_volume. Let's be the same
if root_volume and not boot_volume:
boot_volume = root_volume
kwargs = self._get_boot_from_volume_kwargs(
image=image, boot_from_volume=boot_from_volume,
boot_volume=boot_volume, volume_size=str(volume_size),
terminate_volume=terminate_volume,
volumes=volumes, kwargs=kwargs)
kwargs['name'] = name
endpoint = '/servers'
# TODO(mordred) We're only testing this in functional tests. We need
# to add unit tests for this too.
if 'block_device_mapping_v2' in kwargs:
endpoint = '/os-volumes_boot'
with _utils.shade_exceptions("Error in creating instance"):
server_json = {'server': kwargs}
if hints:
server_json['os:scheduler_hints'] = hints
data = self._compute_client.post(
endpoint, json=server_json)
server = self._get_and_munchify('server', data)
admin_pass = server.get('adminPass') or kwargs.get('admin_pass')
if not wait:
# This is a direct get call to skip the list_servers
# cache which has absolutely no chance of containing the
# new server.
# Only do this if we're not going to wait for the server
# to complete booting, because the only reason we do it
# is to get a server record that is the return value from
# get/list rather than the return value of create. If we're
# going to do the wait loop below, this is a waste of a call
server = self.get_server_by_id(server.id)
if server.status == 'ERROR':
raise exc.OpenStackCloudCreateException(
resource='server', resource_id=server.id)
if wait:
server = self.wait_for_server(
server,
auto_ip=auto_ip, ips=ips, ip_pool=ip_pool,
reuse=reuse_ips, timeout=timeout,
nat_destination=nat_destination,
)
server.adminPass = admin_pass
return server
def wait_for_server(
self, server, auto_ip=True, ips=None, ip_pool=None,
reuse=True, timeout=180, nat_destination=None):
"""
Wait for a server to reach ACTIVE status.
"""
server_id = server['id']
timeout_message = "Timeout waiting for the server to come up."
start_time = time.time()
# There is no point in iterating faster than the list_servers cache
for count in _utils._iterate_timeout(
timeout,
timeout_message,
# if _SERVER_AGE is 0 we still want to wait a bit
# to be friendly with the server.
wait=self._SERVER_AGE or 2):
try:
# Use the get_server call so that the list_servers
# cache can be leveraged
server = self.get_server(server_id)
except Exception:
continue
if not server:
continue
# We have more work to do, but the details of that are
# hidden from the user. So, calculate remaining timeout
# and pass it down into the IP stack.
remaining_timeout = timeout - int(time.time() - start_time)
if remaining_timeout <= 0:
raise exc.OpenStackCloudTimeout(timeout_message)
server = self.get_active_server(
server=server, reuse=reuse,
auto_ip=auto_ip, ips=ips, ip_pool=ip_pool,
wait=True, timeout=remaining_timeout,
nat_destination=nat_destination)
if server is not None and server['status'] == 'ACTIVE':
return server
def get_active_server(
self, server, auto_ip=True, ips=None, ip_pool=None,
reuse=True, wait=False, timeout=180, nat_destination=None):
if server['status'] == 'ERROR':
if 'fault' in server and 'message' in server['fault']:
raise exc.OpenStackCloudException(
"Error in creating the server: {reason}".format(
reason=server['fault']['message']),
extra_data=dict(server=server))
raise exc.OpenStackCloudException(
"Error in creating the server", extra_data=dict(server=server))
if server['status'] == 'ACTIVE':
if 'addresses' in server and server['addresses']:
return self.add_ips_to_server(
server, auto_ip, ips, ip_pool, reuse=reuse,
nat_destination=nat_destination,
wait=wait, timeout=timeout)
self.log.debug(
'Server %(server)s reached ACTIVE state without'
' being allocated an IP address.'
' Deleting server.', {'server': server['id']})
try:
self._delete_server(
server=server, wait=wait, timeout=timeout)
except Exception as e:
raise exc.OpenStackCloudException(
'Server reached ACTIVE state without being'
' allocated an IP address AND then could not'
' be deleted: {0}'.format(e),
extra_data=dict(server=server))
raise exc.OpenStackCloudException(
'Server reached ACTIVE state without being'
' allocated an IP address.',
extra_data=dict(server=server))
return None
def rebuild_server(self, server_id, image_id, admin_pass=None,
detailed=False, bare=False,
wait=False, timeout=180):
kwargs = {}
if image_id:
kwargs['imageRef'] = image_id
if admin_pass:
kwargs['adminPass'] = admin_pass
data = self._compute_client.post(
'/servers/{server_id}/action'.format(server_id=server_id),
error_message="Error in rebuilding instance",
json={'rebuild': kwargs})
server = self._get_and_munchify('server', data)
if not wait:
return self._expand_server(
self._normalize_server(server), bare=bare, detailed=detailed)
admin_pass = server.get('adminPass') or admin_pass
for count in _utils._iterate_timeout(
timeout,
"Timeout waiting for server {0} to "
"rebuild.".format(server_id),
wait=self._SERVER_AGE):
try:
server = self.get_server(server_id, bare=True)
except Exception:
continue
if not server:
continue
if server['status'] == 'ERROR':
raise exc.OpenStackCloudException(
"Error in rebuilding the server",
extra_data=dict(server=server))
if server['status'] == 'ACTIVE':
server.adminPass = admin_pass
break
return self._expand_server(server, detailed=detailed, bare=bare)
def set_server_metadata(self, name_or_id, metadata):
"""Set metadata in a server instance.
:param str name_or_id: The name or ID of the server instance
to update.
:param dict metadata: A dictionary with the key=value pairs
to set in the server instance. It only updates the key=value
pairs provided. Existing ones will remain untouched.
:raises: OpenStackCloudException on operation error.
"""
server = self.get_server(name_or_id, bare=True)
if not server:
raise exc.OpenStackCloudException(
'Invalid Server {server}'.format(server=name_or_id))
self._compute_client.post(
'/servers/{server_id}/metadata'.format(server_id=server['id']),
json={'metadata': metadata},
error_message='Error updating server metadata')
def delete_server_metadata(self, name_or_id, metadata_keys):
"""Delete metadata from a server instance.
:param str name_or_id: The name or ID of the server instance
to update.
:param list metadata_keys: A list with the keys to be deleted
from the server instance.
:raises: OpenStackCloudException on operation error.
"""
server = self.get_server(name_or_id, bare=True)
if not server:
raise exc.OpenStackCloudException(
'Invalid Server {server}'.format(server=name_or_id))
for key in metadata_keys:
error_message = 'Error deleting metadata {key} on {server}'.format(
key=key, server=name_or_id)
self._compute_client.delete(
'/servers/{server_id}/metadata/{key}'.format(
server_id=server['id'],
key=key),
error_message=error_message)
def delete_server(
self, name_or_id, wait=False, timeout=180, delete_ips=False,
delete_ip_retry=1):
"""Delete a server instance.
:param name_or_id: name or ID of the server to delete
:param bool wait: If true, waits for server to be deleted.
:param int timeout: Seconds to wait for server deletion.
:param bool delete_ips: If true, deletes any floating IPs
associated with the instance.
:param int delete_ip_retry: Number of times to retry deleting
any floating ips, should the first try be unsuccessful.
:returns: True if delete succeeded, False otherwise if the
server does not exist.
:raises: OpenStackCloudException on operation error.
"""
# If delete_ips is True, we need the server to not be bare.
server = self.get_server(name_or_id, bare=True)
if not server:
return False
# This portion of the code is intentionally left as a separate
# private method in order to avoid an unnecessary API call to get
# a server we already have.
return self._delete_server(
server, wait=wait, timeout=timeout, delete_ips=delete_ips,
delete_ip_retry=delete_ip_retry)
def _delete_server_floating_ips(self, server, delete_ip_retry):
# Does the server have floating ips in its
# addresses dict? If not, skip this.
server_floats = meta.find_nova_interfaces(
server['addresses'], ext_tag='floating')
for fip in server_floats:
try:
ip = self.get_floating_ip(id=None, filters={
'floating_ip_address': fip['addr']})
except exc.OpenStackCloudURINotFound:
# We're deleting. If it doesn't exist - awesome
# NOTE(mordred) If the cloud is a nova FIP cloud but
# floating_ip_source is set to neutron, this
# can lead to a FIP leak.
continue
if not ip:
continue
deleted = self.delete_floating_ip(
ip['id'], retry=delete_ip_retry)
if not deleted:
raise exc.OpenStackCloudException(
"Tried to delete floating ip {floating_ip}"
" associated with server {id} but there was"
" an error deleting it. Not deleting server.".format(
floating_ip=ip['floating_ip_address'],
id=server['id']))
def _delete_server(
self, server, wait=False, timeout=180, delete_ips=False,
delete_ip_retry=1):
if not server:
return False
if delete_ips and self._has_floating_ips():
self._delete_server_floating_ips(server, delete_ip_retry)
try:
self._compute_client.delete(
'/servers/{id}'.format(id=server['id']),
error_message="Error in deleting server")
except exc.OpenStackCloudURINotFound:
return False
except Exception:
raise
if not wait:
return True
# If the server has volume attachments, or if it has booted
# from volume, deleting it will change volume state so we will
# need to invalidate the cache. Avoid the extra API call if
# caching is not enabled.
reset_volume_cache = False
if (self.cache_enabled
and self.has_service('volume')
and self.get_volumes(server)):
reset_volume_cache = True
for count in _utils._iterate_timeout(
timeout,
"Timed out waiting for server to get deleted.",
# if _SERVER_AGE is 0 we still want to wait a bit
# to be friendly with the server.
wait=self._SERVER_AGE or 2):
with _utils.shade_exceptions("Error in deleting server"):
server = self.get_server(server['id'], bare=True)
if not server:
break
if reset_volume_cache:
self.list_volumes.invalidate(self)
# Reset the list servers cache time so that the next list server
# call gets a new list
self._servers_time = self._servers_time - self._SERVER_AGE
return True
@_utils.valid_kwargs(
'name', 'description')
def update_server(self, name_or_id, detailed=False, bare=False, **kwargs):
"""Update a server.
:param name_or_id: Name of the server to be updated.
:param detailed: Whether or not to add detailed additional information.
Defaults to False.
:param bare: Whether to skip adding any additional information to the
server record. Defaults to False, meaning the addresses
dict will be populated as needed from neutron. Setting
to True implies detailed = False.
:name: New name for the server
:description: New description for the server
:returns: a dictionary representing the updated server.
:raises: OpenStackCloudException on operation error.
"""
server = self.get_server(name_or_id=name_or_id, bare=True)
if server is None:
raise exc.OpenStackCloudException(
"failed to find server '{server}'".format(server=name_or_id))
data = self._compute_client.put(
'/servers/{server_id}'.format(server_id=server['id']),
error_message="Error updating server {0}".format(name_or_id),
json={'server': kwargs})
server = self._normalize_server(
self._get_and_munchify('server', data))
return self._expand_server(server, bare=bare, detailed=detailed)
def create_server_group(self, name, policies):
"""Create a new server group.
:param name: Name of the server group being created
:param policies: List of policies for the server group.
:returns: a dict representing the new server group.
:raises: OpenStackCloudException on operation error.
"""
data = self._compute_client.post(
'/os-server-groups',
json={
'server_group': {
'name': name,
'policies': policies}},
error_message="Unable to create server group {name}".format(
name=name))
return self._get_and_munchify('server_group', data)
def delete_server_group(self, name_or_id):
"""Delete a server group.
:param name_or_id: Name or ID of the server group to delete
:returns: True if delete succeeded, False otherwise
:raises: OpenStackCloudException on operation error.
"""
server_group = self.get_server_group(name_or_id)
if not server_group:
self.log.debug("Server group %s not found for deleting",
name_or_id)
return False
self._compute_client.delete(
'/os-server-groups/{id}'.format(id=server_group['id']),
error_message="Error deleting server group {name}".format(
name=name_or_id))
return True
def list_containers(self, full_listing=True):
"""List containers.
:param full_listing: Ignored. Present for backwards compat
:returns: list of Munch of the container objects
:raises: OpenStackCloudException on operation error.
"""
return self._object_store_client.get('/', params=dict(format='json'))
def get_container(self, name, skip_cache=False):
if skip_cache or name not in self._container_cache:
try:
container = self._object_store_client.head(name)
self._container_cache[name] = container.headers
except exc.OpenStackCloudHTTPError as e:
if e.response.status_code == 404:
return None
raise
return self._container_cache[name]
def create_container(self, name, public=False):
container = self.get_container(name)
if container:
return container
self._object_store_client.put(name)
if public:
self.set_container_access(name, 'public')
return self.get_container(name, skip_cache=True)
def delete_container(self, name):
try:
self._object_store_client.delete(name)
return True
except exc.OpenStackCloudHTTPError as e:
if e.response.status_code == 404:
return False
if e.response.status_code == 409:
raise exc.OpenStackCloudException(
'Attempt to delete container {container} failed. The'
' container is not empty. Please delete the objects'
' inside it before deleting the container'.format(
container=name))
raise
def update_container(self, name, headers):
self._object_store_client.post(name, headers=headers)
def set_container_access(self, name, access):
if access not in OBJECT_CONTAINER_ACLS:
raise exc.OpenStackCloudException(
"Invalid container access specified: %s. Must be one of %s"
% (access, list(OBJECT_CONTAINER_ACLS.keys())))
header = {'x-container-read': OBJECT_CONTAINER_ACLS[access]}
self.update_container(name, header)
def get_container_access(self, name):
container = self.get_container(name, skip_cache=True)
if not container:
raise exc.OpenStackCloudException("Container not found: %s" % name)
acl = container.get('x-container-read', '')
for key, value in OBJECT_CONTAINER_ACLS.items():
# Convert to string for the comparison because swiftclient
# returns byte values as bytes sometimes and apparently ==
# on bytes doesn't work like you'd think
if str(acl) == str(value):
return key
raise exc.OpenStackCloudException(
"Could not determine container access for ACL: %s." % acl)
def _get_file_hashes(self, filename):
file_key = "{filename}:{mtime}".format(
filename=filename,
mtime=os.stat(filename).st_mtime)
if file_key not in self._file_hash_cache:
self.log.debug(
'Calculating hashes for %(filename)s', {'filename': filename})
md5 = hashlib.md5()
sha256 = hashlib.sha256()
with open(filename, 'rb') as file_obj:
for chunk in iter(lambda: file_obj.read(8192), b''):
md5.update(chunk)
sha256.update(chunk)
self._file_hash_cache[file_key] = dict(
md5=md5.hexdigest(), sha256=sha256.hexdigest())
self.log.debug(
"Image file %(filename)s md5:%(md5)s sha256:%(sha256)s",
{'filename': filename,
'md5': self._file_hash_cache[file_key]['md5'],
'sha256': self._file_hash_cache[file_key]['sha256']})
return (self._file_hash_cache[file_key]['md5'],
self._file_hash_cache[file_key]['sha256'])
@_utils.cache_on_arguments()
def get_object_capabilities(self):
# The endpoint in the catalog has version and project-id in it
# To get capabilities, we have to disassemble and reassemble the URL
# This logic is taken from swiftclient
endpoint = urllib.parse.urlparse(
self._object_store_client.get_endpoint())
url = "{scheme}://{netloc}/info".format(
scheme=endpoint.scheme, netloc=endpoint.netloc)
return self._object_store_client.get(url)
def get_object_segment_size(self, segment_size):
"""Get a segment size that will work given capabilities"""
if segment_size is None:
segment_size = DEFAULT_OBJECT_SEGMENT_SIZE
min_segment_size = 0
try:
caps = self.get_object_capabilities()
except exc.OpenStackCloudHTTPError as e:
if e.response.status_code in (404, 412):
# Clear the exception so that it doesn't linger
# and get reported as an Inner Exception later
_utils._exc_clear()
server_max_file_size = DEFAULT_MAX_FILE_SIZE
self.log.info(
"Swift capabilities not supported. "
"Using default max file size.")
else:
raise
else:
server_max_file_size = caps.get('swift', {}).get('max_file_size',
0)
min_segment_size = caps.get('slo', {}).get('min_segment_size', 0)
if segment_size > server_max_file_size:
return server_max_file_size
if segment_size < min_segment_size:
return min_segment_size
return segment_size
def is_object_stale(
self, container, name, filename, file_md5=None, file_sha256=None):
metadata = self.get_object_metadata(container, name)
if not metadata:
self.log.debug(
"swift stale check, no object: {container}/{name}".format(
container=container, name=name))
return True
if not (file_md5 or file_sha256):
(file_md5, file_sha256) = self._get_file_hashes(filename)
md5_key = metadata.get(OBJECT_MD5_KEY, '')
sha256_key = metadata.get(OBJECT_SHA256_KEY, '')
up_to_date = self._hashes_up_to_date(
md5=file_md5, sha256=file_sha256,
md5_key=md5_key, sha256_key=sha256_key)
if not up_to_date:
self.log.debug(
"swift checksum mismatch: "
" %(filename)s!=%(container)s/%(name)s",
{'filename': filename, 'container': container, 'name': name})
return True
self.log.debug(
"swift object up to date: %(container)s/%(name)s",
{'container': container, 'name': name})
return False
def create_object(
self, container, name, filename=None,
md5=None, sha256=None, segment_size=None,
use_slo=True, metadata=None,
**headers):
"""Create a file object
:param container: The name of the container to store the file in.
This container will be created if it does not exist already.
:param name: Name for the object within the container.
:param filename: The path to the local file whose contents will be
uploaded.
:param md5: A hexadecimal md5 of the file. (Optional), if it is known
and can be passed here, it will save repeating the expensive md5
process. It is assumed to be accurate.
:param sha256: A hexadecimal sha256 of the file. (Optional) See md5.
:param segment_size: Break the uploaded object into segments of this
many bytes. (Optional) Shade will attempt to discover the maximum
value for this from the server if it is not specified, or will use
a reasonable default.
:param headers: These will be passed through to the object creation
API as HTTP Headers.
:param use_slo: If the object is large enough to need to be a Large
Object, use a static rather than dynamic object. Static Objects
will delete segment objects when the manifest object is deleted.
(optional, defaults to True)
:param metadata: This dict will get changed into headers that set
metadata of the object
:raises: ``OpenStackCloudException`` on operation error.
"""
if not metadata:
metadata = {}
if not filename:
filename = name
# segment_size gets used as a step value in a range call, so needs
# to be an int
if segment_size:
segment_size = int(segment_size)
segment_size = self.get_object_segment_size(segment_size)
file_size = os.path.getsize(filename)
if not (md5 or sha256):
(md5, sha256) = self._get_file_hashes(filename)
headers[OBJECT_MD5_KEY] = md5 or ''
headers[OBJECT_SHA256_KEY] = sha256 or ''
for (k, v) in metadata.items():
headers['x-object-meta-' + k] = v
# On some clouds this is not necessary. On others it is. I'm confused.
self.create_container(container)
if self.is_object_stale(container, name, filename, md5, sha256):
endpoint = '{container}/{name}'.format(
container=container, name=name)
self.log.debug(
"swift uploading %(filename)s to %(endpoint)s",
{'filename': filename, 'endpoint': endpoint})
if file_size <= segment_size:
self._upload_object(endpoint, filename, headers)
else:
self._upload_large_object(
endpoint, filename, headers,
file_size, segment_size, use_slo)
def _upload_object(self, endpoint, filename, headers):
return self._object_store_client.put(
endpoint, headers=headers, data=open(filename, 'r'))
def _get_file_segments(self, endpoint, filename, file_size, segment_size):
# Use an ordered dict here so that testing can replicate things
segments = collections.OrderedDict()
for (index, offset) in enumerate(range(0, file_size, segment_size)):
remaining = file_size - (index * segment_size)
segment = _utils.FileSegment(
filename, offset,
segment_size if segment_size < remaining else remaining)
name = '{endpoint}/{index:0>6}'.format(
endpoint=endpoint, index=index)
segments[name] = segment
return segments
def _object_name_from_url(self, url):
'''Get container_name/object_name from the full URL called.
Remove the Swift endpoint from the front of the URL, and remove
the leaving / that will leave behind.'''
endpoint = self._object_store_client.get_endpoint()
object_name = url.replace(endpoint, '')
if object_name.startswith('/'):
object_name = object_name[1:]
return object_name
def _add_etag_to_manifest(self, segment_results, manifest):
for result in segment_results:
if 'Etag' not in result.headers:
continue
name = self._object_name_from_url(result.url)
for entry in manifest:
if entry['path'] == '/{name}'.format(name=name):
entry['etag'] = result.headers['Etag']
def _upload_large_object(
self, endpoint, filename,
headers, file_size, segment_size, use_slo):
# If the object is big, we need to break it up into segments that
# are no larger than segment_size, upload each of them individually
# and then upload a manifest object. The segments can be uploaded in
# parallel, so we'll use the async feature of the TaskManager.
segment_futures = []
segment_results = []
retry_results = []
retry_futures = []
manifest = []
# Get an OrderedDict with keys being the swift location for the
# segment, the value a FileSegment file-like object that is a
# slice of the data for the segment.
segments = self._get_file_segments(
endpoint, filename, file_size, segment_size)
# Schedule the segments for upload
for name, segment in segments.items():
# Async call to put - schedules execution and returns a future
segment_future = self._object_store_client.put(
name, headers=headers, data=segment, run_async=True)
segment_futures.append(segment_future)
# TODO(mordred) Collect etags from results to add to this manifest
# dict. Then sort the list of dicts by path.
manifest.append(dict(
path='/{name}'.format(name=name),
size_bytes=segment.length))
# Try once and collect failed results to retry
segment_results, retry_results = task_manager.wait_for_futures(
segment_futures, raise_on_error=False)
self._add_etag_to_manifest(segment_results, manifest)
for result in retry_results:
# Grab the FileSegment for the failed upload so we can retry
name = self._object_name_from_url(result.url)
segment = segments[name]
segment.seek(0)
# Async call to put - schedules execution and returns a future
segment_future = self._object_store_client.put(
name, headers=headers, data=segment, run_async=True)
# TODO(mordred) Collect etags from results to add to this manifest
# dict. Then sort the list of dicts by path.
retry_futures.append(segment_future)
# If any segments fail the second time, just throw the error
segment_results, retry_results = task_manager.wait_for_futures(
retry_futures, raise_on_error=True)
self._add_etag_to_manifest(segment_results, manifest)
if use_slo:
return self._finish_large_object_slo(endpoint, headers, manifest)
else:
return self._finish_large_object_dlo(endpoint, headers)
def _finish_large_object_slo(self, endpoint, headers, manifest):
# TODO(mordred) send an etag of the manifest, which is the md5sum
# of the concatenation of the etags of the results
headers = headers.copy()
return self._object_store_client.put(
endpoint,
params={'multipart-manifest': 'put'},
headers=headers, data=json.dumps(manifest))
def _finish_large_object_dlo(self, endpoint, headers):
headers = headers.copy()
headers['X-Object-Manifest'] = endpoint
return self._object_store_client.put(endpoint, headers=headers)
def update_object(self, container, name, metadata=None, **headers):
"""Update the metadata of an object
:param container: The name of the container the object is in
:param name: Name for the object within the container.
:param metadata: This dict will get changed into headers that set
metadata of the object
:param headers: These will be passed through to the object update
API as HTTP Headers.
:raises: ``OpenStackCloudException`` on operation error.
"""
if not metadata:
metadata = {}
metadata_headers = {}
for (k, v) in metadata.items():
metadata_headers['x-object-meta-' + k] = v
headers = dict(headers, **metadata_headers)
return self._object_store_client.post(
'{container}/{object}'.format(
container=container, object=name),
headers=headers)
def list_objects(self, container, full_listing=True):
"""List objects.
:param container: Name of the container to list objects in.
:param full_listing: Ignored. Present for backwards compat
:returns: list of Munch of the objects
:raises: OpenStackCloudException on operation error.
"""
return self._object_store_client.get(
container, params=dict(format='json'))
def delete_object(self, container, name, meta=None):
"""Delete an object from a container.
:param string container: Name of the container holding the object.
:param string name: Name of the object to delete.
:param dict meta: Metadata for the object in question. (optional, will
be fetched if not provided)
:returns: True if delete succeeded, False if the object was not found.
:raises: OpenStackCloudException on operation error.
"""
# TODO(mordred) DELETE for swift returns status in text/plain format
# like so:
# Number Deleted: 15
# Number Not Found: 0
# Response Body:
# Response Status: 200 OK
# Errors:
# We should ultimately do something with that
try:
if not meta:
meta = self.get_object_metadata(container, name)
if not meta:
return False
params = {}
if meta.get('X-Static-Large-Object', None) == 'True':
params['multipart-manifest'] = 'delete'
self._object_store_client.delete(
'{container}/{object}'.format(
container=container, object=name),
params=params)
return True
except exc.OpenStackCloudHTTPError:
return False
def delete_autocreated_image_objects(
self, container=OBJECT_AUTOCREATE_CONTAINER):
"""Delete all objects autocreated for image uploads.
This method should generally not be needed, as shade should clean up
the objects it uses for object-based image creation. If something
goes wrong and it is found that there are leaked objects, this method
can be used to delete any objects that shade has created on the user's
behalf in service of image uploads.
"""
# This method only makes sense on clouds that use tasks
if not self.image_api_use_tasks:
return False
deleted = False
for obj in self.list_objects(container):
meta = self.get_object_metadata(container, obj['name'])
if meta.get(OBJECT_AUTOCREATE_KEY) == 'true':
if self.delete_object(container, obj['name'], meta):
deleted = True
return deleted
def get_object_metadata(self, container, name):
try:
return self._object_store_client.head(
'{container}/{object}'.format(
container=container, object=name)).headers
except exc.OpenStackCloudException as e:
if e.response.status_code == 404:
return None
raise
def get_object(self, container, obj, query_string=None,
resp_chunk_size=1024, outfile=None):
"""Get the headers and body of an object
:param string container: name of the container.
:param string obj: name of the object.
:param string query_string: query args for uri.
(delimiter, prefix, etc.)
:param int resp_chunk_size: chunk size of data to read. Only used
if the results are being written to a
file. (optional, defaults to 1k)
:param outfile: Write the object to a file instead of
returning the contents. If this option is
given, body in the return tuple will be None. outfile
can either be a file path given as a string, or a
File like object.
:returns: Tuple (headers, body) of the object, or None if the object
is not found (404)
:raises: OpenStackCloudException on operation error.
"""
# TODO(mordred) implement resp_chunk_size
try:
endpoint = '{container}/{object}'.format(
container=container, object=obj)
if query_string:
endpoint = '{endpoint}?{query_string}'.format(
endpoint=endpoint, query_string=query_string)
response = self._object_store_client.get(
endpoint, stream=True)
response_headers = {
k.lower(): v for k, v in response.headers.items()}
if outfile:
if isinstance(outfile, six.string_types):
outfile_handle = open(outfile, 'wb')
else:
outfile_handle = outfile
for chunk in response.iter_content(
resp_chunk_size, decode_unicode=False):
outfile_handle.write(chunk)
if isinstance(outfile, six.string_types):
outfile_handle.close()
else:
outfile_handle.flush()
return (response_headers, None)
else:
return (response_headers, response.text)
except exc.OpenStackCloudHTTPError as e:
if e.response.status_code == 404:
return None
raise
def create_subnet(self, network_name_or_id, cidr=None, ip_version=4,
enable_dhcp=False, subnet_name=None, tenant_id=None,
allocation_pools=None,
gateway_ip=None, disable_gateway_ip=False,
dns_nameservers=None, host_routes=None,
ipv6_ra_mode=None, ipv6_address_mode=None,
use_default_subnetpool=False):
"""Create a subnet on a specified network.
:param string network_name_or_id:
The unique name or ID of the attached network. If a non-unique
name is supplied, an exception is raised.
:param string cidr:
The CIDR.
:param int ip_version:
The IP version, which is 4 or 6.
:param bool enable_dhcp:
Set to ``True`` if DHCP is enabled and ``False`` if disabled.
Default is ``False``.
:param string subnet_name:
The name of the subnet.
:param string tenant_id:
The ID of the tenant who owns the network. Only administrative users
can specify a tenant ID other than their own.
:param list allocation_pools:
A list of dictionaries of the start and end addresses for the
allocation pools. For example::
[
{
"start": "192.168.199.2",
"end": "192.168.199.254"
}
]
:param string gateway_ip:
The gateway IP address. When you specify both allocation_pools and
gateway_ip, you must ensure that the gateway IP does not overlap
with the specified allocation pools.
:param bool disable_gateway_ip:
Set to ``True`` if gateway IP address is disabled and ``False`` if
enabled. It is not allowed with gateway_ip.
Default is ``False``.
:param list dns_nameservers:
A list of DNS name servers for the subnet. For example::
[ "8.8.8.7", "8.8.8.8" ]
:param list host_routes:
A list of host route dictionaries for the subnet. For example::
[
{
"destination": "0.0.0.0/0",
"nexthop": "123.456.78.9"
},
{
"destination": "192.168.0.0/24",
"nexthop": "192.168.0.1"
}
]
:param string ipv6_ra_mode:
IPv6 Router Advertisement mode. Valid values are: 'dhcpv6-stateful',
'dhcpv6-stateless', or 'slaac'.
:param string ipv6_address_mode:
IPv6 address mode. Valid values are: 'dhcpv6-stateful',
'dhcpv6-stateless', or 'slaac'.
:param bool use_default_subnetpool:
Use the default subnetpool for ``ip_version`` to obtain a CIDR. It
is required to pass ``None`` to the ``cidr`` argument when enabling
this option.
:returns: The new subnet object.
:raises: OpenStackCloudException on operation error.
"""
if tenant_id is not None:
filters = {'tenant_id': tenant_id}
else:
filters = None
network = self.get_network(network_name_or_id, filters)
if not network:
raise exc.OpenStackCloudException(
"Network %s not found." % network_name_or_id)
if disable_gateway_ip and gateway_ip:
raise exc.OpenStackCloudException(
'arg:disable_gateway_ip is not allowed with arg:gateway_ip')
if not cidr and not use_default_subnetpool:
raise exc.OpenStackCloudException(
'arg:cidr is required when a subnetpool is not used')
if cidr and use_default_subnetpool:
raise exc.OpenStackCloudException(
'arg:cidr must be set to None when use_default_subnetpool == '
'True')
# Be friendly on ip_version and allow strings
if isinstance(ip_version, six.string_types):
try:
ip_version = int(ip_version)
except ValueError:
raise exc.OpenStackCloudException(
'ip_version must be an integer')
# The body of the neutron message for the subnet we wish to create.
# This includes attributes that are required or have defaults.
subnet = {
'network_id': network['id'],
'ip_version': ip_version,
'enable_dhcp': enable_dhcp
}
# Add optional attributes to the message.
if cidr:
subnet['cidr'] = cidr
if subnet_name:
subnet['name'] = subnet_name
if tenant_id:
subnet['tenant_id'] = tenant_id
if allocation_pools:
subnet['allocation_pools'] = allocation_pools
if gateway_ip:
subnet['gateway_ip'] = gateway_ip
if disable_gateway_ip:
subnet['gateway_ip'] = None
if dns_nameservers:
subnet['dns_nameservers'] = dns_nameservers
if host_routes:
subnet['host_routes'] = host_routes
if ipv6_ra_mode:
subnet['ipv6_ra_mode'] = ipv6_ra_mode
if ipv6_address_mode:
subnet['ipv6_address_mode'] = ipv6_address_mode
if use_default_subnetpool:
subnet['use_default_subnetpool'] = True
data = self._network_client.post("/subnets.json",
json={"subnet": subnet})
return self._get_and_munchify('subnet', data)
def delete_subnet(self, name_or_id):
"""Delete a subnet.
If a name, instead of a unique UUID, is supplied, it is possible
that we could find more than one matching subnet since names are
not required to be unique. An error will be raised in this case.
:param name_or_id: Name or ID of the subnet being deleted.
:returns: True if delete succeeded, False otherwise.
:raises: OpenStackCloudException on operation error.
"""
subnet = self.get_subnet(name_or_id)
if not subnet:
self.log.debug("Subnet %s not found for deleting", name_or_id)
return False
self._network_client.delete(
"/subnets/{subnet_id}.json".format(subnet_id=subnet['id']))
return True
def update_subnet(self, name_or_id, subnet_name=None, enable_dhcp=None,
gateway_ip=None, disable_gateway_ip=None,
allocation_pools=None, dns_nameservers=None,
host_routes=None):
"""Update an existing subnet.
:param string name_or_id:
Name or ID of the subnet to update.
:param string subnet_name:
The new name of the subnet.
:param bool enable_dhcp:
Set to ``True`` if DHCP is enabled and ``False`` if disabled.
:param string gateway_ip:
The gateway IP address. When you specify both allocation_pools and
gateway_ip, you must ensure that the gateway IP does not overlap
with the specified allocation pools.
:param bool disable_gateway_ip:
Set to ``True`` if gateway IP address is disabled and ``False`` if
enabled. It is not allowed with gateway_ip.
Default is ``False``.
:param list allocation_pools:
A list of dictionaries of the start and end addresses for the
allocation pools. For example::
[
{
"start": "192.168.199.2",
"end": "192.168.199.254"
}
]
:param list dns_nameservers:
A list of DNS name servers for the subnet. For example::
[ "8.8.8.7", "8.8.8.8" ]
:param list host_routes:
A list of host route dictionaries for the subnet. For example::
[
{
"destination": "0.0.0.0/0",
"nexthop": "123.456.78.9"
},
{
"destination": "192.168.0.0/24",
"nexthop": "192.168.0.1"
}
]
:returns: The updated subnet object.
:raises: OpenStackCloudException on operation error.
"""
subnet = {}
if subnet_name:
subnet['name'] = subnet_name
if enable_dhcp is not None:
subnet['enable_dhcp'] = enable_dhcp
if gateway_ip:
subnet['gateway_ip'] = gateway_ip
if disable_gateway_ip:
subnet['gateway_ip'] = None
if allocation_pools:
subnet['allocation_pools'] = allocation_pools
if dns_nameservers:
subnet['dns_nameservers'] = dns_nameservers
if host_routes:
subnet['host_routes'] = host_routes
if not subnet:
self.log.debug("No subnet data to update")
return
if disable_gateway_ip and gateway_ip:
raise exc.OpenStackCloudException(
'arg:disable_gateway_ip is not allowed with arg:gateway_ip')
curr_subnet = self.get_subnet(name_or_id)
if not curr_subnet:
raise exc.OpenStackCloudException(
"Subnet %s not found." % name_or_id)
data = self._network_client.put(
"/subnets/{subnet_id}.json".format(subnet_id=curr_subnet['id']),
json={"subnet": subnet})
return self._get_and_munchify('subnet', data)
@_utils.valid_kwargs('name', 'admin_state_up', 'mac_address', 'fixed_ips',
'subnet_id', 'ip_address', 'security_groups',
'allowed_address_pairs', 'extra_dhcp_opts',
'device_owner', 'device_id')
def create_port(self, network_id, **kwargs):
"""Create a port
:param network_id: The ID of the network. (Required)
:param name: A symbolic name for the port. (Optional)
:param admin_state_up: The administrative status of the port,
which is up (true, default) or down (false). (Optional)
:param mac_address: The MAC address. (Optional)
:param fixed_ips: List of ip_addresses and subnet_ids. See subnet_id
and ip_address. (Optional)
For example::
[
{
"ip_address": "10.29.29.13",
"subnet_id": "a78484c4-c380-4b47-85aa-21c51a2d8cbd"
}, ...
]
:param subnet_id: If you specify only a subnet ID, OpenStack Networking
allocates an available IP from that subnet to the port. (Optional)
If you specify both a subnet ID and an IP address, OpenStack
Networking tries to allocate the specified address to the port.
:param ip_address: If you specify both a subnet ID and an IP address,
OpenStack Networking tries to allocate the specified address to
the port.
:param security_groups: List of security group UUIDs. (Optional)
:param allowed_address_pairs: Allowed address pairs list (Optional)
For example::
[
{
"ip_address": "23.23.23.1",
"mac_address": "fa:16:3e:c4:cd:3f"
}, ...
]
:param extra_dhcp_opts: Extra DHCP options. (Optional).
For example::
[
{
"opt_name": "opt name1",
"opt_value": "value1"
}, ...
]
:param device_owner: The ID of the entity that uses this port.
For example, a DHCP agent. (Optional)
:param device_id: The ID of the device that uses this port.
For example, a virtual server. (Optional)
:returns: a ``munch.Munch`` describing the created port.
:raises: ``OpenStackCloudException`` on operation error.
"""
kwargs['network_id'] = network_id
data = self._network_client.post(
"/ports.json", json={'port': kwargs},
error_message="Error creating port for network {0}".format(
network_id))
return self._get_and_munchify('port', data)
@_utils.valid_kwargs('name', 'admin_state_up', 'fixed_ips',
'security_groups', 'allowed_address_pairs',
'extra_dhcp_opts', 'device_owner', 'device_id')
def update_port(self, name_or_id, **kwargs):
"""Update a port
Note: to unset an attribute use None value. To leave an attribute
untouched just omit it.
:param name_or_id: name or ID of the port to update. (Required)
:param name: A symbolic name for the port. (Optional)
:param admin_state_up: The administrative status of the port,
which is up (true) or down (false). (Optional)
:param fixed_ips: List of ip_addresses and subnet_ids. (Optional)
If you specify only a subnet ID, OpenStack Networking allocates
an available IP from that subnet to the port.
If you specify both a subnet ID and an IP address, OpenStack
Networking tries to allocate the specified address to the port.
For example::
[
{
"ip_address": "10.29.29.13",
"subnet_id": "a78484c4-c380-4b47-85aa-21c51a2d8cbd"
}, ...
]
:param security_groups: List of security group UUIDs. (Optional)
:param allowed_address_pairs: Allowed address pairs list (Optional)
For example::
[
{
"ip_address": "23.23.23.1",
"mac_address": "fa:16:3e:c4:cd:3f"
}, ...
]
:param extra_dhcp_opts: Extra DHCP options. (Optional).
For example::
[
{
"opt_name": "opt name1",
"opt_value": "value1"
}, ...
]
:param device_owner: The ID of the entity that uses this port.
For example, a DHCP agent. (Optional)
:param device_id: The ID of the resource this port is attached to.
:returns: a ``munch.Munch`` describing the updated port.
:raises: OpenStackCloudException on operation error.
"""
port = self.get_port(name_or_id=name_or_id)
if port is None:
raise exc.OpenStackCloudException(
"failed to find port '{port}'".format(port=name_or_id))
data = self._network_client.put(
"/ports/{port_id}.json".format(port_id=port['id']),
json={"port": kwargs},
error_message="Error updating port {0}".format(name_or_id))
return self._get_and_munchify('port', data)
def delete_port(self, name_or_id):
"""Delete a port
:param name_or_id: ID or name of the port to delete.
:returns: True if delete succeeded, False otherwise.
:raises: OpenStackCloudException on operation error.
"""
port = self.get_port(name_or_id=name_or_id)
if port is None:
self.log.debug("Port %s not found for deleting", name_or_id)
return False
self._network_client.delete(
"/ports/{port_id}.json".format(port_id=port['id']),
error_message="Error deleting port {0}".format(name_or_id))
return True
def create_security_group(self, name, description, project_id=None):
"""Create a new security group
:param string name: A name for the security group.
:param string description: Describes the security group.
:param string project_id:
Specify the project ID this security group will be created
on (admin-only).
:returns: A ``munch.Munch`` representing the new security group.
:raises: OpenStackCloudException on operation error.
:raises: OpenStackCloudUnavailableFeature if security groups are
not supported on this cloud.
"""
# Security groups not supported
if not self._has_secgroups():
raise exc.OpenStackCloudUnavailableFeature(
"Unavailable feature: security groups"
)
data = []
security_group_json = {
'security_group': {
'name': name, 'description': description
}}
if project_id is not None:
security_group_json['security_group']['tenant_id'] = project_id
if self._use_neutron_secgroups():
data = self._network_client.post(
'/security-groups.json',
json=security_group_json,
error_message="Error creating security group {0}".format(name))
else:
data = self._compute_client.post(
'/os-security-groups', json=security_group_json)
return self._normalize_secgroup(
self._get_and_munchify('security_group', data))
def delete_security_group(self, name_or_id):
"""Delete a security group
:param string name_or_id: The name or unique ID of the security group.
:returns: True if delete succeeded, False otherwise.
:raises: OpenStackCloudException on operation error.
:raises: OpenStackCloudUnavailableFeature if security groups are
not supported on this cloud.
"""
# Security groups not supported
if not self._has_secgroups():
raise exc.OpenStackCloudUnavailableFeature(
"Unavailable feature: security groups"
)
# TODO(mordred): Let's come back and stop doing a GET before we do
# the delete.
secgroup = self.get_security_group(name_or_id)
if secgroup is None:
self.log.debug('Security group %s not found for deleting',
name_or_id)
return False
if self._use_neutron_secgroups():
self._network_client.delete(
'/security-groups/{sg_id}.json'.format(sg_id=secgroup['id']),
error_message="Error deleting security group {0}".format(
name_or_id)
)
return True
else:
self._compute_client.delete(
'/os-security-groups/{id}'.format(id=secgroup['id']))
return True
@_utils.valid_kwargs('name', 'description')
def update_security_group(self, name_or_id, **kwargs):
"""Update a security group
:param string name_or_id: Name or ID of the security group to update.
:param string name: New name for the security group.
:param string description: New description for the security group.
:returns: A ``munch.Munch`` describing the updated security group.
:raises: OpenStackCloudException on operation error.
"""
# Security groups not supported
if not self._has_secgroups():
raise exc.OpenStackCloudUnavailableFeature(
"Unavailable feature: security groups"
)
group = self.get_security_group(name_or_id)
if group is None:
raise exc.OpenStackCloudException(
"Security group %s not found." % name_or_id)
if self._use_neutron_secgroups():
data = self._network_client.put(
'/security-groups/{sg_id}.json'.format(sg_id=group['id']),
json={'security_group': kwargs},
error_message="Error updating security group {0}".format(
name_or_id))
else:
for key in ('name', 'description'):
kwargs.setdefault(key, group[key])
data = self._compute_client.put(
'/os-security-groups/{id}'.format(id=group['id']),
json={'security-group': kwargs})
return self._normalize_secgroup(
self._get_and_munchify('security_group', data))
def create_security_group_rule(self,
secgroup_name_or_id,
port_range_min=None,
port_range_max=None,
protocol=None,
remote_ip_prefix=None,
remote_group_id=None,
direction='ingress',
ethertype='IPv4',
project_id=None):
"""Create a new security group rule
:param string secgroup_name_or_id:
The security group name or ID to associate with this security
group rule. If a non-unique group name is given, an exception
is raised.
:param int port_range_min:
The minimum port number in the range that is matched by the
security group rule. If the protocol is TCP or UDP, this value
must be less than or equal to the port_range_max attribute value.
If nova is used by the cloud provider for security groups, then
a value of None will be transformed to -1.
:param int port_range_max:
The maximum port number in the range that is matched by the
security group rule. The port_range_min attribute constrains the
port_range_max attribute. If nova is used by the cloud provider
for security groups, then a value of None will be transformed
to -1.
:param string protocol:
The protocol that is matched by the security group rule. Valid
values are None, tcp, udp, and icmp.
:param string remote_ip_prefix:
The remote IP prefix to be associated with this security group
rule. This attribute matches the specified IP prefix as the
source IP address of the IP packet.
:param string remote_group_id:
The remote group ID to be associated with this security group
rule.
:param string direction:
Ingress or egress: The direction in which the security group
rule is applied. For a compute instance, an ingress security
group rule is applied to incoming (ingress) traffic for that
instance. An egress rule is applied to traffic leaving the
instance.
:param string ethertype:
Must be IPv4 or IPv6, and addresses represented in CIDR must
match the ingress or egress rules.
:param string project_id:
Specify the project ID this security group will be created
on (admin-only).
:returns: A ``munch.Munch`` representing the new security group rule.
:raises: OpenStackCloudException on operation error.
"""
# Security groups not supported
if not self._has_secgroups():
raise exc.OpenStackCloudUnavailableFeature(
"Unavailable feature: security groups"
)
secgroup = self.get_security_group(secgroup_name_or_id)
if not secgroup:
raise exc.OpenStackCloudException(
"Security group %s not found." % secgroup_name_or_id)
if self._use_neutron_secgroups():
# NOTE: Nova accepts -1 port numbers, but Neutron accepts None
# as the equivalent value.
rule_def = {
'security_group_id': secgroup['id'],
'port_range_min':
None if port_range_min == -1 else port_range_min,
'port_range_max':
None if port_range_max == -1 else port_range_max,
'protocol': protocol,
'remote_ip_prefix': remote_ip_prefix,
'remote_group_id': remote_group_id,
'direction': direction,
'ethertype': ethertype
}
if project_id is not None:
rule_def['tenant_id'] = project_id
data = self._network_client.post(
'/security-group-rules.json',
json={'security_group_rule': rule_def},
error_message="Error creating security group rule")
else:
# NOTE: Neutron accepts None for protocol. Nova does not.
if protocol is None:
raise exc.OpenStackCloudException('Protocol must be specified')
if direction == 'egress':
self.log.debug(
'Rule creation failed: Nova does not support egress rules'
)
raise exc.OpenStackCloudException(
'No support for egress rules')
# NOTE: Neutron accepts None for ports, but Nova requires -1
# as the equivalent value for ICMP.
#
# For TCP/UDP, if both are None, Neutron allows this and Nova
# represents this as all ports (1-65535). Nova does not accept
# None values, so to hide this difference, we will automatically
# convert to the full port range. If only a single port value is
# specified, it will error as normal.
if protocol == 'icmp':
if port_range_min is None:
port_range_min = -1
if port_range_max is None:
port_range_max = -1
elif protocol in ['tcp', 'udp']:
if port_range_min is None and port_range_max is None:
port_range_min = 1
port_range_max = 65535
security_group_rule_dict = dict(security_group_rule=dict(
parent_group_id=secgroup['id'],
ip_protocol=protocol,
from_port=port_range_min,
to_port=port_range_max,
cidr=remote_ip_prefix,
group_id=remote_group_id
))
if project_id is not None:
security_group_rule_dict[
'security_group_rule']['tenant_id'] = project_id
data = self._compute_client.post(
'/os-security-group-rules', json=security_group_rule_dict
)
return self._normalize_secgroup_rule(
self._get_and_munchify('security_group_rule', data))
def delete_security_group_rule(self, rule_id):
"""Delete a security group rule
:param string rule_id: The unique ID of the security group rule.
:returns: True if delete succeeded, False otherwise.
:raises: OpenStackCloudException on operation error.
:raises: OpenStackCloudUnavailableFeature if security groups are
not supported on this cloud.
"""
# Security groups not supported
if not self._has_secgroups():
raise exc.OpenStackCloudUnavailableFeature(
"Unavailable feature: security groups"
)
if self._use_neutron_secgroups():
try:
self._network_client.delete(
'/security-group-rules/{sg_id}.json'.format(sg_id=rule_id),
error_message="Error deleting security group rule "
"{0}".format(rule_id))
except exc.OpenStackCloudResourceNotFound:
return False
return True
else:
self._compute_client.delete(
'/os-security-group-rules/{id}'.format(id=rule_id))
return True
def list_zones(self):
"""List all available zones.
:returns: A list of zones dicts.
"""
data = self._dns_client.get(
"/zones",
error_message="Error fetching zones list")
return self._get_and_munchify('zones', data)
def get_zone(self, name_or_id, filters=None):
"""Get a zone by name or ID.
:param name_or_id: Name or ID of the zone
:param filters:
A dictionary of meta data to use for further filtering
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A zone dict or None if no matching zone is found.
"""
return _utils._get_entity(self, 'zone', name_or_id, filters)
def search_zones(self, name_or_id=None, filters=None):
zones = self.list_zones()
return _utils._filter_list(zones, name_or_id, filters)
def create_zone(self, name, zone_type=None, email=None, description=None,
ttl=None, masters=None):
"""Create a new zone.
:param name: Name of the zone being created.
:param zone_type: Type of the zone (primary/secondary)
:param email: Email of the zone owner (only
applies if zone_type is primary)
:param description: Description of the zone
:param ttl: TTL (Time to live) value in seconds
:param masters: Master nameservers (only applies
if zone_type is secondary)
:returns: a dict representing the created zone.
:raises: OpenStackCloudException on operation error.
"""
# We capitalize in case the user passes time in lowercase, as
# designate call expects PRIMARY/SECONDARY
if zone_type is not None:
zone_type = zone_type.upper()
if zone_type not in ('PRIMARY', 'SECONDARY'):
raise exc.OpenStackCloudException(
"Invalid type %s, valid choices are PRIMARY or SECONDARY" %
zone_type)
zone = {
"name": name,
"email": email,
"description": description,
}
if ttl is not None:
zone["ttl"] = ttl
if zone_type is not None:
zone["type"] = zone_type
if masters is not None:
zone["masters"] = masters
data = self._dns_client.post(
"/zones", json=zone,
error_message="Unable to create zone {name}".format(name=name))
return self._get_and_munchify(key=None, data=data)
@_utils.valid_kwargs('email', 'description', 'ttl', 'masters')
def update_zone(self, name_or_id, **kwargs):
"""Update a zone.
:param name_or_id: Name or ID of the zone being updated.
:param email: Email of the zone owner (only
applies if zone_type is primary)
:param description: Description of the zone
:param ttl: TTL (Time to live) value in seconds
:param masters: Master nameservers (only applies
if zone_type is secondary)
:returns: a dict representing the updated zone.
:raises: OpenStackCloudException on operation error.
"""
zone = self.get_zone(name_or_id)
if not zone:
raise exc.OpenStackCloudException(
"Zone %s not found." % name_or_id)
data = self._dns_client.patch(
"/zones/{zone_id}".format(zone_id=zone['id']), json=kwargs,
error_message="Error updating zone {0}".format(name_or_id))
return self._get_and_munchify(key=None, data=data)
def delete_zone(self, name_or_id):
"""Delete a zone.
:param name_or_id: Name or ID of the zone being deleted.
:returns: True if delete succeeded, False otherwise.
:raises: OpenStackCloudException on operation error.
"""
zone = self.get_zone(name_or_id)
if zone is None:
self.log.debug("Zone %s not found for deleting", name_or_id)
return False
return self._dns_client.delete(
"/zones/{zone_id}".format(zone_id=zone['id']),
error_message="Error deleting zone {0}".format(name_or_id))
return True
def list_recordsets(self, zone):
"""List all available recordsets.
:param zone: Name or ID of the zone managing the recordset
:returns: A list of recordsets.
"""
return self._dns_client.get(
"/zones/{zone_id}/recordsets".format(zone_id=zone),
error_message="Error fetching recordsets list")
def get_recordset(self, zone, name_or_id):
"""Get a recordset by name or ID.
:param zone: Name or ID of the zone managing the recordset
:param name_or_id: Name or ID of the recordset
:returns: A recordset dict or None if no matching recordset is
found.
"""
try:
return self._dns_client.get(
"/zones/{zone_id}/recordsets/{recordset_id}".format(
zone_id=zone, recordset_id=name_or_id),
error_message="Error fetching recordset")
except Exception:
return None
def search_recordsets(self, zone, name_or_id=None, filters=None):
recordsets = self.list_recordsets(zone=zone)
return _utils._filter_list(recordsets, name_or_id, filters)
def create_recordset(self, zone, name, recordset_type, records,
description=None, ttl=None):
"""Create a recordset.
:param zone: Name or ID of the zone managing the recordset
:param name: Name of the recordset
:param recordset_type: Type of the recordset
:param records: List of the recordset definitions
:param description: Description of the recordset
:param ttl: TTL value of the recordset
:returns: a dict representing the created recordset.
:raises: OpenStackCloudException on operation error.
"""
if self.get_zone(zone) is None:
raise exc.OpenStackCloudException(
"Zone %s not found." % zone)
# We capitalize the type in case the user sends in lowercase
recordset_type = recordset_type.upper()
body = {
'name': name,
'type': recordset_type,
'records': records
}
if description:
body['description'] = description
if ttl:
body['ttl'] = ttl
return self._dns_client.post(
"/zones/{zone_id}/recordsets".format(zone_id=zone),
json=body,
error_message="Error creating recordset {name}".format(name=name))
@_utils.valid_kwargs('description', 'ttl', 'records')
def update_recordset(self, zone, name_or_id, **kwargs):
"""Update a recordset.
:param zone: Name or ID of the zone managing the recordset
:param name_or_id: Name or ID of the recordset being updated.
:param records: List of the recordset definitions
:param description: Description of the recordset
:param ttl: TTL (Time to live) value in seconds of the recordset
:returns: a dict representing the updated recordset.
:raises: OpenStackCloudException on operation error.
"""
zone_obj = self.get_zone(zone)
if zone_obj is None:
raise exc.OpenStackCloudException(
"Zone %s not found." % zone)
recordset_obj = self.get_recordset(zone, name_or_id)
if recordset_obj is None:
raise exc.OpenStackCloudException(
"Recordset %s not found." % name_or_id)
new_recordset = self._dns_client.put(
"/zones/{zone_id}/recordsets/{recordset_id}".format(
zone_id=zone_obj['id'], recordset_id=name_or_id), json=kwargs,
error_message="Error updating recordset {0}".format(name_or_id))
return new_recordset
def delete_recordset(self, zone, name_or_id):
"""Delete a recordset.
:param zone: Name or ID of the zone managing the recordset.
:param name_or_id: Name or ID of the recordset being deleted.
:returns: True if delete succeeded, False otherwise.
:raises: OpenStackCloudException on operation error.
"""
zone = self.get_zone(zone)
if zone is None:
self.log.debug("Zone %s not found for deleting", zone)
return False
recordset = self.get_recordset(zone['id'], name_or_id)
if recordset is None:
self.log.debug("Recordset %s not found for deleting", name_or_id)
return False
self._dns_client.delete(
"/zones/{zone_id}/recordsets/{recordset_id}".format(
zone_id=zone['id'], recordset_id=name_or_id),
error_message="Error deleting recordset {0}".format(name_or_id))
return True
@_utils.cache_on_arguments()
def list_cluster_templates(self, detail=False):
"""List cluster templates.
:param bool detail. Ignored. Included for backwards compat.
ClusterTemplates are always returned with full details.
:returns: a list of dicts containing the cluster template details.
:raises: ``OpenStackCloudException``: if something goes wrong during
the OpenStack API call.
"""
with _utils.shade_exceptions("Error fetching cluster template list"):
try:
data = self._container_infra_client.get('/clustertemplates')
# NOTE(flwang): Magnum adds /clustertemplates and /cluster
# to deprecate /baymodels and /bay since Newton release. So
# we're using a small tag to indicate if current
# cloud has those two new API endpoints.
self._container_infra_client._has_magnum_after_newton = True
return self._normalize_cluster_templates(
self._get_and_munchify('clustertemplates', data))
except exc.OpenStackCloudURINotFound:
data = self._container_infra_client.get('/baymodels/detail')
return self._normalize_cluster_templates(
self._get_and_munchify('baymodels', data))
list_baymodels = list_cluster_templates
list_coe_cluster_templates = list_cluster_templates
def search_cluster_templates(
self, name_or_id=None, filters=None, detail=False):
"""Search cluster templates.
:param name_or_id: cluster template name or ID.
:param filters: a dict containing additional filters to use.
:param detail: a boolean to control if we need summarized or
detailed output.
:returns: a list of dict containing the cluster templates
:raises: ``OpenStackCloudException``: if something goes wrong during
the OpenStack API call.
"""
cluster_templates = self.list_cluster_templates(detail=detail)
return _utils._filter_list(
cluster_templates, name_or_id, filters)
search_baymodels = search_cluster_templates
search_coe_cluster_templates = search_cluster_templates
def get_cluster_template(self, name_or_id, filters=None, detail=False):
"""Get a cluster template by name or ID.
:param name_or_id: Name or ID of the cluster template.
:param filters:
A dictionary of meta data to use for further filtering. Elements
of this dictionary may, themselves, be dictionaries. Example::
{
'last_name': 'Smith',
'other': {
'gender': 'Female'
}
}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A cluster template dict or None if no matching
cluster template is found.
"""
return _utils._get_entity(self, 'cluster_template', name_or_id,
filters=filters, detail=detail)
get_baymodel = get_cluster_template
get_coe_cluster_template = get_cluster_template
def create_cluster_template(
self, name, image_id=None, keypair_id=None, coe=None, **kwargs):
"""Create a cluster template.
:param string name: Name of the cluster template.
:param string image_id: Name or ID of the image to use.
:param string keypair_id: Name or ID of the keypair to use.
:param string coe: Name of the coe for the cluster template.
Other arguments will be passed in kwargs.
:returns: a dict containing the cluster template description
:raises: ``OpenStackCloudException`` if something goes wrong during
the OpenStack API call
"""
error_message = ("Error creating cluster template of name"
" {cluster_template_name}".format(
cluster_template_name=name))
with _utils.shade_exceptions(error_message):
body = kwargs.copy()
body['name'] = name
body['image_id'] = image_id
body['keypair_id'] = keypair_id
body['coe'] = coe
try:
cluster_template = self._container_infra_client.post(
'/clustertemplates', json=body)
self._container_infra_client._has_magnum_after_newton = True
except exc.OpenStackCloudURINotFound:
cluster_template = self._container_infra_client.post(
'/baymodels', json=body)
self.list_cluster_templates.invalidate(self)
return cluster_template
create_baymodel = create_cluster_template
create_coe_cluster_template = create_cluster_template
def delete_cluster_template(self, name_or_id):
"""Delete a cluster template.
:param name_or_id: Name or unique ID of the cluster template.
:returns: True if the delete succeeded, False if the
cluster template was not found.
:raises: OpenStackCloudException on operation error.
"""
cluster_template = self.get_cluster_template(name_or_id)
if not cluster_template:
self.log.debug(
"Cluster template %(name_or_id)s does not exist",
{'name_or_id': name_or_id},
exc_info=True)
return False
with _utils.shade_exceptions("Error in deleting cluster template"):
if getattr(self._container_infra_client,
'_has_magnum_after_newton', False):
self._container_infra_client.delete(
'/clustertemplates/{id}'.format(id=cluster_template['id']))
else:
self._container_infra_client.delete(
'/baymodels/{id}'.format(id=cluster_template['id']))
self.list_cluster_templates.invalidate(self)
return True
delete_baymodel = delete_cluster_template
delete_coe_cluster_template = delete_cluster_template
@_utils.valid_kwargs('name', 'image_id', 'flavor_id', 'master_flavor_id',
'keypair_id', 'external_network_id', 'fixed_network',
'dns_nameserver', 'docker_volume_size', 'labels',
'coe', 'http_proxy', 'https_proxy', 'no_proxy',
'network_driver', 'tls_disabled', 'public',
'registry_enabled', 'volume_driver')
def update_cluster_template(self, name_or_id, operation, **kwargs):
"""Update a cluster template.
:param name_or_id: Name or ID of the cluster template being updated.
:param operation: Operation to perform - add, remove, replace.
Other arguments will be passed with kwargs.
:returns: a dict representing the updated cluster template.
:raises: OpenStackCloudException on operation error.
"""
self.list_cluster_templates.invalidate(self)
cluster_template = self.get_cluster_template(name_or_id)
if not cluster_template:
raise exc.OpenStackCloudException(
"Cluster template %s not found." % name_or_id)
if operation not in ['add', 'replace', 'remove']:
raise TypeError(
"%s operation not in 'add', 'replace', 'remove'" % operation)
patches = _utils.generate_patches_from_kwargs(operation, **kwargs)
# No need to fire an API call if there is an empty patch
if not patches:
return cluster_template
with _utils.shade_exceptions(
"Error updating cluster template {0}".format(name_or_id)):
if getattr(self._container_infra_client,
'_has_magnum_after_newton', False):
self._container_infra_client.patch(
'/clustertemplates/{id}'.format(id=cluster_template['id']),
json=patches)
else:
self._container_infra_client.patch(
'/baymodels/{id}'.format(id=cluster_template['id']),
json=patches)
new_cluster_template = self.get_cluster_template(name_or_id)
return new_cluster_template
update_baymodel = update_cluster_template
update_coe_cluster_template = update_cluster_template
def list_nics(self):
msg = "Error fetching machine port list"
data = self._baremetal_client.get("/ports",
microversion="1.6",
error_message=msg)
return data['ports']
def list_nics_for_machine(self, uuid):
"""Returns a list of ports present on the machine node.
:param uuid: String representing machine UUID value in
order to identify the machine.
:returns: A list of ports.
"""
msg = "Error fetching port list for node {node_id}".format(
node_id=uuid)
url = "/nodes/{node_id}/ports".format(node_id=uuid)
data = self._baremetal_client.get(url,
microversion="1.6",
error_message=msg)
return data['ports']
def get_nic_by_mac(self, mac):
try:
url = '/ports/detail?address=%s' % mac
data = self._baremetal_client.get(url)
if len(data['ports']) == 1:
return data['ports'][0]
except Exception:
pass
return None
def list_machines(self):
msg = "Error fetching machine node list"
data = self._baremetal_client.get("/nodes",
microversion="1.6",
error_message=msg)
return self._get_and_munchify('nodes', data)
def get_machine(self, name_or_id):
"""Get Machine by name or uuid
Search the baremetal host out by utilizing the supplied id value
which can consist of a name or UUID.
:param name_or_id: A node name or UUID that will be looked up.
:returns: ``munch.Munch`` representing the node found or None if no
nodes are found.
"""
# NOTE(TheJulia): This is the initial microversion shade support for
# ironic was created around. Ironic's default behavior for newer
# versions is to expose the field, but with a value of None for
# calls by a supported, yet older microversion.
# Consensus for moving forward with microversion handling in shade
# seems to be to take the same approach, although ironic's API
# does it for the user.
version = "1.6"
try:
url = '/nodes/{node_id}'.format(node_id=name_or_id)
return self._normalize_machine(
self._baremetal_client.get(url, microversion=version))
except Exception:
return None
def get_machine_by_mac(self, mac):
"""Get machine by port MAC address
:param mac: Port MAC address to query in order to return a node.
:returns: ``munch.Munch`` representing the node found or None
if the node is not found.
"""
try:
port_url = '/ports/detail?address={mac}'.format(mac=mac)
port = self._baremetal_client.get(port_url, microversion=1.6)
machine_url = '/nodes/{machine}'.format(
machine=port['ports'][0]['node_uuid'])
return self._baremetal_client.get(machine_url, microversion=1.6)
except Exception:
return None
def inspect_machine(self, name_or_id, wait=False, timeout=3600):
"""Inspect a Barmetal machine
Engages the Ironic node inspection behavior in order to collect
metadata about the baremetal machine.
:param name_or_id: String representing machine name or UUID value in
order to identify the machine.
:param wait: Boolean value controlling if the method is to wait for
the desired state to be reached or a failure to occur.
:param timeout: Integer value, defautling to 3600 seconds, for the$
wait state to reach completion.
:returns: ``munch.Munch`` representing the current state of the machine
upon exit of the method.
"""
return_to_available = False
machine = self.get_machine(name_or_id)
if not machine:
raise exc.OpenStackCloudException(
"Machine inspection failed to find: %s." % name_or_id)
# NOTE(TheJulia): If in available state, we can do this, however
# We need to to move the host back to m
if "available" in machine['provision_state']:
return_to_available = True
# NOTE(TheJulia): Changing available machine to managedable state
# and due to state transitions we need to until that transition has
# completd.
self.node_set_provision_state(machine['uuid'], 'manage',
wait=True, timeout=timeout)
elif ("manage" not in machine['provision_state'] and
"inspect failed" not in machine['provision_state']):
raise exc.OpenStackCloudException(
"Machine must be in 'manage' or 'available' state to "
"engage inspection: Machine: %s State: %s"
% (machine['uuid'], machine['provision_state']))
with _utils.shade_exceptions("Error inspecting machine"):
machine = self.node_set_provision_state(machine['uuid'], 'inspect')
if wait:
for count in _utils._iterate_timeout(
timeout,
"Timeout waiting for node transition to "
"target state of 'inspect'"):
machine = self.get_machine(name_or_id)
if "inspect failed" in machine['provision_state']:
raise exc.OpenStackCloudException(
"Inspection of node %s failed, last error: %s"
% (machine['uuid'], machine['last_error']))
if "manageable" in machine['provision_state']:
break
if return_to_available:
machine = self.node_set_provision_state(
machine['uuid'], 'provide', wait=wait, timeout=timeout)
return(machine)
def register_machine(self, nics, wait=False, timeout=3600,
lock_timeout=600, **kwargs):
"""Register Baremetal with Ironic
Allows for the registration of Baremetal nodes with Ironic
and population of pertinant node information or configuration
to be passed to the Ironic API for the node.
This method also creates ports for a list of MAC addresses passed
in to be utilized for boot and potentially network configuration.
If a failure is detected creating the network ports, any ports
created are deleted, and the node is removed from Ironic.
:param list nics:
An array of MAC addresses that represent the
network interfaces for the node to be created.
Example::
[
{'mac': 'aa:bb:cc:dd:ee:01'},
{'mac': 'aa:bb:cc:dd:ee:02'}
]
:param wait: Boolean value, defaulting to false, to wait for the
node to reach the available state where the node can be
provisioned. It must be noted, when set to false, the
method will still wait for locks to clear before sending
the next required command.
:param timeout: Integer value, defautling to 3600 seconds, for the
wait state to reach completion.
:param lock_timeout: Integer value, defaulting to 600 seconds, for
locks to clear.
:param kwargs: Key value pairs to be passed to the Ironic API,
including uuid, name, chassis_uuid, driver_info,
parameters.
:raises: OpenStackCloudException on operation error.
:returns: Returns a ``munch.Munch`` representing the new
baremetal node.
"""
msg = ("Baremetal machine node failed to be created.")
port_msg = ("Baremetal machine port failed to be created.")
url = '/nodes'
# TODO(TheJulia): At some point we need to figure out how to
# handle data across when the requestor is defining newer items
# with the older api.
machine = self._baremetal_client.post(url,
json=kwargs,
error_message=msg,
microversion="1.6")
created_nics = []
try:
for row in nics:
payload = {'address': row['mac'],
'node_uuid': machine['uuid']}
nic = self._baremetal_client.post('/ports',
json=payload,
error_message=port_msg)
created_nics.append(nic['uuid'])
except Exception as e:
self.log.debug("ironic NIC registration failed", exc_info=True)
# TODO(mordred) Handle failures here
try:
for uuid in created_nics:
try:
port_url = '/ports/{uuid}'.format(uuid=uuid)
# NOTE(TheJulia): Added in hope that it is logged.
port_msg = ('Failed to delete port {port} for node'
'{node}').format(port=uuid,
node=machine['uuid'])
self._baremetal_client.delete(port_url,
error_message=port_msg)
except Exception:
pass
finally:
version = "1.6"
msg = "Baremetal machine failed to be deleted."
url = '/nodes/{node_id}'.format(
node_id=machine['uuid'])
self._baremetal_client.delete(url,
error_message=msg,
microversion=version)
raise exc.OpenStackCloudException(
"Error registering NICs with the baremetal service: %s"
% str(e))
with _utils.shade_exceptions(
"Error transitioning node to available state"):
if wait:
for count in _utils._iterate_timeout(
timeout,
"Timeout waiting for node transition to "
"available state"):
machine = self.get_machine(machine['uuid'])
# Note(TheJulia): Per the Ironic state code, a node
# that fails returns to enroll state, which means a failed
# node cannot be determined at this point in time.
if machine['provision_state'] in ['enroll']:
self.node_set_provision_state(
machine['uuid'], 'manage')
elif machine['provision_state'] in ['manageable']:
self.node_set_provision_state(
machine['uuid'], 'provide')
elif machine['last_error'] is not None:
raise exc.OpenStackCloudException(
"Machine encountered a failure: %s"
% machine['last_error'])
# Note(TheJulia): Earlier versions of Ironic default to
# None and later versions default to available up until
# the introduction of enroll state.
# Note(TheJulia): The node will transition through
# cleaning if it is enabled, and we will wait for
# completion.
elif machine['provision_state'] in ['available', None]:
break
else:
if machine['provision_state'] in ['enroll']:
self.node_set_provision_state(machine['uuid'], 'manage')
# Note(TheJulia): We need to wait for the lock to clear
# before we attempt to set the machine into provide state
# which allows for the transition to available.
for count in _utils._iterate_timeout(
lock_timeout,
"Timeout waiting for reservation to clear "
"before setting provide state"):
machine = self.get_machine(machine['uuid'])
if (machine['reservation'] is None and
machine['provision_state'] is not 'enroll'):
# NOTE(TheJulia): In this case, the node has
# has moved on from the previous state and is
# likely not being verified, as no lock is
# present on the node.
self.node_set_provision_state(
machine['uuid'], 'provide')
machine = self.get_machine(machine['uuid'])
break
elif machine['provision_state'] in [
'cleaning',
'available']:
break
elif machine['last_error'] is not None:
raise exc.OpenStackCloudException(
"Machine encountered a failure: %s"
% machine['last_error'])
if not isinstance(machine, str):
return self._normalize_machine(machine)
else:
return machine
def unregister_machine(self, nics, uuid, wait=False, timeout=600):
"""Unregister Baremetal from Ironic
Removes entries for Network Interfaces and baremetal nodes
from an Ironic API
:param list nics: An array of strings that consist of MAC addresses
to be removed.
:param string uuid: The UUID of the node to be deleted.
:param wait: Boolean value, defaults to false, if to block the method
upon the final step of unregistering the machine.
:param timeout: Integer value, representing seconds with a default
value of 600, which controls the maximum amount of
time to block the method's completion on.
:raises: OpenStackCloudException on operation failure.
"""
machine = self.get_machine(uuid)
invalid_states = ['active', 'cleaning', 'clean wait', 'clean failed']
if machine['provision_state'] in invalid_states:
raise exc.OpenStackCloudException(
"Error unregistering node '%s' due to current provision "
"state '%s'" % (uuid, machine['provision_state']))
# NOTE(TheJulia) There is a high possibility of a lock being present
# if the machine was just moved through the state machine. This was
# previously concealed by exception retry logic that detected the
# failure, and resubitted the request in python-ironicclient.
try:
self.wait_for_baremetal_node_lock(machine, timeout=timeout)
except exc.OpenStackCloudException as e:
raise exc.OpenStackCloudException(
"Error unregistering node '%s': Exception occured while"
" waiting to be able to proceed: %s"
% (machine['uuid'], e))
for nic in nics:
port_msg = ("Error removing NIC {nic} from baremetal API for "
"node {uuid}").format(nic=nic, uuid=uuid)
port_url = '/ports/detail?address={mac}'.format(mac=nic['mac'])
port = self._baremetal_client.get(port_url, microversion=1.6,
error_message=port_msg)
port_url = '/ports/{uuid}'.format(uuid=port['ports'][0]['uuid'])
_utils._call_client_and_retry(self._baremetal_client.delete,
port_url, retry_on=[409, 503],
error_message=port_msg)
with _utils.shade_exceptions(
"Error unregistering machine {node_id} from the baremetal "
"API".format(node_id=uuid)):
# NOTE(TheJulia): While this should not matter microversion wise,
# ironic assumes all calls without an explicit microversion to be
# version 1.0. Ironic expects to deprecate support for older
# microversions in future releases, as such, we explicitly set
# the version to what we have been using with the client library..
version = "1.6"
msg = "Baremetal machine failed to be deleted"
url = '/nodes/{node_id}'.format(
node_id=uuid)
_utils._call_client_and_retry(self._baremetal_client.delete,
url, retry_on=[409, 503],
error_message=msg,
microversion=version)
if wait:
for count in _utils._iterate_timeout(
timeout,
"Timeout waiting for machine to be deleted"):
if not self.get_machine(uuid):
break
def patch_machine(self, name_or_id, patch):
"""Patch Machine Information
This method allows for an interface to manipulate node entries
within Ironic.
:param node_id: The server object to attach to.
:param patch:
The JSON Patch document is a list of dictonary objects
that comply with RFC 6902 which can be found at
https://tools.ietf.org/html/rfc6902.
Example patch construction::
patch=[]
patch.append({
'op': 'remove',
'path': '/instance_info'
})
patch.append({
'op': 'replace',
'path': '/name',
'value': 'newname'
})
patch.append({
'op': 'add',
'path': '/driver_info/username',
'value': 'administrator'
})
:raises: OpenStackCloudException on operation error.
:returns: ``munch.Munch`` representing the newly updated node.
"""
msg = ("Error updating machine via patch operation on node "
"{node}".format(node=name_or_id))
url = '/nodes/{node_id}'.format(node_id=name_or_id)
return self._normalize_machine(
self._baremetal_client.patch(url,
json=patch,
error_message=msg))
def update_machine(self, name_or_id, chassis_uuid=None, driver=None,
driver_info=None, name=None, instance_info=None,
instance_uuid=None, properties=None):
"""Update a machine with new configuration information
A user-friendly method to perform updates of a machine, in whole or
part.
:param string name_or_id: A machine name or UUID to be updated.
:param string chassis_uuid: Assign a chassis UUID to the machine.
NOTE: As of the Kilo release, this value
cannot be changed once set. If a user
attempts to change this value, then the
Ironic API, as of Kilo, will reject the
request.
:param string driver: The driver name for controlling the machine.
:param dict driver_info: The dictonary defining the configuration
that the driver will utilize to control
the machine. Permutations of this are
dependent upon the specific driver utilized.
:param string name: A human relatable name to represent the machine.
:param dict instance_info: A dictonary of configuration information
that conveys to the driver how the host
is to be configured when deployed.
be deployed to the machine.
:param string instance_uuid: A UUID value representing the instance
that the deployed machine represents.
:param dict properties: A dictonary defining the properties of a
machine.
:raises: OpenStackCloudException on operation error.
:returns: ``munch.Munch`` containing a machine sub-dictonary consisting
of the updated data returned from the API update operation,
and a list named changes which contains all of the API paths
that received updates.
"""
machine = self.get_machine(name_or_id)
if not machine:
raise exc.OpenStackCloudException(
"Machine update failed to find Machine: %s. " % name_or_id)
machine_config = {}
new_config = {}
try:
if chassis_uuid:
machine_config['chassis_uuid'] = machine['chassis_uuid']
new_config['chassis_uuid'] = chassis_uuid
if driver:
machine_config['driver'] = machine['driver']
new_config['driver'] = driver
if driver_info:
machine_config['driver_info'] = machine['driver_info']
new_config['driver_info'] = driver_info
if name:
machine_config['name'] = machine['name']
new_config['name'] = name
if instance_info:
machine_config['instance_info'] = machine['instance_info']
new_config['instance_info'] = instance_info
if instance_uuid:
machine_config['instance_uuid'] = machine['instance_uuid']
new_config['instance_uuid'] = instance_uuid
if properties:
machine_config['properties'] = machine['properties']
new_config['properties'] = properties
except KeyError as e:
self.log.debug(
"Unexpected machine response missing key %s [%s]",
e.args[0], name_or_id)
raise exc.OpenStackCloudException(
"Machine update failed - machine [%s] missing key %s. "
"Potential API issue."
% (name_or_id, e.args[0]))
try:
patch = jsonpatch.JsonPatch.from_diff(machine_config, new_config)
except Exception as e:
raise exc.OpenStackCloudException(
"Machine update failed - Error generating JSON patch object "
"for submission to the API. Machine: %s Error: %s"
% (name_or_id, str(e)))
with _utils.shade_exceptions(
"Machine update failed - patch operation failed on Machine "
"{node}".format(node=name_or_id)
):
if not patch:
return dict(
node=machine,
changes=None
)
else:
machine = self.patch_machine(machine['uuid'], list(patch))
change_list = []
for change in list(patch):
change_list.append(change['path'])
return dict(
node=machine,
changes=change_list
)
def validate_node(self, uuid):
"""Returns node validation information
:param string uuid: A UUID value representing the baremetal node.
:raises: OpenStackCloudException on operation error or
if deploy and power informations are not present.
:returns: dict containing validation information for each
interface: boot, console, deploy, inspect, management,
network, power, raid, rescue, storage, ...
"""
msg = ("Failed to query the API for validation status of "
"node {node_id}").format(node_id=uuid)
url = '/nodes/{node_id}/validate'.format(node_id=uuid)
validate_resp = self._baremetal_client.get(url, error_message=msg)
is_deploy_valid = validate_resp.get(
'deploy', {'result': False}).get('result', False)
is_power_valid = validate_resp.get(
'power', {'result': False}).get('result', False)
if not is_deploy_valid or not is_power_valid:
raise exc.OpenStackCloudException(
"ironic node {} failed to validate. "
"(deploy: {}, power: {})".format(
uuid,
validate_resp.get('deploy'),
validate_resp.get('power')))
return validate_resp
def node_set_provision_state(self,
name_or_id,
state,
configdrive=None,
wait=False,
timeout=3600):
"""Set Node Provision State
Enables a user to provision a Machine and optionally define a
config drive to be utilized.
:param string name_or_id: The Name or UUID value representing the
baremetal node.
:param string state: The desired provision state for the
baremetal node.
:param string configdrive: An optional URL or file or path
representing the configdrive. In the
case of a directory, the client API
will create a properly formatted
configuration drive file and post the
file contents to the API for
deployment.
:param boolean wait: A boolean value, defaulted to false, to control
if the method will wait for the desire end state
to be reached before returning.
:param integer timeout: Integer value, defaulting to 3600 seconds,
representing the amount of time to wait for
the desire end state to be reached.
:raises: OpenStackCloudException on operation error.
:returns: ``munch.Munch`` representing the current state of the machine
upon exit of the method.
"""
# NOTE(TheJulia): Default microversion for this call is 1.6.
# Setting locally until we have determined our master plan regarding
# microversion handling.
version = "1.6"
msg = ("Baremetal machine node failed change provision state to "
"{state}".format(state=state))
url = '/nodes/{node_id}/states/provision'.format(
node_id=name_or_id)
payload = {'target': state}
if configdrive:
payload['configdrive'] = configdrive
machine = _utils._call_client_and_retry(self._baremetal_client.put,
url,
retry_on=[409, 503],
json=payload,
error_message=msg,
microversion=version)
if wait:
for count in _utils._iterate_timeout(
timeout,
"Timeout waiting for node transition to "
"target state of '%s'" % state):
machine = self.get_machine(name_or_id)
if 'failed' in machine['provision_state']:
raise exc.OpenStackCloudException(
"Machine encountered a failure.")
# NOTE(TheJulia): This performs matching if the requested
# end state matches the state the node has reached.
if state in machine['provision_state']:
break
# NOTE(TheJulia): This performs matching for cases where
# the reqeusted state action ends in available state.
if ("available" in machine['provision_state'] and
state in ["provide", "deleted"]):
break
else:
machine = self.get_machine(name_or_id)
return machine
def set_machine_maintenance_state(
self,
name_or_id,
state=True,
reason=None):
"""Set Baremetal Machine Maintenance State
Sets Baremetal maintenance state and maintenance reason.
:param string name_or_id: The Name or UUID value representing the
baremetal node.
:param boolean state: The desired state of the node. True being in
maintenance where as False means the machine
is not in maintenance mode. This value
defaults to True if not explicitly set.
:param string reason: An optional freeform string that is supplied to
the baremetal API to allow for notation as to why
the node is in maintenance state.
:raises: OpenStackCloudException on operation error.
:returns: None
"""
msg = ("Error setting machine maintenance state to {state} on node "
"{node}").format(state=state, node=name_or_id)
url = '/nodes/{name_or_id}/maintenance'.format(name_or_id=name_or_id)
if state:
payload = {'reason': reason}
self._baremetal_client.put(url,
json=payload,
error_message=msg)
else:
self._baremetal_client.delete(url, error_message=msg)
return None
def remove_machine_from_maintenance(self, name_or_id):
"""Remove Baremetal Machine from Maintenance State
Similarly to set_machine_maintenance_state, this method
removes a machine from maintenance state. It must be noted
that this method simpily calls set_machine_maintenace_state
for the name_or_id requested and sets the state to False.
:param string name_or_id: The Name or UUID value representing the
baremetal node.
:raises: OpenStackCloudException on operation error.
:returns: None
"""
self.set_machine_maintenance_state(name_or_id, False)
def _set_machine_power_state(self, name_or_id, state):
"""Set machine power state to on or off
This private method allows a user to turn power on or off to
a node via the Baremetal API.
:params string name_or_id: A string representing the baremetal
node to have power turned to an "on"
state.
:params string state: A value of "on", "off", or "reboot" that is
passed to the baremetal API to be asserted to
the machine. In the case of the "reboot" state,
Ironic will return the host to the "on" state.
:raises: OpenStackCloudException on operation error or.
:returns: None
"""
msg = ("Error setting machine power state to {state} on node "
"{node}").format(state=state, node=name_or_id)
url = '/nodes/{name_or_id}/states/power'.format(name_or_id=name_or_id)
if 'reboot' in state:
desired_state = 'rebooting'
else:
desired_state = 'power {state}'.format(state=state)
payload = {'target': desired_state}
_utils._call_client_and_retry(self._baremetal_client.put,
url,
retry_on=[409, 503],
json=payload,
error_message=msg,
microversion="1.6")
return None
def set_machine_power_on(self, name_or_id):
"""Activate baremetal machine power
This is a method that sets the node power state to "on".
:params string name_or_id: A string representing the baremetal
node to have power turned to an "on"
state.
:raises: OpenStackCloudException on operation error.
:returns: None
"""
self._set_machine_power_state(name_or_id, 'on')
def set_machine_power_off(self, name_or_id):
"""De-activate baremetal machine power
This is a method that sets the node power state to "off".
:params string name_or_id: A string representing the baremetal
node to have power turned to an "off"
state.
:raises: OpenStackCloudException on operation error.
:returns:
"""
self._set_machine_power_state(name_or_id, 'off')
def set_machine_power_reboot(self, name_or_id):
"""De-activate baremetal machine power
This is a method that sets the node power state to "reboot", which
in essence changes the machine power state to "off", and that back
to "on".
:params string name_or_id: A string representing the baremetal
node to have power turned to an "off"
state.
:raises: OpenStackCloudException on operation error.
:returns: None
"""
self._set_machine_power_state(name_or_id, 'reboot')
def activate_node(self, uuid, configdrive=None,
wait=False, timeout=1200):
self.node_set_provision_state(
uuid, 'active', configdrive, wait=wait, timeout=timeout)
def deactivate_node(self, uuid, wait=False,
timeout=1200):
self.node_set_provision_state(
uuid, 'deleted', wait=wait, timeout=timeout)
def set_node_instance_info(self, uuid, patch):
msg = ("Error updating machine via patch operation on node "
"{node}".format(node=uuid))
url = '/nodes/{node_id}'.format(node_id=uuid)
return self._baremetal_client.patch(url,
json=patch,
error_message=msg)
def purge_node_instance_info(self, uuid):
patch = []
patch.append({'op': 'remove', 'path': '/instance_info'})
msg = ("Error updating machine via patch operation on node "
"{node}".format(node=uuid))
url = '/nodes/{node_id}'.format(node_id=uuid)
return self._baremetal_client.patch(url,
json=patch,
error_message=msg)
def wait_for_baremetal_node_lock(self, node, timeout=30):
"""Wait for a baremetal node to have no lock.
Baremetal nodes in ironic have a reservation lock that
is used to represent that a conductor has locked the node
while performing some sort of action, such as changing
configuration as a result of a machine state change.
This lock can occur during power syncronization, and prevents
updates to objects attached to the node, such as ports.
In the vast majority of cases, locks should clear in a few
seconds, and as such this method will only wait for 30 seconds.
The default wait is two seconds between checking if the lock
has cleared.
This method is intended for use by methods that need to
gracefully block without genreating errors, however this
method does prevent another client or a timer from
triggering a lock immediately after we see the lock as
having cleared.
:param node: The json representation of the node,
specificially looking for the node
'uuid' and 'reservation' fields.
:param timeout: Integer in seconds to wait for the
lock to clear. Default: 30
:raises: OpenStackCloudException upon client failure.
:returns: None
"""
# TODO(TheJulia): This _can_ still fail with a race
# condition in that between us checking the status,
# a conductor where the conductor could still obtain
# a lock before we are able to obtain a lock.
# This means we should handle this with such conections
if node['reservation'] is None:
return
else:
msg = 'Waiting for lock to be released for node {node}'.format(
node=node['uuid'])
for count in _utils._iterate_timeout(timeout, msg, 2):
current_node = self.get_machine(node['uuid'])
if current_node['reservation'] is None:
return
@_utils.valid_kwargs('type', 'service_type', 'description')
def create_service(self, name, enabled=True, **kwargs):
"""Create a service.
:param name: Service name.
:param type: Service type. (type or service_type required.)
:param service_type: Service type. (type or service_type required.)
:param description: Service description (optional).
:param enabled: Whether the service is enabled (v3 only)
:returns: a ``munch.Munch`` containing the services description,
i.e. the following attributes::
- id: <service id>
- name: <service name>
- type: <service type>
- service_type: <service type>
- description: <service description>
:raises: ``OpenStackCloudException`` if something goes wrong during the
openstack API call.
"""
type_ = kwargs.pop('type', None)
service_type = kwargs.pop('service_type', None)
# TODO(mordred) When this changes to REST, force interface=admin
# in the adapter call
if self._is_client_version('identity', 2):
url, key = '/OS-KSADM/services', 'OS-KSADM:service'
kwargs['type'] = type_ or service_type
else:
url, key = '/services', 'service'
kwargs['type'] = type_ or service_type
kwargs['enabled'] = enabled
kwargs['name'] = name
msg = 'Failed to create service {name}'.format(name=name)
data = self._identity_client.post(
url, json={key: kwargs}, error_message=msg)
service = self._get_and_munchify(key, data)
return _utils.normalize_keystone_services([service])[0]
@_utils.valid_kwargs('name', 'enabled', 'type', 'service_type',
'description')
def update_service(self, name_or_id, **kwargs):
# NOTE(SamYaple): Service updates are only available on v3 api
if self._is_client_version('identity', 2):
raise exc.OpenStackCloudUnavailableFeature(
'Unavailable Feature: Service update requires Identity v3'
)
# NOTE(SamYaple): Keystone v3 only accepts 'type' but shade accepts
# both 'type' and 'service_type' with a preference
# towards 'type'
type_ = kwargs.pop('type', None)
service_type = kwargs.pop('service_type', None)
if type_ or service_type:
kwargs['type'] = type_ or service_type
if self._is_client_version('identity', 2):
url, key = '/OS-KSADM/services', 'OS-KSADM:service'
else:
url, key = '/services', 'service'
service = self.get_service(name_or_id)
msg = 'Error in updating service {service}'.format(service=name_or_id)
data = self._identity_client.patch(
'{url}/{id}'.format(url=url, id=service['id']), json={key: kwargs},
endpoint_filter={'interface': 'admin'}, error_message=msg)
service = self._get_and_munchify(key, data)
return _utils.normalize_keystone_services([service])[0]
def list_services(self):
"""List all Keystone services.
:returns: a list of ``munch.Munch`` containing the services description
:raises: ``OpenStackCloudException`` if something goes wrong during the
openstack API call.
"""
if self._is_client_version('identity', 2):
url, key = '/OS-KSADM/services', 'OS-KSADM:services'
else:
url, key = '/services', 'services'
data = self._identity_client.get(
url, endpoint_filter={'interface': 'admin'},
error_message="Failed to list services")
services = self._get_and_munchify(key, data)
return _utils.normalize_keystone_services(services)
def search_services(self, name_or_id=None, filters=None):
"""Search Keystone services.
:param name_or_id: Name or id of the desired service.
:param filters: a dict containing additional filters to use. e.g.
{'type': 'network'}.
:returns: a list of ``munch.Munch`` containing the services description
:raises: ``OpenStackCloudException`` if something goes wrong during the
openstack API call.
"""
services = self.list_services()
return _utils._filter_list(services, name_or_id, filters)
def get_service(self, name_or_id, filters=None):
"""Get exactly one Keystone service.
:param name_or_id: Name or id of the desired service.
:param filters: a dict containing additional filters to use. e.g.
{'type': 'network'}
:returns: a ``munch.Munch`` containing the services description,
i.e. the following attributes::
- id: <service id>
- name: <service name>
- type: <service type>
- description: <service description>
:raises: ``OpenStackCloudException`` if something goes wrong during the
openstack API call or if multiple matches are found.
"""
return _utils._get_entity(self, 'service', name_or_id, filters)
def delete_service(self, name_or_id):
"""Delete a Keystone service.
:param name_or_id: Service name or id.
:returns: True if delete succeeded, False otherwise.
:raises: ``OpenStackCloudException`` if something goes wrong during
the openstack API call
"""
service = self.get_service(name_or_id=name_or_id)
if service is None:
self.log.debug("Service %s not found for deleting", name_or_id)
return False
if self._is_client_version('identity', 2):
url = '/OS-KSADM/services'
else:
url = '/services'
error_msg = 'Failed to delete service {id}'.format(id=service['id'])
self._identity_client.delete(
'{url}/{id}'.format(url=url, id=service['id']),
endpoint_filter={'interface': 'admin'}, error_message=error_msg)
return True
@_utils.valid_kwargs('public_url', 'internal_url', 'admin_url')
def create_endpoint(self, service_name_or_id, url=None, interface=None,
region=None, enabled=True, **kwargs):
"""Create a Keystone endpoint.
:param service_name_or_id: Service name or id for this endpoint.
:param url: URL of the endpoint
:param interface: Interface type of the endpoint
:param public_url: Endpoint public URL.
:param internal_url: Endpoint internal URL.
:param admin_url: Endpoint admin URL.
:param region: Endpoint region.
:param enabled: Whether the endpoint is enabled
NOTE: Both v2 (public_url, internal_url, admin_url) and v3
(url, interface) calling semantics are supported. But
you can only use one of them at a time.
:returns: a list of ``munch.Munch`` containing the endpoint description
:raises: OpenStackCloudException if the service cannot be found or if
something goes wrong during the openstack API call.
"""
public_url = kwargs.pop('public_url', None)
internal_url = kwargs.pop('internal_url', None)
admin_url = kwargs.pop('admin_url', None)
if (url or interface) and (public_url or internal_url or admin_url):
raise exc.OpenStackCloudException(
"create_endpoint takes either url and interface OR"
" public_url, internal_url, admin_url")
service = self.get_service(name_or_id=service_name_or_id)
if service is None:
raise exc.OpenStackCloudException(
"service {service} not found".format(
service=service_name_or_id))
if self._is_client_version('identity', 2):
if url:
# v2.0 in use, v3-like arguments, one endpoint created
if interface != 'public':
raise exc.OpenStackCloudException(
"Error adding endpoint for service {service}."
" On a v2 cloud the url/interface API may only be"
" used for public url. Try using the public_url,"
" internal_url, admin_url parameters instead of"
" url and interface".format(
service=service_name_or_id))
endpoint_args = {'publicurl': url}
else:
# v2.0 in use, v2.0-like arguments, one endpoint created
endpoint_args = {}
if public_url:
endpoint_args.update({'publicurl': public_url})
if internal_url:
endpoint_args.update({'internalurl': internal_url})
if admin_url:
endpoint_args.update({'adminurl': admin_url})
# keystone v2.0 requires 'region' arg even if it is None
endpoint_args.update(
{'service_id': service['id'], 'region': region})
data = self._identity_client.post(
'/endpoints', json={'endpoint': endpoint_args},
endpoint_filter={'interface': 'admin'},
error_message=("Failed to create endpoint for service"
" {service}".format(service=service['name'])))
return [self._get_and_munchify('endpoint', data)]
else:
endpoints_args = []
if url:
# v3 in use, v3-like arguments, one endpoint created
endpoints_args.append(
{'url': url, 'interface': interface,
'service_id': service['id'], 'enabled': enabled,
'region': region})
else:
# v3 in use, v2.0-like arguments, one endpoint created for each
# interface url provided
endpoint_args = {'region': region, 'enabled': enabled,
'service_id': service['id']}
if public_url:
endpoint_args.update({'url': public_url,
'interface': 'public'})
endpoints_args.append(endpoint_args.copy())
if internal_url:
endpoint_args.update({'url': internal_url,
'interface': 'internal'})
endpoints_args.append(endpoint_args.copy())
if admin_url:
endpoint_args.update({'url': admin_url,
'interface': 'admin'})
endpoints_args.append(endpoint_args.copy())
endpoints = []
error_msg = ("Failed to create endpoint for service"
" {service}".format(service=service['name']))
for args in endpoints_args:
data = self._identity_client.post(
'/endpoints', json={'endpoint': args},
error_message=error_msg)
endpoints.append(self._get_and_munchify('endpoint', data))
return endpoints
@_utils.valid_kwargs('enabled', 'service_name_or_id', 'url', 'interface',
'region')
def update_endpoint(self, endpoint_id, **kwargs):
# NOTE(SamYaple): Endpoint updates are only available on v3 api
if self._is_client_version('identity', 2):
raise exc.OpenStackCloudUnavailableFeature(
'Unavailable Feature: Endpoint update'
)
service_name_or_id = kwargs.pop('service_name_or_id', None)
if service_name_or_id is not None:
kwargs['service_id'] = service_name_or_id
data = self._identity_client.patch(
'/endpoints/{}'.format(endpoint_id), json={'endpoint': kwargs},
error_message="Failed to update endpoint {}".format(endpoint_id))
return self._get_and_munchify('endpoint', data)
def list_endpoints(self):
"""List Keystone endpoints.
:returns: a list of ``munch.Munch`` containing the endpoint description
:raises: ``OpenStackCloudException``: if something goes wrong during
the openstack API call.
"""
# Force admin interface if v2.0 is in use
v2 = self._is_client_version('identity', 2)
kwargs = {'endpoint_filter': {'interface': 'admin'}} if v2 else {}
data = self._identity_client.get(
'/endpoints', error_message="Failed to list endpoints", **kwargs)
endpoints = self._get_and_munchify('endpoints', data)
return endpoints
def search_endpoints(self, id=None, filters=None):
"""List Keystone endpoints.
:param id: endpoint id.
:param filters: a dict containing additional filters to use. e.g.
{'region': 'region-a.geo-1'}
:returns: a list of ``munch.Munch`` containing the endpoint
description. Each dict contains the following attributes::
- id: <endpoint id>
- region: <endpoint region>
- public_url: <endpoint public url>
- internal_url: <endpoint internal url> (optional)
- admin_url: <endpoint admin url> (optional)
:raises: ``OpenStackCloudException``: if something goes wrong during
the openstack API call.
"""
# NOTE(SamYaple): With keystone v3 we can filter directly via the
# the keystone api, but since the return of all the endpoints even in
# large environments is small, we can continue to filter in shade just
# like the v2 api.
endpoints = self.list_endpoints()
return _utils._filter_list(endpoints, id, filters)
def get_endpoint(self, id, filters=None):
"""Get exactly one Keystone endpoint.
:param id: endpoint id.
:param filters: a dict containing additional filters to use. e.g.
{'region': 'region-a.geo-1'}
:returns: a ``munch.Munch`` containing the endpoint description.
i.e. a ``munch.Munch`` containing the following attributes::
- id: <endpoint id>
- region: <endpoint region>
- public_url: <endpoint public url>
- internal_url: <endpoint internal url> (optional)
- admin_url: <endpoint admin url> (optional)
"""
return _utils._get_entity(self, 'endpoint', id, filters)
def delete_endpoint(self, id):
"""Delete a Keystone endpoint.
:param id: Id of the endpoint to delete.
:returns: True if delete succeeded, False otherwise.
:raises: ``OpenStackCloudException`` if something goes wrong during
the openstack API call.
"""
endpoint = self.get_endpoint(id=id)
if endpoint is None:
self.log.debug("Endpoint %s not found for deleting", id)
return False
# Force admin interface if v2.0 is in use
v2 = self._is_client_version('identity', 2)
kwargs = {'endpoint_filter': {'interface': 'admin'}} if v2 else {}
error_msg = "Failed to delete endpoint {id}".format(id=id)
self._identity_client.delete('/endpoints/{id}'.format(id=id),
error_message=error_msg, **kwargs)
return True
def create_domain(self, name, description=None, enabled=True):
"""Create a domain.
:param name: The name of the domain.
:param description: A description of the domain.
:param enabled: Is the domain enabled or not (default True).
:returns: a ``munch.Munch`` containing the domain representation.
:raise exc.OpenStackCloudException: if the domain cannot be created.
"""
domain_ref = {'name': name, 'enabled': enabled}
if description is not None:
domain_ref['description'] = description
msg = 'Failed to create domain {name}'.format(name=name)
data = self._identity_client.post(
'/domains', json={'domain': domain_ref}, error_message=msg)
domain = self._get_and_munchify('domain', data)
return _utils.normalize_domains([domain])[0]
def update_domain(
self, domain_id=None, name=None, description=None,
enabled=None, name_or_id=None):
if domain_id is None:
if name_or_id is None:
raise exc.OpenStackCloudException(
"You must pass either domain_id or name_or_id value"
)
dom = self.get_domain(None, name_or_id)
if dom is None:
raise exc.OpenStackCloudException(
"Domain {0} not found for updating".format(name_or_id)
)
domain_id = dom['id']
domain_ref = {}
domain_ref.update({'name': name} if name else {})
domain_ref.update({'description': description} if description else {})
domain_ref.update({'enabled': enabled} if enabled is not None else {})
error_msg = "Error in updating domain {id}".format(id=domain_id)
data = self._identity_client.patch(
'/domains/{id}'.format(id=domain_id),
json={'domain': domain_ref}, error_message=error_msg)
domain = self._get_and_munchify('domain', data)
return _utils.normalize_domains([domain])[0]
def delete_domain(self, domain_id=None, name_or_id=None):
"""Delete a domain.
:param domain_id: ID of the domain to delete.
:param name_or_id: Name or ID of the domain to delete.
:returns: True if delete succeeded, False otherwise.
:raises: ``OpenStackCloudException`` if something goes wrong during
the openstack API call.
"""
if domain_id is None:
if name_or_id is None:
raise exc.OpenStackCloudException(
"You must pass either domain_id or name_or_id value"
)
dom = self.get_domain(name_or_id=name_or_id)
if dom is None:
self.log.debug(
"Domain %s not found for deleting", name_or_id)
return False
domain_id = dom['id']
# A domain must be disabled before deleting
self.update_domain(domain_id, enabled=False)
error_msg = "Failed to delete domain {id}".format(id=domain_id)
self._identity_client.delete('/domains/{id}'.format(id=domain_id),
error_message=error_msg)
return True
def list_domains(self, **filters):
"""List Keystone domains.
:returns: a list of ``munch.Munch`` containing the domain description.
:raises: ``OpenStackCloudException``: if something goes wrong during
the openstack API call.
"""
data = self._identity_client.get(
'/domains', params=filters, error_message="Failed to list domains")
domains = self._get_and_munchify('domains', data)
return _utils.normalize_domains(domains)
def search_domains(self, filters=None, name_or_id=None):
"""Search Keystone domains.
:param name_or_id: domain name or id
:param dict filters: A dict containing additional filters to use.
Keys to search on are id, name, enabled and description.
:returns: a list of ``munch.Munch`` containing the domain description.
Each ``munch.Munch`` contains the following attributes::
- id: <domain id>
- name: <domain name>
- description: <domain description>
:raises: ``OpenStackCloudException``: if something goes wrong during
the openstack API call.
"""
if filters is None:
filters = {}
if name_or_id is not None:
domains = self.list_domains()
return _utils._filter_list(domains, name_or_id, filters)
else:
return self.list_domains(**filters)
def get_domain(self, domain_id=None, name_or_id=None, filters=None):
"""Get exactly one Keystone domain.
:param domain_id: domain id.
:param name_or_id: domain name or id.
:param dict filters: A dict containing additional filters to use.
Keys to search on are id, name, enabled and description.
:returns: a ``munch.Munch`` containing the domain description, or None
if not found. Each ``munch.Munch`` contains the following
attributes::
- id: <domain id>
- name: <domain name>
- description: <domain description>
:raises: ``OpenStackCloudException``: if something goes wrong during
the openstack API call.
"""
if domain_id is None:
# NOTE(SamYaple): search_domains() has filters and name_or_id
# in the wrong positional order which prevents _get_entity from
# being able to return quickly if passing a domain object so we
# duplicate that logic here
if hasattr(name_or_id, 'id'):
return name_or_id
return _utils._get_entity(self, 'domain', filters, name_or_id)
else:
error_msg = 'Failed to get domain {id}'.format(id=domain_id)
data = self._identity_client.get(
'/domains/{id}'.format(id=domain_id),
error_message=error_msg)
domain = self._get_and_munchify('domain', data)
return _utils.normalize_domains([domain])[0]
@_utils.valid_kwargs('domain_id')
@_utils.cache_on_arguments()
def list_groups(self, **kwargs):
"""List Keystone Groups.
:param domain_id: domain id.
:returns: A list of ``munch.Munch`` containing the group description.
:raises: ``OpenStackCloudException``: if something goes wrong during
the openstack API call.
"""
data = self._identity_client.get(
'/groups', params=kwargs, error_message="Failed to list groups")
return _utils.normalize_groups(self._get_and_munchify('groups', data))
@_utils.valid_kwargs('domain_id')
def search_groups(self, name_or_id=None, filters=None, **kwargs):
"""Search Keystone groups.
:param name: Group name or id.
:param filters: A dict containing additional filters to use.
:param domain_id: domain id.
:returns: A list of ``munch.Munch`` containing the group description.
:raises: ``OpenStackCloudException``: if something goes wrong during
the openstack API call.
"""
groups = self.list_groups(**kwargs)
return _utils._filter_list(groups, name_or_id, filters)
@_utils.valid_kwargs('domain_id')
def get_group(self, name_or_id, filters=None, **kwargs):
"""Get exactly one Keystone group.
:param id: Group name or id.
:param filters: A dict containing additional filters to use.
:param domain_id: domain id.
:returns: A ``munch.Munch`` containing the group description.
:raises: ``OpenStackCloudException``: if something goes wrong during
the openstack API call.
"""
return _utils._get_entity(self, 'group', name_or_id, filters, **kwargs)
def create_group(self, name, description, domain=None):
"""Create a group.
:param string name: Group name.
:param string description: Group description.
:param string domain: Domain name or ID for the group.
:returns: A ``munch.Munch`` containing the group description.
:raises: ``OpenStackCloudException``: if something goes wrong during
the openstack API call.
"""
group_ref = {'name': name}
if description:
group_ref['description'] = description
if domain:
dom = self.get_domain(domain)
if not dom:
raise exc.OpenStackCloudException(
"Creating group {group} failed: Invalid domain "
"{domain}".format(group=name, domain=domain)
)
group_ref['domain_id'] = dom['id']
error_msg = "Error creating group {group}".format(group=name)
data = self._identity_client.post(
'/groups', json={'group': group_ref}, error_message=error_msg)
group = self._get_and_munchify('group', data)
self.list_groups.invalidate(self)
return _utils.normalize_groups([group])[0]
@_utils.valid_kwargs('domain_id')
def update_group(self, name_or_id, name=None, description=None,
**kwargs):
"""Update an existing group
:param string name: New group name.
:param string description: New group description.
:param domain_id: domain id.
:returns: A ``munch.Munch`` containing the group description.
:raises: ``OpenStackCloudException``: if something goes wrong during
the openstack API call.
"""
self.list_groups.invalidate(self)
group = self.get_group(name_or_id, **kwargs)
if group is None:
raise exc.OpenStackCloudException(
"Group {0} not found for updating".format(name_or_id)
)
group_ref = {}
if name:
group_ref['name'] = name
if description:
group_ref['description'] = description
error_msg = "Unable to update group {name}".format(name=name_or_id)
data = self._identity_client.patch(
'/groups/{id}'.format(id=group['id']),
json={'group': group_ref}, error_message=error_msg)
group = self._get_and_munchify('group', data)
self.list_groups.invalidate(self)
return _utils.normalize_groups([group])[0]
@_utils.valid_kwargs('domain_id')
def delete_group(self, name_or_id, **kwargs):
"""Delete a group
:param name_or_id: ID or name of the group to delete.
:param domain_id: domain id.
:returns: True if delete succeeded, False otherwise.
:raises: ``OpenStackCloudException``: if something goes wrong during
the openstack API call.
"""
group = self.get_group(name_or_id, **kwargs)
if group is None:
self.log.debug(
"Group %s not found for deleting", name_or_id)
return False
error_msg = "Unable to delete group {name}".format(name=name_or_id)
self._identity_client.delete('/groups/{id}'.format(id=group['id']),
error_message=error_msg)
self.list_groups.invalidate(self)
return True
@_utils.valid_kwargs('domain_id')
def list_roles(self, **kwargs):
"""List Keystone roles.
:param domain_id: domain id for listing roles (v3)
:returns: a list of ``munch.Munch`` containing the role description.
:raises: ``OpenStackCloudException``: if something goes wrong during
the openstack API call.
"""
v2 = self._is_client_version('identity', 2)
url = '/OS-KSADM/roles' if v2 else '/roles'
data = self._identity_client.get(
url, params=kwargs, error_message="Failed to list roles")
return self._normalize_roles(self._get_and_munchify('roles', data))
@_utils.valid_kwargs('domain_id')
def search_roles(self, name_or_id=None, filters=None, **kwargs):
"""Seach Keystone roles.
:param string name: role name or id.
:param dict filters: a dict containing additional filters to use.
:param domain_id: domain id (v3)
:returns: a list of ``munch.Munch`` containing the role description.
Each ``munch.Munch`` contains the following attributes::
- id: <role id>
- name: <role name>
- description: <role description>
:raises: ``OpenStackCloudException``: if something goes wrong during
the openstack API call.
"""
roles = self.list_roles(**kwargs)
return _utils._filter_list(roles, name_or_id, filters)
@_utils.valid_kwargs('domain_id')
def get_role(self, name_or_id, filters=None, **kwargs):
"""Get exactly one Keystone role.
:param id: role name or id.
:param filters: a dict containing additional filters to use.
:param domain_id: domain id (v3)
:returns: a single ``munch.Munch`` containing the role description.
Each ``munch.Munch`` contains the following attributes::
- id: <role id>
- name: <role name>
- description: <role description>
:raises: ``OpenStackCloudException``: if something goes wrong during
the openstack API call.
"""
return _utils._get_entity(self, 'role', name_or_id, filters, **kwargs)
def _keystone_v2_role_assignments(self, user, project=None,
role=None, **kwargs):
data = self._identity_client.get(
"/tenants/{tenant}/users/{user}/roles".format(
tenant=project, user=user),
error_message="Failed to list role assignments")
roles = self._get_and_munchify('roles', data)
ret = []
for tmprole in roles:
if role is not None and role != tmprole.id:
continue
ret.append({
'role': {
'id': tmprole.id
},
'scope': {
'project': {
'id': project,
}
},
'user': {
'id': user,
}
})
return ret
def _keystone_v3_role_assignments(self, **filters):
# NOTE(samueldmq): different parameters have different representation
# patterns as query parameters in the call to the list role assignments
# API. The code below handles each set of patterns separately and
# renames the parameters names accordingly, ignoring 'effective',
# 'include_names' and 'include_subtree' whose do not need any renaming.
for k in ('group', 'role', 'user'):
if k in filters:
filters[k + '.id'] = filters[k]
del filters[k]
for k in ('project', 'domain'):
if k in filters:
filters['scope.' + k + '.id'] = filters[k]
del filters[k]
if 'os_inherit_extension_inherited_to' in filters:
filters['scope.OS-INHERIT:inherited_to'] = (
filters['os_inherit_extension_inherited_to'])
del filters['os_inherit_extension_inherited_to']
data = self._identity_client.get(
'/role_assignments', params=filters,
error_message="Failed to list role assignments")
return self._get_and_munchify('role_assignments', data)
def list_role_assignments(self, filters=None):
"""List Keystone role assignments
:param dict filters: Dict of filter conditions. Acceptable keys are:
* 'user' (string) - User ID to be used as query filter.
* 'group' (string) - Group ID to be used as query filter.
* 'project' (string) - Project ID to be used as query filter.
* 'domain' (string) - Domain ID to be used as query filter.
* 'role' (string) - Role ID to be used as query filter.
* 'os_inherit_extension_inherited_to' (string) - Return inherited
role assignments for either 'projects' or 'domains'
* 'effective' (boolean) - Return effective role assignments.
* 'include_subtree' (boolean) - Include subtree
'user' and 'group' are mutually exclusive, as are 'domain' and
'project'.
NOTE: For keystone v2, only user, project, and role are used.
Project and user are both required in filters.
:returns: a list of ``munch.Munch`` containing the role assignment
description. Contains the following attributes::
- id: <role id>
- user|group: <user or group id>
- project|domain: <project or domain id>
:raises: ``OpenStackCloudException``: if something goes wrong during
the openstack API call.
"""
# NOTE(samueldmq): although 'include_names' is a valid query parameter
# in the keystone v3 list role assignments API, it would have NO effect
# on shade due to normalization. It is not documented as an acceptable
# filter in the docs above per design!
if not filters:
filters = {}
# NOTE(samueldmq): the docs above say filters are *IDs*, though if
# munch.Munch objects are passed, this still works for backwards
# compatibility as keystoneclient allows either IDs or objects to be
# passed in.
# TODO(samueldmq): fix the docs above to advertise munch.Munch objects
# can be provided as parameters too
for k, v in filters.items():
if isinstance(v, munch.Munch):
filters[k] = v['id']
if self._is_client_version('identity', 2):
if filters.get('project') is None or filters.get('user') is None:
raise exc.OpenStackCloudException(
"Must provide project and user for keystone v2"
)
assignments = self._keystone_v2_role_assignments(**filters)
else:
assignments = self._keystone_v3_role_assignments(**filters)
return _utils.normalize_role_assignments(assignments)
def create_flavor(self, name, ram, vcpus, disk, flavorid="auto",
ephemeral=0, swap=0, rxtx_factor=1.0, is_public=True):
"""Create a new flavor.
:param name: Descriptive name of the flavor
:param ram: Memory in MB for the flavor
:param vcpus: Number of VCPUs for the flavor
:param disk: Size of local disk in GB
:param flavorid: ID for the flavor (optional)
:param ephemeral: Ephemeral space size in GB
:param swap: Swap space in MB
:param rxtx_factor: RX/TX factor
:param is_public: Make flavor accessible to the public
:returns: A ``munch.Munch`` describing the new flavor.
:raises: OpenStackCloudException on operation error.
"""
with _utils.shade_exceptions("Failed to create flavor {name}".format(
name=name)):
payload = {
'disk': disk,
'OS-FLV-EXT-DATA:ephemeral': ephemeral,
'id': flavorid,
'os-flavor-access:is_public': is_public,
'name': name,
'ram': ram,
'rxtx_factor': rxtx_factor,
'swap': swap,
'vcpus': vcpus,
}
if flavorid == 'auto':
payload['id'] = None
data = self._compute_client.post(
'/flavors',
json=dict(flavor=payload))
return self._normalize_flavor(
self._get_and_munchify('flavor', data))
def delete_flavor(self, name_or_id):
"""Delete a flavor
:param name_or_id: ID or name of the flavor to delete.
:returns: True if delete succeeded, False otherwise.
:raises: OpenStackCloudException on operation error.
"""
flavor = self.get_flavor(name_or_id, get_extra=False)
if flavor is None:
self.log.debug(
"Flavor %s not found for deleting", name_or_id)
return False
with _utils.shade_exceptions("Unable to delete flavor {name}".format(
name=name_or_id)):
self._compute_client.delete(
'/flavors/{id}'.format(id=flavor['id']))
return True
def set_flavor_specs(self, flavor_id, extra_specs):
"""Add extra specs to a flavor
:param string flavor_id: ID of the flavor to update.
:param dict extra_specs: Dictionary of key-value pairs.
:raises: OpenStackCloudException on operation error.
:raises: OpenStackCloudResourceNotFound if flavor ID is not found.
"""
try:
self._compute_client.post(
"/flavors/{id}/os-extra_specs".format(id=flavor_id),
json=dict(extra_specs=extra_specs))
except Exception as e:
raise exc.OpenStackCloudException(
"Unable to set flavor specs: {0}".format(str(e))
)
def unset_flavor_specs(self, flavor_id, keys):
"""Delete extra specs from a flavor
:param string flavor_id: ID of the flavor to update.
:param list keys: List of spec keys to delete.
:raises: OpenStackCloudException on operation error.
:raises: OpenStackCloudResourceNotFound if flavor ID is not found.
"""
for key in keys:
try:
self._compute_client.delete(
"/flavors/{id}/os-extra_specs/{key}".format(
id=flavor_id, key=key))
except Exception as e:
raise exc.OpenStackCloudException(
"Unable to delete flavor spec {0}: {1}".format(
key, str(e)))
def _mod_flavor_access(self, action, flavor_id, project_id):
"""Common method for adding and removing flavor access
"""
with _utils.shade_exceptions("Error trying to {action} access from "
"flavor ID {flavor}".format(
action=action, flavor=flavor_id)):
endpoint = '/flavors/{id}/action'.format(id=flavor_id)
access = {'tenant': project_id}
access_key = '{action}TenantAccess'.format(action=action)
self._compute_client.post(endpoint, json={access_key: access})
def add_flavor_access(self, flavor_id, project_id):
"""Grant access to a private flavor for a project/tenant.
:param string flavor_id: ID of the private flavor.
:param string project_id: ID of the project/tenant.
:raises: OpenStackCloudException on operation error.
"""
self._mod_flavor_access('add', flavor_id, project_id)
def remove_flavor_access(self, flavor_id, project_id):
"""Revoke access from a private flavor for a project/tenant.
:param string flavor_id: ID of the private flavor.
:param string project_id: ID of the project/tenant.
:raises: OpenStackCloudException on operation error.
"""
self._mod_flavor_access('remove', flavor_id, project_id)
def list_flavor_access(self, flavor_id):
"""List access from a private flavor for a project/tenant.
:param string flavor_id: ID of the private flavor.
:returns: a list of ``munch.Munch`` containing the access description
:raises: OpenStackCloudException on operation error.
"""
with _utils.shade_exceptions("Error trying to list access from "
"flavor ID {flavor}".format(
flavor=flavor_id)):
data = self._compute_client.get(
'/flavors/{id}/os-flavor-access'.format(id=flavor_id))
return _utils.normalize_flavor_accesses(
self._get_and_munchify('flavor_access', data))
@_utils.valid_kwargs('domain_id')
def create_role(self, name, **kwargs):
"""Create a Keystone role.
:param string name: The name of the role.
:param domain_id: domain id (v3)
:returns: a ``munch.Munch`` containing the role description
:raise exc.OpenStackCloudException: if the role cannot be created
"""
v2 = self._is_client_version('identity', 2)
url = '/OS-KSADM/roles' if v2 else '/roles'
kwargs['name'] = name
msg = 'Failed to create role {name}'.format(name=name)
data = self._identity_client.post(
url, json={'role': kwargs}, error_message=msg)
role = self._get_and_munchify('role', data)
return self._normalize_role(role)
@_utils.valid_kwargs('domain_id')
def update_role(self, name_or_id, name, **kwargs):
"""Update a Keystone role.
:param name_or_id: Name or id of the role to update
:param string name: The new role name
:param domain_id: domain id
:returns: a ``munch.Munch`` containing the role description
:raise exc.OpenStackCloudException: if the role cannot be created
"""
if self._is_client_version('identity', 2):
raise exc.OpenStackCloudUnavailableFeature(
'Unavailable Feature: Role update requires Identity v3'
)
kwargs['name_or_id'] = name_or_id
role = self.get_role(**kwargs)
if role is None:
self.log.debug(
"Role %s not found for updating", name_or_id)
return False
msg = 'Failed to update role {name}'.format(name=name_or_id)
json_kwargs = {'role_id': role.id, 'role': {'name': name}}
data = self._identity_client.patch('/roles', error_message=msg,
json=json_kwargs)
role = self._get_and_munchify('role', data)
return self._normalize_role(role)
@_utils.valid_kwargs('domain_id')
def delete_role(self, name_or_id, **kwargs):
"""Delete a Keystone role.
:param string id: Name or id of the role to delete.
:param domain_id: domain id (v3)
:returns: True if delete succeeded, False otherwise.
:raises: ``OpenStackCloudException`` if something goes wrong during
the openstack API call.
"""
role = self.get_role(name_or_id, **kwargs)
if role is None:
self.log.debug(
"Role %s not found for deleting", name_or_id)
return False
v2 = self._is_client_version('identity', 2)
url = '{preffix}/{id}'.format(
preffix='/OS-KSADM/roles' if v2 else '/roles', id=role['id'])
error_msg = "Unable to delete role {name}".format(name=name_or_id)
self._identity_client.delete(url, error_message=error_msg)
return True
def _get_grant_revoke_params(self, role, user=None, group=None,
project=None, domain=None):
role = self.get_role(role)
if role is None:
return {}
data = {'role': role.id}
# domain and group not available in keystone v2.0
is_keystone_v2 = self._is_client_version('identity', 2)
filters = {}
if not is_keystone_v2 and domain:
filters['domain_id'] = data['domain'] = \
self.get_domain(domain)['id']
if user:
data['user'] = self.get_user(user, filters=filters)
if project:
# drop domain in favor of project
data.pop('domain', None)
data['project'] = self.get_project(project, filters=filters)
if not is_keystone_v2 and group:
data['group'] = self.get_group(group, filters=filters)
return data
def grant_role(self, name_or_id, user=None, group=None,
project=None, domain=None, wait=False, timeout=60):
"""Grant a role to a user.
:param string name_or_id: The name or id of the role.
:param string user: The name or id of the user.
:param string group: The name or id of the group. (v3)
:param string project: The name or id of the project.
:param string domain: The id of the domain. (v3)
:param bool wait: Wait for role to be granted
:param int timeout: Timeout to wait for role to be granted
NOTE: domain is a required argument when the grant is on a project,
user or group specified by name. In that situation, they are all
considered to be in that domain. If different domains are in use
in the same role grant, it is required to specify those by ID.
NOTE: for wait and timeout, sometimes granting roles is not
instantaneous.
NOTE: project is required for keystone v2
:returns: True if the role is assigned, otherwise False
:raise exc.OpenStackCloudException: if the role cannot be granted
"""
data = self._get_grant_revoke_params(name_or_id, user, group,
project, domain)
filters = data.copy()
if not data:
raise exc.OpenStackCloudException(
'Role {0} not found.'.format(name_or_id))
if data.get('user') is not None and data.get('group') is not None:
raise exc.OpenStackCloudException(
'Specify either a group or a user, not both')
if data.get('user') is None and data.get('group') is None:
raise exc.OpenStackCloudException(
'Must specify either a user or a group')
if self._is_client_version('identity', 2) and \
data.get('project') is None:
raise exc.OpenStackCloudException(
'Must specify project for keystone v2')
if self.list_role_assignments(filters=filters):
self.log.debug('Assignment already exists')
return False
error_msg = "Error granting access to role: {0}".format(data)
if self._is_client_version('identity', 2):
# For v2.0, only tenant/project assignment is supported
url = "/tenants/{t}/users/{u}/roles/OS-KSADM/{r}".format(
t=data['project']['id'], u=data['user']['id'], r=data['role'])
self._identity_client.put(url, error_message=error_msg,
endpoint_filter={'interface': 'admin'})
else:
if data.get('project') is None and data.get('domain') is None:
raise exc.OpenStackCloudException(
'Must specify either a domain or project')
# For v3, figure out the assignment type and build the URL
if data.get('domain'):
url = "/domains/{}".format(data['domain'])
else:
url = "/projects/{}".format(data['project']['id'])
if data.get('group'):
url += "/groups/{}".format(data['group']['id'])
else:
url += "/users/{}".format(data['user']['id'])
url += "/roles/{}".format(data.get('role'))
self._identity_client.put(url, error_message=error_msg)
if wait:
for count in _utils._iterate_timeout(
timeout,
"Timeout waiting for role to be granted"):
if self.list_role_assignments(filters=filters):
break
return True
def revoke_role(self, name_or_id, user=None, group=None,
project=None, domain=None, wait=False, timeout=60):
"""Revoke a role from a user.
:param string name_or_id: The name or id of the role.
:param string user: The name or id of the user.
:param string group: The name or id of the group. (v3)
:param string project: The name or id of the project.
:param string domain: The id of the domain. (v3)
:param bool wait: Wait for role to be revoked
:param int timeout: Timeout to wait for role to be revoked
NOTE: for wait and timeout, sometimes revoking roles is not
instantaneous.
NOTE: project is required for keystone v2
:returns: True if the role is revoke, otherwise False
:raise exc.OpenStackCloudException: if the role cannot be removed
"""
data = self._get_grant_revoke_params(name_or_id, user, group,
project, domain)
filters = data.copy()
if not data:
raise exc.OpenStackCloudException(
'Role {0} not found.'.format(name_or_id))
if data.get('user') is not None and data.get('group') is not None:
raise exc.OpenStackCloudException(
'Specify either a group or a user, not both')
if data.get('user') is None and data.get('group') is None:
raise exc.OpenStackCloudException(
'Must specify either a user or a group')
if self._is_client_version('identity', 2) and \
data.get('project') is None:
raise exc.OpenStackCloudException(
'Must specify project for keystone v2')
if not self.list_role_assignments(filters=filters):
self.log.debug('Assignment does not exist')
return False
error_msg = "Error revoking access to role: {0}".format(data)
if self._is_client_version('identity', 2):
# For v2.0, only tenant/project assignment is supported
url = "/tenants/{t}/users/{u}/roles/OS-KSADM/{r}".format(
t=data['project']['id'], u=data['user']['id'], r=data['role'])
self._identity_client.delete(
url, error_message=error_msg,
endpoint_filter={'interface': 'admin'})
else:
if data.get('project') is None and data.get('domain') is None:
raise exc.OpenStackCloudException(
'Must specify either a domain or project')
# For v3, figure out the assignment type and build the URL
if data.get('domain'):
url = "/domains/{}".format(data['domain'])
else:
url = "/projects/{}".format(data['project']['id'])
if data.get('group'):
url += "/groups/{}".format(data['group']['id'])
else:
url += "/users/{}".format(data['user']['id'])
url += "/roles/{}".format(data.get('role'))
self._identity_client.delete(url, error_message=error_msg)
if wait:
for count in _utils._iterate_timeout(
timeout,
"Timeout waiting for role to be revoked"):
if not self.list_role_assignments(filters=filters):
break
return True
def list_hypervisors(self):
"""List all hypervisors
:returns: A list of hypervisor ``munch.Munch``.
"""
data = self._compute_client.get(
'/os-hypervisors/detail',
error_message="Error fetching hypervisor list")
return self._get_and_munchify('hypervisors', data)
def search_aggregates(self, name_or_id=None, filters=None):
"""Seach host aggregates.
:param name: aggregate name or id.
:param filters: a dict containing additional filters to use.
:returns: a list of dicts containing the aggregates
:raises: ``OpenStackCloudException``: if something goes wrong during
the openstack API call.
"""
aggregates = self.list_aggregates()
return _utils._filter_list(aggregates, name_or_id, filters)
def list_aggregates(self):
"""List all available host aggregates.
:returns: A list of aggregate dicts.
"""
data = self._compute_client.get(
'/os-aggregates',
error_message="Error fetching aggregate list")
return self._get_and_munchify('aggregates', data)
def get_aggregate(self, name_or_id, filters=None):
"""Get an aggregate by name or ID.
:param name_or_id: Name or ID of the aggregate.
:param dict filters:
A dictionary of meta data to use for further filtering. Elements
of this dictionary may, themselves, be dictionaries. Example::
{
'availability_zone': 'nova',
'metadata': {
'cpu_allocation_ratio': '1.0'
}
}
:returns: An aggregate dict or None if no matching aggregate is
found.
"""
return _utils._get_entity(self, 'aggregate', name_or_id, filters)
def create_aggregate(self, name, availability_zone=None):
"""Create a new host aggregate.
:param name: Name of the host aggregate being created
:param availability_zone: Availability zone to assign hosts
:returns: a dict representing the new host aggregate.
:raises: OpenStackCloudException on operation error.
"""
data = self._compute_client.post(
'/os-aggregates',
json={'aggregate': {
'name': name,
'availability_zone': availability_zone
}},
error_message="Unable to create host aggregate {name}".format(
name=name))
return self._get_and_munchify('aggregate', data)
@_utils.valid_kwargs('name', 'availability_zone')
def update_aggregate(self, name_or_id, **kwargs):
"""Update a host aggregate.
:param name_or_id: Name or ID of the aggregate being updated.
:param name: New aggregate name
:param availability_zone: Availability zone to assign to hosts
:returns: a dict representing the updated host aggregate.
:raises: OpenStackCloudException on operation error.
"""
aggregate = self.get_aggregate(name_or_id)
if not aggregate:
raise exc.OpenStackCloudException(
"Host aggregate %s not found." % name_or_id)
data = self._compute_client.put(
'/os-aggregates/{id}'.format(id=aggregate['id']),
json={'aggregate': kwargs},
error_message="Error updating aggregate {name}".format(
name=name_or_id))
return self._get_and_munchify('aggregate', data)
def delete_aggregate(self, name_or_id):
"""Delete a host aggregate.
:param name_or_id: Name or ID of the host aggregate to delete.
:returns: True if delete succeeded, False otherwise.
:raises: OpenStackCloudException on operation error.
"""
aggregate = self.get_aggregate(name_or_id)
if not aggregate:
self.log.debug("Aggregate %s not found for deleting", name_or_id)
return False
return self._compute_client.delete(
'/os-aggregates/{id}'.format(id=aggregate['id']),
error_message="Error deleting aggregate {name}".format(
name=name_or_id))
return True
def set_aggregate_metadata(self, name_or_id, metadata):
"""Set aggregate metadata, replacing the existing metadata.
:param name_or_id: Name of the host aggregate to update
:param metadata: Dict containing metadata to replace (Use
{'key': None} to remove a key)
:returns: a dict representing the new host aggregate.
:raises: OpenStackCloudException on operation error.
"""
aggregate = self.get_aggregate(name_or_id)
if not aggregate:
raise exc.OpenStackCloudException(
"Host aggregate %s not found." % name_or_id)
err_msg = "Unable to set metadata for host aggregate {name}".format(
name=name_or_id)
data = self._compute_client.post(
'/os-aggregates/{id}/action'.format(id=aggregate['id']),
json={'set_metadata': {'metadata': metadata}},
error_message=err_msg)
return self._get_and_munchify('aggregate', data)
def add_host_to_aggregate(self, name_or_id, host_name):
"""Add a host to an aggregate.
:param name_or_id: Name or ID of the host aggregate.
:param host_name: Host to add.
:raises: OpenStackCloudException on operation error.
"""
aggregate = self.get_aggregate(name_or_id)
if not aggregate:
raise exc.OpenStackCloudException(
"Host aggregate %s not found." % name_or_id)
err_msg = "Unable to add host {host} to aggregate {name}".format(
host=host_name, name=name_or_id)
return self._compute_client.post(
'/os-aggregates/{id}/action'.format(id=aggregate['id']),
json={'add_host': {'host': host_name}},
error_message=err_msg)
def remove_host_from_aggregate(self, name_or_id, host_name):
"""Remove a host from an aggregate.
:param name_or_id: Name or ID of the host aggregate.
:param host_name: Host to remove.
:raises: OpenStackCloudException on operation error.
"""
aggregate = self.get_aggregate(name_or_id)
if not aggregate:
raise exc.OpenStackCloudException(
"Host aggregate %s not found." % name_or_id)
err_msg = "Unable to remove host {host} to aggregate {name}".format(
host=host_name, name=name_or_id)
return self._compute_client.post(
'/os-aggregates/{id}/action'.format(id=aggregate['id']),
json={'remove_host': {'host': host_name}},
error_message=err_msg)
def get_volume_type_access(self, name_or_id):
"""Return a list of volume_type_access.
:param name_or_id: Name or ID of the volume type.
:raises: OpenStackCloudException on operation error.
"""
volume_type = self.get_volume_type(name_or_id)
if not volume_type:
raise exc.OpenStackCloudException(
"VolumeType not found: %s" % name_or_id)
data = self._volume_client.get(
'/types/{id}/os-volume-type-access'.format(id=volume_type.id),
error_message="Unable to get volume type access"
" {name}".format(name=name_or_id))
return self._normalize_volume_type_accesses(
self._get_and_munchify('volume_type_access', data))
def add_volume_type_access(self, name_or_id, project_id):
"""Grant access on a volume_type to a project.
:param name_or_id: ID or name of a volume_type
:param project_id: A project id
NOTE: the call works even if the project does not exist.
:raises: OpenStackCloudException on operation error.
"""
volume_type = self.get_volume_type(name_or_id)
if not volume_type:
raise exc.OpenStackCloudException(
"VolumeType not found: %s" % name_or_id)
with _utils.shade_exceptions():
payload = {'project': project_id}
self._volume_client.post(
'/types/{id}/action'.format(id=volume_type.id),
json=dict(addProjectAccess=payload),
error_message="Unable to authorize {project} "
"to use volume type {name}".format(
name=name_or_id, project=project_id))
def remove_volume_type_access(self, name_or_id, project_id):
"""Revoke access on a volume_type to a project.
:param name_or_id: ID or name of a volume_type
:param project_id: A project id
:raises: OpenStackCloudException on operation error.
"""
volume_type = self.get_volume_type(name_or_id)
if not volume_type:
raise exc.OpenStackCloudException(
"VolumeType not found: %s" % name_or_id)
with _utils.shade_exceptions():
payload = {'project': project_id}
self._volume_client.post(
'/types/{id}/action'.format(id=volume_type.id),
json=dict(removeProjectAccess=payload),
error_message="Unable to revoke {project} "
"to use volume type {name}".format(
name=name_or_id, project=project_id))
def set_compute_quotas(self, name_or_id, **kwargs):
""" Set a quota in a project
:param name_or_id: project name or id
:param kwargs: key/value pairs of quota name and quota value
:raises: OpenStackCloudException if the resource to set the
quota does not exist.
"""
proj = self.get_project(name_or_id)
if not proj:
raise exc.OpenStackCloudException("project does not exist")
# compute_quotas = {key: val for key, val in kwargs.items()
# if key in quota.COMPUTE_QUOTAS}
# TODO(ghe): Manage volume and network quotas
# network_quotas = {key: val for key, val in kwargs.items()
# if key in quota.NETWORK_QUOTAS}
# volume_quotas = {key: val for key, val in kwargs.items()
# if key in quota.VOLUME_QUOTAS}
kwargs['force'] = True
self._compute_client.put(
'/os-quota-sets/{project}'.format(project=proj.id),
json={'quota_set': kwargs},
error_message="No valid quota or resource")
def get_compute_quotas(self, name_or_id):
""" Get quota for a project
:param name_or_id: project name or id
:raises: OpenStackCloudException if it's not a valid project
:returns: Munch object with the quotas
"""
proj = self.get_project(name_or_id)
if not proj:
raise exc.OpenStackCloudException("project does not exist")
data = self._compute_client.get(
'/os-quota-sets/{project}'.format(project=proj.id))
return self._get_and_munchify('quota_set', data)
def delete_compute_quotas(self, name_or_id):
""" Delete quota for a project
:param name_or_id: project name or id
:raises: OpenStackCloudException if it's not a valid project or the
nova client call failed
:returns: dict with the quotas
"""
proj = self.get_project(name_or_id)
if not proj:
raise exc.OpenStackCloudException("project does not exist")
return self._compute_client.delete(
'/os-quota-sets/{project}'.format(project=proj.id))
def get_compute_usage(self, name_or_id, start=None, end=None):
""" Get usage for a specific project
:param name_or_id: project name or id
:param start: :class:`datetime.datetime` or string. Start date in UTC
Defaults to 2010-07-06T12:00:00Z (the date the OpenStack
project was started)
:param end: :class:`datetime.datetime` or string. End date in UTC.
Defaults to now
:raises: OpenStackCloudException if it's not a valid project
:returns: Munch object with the usage
"""
def parse_date(date):
try:
return iso8601.parse_date(date)
except iso8601.iso8601.ParseError:
# Yes. This is an exception mask. However,iso8601 is an
# implementation detail - and the error message is actually
# less informative.
raise exc.OpenStackCloudException(
"Date given, {date}, is invalid. Please pass in a date"
" string in ISO 8601 format -"
" YYYY-MM-DDTHH:MM:SS".format(
date=date))
def parse_datetime_for_nova(date):
# Must strip tzinfo from the date- it breaks Nova. Also,
# Nova is expecting this in UTC. If someone passes in an
# ISO8601 date string or a datetime with timzeone data attached,
# strip the timezone data but apply offset math first so that
# the user's well formed perfectly valid date will be used
# correctly.
offset = date.utcoffset()
if offset:
date = date - datetime.timedelta(hours=offset)
return date.replace(tzinfo=None)
if not start:
start = parse_date('2010-07-06')
elif not isinstance(start, datetime.datetime):
start = parse_date(start)
if not end:
end = datetime.datetime.utcnow()
elif not isinstance(start, datetime.datetime):
end = parse_date(end)
start = parse_datetime_for_nova(start)
end = parse_datetime_for_nova(end)
proj = self.get_project(name_or_id)
if not proj:
raise exc.OpenStackCloudException(
"project does not exist: {}".format(name=proj.id))
data = self._compute_client.get(
'/os-simple-tenant-usage/{project}'.format(project=proj.id),
params=dict(start=start.isoformat(), end=end.isoformat()),
error_message="Unable to get usage for project: {name}".format(
name=proj.id))
return self._normalize_compute_usage(
self._get_and_munchify('tenant_usage', data))
def set_volume_quotas(self, name_or_id, **kwargs):
""" Set a volume quota in a project
:param name_or_id: project name or id
:param kwargs: key/value pairs of quota name and quota value
:raises: OpenStackCloudException if the resource to set the
quota does not exist.
"""
proj = self.get_project(name_or_id)
if not proj:
raise exc.OpenStackCloudException("project does not exist")
kwargs['tenant_id'] = proj.id
self._volume_client.put(
'/os-quota-sets/{tenant_id}'.format(tenant_id=proj.id),
json={'quota_set': kwargs},
error_message="No valid quota or resource")
def get_volume_quotas(self, name_or_id):
""" Get volume quotas for a project
:param name_or_id: project name or id
:raises: OpenStackCloudException if it's not a valid project
:returns: Munch object with the quotas
"""
proj = self.get_project(name_or_id)
if not proj:
raise exc.OpenStackCloudException("project does not exist")
data = self._volume_client.get(
'/os-quota-sets/{tenant_id}'.format(tenant_id=proj.id),
error_message="cinder client call failed")
return self._get_and_munchify('quota_set', data)
def delete_volume_quotas(self, name_or_id):
""" Delete volume quotas for a project
:param name_or_id: project name or id
:raises: OpenStackCloudException if it's not a valid project or the
cinder client call failed
:returns: dict with the quotas
"""
proj = self.get_project(name_or_id)
if not proj:
raise exc.OpenStackCloudException("project does not exist")
return self._volume_client.delete(
'/os-quota-sets/{tenant_id}'.format(tenant_id=proj.id),
error_message="cinder client call failed")
def set_network_quotas(self, name_or_id, **kwargs):
""" Set a network quota in a project
:param name_or_id: project name or id
:param kwargs: key/value pairs of quota name and quota value
:raises: OpenStackCloudException if the resource to set the
quota does not exist.
"""
proj = self.get_project(name_or_id)
if not proj:
raise exc.OpenStackCloudException("project does not exist")
self._network_client.put(
'/quotas/{project_id}.json'.format(project_id=proj.id),
json={'quota': kwargs},
error_message=("Error setting Neutron's quota for "
"project {0}".format(proj.id)))
def get_network_quotas(self, name_or_id, details=False):
""" Get network quotas for a project
:param name_or_id: project name or id
:param details: if set to True it will return details about usage
of quotas by given project
:raises: OpenStackCloudException if it's not a valid project
:returns: Munch object with the quotas
"""
proj = self.get_project(name_or_id)
if not proj:
raise exc.OpenStackCloudException("project does not exist")
url = '/quotas/{project_id}'.format(project_id=proj.id)
if details:
url = url + "/details"
url = url + ".json"
data = self._network_client.get(
url,
error_message=("Error fetching Neutron's quota for "
"project {0}".format(proj.id)))
return self._get_and_munchify('quota', data)
def get_network_extensions(self):
"""Get Cloud provided network extensions
:returns: set of Neutron extension aliases
"""
return self._neutron_extensions()
def delete_network_quotas(self, name_or_id):
""" Delete network quotas for a project
:param name_or_id: project name or id
:raises: OpenStackCloudException if it's not a valid project or the
network client call failed
:returns: dict with the quotas
"""
proj = self.get_project(name_or_id)
if not proj:
raise exc.OpenStackCloudException("project does not exist")
self._network_client.delete(
'/quotas/{project_id}.json'.format(project_id=proj.id),
error_message=("Error deleting Neutron's quota for "
"project {0}".format(proj.id)))
def list_magnum_services(self):
"""List all Magnum services.
:returns: a list of dicts containing the service details.
:raises: OpenStackCloudException on operation error.
"""
with _utils.shade_exceptions("Error fetching Magnum services list"):
data = self._container_infra_client.get('/mservices')
return self._normalize_magnum_services(
self._get_and_munchify('mservices', data))
|