/usr/share/pyshared/ganeti/rapi/client.py is in python-ganeti-rapi 2.15.2-3.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | #
#
# Copyright (C) 2010, 2011, 2012 Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Ganeti RAPI client.
@attention: To use the RAPI client, the application B{must} call
C{pycurl.global_init} during initialization and
C{pycurl.global_cleanup} before exiting the process. This is very
important in multi-threaded programs. See curl_global_init(3) and
curl_global_cleanup(3) for details. The decorator L{UsesRapiClient}
can be used.
"""
# No Ganeti-specific modules should be imported. The RAPI client is supposed to
# be standalone.
import logging
import simplejson
import socket
import urllib
import threading
import pycurl
import time
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
GANETI_RAPI_PORT = 5080
GANETI_RAPI_VERSION = 2
HTTP_DELETE = "DELETE"
HTTP_GET = "GET"
HTTP_PUT = "PUT"
HTTP_POST = "POST"
HTTP_OK = 200
HTTP_NOT_FOUND = 404
HTTP_APP_JSON = "application/json"
REPLACE_DISK_PRI = "replace_on_primary"
REPLACE_DISK_SECONDARY = "replace_on_secondary"
REPLACE_DISK_CHG = "replace_new_secondary"
REPLACE_DISK_AUTO = "replace_auto"
NODE_EVAC_PRI = "primary-only"
NODE_EVAC_SEC = "secondary-only"
NODE_EVAC_ALL = "all"
NODE_ROLE_DRAINED = "drained"
NODE_ROLE_MASTER_CANDIDATE = "master-candidate"
NODE_ROLE_MASTER = "master"
NODE_ROLE_OFFLINE = "offline"
NODE_ROLE_REGULAR = "regular"
JOB_STATUS_QUEUED = "queued"
JOB_STATUS_WAITING = "waiting"
JOB_STATUS_CANCELING = "canceling"
JOB_STATUS_RUNNING = "running"
JOB_STATUS_CANCELED = "canceled"
JOB_STATUS_SUCCESS = "success"
JOB_STATUS_ERROR = "error"
JOB_STATUS_PENDING = frozenset([
JOB_STATUS_QUEUED,
JOB_STATUS_WAITING,
JOB_STATUS_CANCELING,
])
JOB_STATUS_FINALIZED = frozenset([
JOB_STATUS_CANCELED,
JOB_STATUS_SUCCESS,
JOB_STATUS_ERROR,
])
JOB_STATUS_ALL = frozenset([
JOB_STATUS_RUNNING,
]) | JOB_STATUS_PENDING | JOB_STATUS_FINALIZED
# Legacy name
JOB_STATUS_WAITLOCK = JOB_STATUS_WAITING
# Internal constants
_REQ_DATA_VERSION_FIELD = "__version__"
_QPARAM_DRY_RUN = "dry-run"
_QPARAM_FORCE = "force"
# Feature strings
INST_CREATE_REQV1 = "instance-create-reqv1"
INST_REINSTALL_REQV1 = "instance-reinstall-reqv1"
NODE_MIGRATE_REQV1 = "node-migrate-reqv1"
NODE_EVAC_RES1 = "node-evac-res1"
# Old feature constant names in case they're references by users of this module
_INST_CREATE_REQV1 = INST_CREATE_REQV1
_INST_REINSTALL_REQV1 = INST_REINSTALL_REQV1
_NODE_MIGRATE_REQV1 = NODE_MIGRATE_REQV1
_NODE_EVAC_RES1 = NODE_EVAC_RES1
#: Resolver errors
ECODE_RESOLVER = "resolver_error"
#: Not enough resources (iallocator failure, disk space, memory, etc.)
ECODE_NORES = "insufficient_resources"
#: Temporarily out of resources; operation can be tried again
ECODE_TEMP_NORES = "temp_insufficient_resources"
#: Wrong arguments (at syntax level)
ECODE_INVAL = "wrong_input"
#: Wrong entity state
ECODE_STATE = "wrong_state"
#: Entity not found
ECODE_NOENT = "unknown_entity"
#: Entity already exists
ECODE_EXISTS = "already_exists"
#: Resource not unique (e.g. MAC or IP duplication)
ECODE_NOTUNIQUE = "resource_not_unique"
#: Internal cluster error
ECODE_FAULT = "internal_error"
#: Environment error (e.g. node disk error)
ECODE_ENVIRON = "environment_error"
#: List of all failure types
ECODE_ALL = frozenset([
ECODE_RESOLVER,
ECODE_NORES,
ECODE_TEMP_NORES,
ECODE_INVAL,
ECODE_STATE,
ECODE_NOENT,
ECODE_EXISTS,
ECODE_NOTUNIQUE,
ECODE_FAULT,
ECODE_ENVIRON,
])
# Older pycURL versions don't have all error constants
try:
_CURLE_SSL_CACERT = pycurl.E_SSL_CACERT
_CURLE_SSL_CACERT_BADFILE = pycurl.E_SSL_CACERT_BADFILE
except AttributeError:
_CURLE_SSL_CACERT = 60
_CURLE_SSL_CACERT_BADFILE = 77
_CURL_SSL_CERT_ERRORS = frozenset([
_CURLE_SSL_CACERT,
_CURLE_SSL_CACERT_BADFILE,
])
class Error(Exception):
"""Base error class for this module.
"""
pass
class GanetiApiError(Error):
"""Generic error raised from Ganeti API.
"""
def __init__(self, msg, code=None):
Error.__init__(self, msg)
self.code = code
class CertificateError(GanetiApiError):
"""Raised when a problem is found with the SSL certificate.
"""
pass
def EpochNano():
"""Return the current timestamp expressed as number of nanoseconds since the
unix epoch
@return: nanoseconds since the Unix epoch
"""
return int(time.time() * 1000000000)
def _AppendIf(container, condition, value):
"""Appends to a list if a condition evaluates to truth.
"""
if condition:
container.append(value)
return condition
def _AppendDryRunIf(container, condition):
"""Appends a "dry-run" parameter if a condition evaluates to truth.
"""
return _AppendIf(container, condition, (_QPARAM_DRY_RUN, 1))
def _AppendForceIf(container, condition):
"""Appends a "force" parameter if a condition evaluates to truth.
"""
return _AppendIf(container, condition, (_QPARAM_FORCE, 1))
def _AppendReason(container, reason):
"""Appends an element to the reason trail.
If the user provided a reason, it is added to the reason trail.
"""
return _AppendIf(container, reason, ("reason", reason))
def _SetItemIf(container, condition, item, value):
"""Sets an item if a condition evaluates to truth.
"""
if condition:
container[item] = value
return condition
def UsesRapiClient(fn):
"""Decorator for code using RAPI client to initialize pycURL.
"""
def wrapper(*args, **kwargs):
# curl_global_init(3) and curl_global_cleanup(3) must be called with only
# one thread running. This check is just a safety measure -- it doesn't
# cover all cases.
assert threading.activeCount() == 1, \
"Found active threads when initializing pycURL"
pycurl.global_init(pycurl.GLOBAL_ALL)
try:
return fn(*args, **kwargs)
finally:
pycurl.global_cleanup()
return wrapper
def GenericCurlConfig(verbose=False, use_signal=False,
use_curl_cabundle=False, cafile=None, capath=None,
proxy=None, verify_hostname=False,
connect_timeout=None, timeout=None,
_pycurl_version_fn=pycurl.version_info):
"""Curl configuration function generator.
@type verbose: bool
@param verbose: Whether to set cURL to verbose mode
@type use_signal: bool
@param use_signal: Whether to allow cURL to use signals
@type use_curl_cabundle: bool
@param use_curl_cabundle: Whether to use cURL's default CA bundle
@type cafile: string
@param cafile: In which file we can find the certificates
@type capath: string
@param capath: In which directory we can find the certificates
@type proxy: string
@param proxy: Proxy to use, None for default behaviour and empty string for
disabling proxies (see curl_easy_setopt(3))
@type verify_hostname: bool
@param verify_hostname: Whether to verify the remote peer certificate's
commonName
@type connect_timeout: number
@param connect_timeout: Timeout for establishing connection in seconds
@type timeout: number
@param timeout: Timeout for complete transfer in seconds (see
curl_easy_setopt(3)).
"""
if use_curl_cabundle and (cafile or capath):
raise Error("Can not use default CA bundle when CA file or path is set")
def _ConfigCurl(curl, logger):
"""Configures a cURL object
@type curl: pycurl.Curl
@param curl: cURL object
"""
logger.debug("Using cURL version %s", pycurl.version)
# pycurl.version_info returns a tuple with information about the used
# version of libcurl. Item 5 is the SSL library linked to it.
# e.g.: (3, '7.18.0', 463360, 'x86_64-pc-linux-gnu', 1581, 'GnuTLS/2.0.4',
# 0, '1.2.3.3', ...)
sslver = _pycurl_version_fn()[5]
if not sslver:
raise Error("No SSL support in cURL")
lcsslver = sslver.lower()
if lcsslver.startswith("openssl/"):
pass
elif lcsslver.startswith("nss/"):
# TODO: investigate compatibility beyond a simple test
pass
elif lcsslver.startswith("gnutls/"):
if capath:
raise Error("cURL linked against GnuTLS has no support for a"
" CA path (%s)" % (pycurl.version, ))
else:
raise NotImplementedError("cURL uses unsupported SSL version '%s'" %
sslver)
curl.setopt(pycurl.VERBOSE, verbose)
curl.setopt(pycurl.NOSIGNAL, not use_signal)
# Whether to verify remote peer's CN
if verify_hostname:
# curl_easy_setopt(3): "When CURLOPT_SSL_VERIFYHOST is 2, that
# certificate must indicate that the server is the server to which you
# meant to connect, or the connection fails. [...] When the value is 1,
# the certificate must contain a Common Name field, but it doesn't matter
# what name it says. [...]"
curl.setopt(pycurl.SSL_VERIFYHOST, 2)
else:
curl.setopt(pycurl.SSL_VERIFYHOST, 0)
if cafile or capath or use_curl_cabundle:
# Require certificates to be checked
curl.setopt(pycurl.SSL_VERIFYPEER, True)
if cafile:
curl.setopt(pycurl.CAINFO, str(cafile))
if capath:
curl.setopt(pycurl.CAPATH, str(capath))
# Not changing anything for using default CA bundle
else:
# Disable SSL certificate verification
curl.setopt(pycurl.SSL_VERIFYPEER, False)
if proxy is not None:
curl.setopt(pycurl.PROXY, str(proxy))
# Timeouts
if connect_timeout is not None:
curl.setopt(pycurl.CONNECTTIMEOUT, connect_timeout)
if timeout is not None:
curl.setopt(pycurl.TIMEOUT, timeout)
return _ConfigCurl
class GanetiRapiClient(object): # pylint: disable=R0904
"""Ganeti RAPI client.
"""
USER_AGENT = "Ganeti RAPI Client"
_json_encoder = simplejson.JSONEncoder(sort_keys=True)
def __init__(self, host, port=GANETI_RAPI_PORT,
username=None, password=None, logger=logging,
curl_config_fn=None, curl_factory=None):
"""Initializes this class.
@type host: string
@param host: the ganeti cluster master to interact with
@type port: int
@param port: the port on which the RAPI is running (default is 5080)
@type username: string
@param username: the username to connect with
@type password: string
@param password: the password to connect with
@type curl_config_fn: callable
@param curl_config_fn: Function to configure C{pycurl.Curl} object
@param logger: Logging object
"""
self._username = username
self._password = password
self._logger = logger
self._curl_config_fn = curl_config_fn
self._curl_factory = curl_factory
try:
socket.inet_pton(socket.AF_INET6, host)
address = "[%s]:%s" % (host, port)
except socket.error:
address = "%s:%s" % (host, port)
self._base_url = "https://%s" % address
if username is not None:
if password is None:
raise Error("Password not specified")
elif password:
raise Error("Specified password without username")
def _CreateCurl(self):
"""Creates a cURL object.
"""
# Create pycURL object if no factory is provided
if self._curl_factory:
curl = self._curl_factory()
else:
curl = pycurl.Curl()
# Default cURL settings
curl.setopt(pycurl.VERBOSE, False)
curl.setopt(pycurl.FOLLOWLOCATION, False)
curl.setopt(pycurl.MAXREDIRS, 5)
curl.setopt(pycurl.NOSIGNAL, True)
curl.setopt(pycurl.USERAGENT, self.USER_AGENT)
curl.setopt(pycurl.SSL_VERIFYHOST, 0)
curl.setopt(pycurl.SSL_VERIFYPEER, False)
curl.setopt(pycurl.HTTPHEADER, [
"Accept: %s" % HTTP_APP_JSON,
"Content-type: %s" % HTTP_APP_JSON,
])
assert ((self._username is None and self._password is None) ^
(self._username is not None and self._password is not None))
if self._username:
# Setup authentication
curl.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
curl.setopt(pycurl.USERPWD,
str("%s:%s" % (self._username, self._password)))
# Call external configuration function
if self._curl_config_fn:
self._curl_config_fn(curl, self._logger)
return curl
@staticmethod
def _EncodeQuery(query):
"""Encode query values for RAPI URL.
@type query: list of two-tuples
@param query: Query arguments
@rtype: list
@return: Query list with encoded values
"""
result = []
for name, value in query:
if value is None:
result.append((name, ""))
elif isinstance(value, bool):
# Boolean values must be encoded as 0 or 1
result.append((name, int(value)))
elif isinstance(value, (list, tuple, dict)):
raise ValueError("Invalid query data type %r" % type(value).__name__)
else:
result.append((name, value))
return result
def _SendRequest(self, method, path, query, content):
"""Sends an HTTP request.
This constructs a full URL, encodes and decodes HTTP bodies, and
handles invalid responses in a pythonic way.
@type method: string
@param method: HTTP method to use
@type path: string
@param path: HTTP URL path
@type query: list of two-tuples
@param query: query arguments to pass to urllib.urlencode
@type content: str or None
@param content: HTTP body content
@rtype: str
@return: JSON-Decoded response
@raises CertificateError: If an invalid SSL certificate is found
@raises GanetiApiError: If an invalid response is returned
"""
assert path.startswith("/")
curl = self._CreateCurl()
if content is not None:
encoded_content = self._json_encoder.encode(content)
else:
encoded_content = ""
# Build URL
urlparts = [self._base_url, path]
if query:
urlparts.append("?")
urlparts.append(urllib.urlencode(self._EncodeQuery(query)))
url = "".join(urlparts)
self._logger.debug("Sending request %s %s (content=%r)",
method, url, encoded_content)
# Buffer for response
encoded_resp_body = StringIO()
# Configure cURL
curl.setopt(pycurl.CUSTOMREQUEST, str(method))
curl.setopt(pycurl.URL, str(url))
curl.setopt(pycurl.POSTFIELDS, str(encoded_content))
curl.setopt(pycurl.WRITEFUNCTION, encoded_resp_body.write)
try:
# Send request and wait for response
try:
curl.perform()
except pycurl.error, err:
if err.args[0] in _CURL_SSL_CERT_ERRORS:
raise CertificateError("SSL certificate error %s" % err,
code=err.args[0])
raise GanetiApiError(str(err), code=err.args[0])
finally:
# Reset settings to not keep references to large objects in memory
# between requests
curl.setopt(pycurl.POSTFIELDS, "")
curl.setopt(pycurl.WRITEFUNCTION, lambda _: None)
# Get HTTP response code
http_code = curl.getinfo(pycurl.RESPONSE_CODE)
# Was anything written to the response buffer?
if encoded_resp_body.tell():
response_content = simplejson.loads(encoded_resp_body.getvalue())
else:
response_content = None
if http_code != HTTP_OK:
if isinstance(response_content, dict):
msg = ("%s %s: %s" %
(response_content["code"],
response_content["message"],
response_content["explain"]))
else:
msg = str(response_content)
raise GanetiApiError(msg, code=http_code)
return response_content
def GetVersion(self):
"""Gets the Remote API version running on the cluster.
@rtype: int
@return: Ganeti Remote API version
"""
return self._SendRequest(HTTP_GET, "/version", None, None)
def GetFeatures(self):
"""Gets the list of optional features supported by RAPI server.
@rtype: list
@return: List of optional features
"""
try:
return self._SendRequest(HTTP_GET, "/%s/features" % GANETI_RAPI_VERSION,
None, None)
except GanetiApiError, err:
# Older RAPI servers don't support this resource
if err.code == HTTP_NOT_FOUND:
return []
raise
def GetOperatingSystems(self, reason=None):
"""Gets the Operating Systems running in the Ganeti cluster.
@rtype: list of str
@return: operating systems
@type reason: string
@param reason: the reason for executing this operation
"""
query = []
_AppendReason(query, reason)
return self._SendRequest(HTTP_GET, "/%s/os" % GANETI_RAPI_VERSION,
query, None)
def GetInfo(self, reason=None):
"""Gets info about the cluster.
@type reason: string
@param reason: the reason for executing this operation
@rtype: dict
@return: information about the cluster
"""
query = []
_AppendReason(query, reason)
return self._SendRequest(HTTP_GET, "/%s/info" % GANETI_RAPI_VERSION,
query, None)
def RedistributeConfig(self, reason=None):
"""Tells the cluster to redistribute its configuration files.
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = []
_AppendReason(query, reason)
return self._SendRequest(HTTP_PUT,
"/%s/redistribute-config" % GANETI_RAPI_VERSION,
query, None)
def ModifyCluster(self, reason=None, **kwargs):
"""Modifies cluster parameters.
More details for parameters can be found in the RAPI documentation.
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = []
_AppendReason(query, reason)
body = kwargs
return self._SendRequest(HTTP_PUT,
"/%s/modify" % GANETI_RAPI_VERSION, query, body)
def GetClusterTags(self, reason=None):
"""Gets the cluster tags.
@type reason: string
@param reason: the reason for executing this operation
@rtype: list of str
@return: cluster tags
"""
query = []
_AppendReason(query, reason)
return self._SendRequest(HTTP_GET, "/%s/tags" % GANETI_RAPI_VERSION,
query, None)
def AddClusterTags(self, tags, dry_run=False, reason=None):
"""Adds tags to the cluster.
@type tags: list of str
@param tags: tags to add to the cluster
@type dry_run: bool
@param dry_run: whether to perform a dry run
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = [("tag", t) for t in tags]
_AppendDryRunIf(query, dry_run)
_AppendReason(query, reason)
return self._SendRequest(HTTP_PUT, "/%s/tags" % GANETI_RAPI_VERSION,
query, None)
def DeleteClusterTags(self, tags, dry_run=False, reason=None):
"""Deletes tags from the cluster.
@type tags: list of str
@param tags: tags to delete
@type dry_run: bool
@param dry_run: whether to perform a dry run
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = [("tag", t) for t in tags]
_AppendDryRunIf(query, dry_run)
_AppendReason(query, reason)
return self._SendRequest(HTTP_DELETE, "/%s/tags" % GANETI_RAPI_VERSION,
query, None)
def GetInstances(self, bulk=False, reason=None):
"""Gets information about instances on the cluster.
@type bulk: bool
@param bulk: whether to return all information about all instances
@type reason: string
@param reason: the reason for executing this operation
@rtype: list of dict or list of str
@return: if bulk is True, info about the instances, else a list of instances
"""
query = []
_AppendIf(query, bulk, ("bulk", 1))
_AppendReason(query, reason)
instances = self._SendRequest(HTTP_GET,
"/%s/instances" % GANETI_RAPI_VERSION,
query, None)
if bulk:
return instances
else:
return [i["id"] for i in instances]
def GetInstance(self, instance, reason=None):
"""Gets information about an instance.
@type instance: str
@param instance: instance whose info to return
@type reason: string
@param reason: the reason for executing this operation
@rtype: dict
@return: info about the instance
"""
query = []
_AppendReason(query, reason)
return self._SendRequest(HTTP_GET,
("/%s/instances/%s" %
(GANETI_RAPI_VERSION, instance)), query, None)
def GetInstanceInfo(self, instance, static=None, reason=None):
"""Gets information about an instance.
@type instance: string
@param instance: Instance name
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: Job ID
"""
query = []
if static is not None:
query.append(("static", static))
_AppendReason(query, reason)
return self._SendRequest(HTTP_GET,
("/%s/instances/%s/info" %
(GANETI_RAPI_VERSION, instance)), query, None)
@staticmethod
def _UpdateWithKwargs(base, **kwargs):
"""Updates the base with params from kwargs.
@param base: The base dict, filled with required fields
@note: This is an inplace update of base
"""
conflicts = set(kwargs.iterkeys()) & set(base.iterkeys())
if conflicts:
raise GanetiApiError("Required fields can not be specified as"
" keywords: %s" % ", ".join(conflicts))
base.update((key, value) for key, value in kwargs.iteritems()
if key != "dry_run")
def InstanceAllocation(self, mode, name, disk_template, disks, nics,
**kwargs):
"""Generates an instance allocation as used by multiallocate.
More details for parameters can be found in the RAPI documentation.
It is the same as used by CreateInstance.
@type mode: string
@param mode: Instance creation mode
@type name: string
@param name: Hostname of the instance to create
@type disk_template: string
@param disk_template: Disk template for instance (e.g. plain, diskless,
file, or drbd)
@type disks: list of dicts
@param disks: List of disk definitions
@type nics: list of dicts
@param nics: List of NIC definitions
@return: A dict with the generated entry
"""
# All required fields for request data version 1
alloc = {
"mode": mode,
"name": name,
"disk_template": disk_template,
"disks": disks,
"nics": nics,
}
self._UpdateWithKwargs(alloc, **kwargs)
return alloc
def InstancesMultiAlloc(self, instances, reason=None, **kwargs):
"""Tries to allocate multiple instances.
More details for parameters can be found in the RAPI documentation.
@param instances: A list of L{InstanceAllocation} results
"""
query = []
body = {
"instances": instances,
}
self._UpdateWithKwargs(body, **kwargs)
_AppendDryRunIf(query, kwargs.get("dry_run"))
_AppendReason(query, reason)
return self._SendRequest(HTTP_POST,
"/%s/instances-multi-alloc" % GANETI_RAPI_VERSION,
query, body)
def CreateInstance(self, mode, name, disk_template, disks, nics,
reason=None, **kwargs):
"""Creates a new instance.
More details for parameters can be found in the RAPI documentation.
@type mode: string
@param mode: Instance creation mode
@type name: string
@param name: Hostname of the instance to create
@type disk_template: string
@param disk_template: Disk template for instance (e.g. plain, diskless,
file, or drbd)
@type disks: list of dicts
@param disks: List of disk definitions
@type nics: list of dicts
@param nics: List of NIC definitions
@type dry_run: bool
@keyword dry_run: whether to perform a dry run
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = []
_AppendDryRunIf(query, kwargs.get("dry_run"))
_AppendReason(query, reason)
if _INST_CREATE_REQV1 in self.GetFeatures():
body = self.InstanceAllocation(mode, name, disk_template, disks, nics,
**kwargs)
body[_REQ_DATA_VERSION_FIELD] = 1
else:
raise GanetiApiError("Server does not support new-style (version 1)"
" instance creation requests")
return self._SendRequest(HTTP_POST, "/%s/instances" % GANETI_RAPI_VERSION,
query, body)
def DeleteInstance(self, instance, dry_run=False, reason=None, **kwargs):
"""Deletes an instance.
@type instance: str
@param instance: the instance to delete
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = []
body = kwargs
_AppendDryRunIf(query, dry_run)
_AppendReason(query, reason)
return self._SendRequest(HTTP_DELETE,
("/%s/instances/%s" %
(GANETI_RAPI_VERSION, instance)), query, body)
def ModifyInstance(self, instance, reason=None, **kwargs):
"""Modifies an instance.
More details for parameters can be found in the RAPI documentation.
@type instance: string
@param instance: Instance name
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
body = kwargs
query = []
_AppendReason(query, reason)
return self._SendRequest(HTTP_PUT,
("/%s/instances/%s/modify" %
(GANETI_RAPI_VERSION, instance)), query, body)
def ActivateInstanceDisks(self, instance, ignore_size=None, reason=None):
"""Activates an instance's disks.
@type instance: string
@param instance: Instance name
@type ignore_size: bool
@param ignore_size: Whether to ignore recorded size
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = []
_AppendIf(query, ignore_size, ("ignore_size", 1))
_AppendReason(query, reason)
return self._SendRequest(HTTP_PUT,
("/%s/instances/%s/activate-disks" %
(GANETI_RAPI_VERSION, instance)), query, None)
def DeactivateInstanceDisks(self, instance, reason=None, force=False):
"""Deactivates an instance's disks.
@type instance: string
@param instance: Instance name
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = []
_AppendForceIf(query, force)
_AppendReason(query, reason)
return self._SendRequest(HTTP_PUT,
("/%s/instances/%s/deactivate-disks" %
(GANETI_RAPI_VERSION, instance)), query, None)
def RecreateInstanceDisks(self, instance, disks=None, nodes=None,
reason=None, iallocator=None):
"""Recreate an instance's disks.
@type instance: string
@param instance: Instance name
@type disks: list of int
@param disks: List of disk indexes
@type nodes: list of string
@param nodes: New instance nodes, if relocation is desired
@type reason: string
@param reason: the reason for executing this operation
@type iallocator: str or None
@param iallocator: instance allocator plugin to use
@rtype: string
@return: job id
"""
body = {}
_SetItemIf(body, disks is not None, "disks", disks)
_SetItemIf(body, nodes is not None, "nodes", nodes)
_SetItemIf(body, iallocator is not None, "iallocator", iallocator)
query = []
_AppendReason(query, reason)
return self._SendRequest(HTTP_POST,
("/%s/instances/%s/recreate-disks" %
(GANETI_RAPI_VERSION, instance)), query, body)
def GrowInstanceDisk(self, instance, disk, amount, wait_for_sync=None,
reason=None):
"""Grows a disk of an instance.
More details for parameters can be found in the RAPI documentation.
@type instance: string
@param instance: Instance name
@type disk: integer
@param disk: Disk index
@type amount: integer
@param amount: Grow disk by this amount (MiB)
@type wait_for_sync: bool
@param wait_for_sync: Wait for disk to synchronize
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
body = {
"amount": amount,
}
_SetItemIf(body, wait_for_sync is not None, "wait_for_sync", wait_for_sync)
query = []
_AppendReason(query, reason)
return self._SendRequest(HTTP_POST,
("/%s/instances/%s/disk/%s/grow" %
(GANETI_RAPI_VERSION, instance, disk)),
query, body)
def GetInstanceTags(self, instance, reason=None):
"""Gets tags for an instance.
@type instance: str
@param instance: instance whose tags to return
@type reason: string
@param reason: the reason for executing this operation
@rtype: list of str
@return: tags for the instance
"""
query = []
_AppendReason(query, reason)
return self._SendRequest(HTTP_GET,
("/%s/instances/%s/tags" %
(GANETI_RAPI_VERSION, instance)), query, None)
def AddInstanceTags(self, instance, tags, dry_run=False, reason=None):
"""Adds tags to an instance.
@type instance: str
@param instance: instance to add tags to
@type tags: list of str
@param tags: tags to add to the instance
@type dry_run: bool
@param dry_run: whether to perform a dry run
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = [("tag", t) for t in tags]
_AppendDryRunIf(query, dry_run)
_AppendReason(query, reason)
return self._SendRequest(HTTP_PUT,
("/%s/instances/%s/tags" %
(GANETI_RAPI_VERSION, instance)), query, None)
def DeleteInstanceTags(self, instance, tags, dry_run=False, reason=None):
"""Deletes tags from an instance.
@type instance: str
@param instance: instance to delete tags from
@type tags: list of str
@param tags: tags to delete
@type dry_run: bool
@param dry_run: whether to perform a dry run
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = [("tag", t) for t in tags]
_AppendDryRunIf(query, dry_run)
_AppendReason(query, reason)
return self._SendRequest(HTTP_DELETE,
("/%s/instances/%s/tags" %
(GANETI_RAPI_VERSION, instance)), query, None)
def RebootInstance(self, instance, reboot_type=None, ignore_secondaries=None,
dry_run=False, reason=None, **kwargs):
"""Reboots an instance.
@type instance: str
@param instance: instance to reboot
@type reboot_type: str
@param reboot_type: one of: hard, soft, full
@type ignore_secondaries: bool
@param ignore_secondaries: if True, ignores errors for the secondary node
while re-assembling disks (in hard-reboot mode only)
@type dry_run: bool
@param dry_run: whether to perform a dry run
@type reason: string
@param reason: the reason for the reboot
@rtype: string
@return: job id
"""
query = []
body = kwargs
_AppendDryRunIf(query, dry_run)
_AppendIf(query, reboot_type, ("type", reboot_type))
_AppendIf(query, ignore_secondaries is not None,
("ignore_secondaries", ignore_secondaries))
_AppendReason(query, reason)
return self._SendRequest(HTTP_POST,
("/%s/instances/%s/reboot" %
(GANETI_RAPI_VERSION, instance)), query, body)
def ShutdownInstance(self, instance, dry_run=False, no_remember=False,
reason=None, **kwargs):
"""Shuts down an instance.
@type instance: str
@param instance: the instance to shut down
@type dry_run: bool
@param dry_run: whether to perform a dry run
@type no_remember: bool
@param no_remember: if true, will not record the state change
@type reason: string
@param reason: the reason for the shutdown
@rtype: string
@return: job id
"""
query = []
body = kwargs
_AppendDryRunIf(query, dry_run)
_AppendIf(query, no_remember, ("no_remember", 1))
_AppendReason(query, reason)
return self._SendRequest(HTTP_PUT,
("/%s/instances/%s/shutdown" %
(GANETI_RAPI_VERSION, instance)), query, body)
def StartupInstance(self, instance, dry_run=False, no_remember=False,
reason=None):
"""Starts up an instance.
@type instance: str
@param instance: the instance to start up
@type dry_run: bool
@param dry_run: whether to perform a dry run
@type no_remember: bool
@param no_remember: if true, will not record the state change
@type reason: string
@param reason: the reason for the startup
@rtype: string
@return: job id
"""
query = []
_AppendDryRunIf(query, dry_run)
_AppendIf(query, no_remember, ("no_remember", 1))
_AppendReason(query, reason)
return self._SendRequest(HTTP_PUT,
("/%s/instances/%s/startup" %
(GANETI_RAPI_VERSION, instance)), query, None)
def ReinstallInstance(self, instance, os=None, no_startup=False,
osparams=None, reason=None):
"""Reinstalls an instance.
@type instance: str
@param instance: The instance to reinstall
@type os: str or None
@param os: The operating system to reinstall. If None, the instance's
current operating system will be installed again
@type no_startup: bool
@param no_startup: Whether to start the instance automatically
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = []
_AppendReason(query, reason)
if _INST_REINSTALL_REQV1 in self.GetFeatures():
body = {
"start": not no_startup,
}
_SetItemIf(body, os is not None, "os", os)
_SetItemIf(body, osparams is not None, "osparams", osparams)
return self._SendRequest(HTTP_POST,
("/%s/instances/%s/reinstall" %
(GANETI_RAPI_VERSION, instance)), query, body)
# Use old request format
if osparams:
raise GanetiApiError("Server does not support specifying OS parameters"
" for instance reinstallation")
query = []
_AppendIf(query, os, ("os", os))
_AppendIf(query, no_startup, ("nostartup", 1))
return self._SendRequest(HTTP_POST,
("/%s/instances/%s/reinstall" %
(GANETI_RAPI_VERSION, instance)), query, None)
def ReplaceInstanceDisks(self, instance, disks=None, mode=REPLACE_DISK_AUTO,
remote_node=None, iallocator=None, reason=None,
early_release=None):
"""Replaces disks on an instance.
@type instance: str
@param instance: instance whose disks to replace
@type disks: list of ints
@param disks: Indexes of disks to replace
@type mode: str
@param mode: replacement mode to use (defaults to replace_auto)
@type remote_node: str or None
@param remote_node: new secondary node to use (for use with
replace_new_secondary mode)
@type iallocator: str or None
@param iallocator: instance allocator plugin to use (for use with
replace_auto mode)
@type reason: string
@param reason: the reason for executing this operation
@type early_release: bool
@param early_release: whether to release locks as soon as possible
@rtype: string
@return: job id
"""
query = [
("mode", mode),
]
# TODO: Convert to body parameters
if disks is not None:
_AppendIf(query, True,
("disks", ",".join(str(idx) for idx in disks)))
_AppendIf(query, remote_node is not None, ("remote_node", remote_node))
_AppendIf(query, iallocator is not None, ("iallocator", iallocator))
_AppendReason(query, reason)
_AppendIf(query, early_release is not None,
("early_release", early_release))
return self._SendRequest(HTTP_POST,
("/%s/instances/%s/replace-disks" %
(GANETI_RAPI_VERSION, instance)), query, None)
def PrepareExport(self, instance, mode, reason=None):
"""Prepares an instance for an export.
@type instance: string
@param instance: Instance name
@type mode: string
@param mode: Export mode
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: Job ID
"""
query = [("mode", mode)]
_AppendReason(query, reason)
return self._SendRequest(HTTP_PUT,
("/%s/instances/%s/prepare-export" %
(GANETI_RAPI_VERSION, instance)), query, None)
def ExportInstance(self, instance, mode, destination, shutdown=None,
remove_instance=None, x509_key_name=None,
destination_x509_ca=None, compress=None, reason=None):
"""Exports an instance.
@type instance: string
@param instance: Instance name
@type mode: string
@param mode: Export mode
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: Job ID
"""
body = {
"destination": destination,
"mode": mode,
}
_SetItemIf(body, shutdown is not None, "shutdown", shutdown)
_SetItemIf(body, remove_instance is not None,
"remove_instance", remove_instance)
_SetItemIf(body, x509_key_name is not None, "x509_key_name", x509_key_name)
_SetItemIf(body, destination_x509_ca is not None,
"destination_x509_ca", destination_x509_ca)
_SetItemIf(body, compress is not None, "compress", compress)
query = []
_AppendReason(query, reason)
return self._SendRequest(HTTP_PUT,
("/%s/instances/%s/export" %
(GANETI_RAPI_VERSION, instance)), query, body)
def MigrateInstance(self, instance, mode=None, cleanup=None,
target_node=None, reason=None):
"""Migrates an instance.
@type instance: string
@param instance: Instance name
@type mode: string
@param mode: Migration mode
@type cleanup: bool
@param cleanup: Whether to clean up a previously failed migration
@type target_node: string
@param target_node: Target Node for externally mirrored instances
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
body = {}
_SetItemIf(body, mode is not None, "mode", mode)
_SetItemIf(body, cleanup is not None, "cleanup", cleanup)
_SetItemIf(body, target_node is not None, "target_node", target_node)
query = []
_AppendReason(query, reason)
return self._SendRequest(HTTP_PUT,
("/%s/instances/%s/migrate" %
(GANETI_RAPI_VERSION, instance)), query, body)
def FailoverInstance(self, instance, iallocator=None,
ignore_consistency=None, target_node=None, reason=None):
"""Does a failover of an instance.
@type instance: string
@param instance: Instance name
@type iallocator: string
@param iallocator: Iallocator for deciding the target node for
shared-storage instances
@type ignore_consistency: bool
@param ignore_consistency: Whether to ignore disk consistency
@type target_node: string
@param target_node: Target node for shared-storage instances
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
body = {}
_SetItemIf(body, iallocator is not None, "iallocator", iallocator)
_SetItemIf(body, ignore_consistency is not None,
"ignore_consistency", ignore_consistency)
_SetItemIf(body, target_node is not None, "target_node", target_node)
query = []
_AppendReason(query, reason)
return self._SendRequest(HTTP_PUT,
("/%s/instances/%s/failover" %
(GANETI_RAPI_VERSION, instance)), query, body)
def RenameInstance(self, instance, new_name, ip_check=None, name_check=None,
reason=None):
"""Changes the name of an instance.
@type instance: string
@param instance: Instance name
@type new_name: string
@param new_name: New instance name
@type ip_check: bool
@param ip_check: Whether to ensure instance's IP address is inactive
@type name_check: bool
@param name_check: Whether to ensure instance's name is resolvable
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
body = {
"new_name": new_name,
}
_SetItemIf(body, ip_check is not None, "ip_check", ip_check)
_SetItemIf(body, name_check is not None, "name_check", name_check)
query = []
_AppendReason(query, reason)
return self._SendRequest(HTTP_PUT,
("/%s/instances/%s/rename" %
(GANETI_RAPI_VERSION, instance)), query, body)
def GetInstanceConsole(self, instance, reason=None):
"""Request information for connecting to instance's console.
@type instance: string
@param instance: Instance name
@type reason: string
@param reason: the reason for executing this operation
@rtype: dict
@return: dictionary containing information about instance's console
"""
query = []
_AppendReason(query, reason)
return self._SendRequest(HTTP_GET,
("/%s/instances/%s/console" %
(GANETI_RAPI_VERSION, instance)), query, None)
def GetJobs(self, bulk=False):
"""Gets all jobs for the cluster.
@type bulk: bool
@param bulk: Whether to return detailed information about jobs.
@rtype: list of int
@return: List of job ids for the cluster or list of dicts with detailed
information about the jobs if bulk parameter was true.
"""
query = []
_AppendIf(query, bulk, ("bulk", 1))
if bulk:
return self._SendRequest(HTTP_GET,
"/%s/jobs" % GANETI_RAPI_VERSION,
query, None)
else:
return [int(j["id"])
for j in self._SendRequest(HTTP_GET,
"/%s/jobs" % GANETI_RAPI_VERSION,
None, None)]
def GetJobStatus(self, job_id):
"""Gets the status of a job.
@type job_id: string
@param job_id: job id whose status to query
@rtype: dict
@return: job status
"""
return self._SendRequest(HTTP_GET,
"/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
None, None)
def WaitForJobCompletion(self, job_id, period=5, retries=-1):
"""Polls cluster for job status until completion.
Completion is defined as any of the following states listed in
L{JOB_STATUS_FINALIZED}.
@type job_id: string
@param job_id: job id to watch
@type period: int
@param period: how often to poll for status (optional, default 5s)
@type retries: int
@param retries: how many time to poll before giving up
(optional, default -1 means unlimited)
@rtype: bool
@return: C{True} if job succeeded or C{False} if failed/status timeout
@deprecated: It is recommended to use L{WaitForJobChange} wherever
possible; L{WaitForJobChange} returns immediately after a job changed and
does not use polling
"""
while retries != 0:
job_result = self.GetJobStatus(job_id)
if job_result and job_result["status"] == JOB_STATUS_SUCCESS:
return True
elif not job_result or job_result["status"] in JOB_STATUS_FINALIZED:
return False
if period:
time.sleep(period)
if retries > 0:
retries -= 1
return False
def WaitForJobChange(self, job_id, fields, prev_job_info, prev_log_serial):
"""Waits for job changes.
@type job_id: string
@param job_id: Job ID for which to wait
@return: C{None} if no changes have been detected and a dict with two keys,
C{job_info} and C{log_entries} otherwise.
@rtype: dict
"""
body = {
"fields": fields,
"previous_job_info": prev_job_info,
"previous_log_serial": prev_log_serial,
}
return self._SendRequest(HTTP_GET,
"/%s/jobs/%s/wait" % (GANETI_RAPI_VERSION, job_id),
None, body)
def CancelJob(self, job_id, dry_run=False):
"""Cancels a job.
@type job_id: string
@param job_id: id of the job to delete
@type dry_run: bool
@param dry_run: whether to perform a dry run
@rtype: tuple
@return: tuple containing the result, and a message (bool, string)
"""
query = []
_AppendDryRunIf(query, dry_run)
return self._SendRequest(HTTP_DELETE,
"/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
query, None)
def GetNodes(self, bulk=False, reason=None):
"""Gets all nodes in the cluster.
@type bulk: bool
@param bulk: whether to return all information about all instances
@type reason: string
@param reason: the reason for executing this operation
@rtype: list of dict or str
@return: if bulk is true, info about nodes in the cluster,
else list of nodes in the cluster
"""
query = []
_AppendIf(query, bulk, ("bulk", 1))
_AppendReason(query, reason)
nodes = self._SendRequest(HTTP_GET, "/%s/nodes" % GANETI_RAPI_VERSION,
query, None)
if bulk:
return nodes
else:
return [n["id"] for n in nodes]
def GetNode(self, node, reason=None):
"""Gets information about a node.
@type node: str
@param node: node whose info to return
@type reason: string
@param reason: the reason for executing this operation
@rtype: dict
@return: info about the node
"""
query = []
_AppendReason(query, reason)
return self._SendRequest(HTTP_GET,
"/%s/nodes/%s" % (GANETI_RAPI_VERSION, node),
query, None)
def EvacuateNode(self, node, iallocator=None, remote_node=None,
dry_run=False, early_release=None,
mode=None, accept_old=False, reason=None):
"""Evacuates instances from a Ganeti node.
@type node: str
@param node: node to evacuate
@type iallocator: str or None
@param iallocator: instance allocator to use
@type remote_node: str
@param remote_node: node to evaucate to
@type dry_run: bool
@param dry_run: whether to perform a dry run
@type early_release: bool
@param early_release: whether to enable parallelization
@type mode: string
@param mode: Node evacuation mode
@type accept_old: bool
@param accept_old: Whether caller is ready to accept old-style (pre-2.5)
results
@type reason: string
@param reason: the reason for executing this operation
@rtype: string, or a list for pre-2.5 results
@return: Job ID or, if C{accept_old} is set and server is pre-2.5,
list of (job ID, instance name, new secondary node); if dry_run was
specified, then the actual move jobs were not submitted and the job IDs
will be C{None}
@raises GanetiApiError: if an iallocator and remote_node are both
specified
"""
if iallocator and remote_node:
raise GanetiApiError("Only one of iallocator or remote_node can be used")
query = []
_AppendDryRunIf(query, dry_run)
_AppendReason(query, reason)
if _NODE_EVAC_RES1 in self.GetFeatures():
# Server supports body parameters
body = {}
_SetItemIf(body, iallocator is not None, "iallocator", iallocator)
_SetItemIf(body, remote_node is not None, "remote_node", remote_node)
_SetItemIf(body, early_release is not None,
"early_release", early_release)
_SetItemIf(body, mode is not None, "mode", mode)
else:
# Pre-2.5 request format
body = None
if not accept_old:
raise GanetiApiError("Server is version 2.4 or earlier and caller does"
" not accept old-style results (parameter"
" accept_old)")
# Pre-2.5 servers can only evacuate secondaries
if mode is not None and mode != NODE_EVAC_SEC:
raise GanetiApiError("Server can only evacuate secondary instances")
_AppendIf(query, iallocator, ("iallocator", iallocator))
_AppendIf(query, remote_node, ("remote_node", remote_node))
_AppendIf(query, early_release, ("early_release", 1))
return self._SendRequest(HTTP_POST,
("/%s/nodes/%s/evacuate" %
(GANETI_RAPI_VERSION, node)), query, body)
def MigrateNode(self, node, mode=None, dry_run=False, iallocator=None,
target_node=None, reason=None):
"""Migrates all primary instances from a node.
@type node: str
@param node: node to migrate
@type mode: string
@param mode: if passed, it will overwrite the live migration type,
otherwise the hypervisor default will be used
@type dry_run: bool
@param dry_run: whether to perform a dry run
@type iallocator: string
@param iallocator: instance allocator to use
@type target_node: string
@param target_node: Target node for shared-storage instances
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = []
_AppendDryRunIf(query, dry_run)
_AppendReason(query, reason)
if _NODE_MIGRATE_REQV1 in self.GetFeatures():
body = {}
_SetItemIf(body, mode is not None, "mode", mode)
_SetItemIf(body, iallocator is not None, "iallocator", iallocator)
_SetItemIf(body, target_node is not None, "target_node", target_node)
assert len(query) <= 1
return self._SendRequest(HTTP_POST,
("/%s/nodes/%s/migrate" %
(GANETI_RAPI_VERSION, node)), query, body)
else:
# Use old request format
if target_node is not None:
raise GanetiApiError("Server does not support specifying target node"
" for node migration")
_AppendIf(query, mode is not None, ("mode", mode))
return self._SendRequest(HTTP_POST,
("/%s/nodes/%s/migrate" %
(GANETI_RAPI_VERSION, node)), query, None)
def GetNodeRole(self, node, reason=None):
"""Gets the current role for a node.
@type node: str
@param node: node whose role to return
@type reason: string
@param reason: the reason for executing this operation
@rtype: str
@return: the current role for a node
"""
query = []
_AppendReason(query, reason)
return self._SendRequest(HTTP_GET,
("/%s/nodes/%s/role" %
(GANETI_RAPI_VERSION, node)), query, None)
def SetNodeRole(self, node, role, force=False, auto_promote=None,
reason=None):
"""Sets the role for a node.
@type node: str
@param node: the node whose role to set
@type role: str
@param role: the role to set for the node
@type force: bool
@param force: whether to force the role change
@type auto_promote: bool
@param auto_promote: Whether node(s) should be promoted to master candidate
if necessary
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = []
_AppendForceIf(query, force)
_AppendIf(query, auto_promote is not None, ("auto-promote", auto_promote))
_AppendReason(query, reason)
return self._SendRequest(HTTP_PUT,
("/%s/nodes/%s/role" %
(GANETI_RAPI_VERSION, node)), query, role)
def PowercycleNode(self, node, force=False, reason=None):
"""Powercycles a node.
@type node: string
@param node: Node name
@type force: bool
@param force: Whether to force the operation
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = []
_AppendForceIf(query, force)
_AppendReason(query, reason)
return self._SendRequest(HTTP_POST,
("/%s/nodes/%s/powercycle" %
(GANETI_RAPI_VERSION, node)), query, None)
def ModifyNode(self, node, reason=None, **kwargs):
"""Modifies a node.
More details for parameters can be found in the RAPI documentation.
@type node: string
@param node: Node name
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = []
_AppendReason(query, reason)
return self._SendRequest(HTTP_POST,
("/%s/nodes/%s/modify" %
(GANETI_RAPI_VERSION, node)), query, kwargs)
def GetNodeStorageUnits(self, node, storage_type, output_fields, reason=None):
"""Gets the storage units for a node.
@type node: str
@param node: the node whose storage units to return
@type storage_type: str
@param storage_type: storage type whose units to return
@type output_fields: str
@param output_fields: storage type fields to return
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id where results can be retrieved
"""
query = [
("storage_type", storage_type),
("output_fields", output_fields),
]
_AppendReason(query, reason)
return self._SendRequest(HTTP_GET,
("/%s/nodes/%s/storage" %
(GANETI_RAPI_VERSION, node)), query, None)
def ModifyNodeStorageUnits(self, node, storage_type, name, allocatable=None,
reason=None):
"""Modifies parameters of storage units on the node.
@type node: str
@param node: node whose storage units to modify
@type storage_type: str
@param storage_type: storage type whose units to modify
@type name: str
@param name: name of the storage unit
@type allocatable: bool or None
@param allocatable: Whether to set the "allocatable" flag on the storage
unit (None=no modification, True=set, False=unset)
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = [
("storage_type", storage_type),
("name", name),
]
_AppendIf(query, allocatable is not None, ("allocatable", allocatable))
_AppendReason(query, reason)
return self._SendRequest(HTTP_PUT,
("/%s/nodes/%s/storage/modify" %
(GANETI_RAPI_VERSION, node)), query, None)
def RepairNodeStorageUnits(self, node, storage_type, name, reason=None):
"""Repairs a storage unit on the node.
@type node: str
@param node: node whose storage units to repair
@type storage_type: str
@param storage_type: storage type to repair
@type name: str
@param name: name of the storage unit to repair
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = [
("storage_type", storage_type),
("name", name),
]
_AppendReason(query, reason)
return self._SendRequest(HTTP_PUT,
("/%s/nodes/%s/storage/repair" %
(GANETI_RAPI_VERSION, node)), query, None)
def GetNodeTags(self, node, reason=None):
"""Gets the tags for a node.
@type node: str
@param node: node whose tags to return
@type reason: string
@param reason: the reason for executing this operation
@rtype: list of str
@return: tags for the node
"""
query = []
_AppendReason(query, reason)
return self._SendRequest(HTTP_GET,
("/%s/nodes/%s/tags" %
(GANETI_RAPI_VERSION, node)), query, None)
def AddNodeTags(self, node, tags, dry_run=False, reason=None):
"""Adds tags to a node.
@type node: str
@param node: node to add tags to
@type tags: list of str
@param tags: tags to add to the node
@type dry_run: bool
@param dry_run: whether to perform a dry run
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = [("tag", t) for t in tags]
_AppendDryRunIf(query, dry_run)
_AppendReason(query, reason)
return self._SendRequest(HTTP_PUT,
("/%s/nodes/%s/tags" %
(GANETI_RAPI_VERSION, node)), query, tags)
def DeleteNodeTags(self, node, tags, dry_run=False, reason=None):
"""Delete tags from a node.
@type node: str
@param node: node to remove tags from
@type tags: list of str
@param tags: tags to remove from the node
@type dry_run: bool
@param dry_run: whether to perform a dry run
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = [("tag", t) for t in tags]
_AppendDryRunIf(query, dry_run)
_AppendReason(query, reason)
return self._SendRequest(HTTP_DELETE,
("/%s/nodes/%s/tags" %
(GANETI_RAPI_VERSION, node)), query, None)
def GetNetworks(self, bulk=False, reason=None):
"""Gets all networks in the cluster.
@type bulk: bool
@param bulk: whether to return all information about the networks
@rtype: list of dict or str
@return: if bulk is true, a list of dictionaries with info about all
networks in the cluster, else a list of names of those networks
"""
query = []
_AppendIf(query, bulk, ("bulk", 1))
_AppendReason(query, reason)
networks = self._SendRequest(HTTP_GET, "/%s/networks" % GANETI_RAPI_VERSION,
query, None)
if bulk:
return networks
else:
return [n["name"] for n in networks]
def GetNetwork(self, network, reason=None):
"""Gets information about a network.
@type network: str
@param network: name of the network whose info to return
@type reason: string
@param reason: the reason for executing this operation
@rtype: dict
@return: info about the network
"""
query = []
_AppendReason(query, reason)
return self._SendRequest(HTTP_GET,
"/%s/networks/%s" % (GANETI_RAPI_VERSION, network),
query, None)
def CreateNetwork(self, network_name, network, gateway=None, network6=None,
gateway6=None, mac_prefix=None,
add_reserved_ips=None, tags=None, dry_run=False,
reason=None):
"""Creates a new network.
@type network_name: str
@param network_name: the name of network to create
@type dry_run: bool
@param dry_run: whether to peform a dry run
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = []
_AppendDryRunIf(query, dry_run)
_AppendReason(query, reason)
if add_reserved_ips:
add_reserved_ips = add_reserved_ips.split(",")
if tags:
tags = tags.split(",")
body = {
"network_name": network_name,
"gateway": gateway,
"network": network,
"gateway6": gateway6,
"network6": network6,
"mac_prefix": mac_prefix,
"add_reserved_ips": add_reserved_ips,
"tags": tags,
}
return self._SendRequest(HTTP_POST, "/%s/networks" % GANETI_RAPI_VERSION,
query, body)
def ConnectNetwork(self, network_name, group_name, mode, link,
vlan="", dry_run=False, reason=None):
"""Connects a Network to a NodeGroup with the given netparams
"""
body = {
"group_name": group_name,
"network_mode": mode,
"network_link": link,
"network_vlan": vlan,
}
query = []
_AppendDryRunIf(query, dry_run)
_AppendReason(query, reason)
return self._SendRequest(HTTP_PUT,
("/%s/networks/%s/connect" %
(GANETI_RAPI_VERSION, network_name)), query, body)
def DisconnectNetwork(self, network_name, group_name, dry_run=False,
reason=None):
"""Connects a Network to a NodeGroup with the given netparams
"""
body = {
"group_name": group_name,
}
query = []
_AppendDryRunIf(query, dry_run)
_AppendReason(query, reason)
return self._SendRequest(HTTP_PUT,
("/%s/networks/%s/disconnect" %
(GANETI_RAPI_VERSION, network_name)), query, body)
def ModifyNetwork(self, network, reason=None, **kwargs):
"""Modifies a network.
More details for parameters can be found in the RAPI documentation.
@type network: string
@param network: Network name
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = []
_AppendReason(query, reason)
return self._SendRequest(HTTP_PUT,
("/%s/networks/%s/modify" %
(GANETI_RAPI_VERSION, network)), None, kwargs)
def DeleteNetwork(self, network, dry_run=False, reason=None):
"""Deletes a network.
@type network: str
@param network: the network to delete
@type dry_run: bool
@param dry_run: whether to peform a dry run
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = []
_AppendDryRunIf(query, dry_run)
_AppendReason(query, reason)
return self._SendRequest(HTTP_DELETE,
("/%s/networks/%s" %
(GANETI_RAPI_VERSION, network)), query, None)
def GetNetworkTags(self, network, reason=None):
"""Gets tags for a network.
@type network: string
@param network: Node group whose tags to return
@type reason: string
@param reason: the reason for executing this operation
@rtype: list of strings
@return: tags for the network
"""
query = []
_AppendReason(query, reason)
return self._SendRequest(HTTP_GET,
("/%s/networks/%s/tags" %
(GANETI_RAPI_VERSION, network)), query, None)
def AddNetworkTags(self, network, tags, dry_run=False, reason=None):
"""Adds tags to a network.
@type network: str
@param network: network to add tags to
@type tags: list of string
@param tags: tags to add to the network
@type dry_run: bool
@param dry_run: whether to perform a dry run
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = [("tag", t) for t in tags]
_AppendDryRunIf(query, dry_run)
_AppendReason(query, reason)
return self._SendRequest(HTTP_PUT,
("/%s/networks/%s/tags" %
(GANETI_RAPI_VERSION, network)), query, None)
def DeleteNetworkTags(self, network, tags, dry_run=False, reason=None):
"""Deletes tags from a network.
@type network: str
@param network: network to delete tags from
@type tags: list of string
@param tags: tags to delete
@type dry_run: bool
@param dry_run: whether to perform a dry run
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = [("tag", t) for t in tags]
_AppendDryRunIf(query, dry_run)
_AppendReason(query, reason)
return self._SendRequest(HTTP_DELETE,
("/%s/networks/%s/tags" %
(GANETI_RAPI_VERSION, network)), query, None)
def GetGroups(self, bulk=False, reason=None):
"""Gets all node groups in the cluster.
@type bulk: bool
@param bulk: whether to return all information about the groups
@type reason: string
@param reason: the reason for executing this operation
@rtype: list of dict or str
@return: if bulk is true, a list of dictionaries with info about all node
groups in the cluster, else a list of names of those node groups
"""
query = []
_AppendIf(query, bulk, ("bulk", 1))
_AppendReason(query, reason)
groups = self._SendRequest(HTTP_GET, "/%s/groups" % GANETI_RAPI_VERSION,
query, None)
if bulk:
return groups
else:
return [g["name"] for g in groups]
def GetGroup(self, group, reason=None):
"""Gets information about a node group.
@type group: str
@param group: name of the node group whose info to return
@type reason: string
@param reason: the reason for executing this operation
@rtype: dict
@return: info about the node group
"""
query = []
_AppendReason(query, reason)
return self._SendRequest(HTTP_GET,
"/%s/groups/%s" % (GANETI_RAPI_VERSION, group),
query, None)
def CreateGroup(self, name, alloc_policy=None, dry_run=False, reason=None):
"""Creates a new node group.
@type name: str
@param name: the name of node group to create
@type alloc_policy: str
@param alloc_policy: the desired allocation policy for the group, if any
@type dry_run: bool
@param dry_run: whether to peform a dry run
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = []
_AppendDryRunIf(query, dry_run)
_AppendReason(query, reason)
body = {
"name": name,
"alloc_policy": alloc_policy,
}
return self._SendRequest(HTTP_POST, "/%s/groups" % GANETI_RAPI_VERSION,
query, body)
def ModifyGroup(self, group, reason=None, **kwargs):
"""Modifies a node group.
More details for parameters can be found in the RAPI documentation.
@type group: string
@param group: Node group name
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = []
_AppendReason(query, reason)
return self._SendRequest(HTTP_PUT,
("/%s/groups/%s/modify" %
(GANETI_RAPI_VERSION, group)), query, kwargs)
def DeleteGroup(self, group, dry_run=False, reason=None):
"""Deletes a node group.
@type group: str
@param group: the node group to delete
@type dry_run: bool
@param dry_run: whether to peform a dry run
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = []
_AppendDryRunIf(query, dry_run)
_AppendReason(query, reason)
return self._SendRequest(HTTP_DELETE,
("/%s/groups/%s" %
(GANETI_RAPI_VERSION, group)), query, None)
def RenameGroup(self, group, new_name, reason=None):
"""Changes the name of a node group.
@type group: string
@param group: Node group name
@type new_name: string
@param new_name: New node group name
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
body = {
"new_name": new_name,
}
query = []
_AppendReason(query, reason)
return self._SendRequest(HTTP_PUT,
("/%s/groups/%s/rename" %
(GANETI_RAPI_VERSION, group)), query, body)
def AssignGroupNodes(self, group, nodes, force=False, dry_run=False,
reason=None):
"""Assigns nodes to a group.
@type group: string
@param group: Node group name
@type nodes: list of strings
@param nodes: List of nodes to assign to the group
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = []
_AppendForceIf(query, force)
_AppendDryRunIf(query, dry_run)
_AppendReason(query, reason)
body = {
"nodes": nodes,
}
return self._SendRequest(HTTP_PUT,
("/%s/groups/%s/assign-nodes" %
(GANETI_RAPI_VERSION, group)), query, body)
def GetGroupTags(self, group, reason=None):
"""Gets tags for a node group.
@type group: string
@param group: Node group whose tags to return
@type reason: string
@param reason: the reason for executing this operation
@rtype: list of strings
@return: tags for the group
"""
query = []
_AppendReason(query, reason)
return self._SendRequest(HTTP_GET,
("/%s/groups/%s/tags" %
(GANETI_RAPI_VERSION, group)), query, None)
def AddGroupTags(self, group, tags, dry_run=False, reason=None):
"""Adds tags to a node group.
@type group: str
@param group: group to add tags to
@type tags: list of string
@param tags: tags to add to the group
@type dry_run: bool
@param dry_run: whether to perform a dry run
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = [("tag", t) for t in tags]
_AppendDryRunIf(query, dry_run)
_AppendReason(query, reason)
return self._SendRequest(HTTP_PUT,
("/%s/groups/%s/tags" %
(GANETI_RAPI_VERSION, group)), query, None)
def DeleteGroupTags(self, group, tags, dry_run=False, reason=None):
"""Deletes tags from a node group.
@type group: str
@param group: group to delete tags from
@type tags: list of string
@param tags: tags to delete
@type dry_run: bool
@param dry_run: whether to perform a dry run
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = [("tag", t) for t in tags]
_AppendDryRunIf(query, dry_run)
_AppendReason(query, reason)
return self._SendRequest(HTTP_DELETE,
("/%s/groups/%s/tags" %
(GANETI_RAPI_VERSION, group)), query, None)
def Query(self, what, fields, qfilter=None, reason=None):
"""Retrieves information about resources.
@type what: string
@param what: Resource name, one of L{constants.QR_VIA_RAPI}
@type fields: list of string
@param fields: Requested fields
@type qfilter: None or list
@param qfilter: Query filter
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = []
_AppendReason(query, reason)
body = {
"fields": fields,
}
_SetItemIf(body, qfilter is not None, "qfilter", qfilter)
# TODO: remove "filter" after 2.7
_SetItemIf(body, qfilter is not None, "filter", qfilter)
return self._SendRequest(HTTP_PUT,
("/%s/query/%s" %
(GANETI_RAPI_VERSION, what)), query, body)
def QueryFields(self, what, fields=None, reason=None):
"""Retrieves available fields for a resource.
@type what: string
@param what: Resource name, one of L{constants.QR_VIA_RAPI}
@type fields: list of string
@param fields: Requested fields
@type reason: string
@param reason: the reason for executing this operation
@rtype: string
@return: job id
"""
query = []
_AppendReason(query, reason)
if fields is not None:
_AppendIf(query, True, ("fields", ",".join(fields)))
return self._SendRequest(HTTP_GET,
("/%s/query/%s/fields" %
(GANETI_RAPI_VERSION, what)), query, None)
def GetFilters(self, bulk=False):
"""Gets all filter rules in the cluster.
@type bulk: bool
@param bulk: whether to return all information about the networks
@rtype: list of dict or str
@return: if bulk is true, a list of dictionaries with info about all
filter rules in the cluster, else a list of UUIDs of those
filters
"""
query = []
_AppendIf(query, bulk, ("bulk", 1))
filters = self._SendRequest(HTTP_GET, "/%s/filters" % GANETI_RAPI_VERSION,
query, None)
if bulk:
return filters
else:
return [f["uuid"] for f in filters]
def GetFilter(self, filter_uuid):
"""Gets information about a filter rule.
@type filter_uuid: str
@param filter_uuid: UUID of the filter whose info to return
@rtype: dict
@return: info about the filter
"""
query = []
return self._SendRequest(HTTP_GET,
"/%s/filters/%s" % (GANETI_RAPI_VERSION,
filter_uuid),
query, None)
def AddFilter(self, priority, predicates, action, reason_trail=None):
"""Adds a filter rule
@type reason_trail: list of (str, str, int) triples
@param reason_trail: the reason trail for executing this operation,
or None
@rtype: string
@return: filter UUID of the added filter
"""
if reason_trail is None:
reason_trail = []
assert isinstance(reason_trail, list)
reason_trail.append(("gnt:client", "", EpochNano(),)) # add client reason
body = {
"priority": priority,
"predicates": predicates,
"action": action,
"reason": reason_trail,
}
query = []
return self._SendRequest(HTTP_POST,
("/%s/filters" % (GANETI_RAPI_VERSION)),
query, body)
def ReplaceFilter(self, uuid, priority, predicates, action,
reason_trail=None):
"""Replaces a filter rule, or creates one if it doesn't already exist
@type reason_trail: list of (str, str, int) triples
@param reason_trail: the reason trail for executing this operation,
or None
@rtype: string
@return: filter UUID of the replaced/added filter
"""
if reason_trail is None:
reason_trail = []
assert isinstance(reason_trail, list)
reason_trail.append(("gnt:client", "", EpochNano(),)) # add client reason
body = {
"priority": priority,
"predicates": predicates,
"action": action,
"reason": reason_trail,
}
query = []
return self._SendRequest(HTTP_PUT,
("/%s/filters/%s" % (GANETI_RAPI_VERSION, uuid)),
query, body)
def DeleteFilter(self, uuid):
"""Deletes a filter rule
@return: None
"""
body = {}
query = []
return self._SendRequest(HTTP_DELETE,
("/%s/filters/%s" % (GANETI_RAPI_VERSION, uuid)),
query, body)
|