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
|
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"path/filepath"
"slices"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/gorilla/mux"
incus "github.com/lxc/incus/v6/client"
"github.com/lxc/incus/v6/internal/filter"
internalInstance "github.com/lxc/incus/v6/internal/instance"
"github.com/lxc/incus/v6/internal/server/auth"
"github.com/lxc/incus/v6/internal/server/certificate"
"github.com/lxc/incus/v6/internal/server/cluster"
clusterConfig "github.com/lxc/incus/v6/internal/server/cluster/config"
clusterRequest "github.com/lxc/incus/v6/internal/server/cluster/request"
"github.com/lxc/incus/v6/internal/server/db"
dbCluster "github.com/lxc/incus/v6/internal/server/db/cluster"
"github.com/lxc/incus/v6/internal/server/db/operationtype"
"github.com/lxc/incus/v6/internal/server/instance"
instanceDrivers "github.com/lxc/incus/v6/internal/server/instance/drivers"
"github.com/lxc/incus/v6/internal/server/lifecycle"
"github.com/lxc/incus/v6/internal/server/node"
"github.com/lxc/incus/v6/internal/server/operations"
"github.com/lxc/incus/v6/internal/server/request"
"github.com/lxc/incus/v6/internal/server/response"
"github.com/lxc/incus/v6/internal/server/state"
localUtil "github.com/lxc/incus/v6/internal/server/util"
internalUtil "github.com/lxc/incus/v6/internal/util"
"github.com/lxc/incus/v6/internal/version"
"github.com/lxc/incus/v6/shared/api"
"github.com/lxc/incus/v6/shared/logger"
"github.com/lxc/incus/v6/shared/osarch"
"github.com/lxc/incus/v6/shared/revert"
localtls "github.com/lxc/incus/v6/shared/tls"
"github.com/lxc/incus/v6/shared/util"
"github.com/lxc/incus/v6/shared/validate"
)
var clusterCmd = APIEndpoint{
Path: "cluster",
Get: APIEndpointAction{Handler: clusterGet, AccessHandler: allowPermission(auth.ObjectTypeServer, auth.EntitlementCanView)},
Put: APIEndpointAction{Handler: clusterPut, AccessHandler: allowPermission(auth.ObjectTypeServer, auth.EntitlementCanEdit)},
}
var clusterNodesCmd = APIEndpoint{
Path: "cluster/members",
Get: APIEndpointAction{Handler: clusterNodesGet, AccessHandler: allowPermission(auth.ObjectTypeServer, auth.EntitlementCanView)},
Post: APIEndpointAction{Handler: clusterNodesPost, AccessHandler: allowPermission(auth.ObjectTypeServer, auth.EntitlementCanEdit)},
}
var clusterNodeCmd = APIEndpoint{
Path: "cluster/members/{name}",
Delete: APIEndpointAction{Handler: clusterNodeDelete, AccessHandler: allowPermission(auth.ObjectTypeServer, auth.EntitlementCanEdit)},
Get: APIEndpointAction{Handler: clusterNodeGet, AccessHandler: allowPermission(auth.ObjectTypeServer, auth.EntitlementCanView)},
Patch: APIEndpointAction{Handler: clusterNodePatch, AccessHandler: allowPermission(auth.ObjectTypeServer, auth.EntitlementCanEdit)},
Put: APIEndpointAction{Handler: clusterNodePut, AccessHandler: allowPermission(auth.ObjectTypeServer, auth.EntitlementCanEdit)},
Post: APIEndpointAction{Handler: clusterNodePost, AccessHandler: allowPermission(auth.ObjectTypeServer, auth.EntitlementCanEdit)},
}
var clusterNodeStateCmd = APIEndpoint{
Path: "cluster/members/{name}/state",
Get: APIEndpointAction{Handler: clusterNodeStateGet, AccessHandler: allowPermission(auth.ObjectTypeServer, auth.EntitlementCanView)},
Post: APIEndpointAction{Handler: clusterNodeStatePost, AccessHandler: allowPermission(auth.ObjectTypeServer, auth.EntitlementCanEdit)},
}
// swagger:operation GET /1.0/cluster cluster cluster_get
//
// Get the cluster configuration
//
// Gets the current cluster configuration.
//
// ---
// produces:
// - application/json
// responses:
// "200":
// description: Cluster configuration
// schema:
// type: object
// description: Sync response
// properties:
// type:
// type: string
// description: Response type
// example: sync
// status:
// type: string
// description: Status description
// example: Success
// status_code:
// type: integer
// description: Status code
// example: 200
// metadata:
// $ref: "#/definitions/Cluster"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func clusterGet(d *Daemon, r *http.Request) response.Response {
s := d.State()
serverName := s.ServerName
// If the name is set to the hard-coded default node name, then
// clustering is not enabled.
if serverName == "none" {
serverName = ""
}
memberConfig, err := clusterGetMemberConfig(r.Context(), s.DB.Cluster)
if err != nil {
return response.SmartError(err)
}
// Sort the member config.
sort.Slice(memberConfig, func(i, j int) bool {
left := memberConfig[i]
right := memberConfig[j]
if left.Entity != right.Entity {
return left.Entity < right.Entity
}
if left.Name != right.Name {
return left.Name < right.Name
}
if left.Key != right.Key {
return left.Key < right.Key
}
return left.Description < right.Description
})
cluster := api.Cluster{
ServerName: serverName,
Enabled: serverName != "",
MemberConfig: memberConfig,
}
return response.SyncResponseETag(true, cluster, cluster)
}
// Fetch information about all node-specific configuration keys set on the
// storage pools and networks of this cluster.
func clusterGetMemberConfig(ctx context.Context, clusterDB *db.Cluster) ([]api.ClusterMemberConfigKey, error) {
var pools map[string]map[string]string
var networks map[string]map[string]string
keys := []api.ClusterMemberConfigKey{}
err := clusterDB.Transaction(ctx, func(ctx context.Context, tx *db.ClusterTx) error {
var err error
pools, err = tx.GetStoragePoolsLocalConfig(ctx)
if err != nil {
return fmt.Errorf("Failed to fetch storage pools configuration: %w", err)
}
networks, err = tx.GetNetworksLocalConfig(ctx)
if err != nil {
return fmt.Errorf("Failed to fetch networks configuration: %w", err)
}
return nil
})
if err != nil {
return nil, err
}
for pool, config := range pools {
for key := range config {
if strings.HasPrefix(key, internalInstance.ConfigVolatilePrefix) {
continue
}
key := api.ClusterMemberConfigKey{
Entity: "storage-pool",
Name: pool,
Key: key,
Description: fmt.Sprintf("\"%s\" property for storage pool \"%s\"", key, pool),
}
keys = append(keys, key)
}
}
for network, config := range networks {
for key := range config {
if strings.HasPrefix(key, internalInstance.ConfigVolatilePrefix) {
continue
}
key := api.ClusterMemberConfigKey{
Entity: "network",
Name: network,
Key: key,
Description: fmt.Sprintf("\"%s\" property for network \"%s\"", key, network),
}
keys = append(keys, key)
}
}
return keys, nil
}
// Depending on the parameters passed and on local state this endpoint will
// either:
//
// - bootstrap a new cluster (if this node is not clustered yet)
// - request to join an existing cluster
// - disable clustering on a node
//
// The client is required to be trusted.
// swagger:operation PUT /1.0/cluster cluster cluster_put
//
// Update the cluster configuration
//
// Updates the entire cluster configuration.
//
// ---
// consumes:
// - application/json
// produces:
// - application/json
// parameters:
// - in: body
// name: cluster
// description: Cluster configuration
// required: true
// schema:
// $ref: "#/definitions/ClusterPut"
// responses:
// "200":
// $ref: "#/responses/EmptySyncResponse"
// "400":
// $ref: "#/responses/BadRequest"
// "403":
// $ref: "#/responses/Forbidden"
// "412":
// $ref: "#/responses/PreconditionFailed"
// "500":
// $ref: "#/responses/InternalServerError"
func clusterPut(d *Daemon, r *http.Request) response.Response {
req := api.ClusterPut{}
// Parse the request
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
return response.BadRequest(err)
}
// Quick checks.
if req.ServerName == "" && req.Enabled {
return response.BadRequest(errors.New("ServerName is required when enabling clustering"))
}
if req.ServerName != "" && !req.Enabled {
return response.BadRequest(errors.New("ServerName must be empty when disabling clustering"))
}
if req.ServerName != "" && strings.HasPrefix(req.ServerName, targetGroupPrefix) {
return response.BadRequest(fmt.Errorf("ServerName may not start with %q", targetGroupPrefix))
}
// Disable clustering.
if !req.Enabled {
return clusterPutDisable(d, r, req)
}
// Depending on the provided parameters we either bootstrap a brand new
// cluster with this node as first node, or perform a request to join a
// given cluster.
if req.ClusterAddress == "" {
return clusterPutBootstrap(d, r, req)
}
return clusterPutJoin(d, r, req)
}
func clusterPutBootstrap(d *Daemon, r *http.Request, req api.ClusterPut) response.Response {
s := d.State()
logger.Info("Bootstrapping cluster", logger.Ctx{"serverName": req.ServerName})
run := func(op *operations.Operation) error {
// Update server name.
d.globalConfigMu.Lock()
d.serverName = req.ServerName
d.serverClustered = true
d.globalConfigMu.Unlock()
d.events.SetLocalLocation(d.serverName)
// Refresh the state.
s = d.State()
// Start clustering tasks
d.startClusterTasks()
err := cluster.Bootstrap(s, d.gateway, req.ServerName)
if err != nil {
d.stopClusterTasks()
return err
}
// Restart the networks.
err = networkStartup(s)
if err != nil {
return err
}
// Return the new server certificate to the client.
clusterCertPath := internalUtil.VarPath("cluster.crt")
if util.PathExists(clusterCertPath) {
cert, err := os.ReadFile(clusterCertPath)
if err != nil {
return err
}
err = op.UpdateMetadata(map[string]any{"certificate": string(cert)})
if err != nil {
return err
}
}
s.Events.SendLifecycle(request.ProjectParam(r), lifecycle.ClusterEnabled.Event(req.ServerName, op.Requestor(), nil))
return nil
}
resources := map[string][]api.URL{}
resources["cluster"] = []api.URL{}
// If there's no cluster.https_address set, but core.https_address is,
// let's default to it.
var err error
var config *node.Config
err = s.DB.Node.Transaction(r.Context(), func(ctx context.Context, tx *db.NodeTx) error {
config, err = node.ConfigLoad(ctx, tx)
if err != nil {
return fmt.Errorf("Failed to fetch member configuration: %w", err)
}
localClusterAddress := config.ClusterAddress()
if localClusterAddress != "" {
return nil
}
localHTTPSAddress := config.HTTPSAddress()
if internalUtil.IsWildCardAddress(localHTTPSAddress) {
return fmt.Errorf("Cannot use wildcard core.https_address %q for cluster.https_address. Please specify a new cluster.https_address or core.https_address", localClusterAddress)
}
_, err = config.Patch(map[string]string{
"cluster.https_address": localHTTPSAddress,
})
if err != nil {
return fmt.Errorf("Copy core.https_address to cluster.https_address: %w", err)
}
return nil
})
if err != nil {
return response.SmartError(err)
}
// Update local config cache.
d.globalConfigMu.Lock()
d.localConfig = config
d.globalConfigMu.Unlock()
op, err := operations.OperationCreate(s, "", operations.OperationClassTask, operationtype.ClusterBootstrap, resources, nil, run, nil, nil, r)
if err != nil {
return response.InternalError(err)
}
// Add the cluster flag from the agent
version.UserAgentFeatures([]string{"cluster"})
return operations.OperationResponse(op)
}
func clusterPutJoin(d *Daemon, r *http.Request, req api.ClusterPut) response.Response {
s := d.State()
logger.Info("Joining cluster", logger.Ctx{"serverName": req.ServerName})
// Make sure basic pre-conditions are met.
if len(req.ClusterCertificate) == 0 {
return response.BadRequest(errors.New("No target cluster member certificate provided"))
}
if s.ServerClustered {
return response.BadRequest(errors.New("This server is already clustered"))
}
// Validate server address.
if req.ServerAddress == "" {
return response.BadRequest(errors.New("No server address provided for this member"))
}
// Check that the provided address is an IP address or DNS, not wildcard and isn't required to specify a port.
err := validate.IsListenAddress(true, false, false)(req.ServerAddress)
if err != nil {
return response.BadRequest(fmt.Errorf("Invalid server address %q: %w", req.ServerAddress, err))
}
// Verify provided address against cluster.https_address if set.
localHTTPSAddress := s.LocalConfig.ClusterAddress()
if localHTTPSAddress != "" {
if !internalUtil.IsAddressCovered(req.ServerAddress, localHTTPSAddress) {
return response.BadRequest(fmt.Errorf(`Server address %q is not covered by %q from "cluster.https_address"`, req.ServerAddress, localHTTPSAddress))
}
} else {
// If cluster.https_address is not set, check against core.https_address
localHTTPSAddress = s.LocalConfig.HTTPSAddress()
var config *node.Config
if localHTTPSAddress == "" {
// As the user always provides a server address, but no networking
// was setup on this node, let's do the job and open the
// port. We'll use the same address both for the REST API and
// for clustering.
// First try to listen to the provided address. If we fail, we
// won't actually update the database config.
err := s.Endpoints.NetworkUpdateAddress(req.ServerAddress)
if err != nil {
return response.SmartError(err)
}
err = s.DB.Node.Transaction(r.Context(), func(ctx context.Context, tx *db.NodeTx) error {
config, err = node.ConfigLoad(ctx, tx)
if err != nil {
return fmt.Errorf("Failed to load cluster config: %w", err)
}
_, err = config.Patch(map[string]string{
"core.https_address": req.ServerAddress,
"cluster.https_address": req.ServerAddress,
})
return err
})
if err != nil {
return response.SmartError(err)
}
} else {
// The user has previously set core.https_address and
// is now providing a cluster address as well. If they
// differ we need to listen to it.
if !internalUtil.IsAddressCovered(req.ServerAddress, localHTTPSAddress) {
err := s.Endpoints.ClusterUpdateAddress(req.ServerAddress)
if err != nil {
return response.SmartError(err)
}
}
// Update the cluster.https_address config key.
err := s.DB.Node.Transaction(r.Context(), func(ctx context.Context, tx *db.NodeTx) error {
var err error
config, err = node.ConfigLoad(ctx, tx)
if err != nil {
return fmt.Errorf("Failed to load cluster config: %w", err)
}
_, err = config.Patch(map[string]string{
"cluster.https_address": req.ServerAddress,
})
return err
})
if err != nil {
return response.SmartError(err)
}
}
// Update local config cache.
d.globalConfigMu.Lock()
d.localConfig = config
d.globalConfigMu.Unlock()
}
// Client parameters to connect to the target cluster node.
serverCert := s.ServerCert()
args := &incus.ConnectionArgs{
TLSClientCert: string(serverCert.PublicKey()),
TLSClientKey: string(serverCert.PrivateKey()),
TLSServerCert: string(req.ClusterCertificate),
UserAgent: version.UserAgent,
}
// Asynchronously join the cluster.
run := func(op *operations.Operation) error {
logger.Debug("Running cluster join operation")
// If the user has provided a join token, setup the trust
// relationship by adding our own certificate to the cluster.
if req.ClusterToken != "" {
err := cluster.SetupTrust(serverCert, req.ServerName, req.ClusterAddress, req.ClusterCertificate, req.ClusterToken)
if err != nil {
return fmt.Errorf("Failed to setup cluster trust: %w", err)
}
}
// Now we are in the remote trust store, ensure our name and type are correct to allow the cluster
// to associate our member name to the server certificate.
err := cluster.UpdateTrust(serverCert, req.ServerName, req.ClusterAddress, req.ClusterCertificate)
if err != nil {
return fmt.Errorf("Failed to update cluster trust: %w", err)
}
// Connect to the target cluster node.
client, err := incus.ConnectIncus(fmt.Sprintf("https://%s", req.ClusterAddress), args)
if err != nil {
return err
}
// Get the cluster members
members, err := client.GetClusterMembers()
if err != nil {
return err
}
// Verify if a node with the same name already exists in the cluster.
for _, member := range members {
if member.ServerName == req.ServerName {
return fmt.Errorf("The cluster already has a member with name: %s", req.ServerName)
}
}
// As ServerAddress field is required to be set it means that we're using the new join API
// introduced with the 'clustering_join' extension.
// Connect to ourselves to initialize storage pools and networks using the API.
localClient, err := incus.ConnectIncusUnix(d.os.GetUnixSocket(), &incus.ConnectionArgs{UserAgent: clusterRequest.UserAgentJoiner})
if err != nil {
return fmt.Errorf("Failed to connect to local server: %w", err)
}
reverter := revert.New()
defer reverter.Fail()
// Update server name.
oldServerName := d.serverName
d.globalConfigMu.Lock()
d.serverName = req.ServerName
d.serverClustered = true
d.globalConfigMu.Unlock()
reverter.Add(func() {
d.globalConfigMu.Lock()
d.serverName = oldServerName
d.serverClustered = false
d.globalConfigMu.Unlock()
d.events.SetLocalLocation(d.serverName)
})
d.events.SetLocalLocation(d.serverName)
// Create all storage pools and networks.
err = clusterInitMember(localClient, client, req.MemberConfig)
if err != nil {
return fmt.Errorf("Failed to initialize member: %w", err)
}
// Get all defined storage pools and networks, so they can be compared to the ones in the cluster.
pools := []api.StoragePool{}
networks := []api.InitNetworksProjectPost{}
err = s.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
poolNames, err := tx.GetStoragePoolNames(ctx)
if err != nil && !response.IsNotFoundError(err) {
return err
}
for _, name := range poolNames {
_, pool, _, err := tx.GetStoragePoolInAnyState(ctx, name)
if err != nil {
return err
}
pools = append(pools, *pool)
}
// Get a list of projects for networks.
var projects []dbCluster.Project
projects, err = dbCluster.GetProjects(ctx, tx.Tx())
if err != nil {
return fmt.Errorf("Failed to load projects for networks: %w", err)
}
for _, p := range projects {
networkNames, err := tx.GetNetworks(ctx, p.Name)
if err != nil && !response.IsNotFoundError(err) {
return err
}
for _, name := range networkNames {
_, network, _, err := tx.GetNetworkInAnyState(ctx, p.Name, name)
if err != nil {
return err
}
internalNetwork := api.InitNetworksProjectPost{
NetworksPost: api.NetworksPost{
NetworkPut: network.NetworkPut,
Name: network.Name,
Type: network.Type,
},
Project: p.Name,
}
networks = append(networks, internalNetwork)
}
}
return nil
})
if err != nil {
return err
}
reverter.Add(func() {
err = client.DeletePendingClusterMember(req.ServerName, true)
if err != nil {
logger.Errorf("Failed request to delete cluster member: %v", err)
}
})
// Now request for this node to be added to the list of cluster nodes.
info, err := clusterAcceptMember(client, req.ServerName, req.ServerAddress, cluster.SchemaVersion, version.APIExtensionsCount(), pools, networks)
if err != nil {
return fmt.Errorf("Failed request to add member: %w", err)
}
// Update our TLS configuration using the returned cluster certificate.
err = internalUtil.WriteCert(s.OS.VarDir, "cluster", []byte(req.ClusterCertificate), info.PrivateKey, nil)
if err != nil {
return fmt.Errorf("Failed to save cluster certificate: %w", err)
}
networkCert, err := internalUtil.LoadClusterCert(s.OS.VarDir)
if err != nil {
return fmt.Errorf("Failed to parse cluster certificate: %w", err)
}
s.Endpoints.NetworkUpdateCert(networkCert)
// Add trusted certificates of other members to local trust store.
trustedCerts, err := client.GetCertificates()
if err != nil {
return fmt.Errorf("Failed to get trusted certificates: %w", err)
}
for _, trustedCert := range trustedCerts {
if trustedCert.Type == api.CertificateTypeServer {
dbType, err := certificate.FromAPIType(trustedCert.Type)
if err != nil {
return err
}
// Store the certificate in the local database.
dbCert := dbCluster.Certificate{
Fingerprint: trustedCert.Fingerprint,
Type: dbType,
Name: trustedCert.Name,
Certificate: trustedCert.Certificate,
Restricted: trustedCert.Restricted,
}
logger.Debugf("Adding certificate %q (%s) to local trust store", trustedCert.Name, trustedCert.Fingerprint)
err = s.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
id, err := dbCluster.CreateCertificate(ctx, tx.Tx(), dbCert)
if err != nil {
return err
}
err = dbCluster.UpdateCertificateProjects(ctx, tx.Tx(), int(id), trustedCert.Projects)
if err != nil {
return err
}
return nil
})
if err != nil && !api.StatusErrorCheck(err, http.StatusConflict) {
return fmt.Errorf("Failed adding local trusted certificate %q (%s): %w", trustedCert.Name, trustedCert.Fingerprint, err)
}
}
}
// Update cached trusted certificates (this adds the server certificates we collected above) so that we are able to join.
// Client and metric type certificates from the cluster we are joining will not be added until later.
s.UpdateCertificateCache()
// Update local setup and possibly join the raft dqlite cluster.
nodes := make([]db.RaftNode, len(info.RaftNodes))
for i, node := range info.RaftNodes {
nodes[i].ID = node.ID
nodes[i].Address = node.Address
nodes[i].Role = db.RaftRole(node.Role)
}
err = cluster.Join(s, d.gateway, networkCert, serverCert, req.ServerName, nodes)
if err != nil {
return err
}
// Add the new node to the default cluster group.
err = s.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
err := tx.AddNodeToClusterGroup(ctx, "default", req.ServerName)
if err != nil {
return fmt.Errorf("Failed to add new member to the default cluster group: %w", err)
}
return nil
})
if err != nil {
return err
}
// Start clustering tasks.
d.startClusterTasks()
reverter.Add(func() { d.stopClusterTasks() })
// Load the configuration.
var nodeConfig *node.Config
err = s.DB.Node.Transaction(context.TODO(), func(ctx context.Context, tx *db.NodeTx) error {
var err error
nodeConfig, err = node.ConfigLoad(ctx, tx)
return err
})
if err != nil {
return err
}
// Get the current (updated) config.
var currentClusterConfig *clusterConfig.Config
err = d.db.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
currentClusterConfig, err = clusterConfig.Load(ctx, tx)
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
d.globalConfigMu.Lock()
d.localConfig = nodeConfig
d.globalConfig = currentClusterConfig
d.globalConfigMu.Unlock()
changes := util.CloneMap(currentClusterConfig.Dump())
err = doApi10UpdateTriggers(d, nil, changes, nodeConfig, currentClusterConfig)
if err != nil {
return err
}
// Refresh the state.
s = d.State()
// Re-connect OVS if needed.
_ = d.setupOVS()
// Re-connect OVN if needed.
_ = d.setupOVN()
// Start up networks so any post-join changes can be applied now that we have a Node ID.
logger.Debug("Starting networks after cluster join")
err = networkStartup(s)
if err != nil {
logger.Errorf("Failed starting networks: %v", err)
}
client, err = cluster.Connect(req.ClusterAddress, s.Endpoints.NetworkCert(), serverCert, r, true)
if err != nil {
return err
}
// Add the cluster flag from the agent
version.UserAgentFeatures([]string{"cluster"})
// Notify the leader of successful join, possibly triggering
// role changes.
_, _, err = client.RawQuery("POST", "/internal/cluster/rebalance", nil, "")
if err != nil {
logger.Warnf("Failed to trigger cluster rebalance: %v", err)
}
// Ensure all images are available after this node has joined.
err = autoSyncImages(s.ShutdownCtx, s)
if err != nil {
logger.Warn("Failed to sync images")
}
// Update the cert cache again to add client and metric certs to the cache.
s.UpdateCertificateCache()
s.Events.SendLifecycle(request.ProjectParam(r), lifecycle.ClusterMemberAdded.Event(req.ServerName, op.Requestor(), nil))
reverter.Success()
return nil
}
resources := map[string][]api.URL{}
resources["cluster"] = []api.URL{}
op, err := operations.OperationCreate(s, "", operations.OperationClassTask, operationtype.ClusterJoin, resources, nil, run, nil, nil, r)
if err != nil {
return response.InternalError(err)
}
return operations.OperationResponse(op)
}
// clusterPutDisableMu is used to prevent the daemon from being replaced/stopped during removal from the
// cluster until such time as the request that initiated the removal has finished. This allows for self removal
// from the cluster when not the leader.
var clusterPutDisableMu sync.Mutex
// Disable clustering on a node.
func clusterPutDisable(d *Daemon, r *http.Request, req api.ClusterPut) response.Response {
s := d.State()
logger.Info("Disabling clustering", logger.Ctx{"serverName": req.ServerName})
// Close the cluster database
err := s.DB.Cluster.Close()
if err != nil {
return response.SmartError(err)
}
// Update our TLS configuration using our original certificate.
for _, suffix := range []string{"crt", "key", "ca"} {
path := filepath.Join(s.OS.VarDir, "cluster."+suffix)
if !util.PathExists(path) {
continue
}
err := os.Remove(path)
if err != nil {
return response.InternalError(err)
}
}
networkCert, err := internalUtil.LoadCert(s.OS.VarDir)
if err != nil {
return response.InternalError(fmt.Errorf("Failed to parse member certificate: %w", err))
}
// Reset the cluster database and make it local to this node.
err = d.gateway.Reset(networkCert)
if err != nil {
return response.SmartError(err)
}
requestor := request.CreateRequestor(r)
s.Events.SendLifecycle(request.ProjectParam(r), lifecycle.ClusterDisabled.Event(req.ServerName, requestor, nil))
// Stop database cluster connection.
d.gateway.Kill()
go func() {
<-r.Context().Done() // Wait until request has finished.
// Wait until we can acquire the lock. This way if another request is holding the lock we won't
// replace/stop the daemon until that request has finished.
clusterPutDisableMu.Lock()
defer clusterPutDisableMu.Unlock()
if d.systemdSocketActivated {
logger.Info("Exiting daemon following removal from cluster")
os.Exit(0)
} else {
logger.Info("Restarting daemon following removal from cluster")
err = localUtil.ReplaceDaemon()
if err != nil {
logger.Error("Failed restarting daemon", logger.Ctx{"err": err})
}
}
}()
return response.ManualResponse(func(w http.ResponseWriter) error {
err := response.EmptySyncResponse.Render(w)
if err != nil {
return err
}
// Send the response before replacing the daemon process.
f, ok := w.(http.Flusher)
if ok {
f.Flush()
} else {
return errors.New("http.ResponseWriter is not type http.Flusher")
}
return nil
})
}
// clusterInitMember initializes storage pools and networks on this member. We pass two client instances, one
// connected to ourselves (the joining member) and one connected to the target cluster member to join.
func clusterInitMember(d incus.InstanceServer, client incus.InstanceServer, memberConfig []api.ClusterMemberConfigKey) error {
data := api.InitLocalPreseed{}
// Fetch all pools currently defined in the cluster.
pools, err := client.GetStoragePools()
if err != nil {
return fmt.Errorf("Failed to fetch information about cluster storage pools: %w", err)
}
// Merge the returned storage pools configs with the node-specific
// configs provided by the user.
for _, pool := range pools {
// Skip pending pools.
if pool.Status == "Pending" {
continue
}
logger.Debugf("Populating init data for storage pool %q", pool.Name)
post := api.StoragePoolsPost{
StoragePoolPut: pool.StoragePoolPut,
Driver: pool.Driver,
Name: pool.Name,
}
// Delete config keys that are automatically populated by the daemon.
delete(post.Config, "volatile.initial_source")
delete(post.Config, "zfs.pool_name")
// Apply the node-specific config supplied by the user.
for _, config := range memberConfig {
if config.Entity != "storage-pool" {
continue
}
if config.Name != pool.Name {
continue
}
if !slices.Contains(db.NodeSpecificStorageConfig, config.Key) {
logger.Warnf("Ignoring config key %q for storage pool %q", config.Key, config.Name)
continue
}
post.Config[config.Key] = config.Value
}
data.StoragePools = append(data.StoragePools, post)
}
projects, err := client.GetProjects()
if err != nil {
return fmt.Errorf("Failed to fetch project information about cluster networks: %w", err)
}
for _, p := range projects {
if util.IsFalseOrEmpty(p.Config["features.networks"]) && p.Name != api.ProjectDefaultName {
// Skip non-default projects that can't have their own networks so we don't try
// and add the same default project networks twice.
continue
}
// We only care about project features at this stage, leave the restrictions and limits for later.
features := map[string]string{}
for k, v := range p.Config {
if strings.HasPrefix(k, "features.") {
features[k] = v
}
}
// Request that the project be created first before the project specific networks.
data.Projects = append(data.Projects, api.ProjectsPost{
Name: p.Name,
ProjectPut: api.ProjectPut{
Description: p.Description,
Config: features,
},
})
// Fetch all project specific networks currently defined in the cluster for the project.
networks, err := client.UseProject(p.Name).GetNetworks()
if err != nil {
return fmt.Errorf("Failed to fetch network information about cluster networks in project %q: %w", p.Name, err)
}
// Merge the returned networks configs with the node-specific configs provided by the user.
for _, network := range networks {
// Skip unmanaged or pending networks.
if !network.Managed || network.Status != api.NetworkStatusCreated {
continue
}
// OVN networks don't need local creation.
if network.Type == "ovn" {
continue
}
post := api.InitNetworksProjectPost{
NetworksPost: api.NetworksPost{
NetworkPut: network.NetworkPut,
Name: network.Name,
Type: network.Type,
},
Project: p.Name,
}
// Apply the node-specific config supplied by the user for networks in the default project.
// At this time project specific networks don't have node specific config options.
if p.Name == api.ProjectDefaultName {
for _, config := range memberConfig {
if config.Entity != "network" {
continue
}
if config.Name != network.Name {
continue
}
if !db.IsNodeSpecificNetworkConfig(config.Key) {
logger.Warnf("Ignoring config key %q for network %q in project %q", config.Key, config.Name, p.Name)
continue
}
post.Config[config.Key] = config.Value
}
}
data.Networks = append(data.Networks, post)
}
}
err = d.ApplyServerPreseed(api.InitPreseed{Server: data})
if err != nil {
return fmt.Errorf("Failed to initialize storage pools and networks: %w", err)
}
return nil
}
// Perform a request to the /internal/cluster/accept endpoint to check if a new
// node can be accepted into the cluster and obtain joining information such as
// the cluster private certificate.
func clusterAcceptMember(client incus.InstanceServer, name string, address string, schema int, apiExt int, pools []api.StoragePool, networks []api.InitNetworksProjectPost) (*internalClusterPostAcceptResponse, error) {
architecture, err := osarch.ArchitectureGetLocalID()
if err != nil {
return nil, err
}
req := internalClusterPostAcceptRequest{
Name: name,
Address: address,
Schema: schema,
API: apiExt,
StoragePools: pools,
Networks: networks,
Architecture: architecture,
}
info := &internalClusterPostAcceptResponse{}
resp, _, err := client.RawQuery("POST", "/internal/cluster/accept", req, "")
if err != nil {
return nil, err
}
err = resp.MetadataAsStruct(&info)
if err != nil {
return nil, err
}
return info, nil
}
// swagger:operation GET /1.0/cluster/members cluster cluster_members_get
//
// Get the cluster members
//
// Returns a list of cluster members (URLs).
//
// ---
// produces:
// - application/json
// parameters:
// - in: query
// name: filter
// description: Collection filter
// type: string
// example: default
// responses:
// "200":
// description: API endpoints
// schema:
// type: object
// description: Sync response
// properties:
// type:
// type: string
// description: Response type
// example: sync
// status:
// type: string
// description: Status description
// example: Success
// status_code:
// type: integer
// description: Status code
// example: 200
// metadata:
// type: array
// description: List of endpoints
// items:
// type: string
// example: |-
// [
// "/1.0/cluster/members/server01",
// "/1.0/cluster/members/server02"
// ]
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
// swagger:operation GET /1.0/cluster/members?recursion=1 cluster cluster_members_get_recursion1
//
// Get the cluster members
//
// Returns a list of cluster members (structs).
//
// ---
// produces:
// - application/json
// parameters:
// - in: query
// name: filter
// description: Collection filter
// type: string
// example: default
// responses:
// "200":
// description: API endpoints
// schema:
// type: object
// description: Sync response
// properties:
// type:
// type: string
// description: Response type
// example: sync
// status:
// type: string
// description: Status description
// example: Success
// status_code:
// type: integer
// description: Status code
// example: 200
// metadata:
// type: array
// description: List of cluster members
// items:
// $ref: "#/definitions/ClusterMember"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func clusterNodesGet(d *Daemon, r *http.Request) response.Response {
recursion := localUtil.IsRecursionRequest(r)
s := d.State()
// Parse filter value.
filterStr := r.FormValue("filter")
clauses, err := filter.Parse(filterStr, filter.QueryOperatorSet())
if err != nil {
return response.BadRequest(fmt.Errorf("Invalid filter: %w", err))
}
leaderAddress, err := s.Cluster.LeaderAddress()
if err != nil {
return response.InternalError(err)
}
var raftNodes []db.RaftNode
err = s.DB.Node.Transaction(r.Context(), func(ctx context.Context, tx *db.NodeTx) error {
raftNodes, err = tx.GetRaftNodes(ctx)
if err != nil {
return fmt.Errorf("Failed loading RAFT nodes: %w", err)
}
return nil
})
if err != nil {
return response.SmartError(err)
}
var members []api.ClusterMember
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
failureDomains, err := tx.GetFailureDomainsNames(ctx)
if err != nil {
return fmt.Errorf("Failed loading failure domains names: %w", err)
}
memberFailureDomains, err := tx.GetNodesFailureDomains(ctx)
if err != nil {
return fmt.Errorf("Failed loading member failure domains: %w", err)
}
nodes, err := tx.GetNodes(ctx)
if err != nil {
return fmt.Errorf("Failed getting cluster members: %w", err)
}
maxVersion, err := tx.GetNodeMaxVersion(ctx)
if err != nil {
return fmt.Errorf("Failed getting max member version: %w", err)
}
args := db.NodeInfoArgs{
LeaderAddress: leaderAddress,
FailureDomains: failureDomains,
MemberFailureDomains: memberFailureDomains,
OfflineThreshold: s.GlobalConfig.OfflineThreshold(),
MaxMemberVersion: maxVersion,
RaftNodes: raftNodes,
}
members = make([]api.ClusterMember, 0, len(nodes))
for i := range nodes {
member, err := nodes[i].ToAPI(ctx, tx, args)
if err != nil {
return err
}
members = append(members, *member)
}
return nil
})
if err != nil {
return response.SmartError(err)
}
// Apply filters.
filtered := make([]api.ClusterMember, 0)
for _, member := range members {
if clauses != nil && len(clauses.Clauses) > 0 {
match, err := filter.Match(member, *clauses)
if err != nil {
return response.SmartError(err)
}
if !match {
continue
}
}
filtered = append(filtered, member)
}
// Return full responses.
if recursion {
return response.SyncResponse(true, filtered)
}
// Return URLs only.
urls := make([]string, 0, len(members))
for _, member := range members {
u := api.NewURL().Path(version.APIVersion, "cluster", "members", member.ServerName)
urls = append(urls, u.String())
}
return response.SyncResponse(true, urls)
}
var clusterNodesPostMu sync.Mutex // Used to prevent races when creating cluster join tokens.
// swagger:operation POST /1.0/cluster/members cluster cluster_members_post
//
// Request a join token
//
// Requests a join token to add a cluster member.
//
// ---
// consumes:
// - application/json
// produces:
// - application/json
// parameters:
// - in: body
// name: cluster
// description: Cluster member add request
// required: true
// schema:
// $ref: "#/definitions/ClusterMembersPost"
// responses:
// "202":
// $ref: "#/responses/Operation"
// "400":
// $ref: "#/responses/BadRequest"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func clusterNodesPost(d *Daemon, r *http.Request) response.Response {
s := d.State()
req := api.ClusterMembersPost{}
// Parse the request.
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
return response.BadRequest(err)
}
// Quick checks.
err = validate.IsAPIName(req.ServerName, false)
if err != nil {
return response.BadRequest(fmt.Errorf("Invalid cluster member name: %w", err))
}
if !s.ServerClustered {
return response.BadRequest(errors.New("This server is not clustered"))
}
expiry, err := internalInstance.GetExpiry(time.Now(), s.GlobalConfig.ClusterJoinTokenExpiry())
if err != nil {
return response.BadRequest(err)
}
// Get target addresses for existing online members, so that it can be encoded into the join token so that
// the joining member will not have to specify a joining address during the join process.
// Use anonymous interface type to align with how the API response will be returned for consistency when
// retrieving remote operations.
onlineNodeAddresses := make([]any, 0)
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
// Get the nodes.
members, err := tx.GetNodes(ctx)
if err != nil {
return fmt.Errorf("Failed getting cluster members: %w", err)
}
// Filter to online members.
for _, member := range members {
// Verify if a node with the same name already exists in the cluster.
if member.Name == req.ServerName {
return fmt.Errorf("The cluster already has a member with name: %s", req.ServerName)
}
if member.State == db.ClusterMemberStateEvacuated || member.IsOffline(s.GlobalConfig.OfflineThreshold()) {
continue
}
onlineNodeAddresses = append(onlineNodeAddresses, member.Address)
}
return nil
})
if err != nil {
return response.SmartError(err)
}
if len(onlineNodeAddresses) < 1 {
return response.InternalError(errors.New("There are no online cluster members"))
}
// Lock to prevent concurrent requests racing the operationsGetByType function and creating duplicates.
// We have to do this because collecting all of the operations from existing cluster members can take time.
clusterNodesPostMu.Lock()
defer clusterNodesPostMu.Unlock()
// Remove any existing join tokens for the requested cluster member, this way we only ever have one active
// join token for each potential new member, and it has the most recent active members list for joining.
// This also ensures any historically unused (but potentially published) join tokens are removed.
ops, err := operationsGetByType(s, r, api.ProjectDefaultName, operationtype.ClusterJoinToken)
if err != nil {
return response.InternalError(fmt.Errorf("Failed getting cluster join token operations: %w", err))
}
for _, op := range ops {
if op.StatusCode != api.Running {
continue // Tokens are single use, so if cancelled but not deleted yet its not available.
}
opServerName, ok := op.Metadata["serverName"]
if !ok {
continue
}
if opServerName == req.ServerName {
// Join token operation matches requested server name, so lets cancel it.
logger.Warn("Cancelling duplicate join token operation", logger.Ctx{"operation": op.ID, "serverName": opServerName})
err = operationCancel(s, r, api.ProjectDefaultName, op)
if err != nil {
return response.InternalError(fmt.Errorf("Failed to cancel operation %q: %w", op.ID, err))
}
}
}
// Generate join secret for new member. This will be stored inside the join token operation and will be
// supplied by the joining member (encoded inside the join token) which will allow us to lookup the correct
// operation in order to validate the requested joining server name is correct and authorised.
joinSecret, err := internalUtil.RandomHexString(32)
if err != nil {
return response.InternalError(err)
}
// Generate fingerprint of network certificate so joining member can automatically trust the correct
// certificate when it is presented during the join process.
fingerprint, err := localtls.CertFingerprintStr(string(s.Endpoints.NetworkPublicKey()))
if err != nil {
return response.InternalError(err)
}
meta := map[string]any{
"serverName": req.ServerName, // Add server name to allow validation of name during join process.
"secret": joinSecret,
"fingerprint": fingerprint,
"addresses": onlineNodeAddresses,
"expiresAt": expiry,
}
resources := map[string][]api.URL{}
resources["cluster"] = []api.URL{}
op, err := operations.OperationCreate(s, api.ProjectDefaultName, operations.OperationClassToken, operationtype.ClusterJoinToken, resources, meta, nil, nil, nil, r)
if err != nil {
return response.InternalError(err)
}
s.Events.SendLifecycle(request.ProjectParam(r), lifecycle.ClusterTokenCreated.Event("members", op.Requestor(), nil))
return operations.OperationResponse(op)
}
// swagger:operation GET /1.0/cluster/members/{name} cluster cluster_member_get
//
// Get the cluster member
//
// Gets a specific cluster member.
//
// ---
// produces:
// - application/json
// responses:
// "200":
// description: Cluster member
// schema:
// type: object
// description: Sync response
// properties:
// type:
// type: string
// description: Response type
// example: sync
// status:
// type: string
// description: Status description
// example: Success
// status_code:
// type: integer
// description: Status code
// example: 200
// metadata:
// $ref: "#/definitions/ClusterMember"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func clusterNodeGet(d *Daemon, r *http.Request) response.Response {
s := d.State()
name, err := url.PathUnescape(mux.Vars(r)["name"])
if err != nil {
return response.SmartError(err)
}
leaderAddress, err := s.Cluster.LeaderAddress()
if err != nil {
return response.InternalError(err)
}
var raftNodes []db.RaftNode
err = s.DB.Node.Transaction(r.Context(), func(ctx context.Context, tx *db.NodeTx) error {
raftNodes, err = tx.GetRaftNodes(ctx)
if err != nil {
return fmt.Errorf("Failed loading RAFT nodes: %w", err)
}
return nil
})
if err != nil {
return response.SmartError(err)
}
var memberInfo *api.ClusterMember
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
failureDomains, err := tx.GetFailureDomainsNames(ctx)
if err != nil {
return fmt.Errorf("Failed loading failure domains names: %w", err)
}
memberFailureDomains, err := tx.GetNodesFailureDomains(ctx)
if err != nil {
return fmt.Errorf("Failed loading member failure domains: %w", err)
}
member, err := tx.GetNodeByName(ctx, name)
if err != nil {
return err
}
maxVersion, err := tx.GetNodeMaxVersion(ctx)
if err != nil {
return fmt.Errorf("Failed getting max member version: %w", err)
}
args := db.NodeInfoArgs{
LeaderAddress: leaderAddress,
FailureDomains: failureDomains,
MemberFailureDomains: memberFailureDomains,
OfflineThreshold: s.GlobalConfig.OfflineThreshold(),
MaxMemberVersion: maxVersion,
RaftNodes: raftNodes,
}
memberInfo, err = member.ToAPI(ctx, tx, args)
if err != nil {
return err
}
return nil
})
if err != nil {
return response.SmartError(err)
}
return response.SyncResponseETag(true, memberInfo, memberInfo.ClusterMemberPut)
}
// swagger:operation PATCH /1.0/cluster/members/{name} cluster cluster_member_patch
//
// Partially update the cluster member
//
// Updates a subset of the cluster member configuration.
//
// ---
// consumes:
// - application/json
// produces:
// - application/json
// parameters:
// - in: body
// name: cluster
// description: Cluster member configuration
// required: true
// schema:
// $ref: "#/definitions/ClusterMemberPut"
// responses:
// "200":
// $ref: "#/responses/EmptySyncResponse"
// "400":
// $ref: "#/responses/BadRequest"
// "403":
// $ref: "#/responses/Forbidden"
// "412":
// $ref: "#/responses/PreconditionFailed"
// "500":
// $ref: "#/responses/InternalServerError"
func clusterNodePatch(d *Daemon, r *http.Request) response.Response {
return updateClusterNode(d.State(), d.gateway, r, true)
}
// swagger:operation PUT /1.0/cluster/members/{name} cluster cluster_member_put
//
// Update the cluster member
//
// Updates the entire cluster member configuration.
//
// ---
// consumes:
// - application/json
// produces:
// - application/json
// parameters:
// - in: body
// name: cluster
// description: Cluster member configuration
// required: true
// schema:
// $ref: "#/definitions/ClusterMemberPut"
// responses:
// "200":
// $ref: "#/responses/EmptySyncResponse"
// "400":
// $ref: "#/responses/BadRequest"
// "403":
// $ref: "#/responses/Forbidden"
// "412":
// $ref: "#/responses/PreconditionFailed"
// "500":
// $ref: "#/responses/InternalServerError"
func clusterNodePut(d *Daemon, r *http.Request) response.Response {
return updateClusterNode(d.State(), d.gateway, r, false)
}
// updateClusterNode is shared between clusterNodePut and clusterNodePatch.
func updateClusterNode(s *state.State, gateway *cluster.Gateway, r *http.Request, isPatch bool) response.Response {
name, err := url.PathUnescape(mux.Vars(r)["name"])
if err != nil {
return response.SmartError(err)
}
leaderAddress, err := s.Cluster.LeaderAddress()
if err != nil {
return response.InternalError(err)
}
var raftNodes []db.RaftNode
err = s.DB.Node.Transaction(r.Context(), func(ctx context.Context, tx *db.NodeTx) error {
raftNodes, err = tx.GetRaftNodes(ctx)
if err != nil {
return fmt.Errorf("Failed loading RAFT nodes: %w", err)
}
return nil
})
if err != nil {
return response.SmartError(err)
}
var member db.NodeInfo
var memberInfo *api.ClusterMember
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
failureDomains, err := tx.GetFailureDomainsNames(ctx)
if err != nil {
return fmt.Errorf("Failed loading failure domains names: %w", err)
}
memberFailureDomains, err := tx.GetNodesFailureDomains(ctx)
if err != nil {
return fmt.Errorf("Failed loading member failure domains: %w", err)
}
member, err = tx.GetNodeByName(ctx, name)
if err != nil {
return err
}
maxVersion, err := tx.GetNodeMaxVersion(ctx)
if err != nil {
return fmt.Errorf("Failed getting max member version: %w", err)
}
args := db.NodeInfoArgs{
LeaderAddress: leaderAddress,
FailureDomains: failureDomains,
MemberFailureDomains: memberFailureDomains,
OfflineThreshold: s.GlobalConfig.OfflineThreshold(),
MaxMemberVersion: maxVersion,
RaftNodes: raftNodes,
}
memberInfo, err = member.ToAPI(ctx, tx, args)
if err != nil {
return err
}
return nil
})
if err != nil {
return response.SmartError(err)
}
// Validate the request is fine
err = localUtil.EtagCheck(r, memberInfo.ClusterMemberPut)
if err != nil {
return response.PreconditionFailed(err)
}
// Parse the request
req := api.ClusterMemberPut{}
err = json.NewDecoder(r.Body).Decode(&req)
if err != nil {
return response.BadRequest(err)
}
// Validate the request
if slices.Contains(memberInfo.Roles, string(db.ClusterRoleDatabase)) && !slices.Contains(req.Roles, string(db.ClusterRoleDatabase)) {
return response.BadRequest(fmt.Errorf("The %q role cannot be dropped at this time", db.ClusterRoleDatabase))
}
if !slices.Contains(memberInfo.Roles, string(db.ClusterRoleDatabase)) && slices.Contains(req.Roles, string(db.ClusterRoleDatabase)) {
return response.BadRequest(fmt.Errorf("The %q role cannot be added at this time", db.ClusterRoleDatabase))
}
// Nodes must belong to at least one group.
if len(req.Groups) == 0 {
return response.BadRequest(errors.New("Cluster members need to belong to at least one group"))
}
// Convert the roles.
newRoles := make([]db.ClusterRole, 0, len(req.Roles))
for _, role := range req.Roles {
newRoles = append(newRoles, db.ClusterRole(role))
}
// Update the database
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
nodeInfo, err := tx.GetNodeByName(ctx, name)
if err != nil {
return fmt.Errorf("Loading node information: %w", err)
}
err = clusterValidateConfig(req.Config)
if err != nil {
return err
}
if isPatch {
// Populate request config with current values.
if req.Config == nil {
req.Config = nodeInfo.Config
} else {
for k, v := range nodeInfo.Config {
_, ok := req.Config[k]
if !ok {
req.Config[k] = v
}
}
}
}
// Update node config.
err = tx.UpdateNodeConfig(ctx, nodeInfo.ID, req.Config)
if err != nil {
return fmt.Errorf("Failed to update cluster member config: %w", err)
}
// Update the description.
if req.Description != memberInfo.Description {
err = tx.SetDescription(nodeInfo.ID, req.Description)
if err != nil {
return fmt.Errorf("Update description: %w", err)
}
}
// Update the roles.
err = tx.UpdateNodeRoles(nodeInfo.ID, newRoles)
if err != nil {
return fmt.Errorf("Update roles: %w", err)
}
err = tx.UpdateNodeFailureDomain(ctx, nodeInfo.ID, req.FailureDomain)
if err != nil {
return fmt.Errorf("Update failure domain: %w", err)
}
// Update the cluster groups.
err = tx.UpdateNodeClusterGroups(ctx, nodeInfo.ID, req.Groups)
if err != nil {
return fmt.Errorf("Update cluster groups: %w", err)
}
return nil
})
if err != nil {
return response.SmartError(err)
}
// If cluster roles changed, then distribute the info to all members.
if s.Endpoints != nil && clusterRolesChanged(member.Roles, newRoles) {
cluster.NotifyHeartbeat(s, gateway)
}
requestor := request.CreateRequestor(r)
s.Events.SendLifecycle(request.ProjectParam(r), lifecycle.ClusterMemberUpdated.Event(name, requestor, nil))
return response.EmptySyncResponse
}
// clusterRolesChanged checks whether the non-internal roles have changed between oldRoles and newRoles.
func clusterRolesChanged(oldRoles []db.ClusterRole, newRoles []db.ClusterRole) bool {
// Build list of external-only roles from the newRoles list (excludes internal roles added by raft).
newExternalRoles := make([]db.ClusterRole, 0, len(newRoles))
for _, r := range newRoles {
// Check list of known external roles.
for _, externalRole := range db.ClusterRoles {
if r == externalRole {
newExternalRoles = append(newExternalRoles, r) // Found external role.
break
}
}
}
for _, r := range oldRoles {
if !cluster.RoleInSlice(r, newExternalRoles) {
return true
}
}
for _, r := range newExternalRoles {
if !cluster.RoleInSlice(r, oldRoles) {
return true
}
}
return false
}
// clusterValidateConfig validates the configuration keys/values for cluster members.
func clusterValidateConfig(config map[string]string) error {
clusterConfigKeys := map[string]func(value string) error{
// gendoc:generate(entity=cluster, group=cluster, key=scheduler.instance)
// Possible values are `all`, `manual`, and `group`. See
// {ref}`clustering-instance-placement` for more information.
// ---
// type: string
// defaultdesc: `all`
// shortdesc: Controls how instances are scheduled to run on this member
"scheduler.instance": validate.Optional(validate.IsOneOf("all", "group", "manual")),
}
for k, v := range config {
// User keys are free for all.
// gendoc:generate(entity=cluster, group=cluster, key=user.*)
// User keys can be used in search.
// ---
// type: string
// shortdesc: Free form user key/value storage
if strings.HasPrefix(k, "user.") {
continue
}
validator, ok := clusterConfigKeys[k]
if !ok {
return fmt.Errorf("Invalid cluster configuration key %q", k)
}
err := validator(v)
if err != nil {
return fmt.Errorf("Invalid cluster configuration key %q value", k)
}
}
return nil
}
// swagger:operation POST /1.0/cluster/members/{name} cluster cluster_member_post
//
// Rename the cluster member
//
// Renames an existing cluster member.
//
// ---
// consumes:
// - application/json
// produces:
// - application/json
// parameters:
// - in: body
// name: cluster
// description: Cluster member rename request
// required: true
// schema:
// $ref: "#/definitions/ClusterMemberPost"
// responses:
// "200":
// $ref: "#/responses/EmptySyncResponse"
// "400":
// $ref: "#/responses/BadRequest"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func clusterNodePost(d *Daemon, r *http.Request) response.Response {
s := d.State()
memberName, err := url.PathUnescape(mux.Vars(r)["name"])
if err != nil {
return response.SmartError(err)
}
// Forward request.
resp := forwardedResponseToNode(s, r, memberName)
if resp != nil {
return resp
}
req := api.ClusterMemberPost{}
// Parse the request
err = json.NewDecoder(r.Body).Decode(&req)
if err != nil {
return response.BadRequest(err)
}
// Quick checks.
err = validate.IsAPIName(req.ServerName, false)
if err != nil {
return response.BadRequest(fmt.Errorf("Invalid cluster member name: %w", err))
}
// Perform the rename.
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.RenameNode(ctx, memberName, req.ServerName)
})
if err != nil {
return response.SmartError(err)
}
// Update local server name.
d.globalConfigMu.Lock()
d.serverName = req.ServerName
d.globalConfigMu.Unlock()
d.events.SetLocalLocation(d.serverName)
requestor := request.CreateRequestor(r)
s.Events.SendLifecycle(request.ProjectParam(r), lifecycle.ClusterMemberRenamed.Event(req.ServerName, requestor, logger.Ctx{"old_name": memberName}))
return response.EmptySyncResponse
}
// swagger:operation DELETE /1.0/cluster/members/{name} cluster cluster_member_delete
//
// Delete the cluster member
//
// Removes the member from the cluster.
//
// ---
// produces:
// - application/json
// responses:
// "200":
// $ref: "#/responses/EmptySyncResponse"
// "400":
// $ref: "#/responses/BadRequest"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func clusterNodeDelete(d *Daemon, r *http.Request) response.Response {
s := d.State()
force, err := strconv.Atoi(r.FormValue("force"))
if err != nil {
force = 0
}
pending, err := strconv.Atoi(r.FormValue("pending"))
if err != nil {
pending = 0
}
name, err := url.PathUnescape(mux.Vars(r)["name"])
if err != nil {
return response.SmartError(err)
}
// Redirect all requests to the leader, which is the one with
// knowing what nodes are part of the raft cluster.
localClusterAddress := s.LocalConfig.ClusterAddress()
leader, err := s.Cluster.LeaderAddress()
if err != nil {
return response.InternalError(err)
}
var localInfo, leaderInfo db.NodeInfo
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
localInfo, err = tx.GetNodeByAddress(ctx, localClusterAddress)
if err != nil {
return fmt.Errorf("Failed loading local member info %q: %w", localClusterAddress, err)
}
leaderInfo, err = tx.GetNodeByAddress(ctx, leader)
if err != nil {
return fmt.Errorf("Failed loading leader member info %q: %w", leader, err)
}
return nil
})
if err != nil {
return response.SmartError(err)
}
// Get information about the cluster.
var nodes []db.RaftNode
err = s.DB.Node.Transaction(r.Context(), func(ctx context.Context, tx *db.NodeTx) error {
var err error
nodes, err = tx.GetRaftNodes(ctx)
return err
})
if err != nil {
return response.SmartError(fmt.Errorf("Unable to get raft nodes: %w", err))
}
if localClusterAddress != leader {
if localInfo.Name == name {
// If the member being removed is ourselves and we are not the leader, then lock the
// clusterPutDisableMu before we forward the request to the leader, so that when the leader
// goes on to request clusterPutDisable back to ourselves it won't be actioned until we
// have returned this request back to the original client.
clusterPutDisableMu.Lock()
logger.Info("Acquired cluster self removal lock", logger.Ctx{"member": localInfo.Name})
go func() {
<-r.Context().Done() // Wait until request is finished.
logger.Info("Releasing cluster self removal lock", logger.Ctx{"member": localInfo.Name})
clusterPutDisableMu.Unlock()
}()
}
logger.Debugf("Redirect member delete request to %s", leader)
client, err := cluster.Connect(leader, s.Endpoints.NetworkCert(), s.ServerCert(), r, false)
if err != nil {
return response.SmartError(err)
}
if pending == 0 {
err = client.DeleteClusterMember(name, force == 1)
if err != nil {
return response.SmartError(err)
}
} else {
err = client.DeletePendingClusterMember(name, force == 1)
if err != nil {
return response.SmartError(err)
}
}
// If we are the only remaining node, wait until promotion to leader,
// then update cluster certs.
if name == leaderInfo.Name && len(nodes) == 2 {
err = d.gateway.WaitLeadership()
if err != nil {
return response.SmartError(err)
}
s.UpdateCertificateCache()
}
return response.ManualResponse(func(w http.ResponseWriter) error {
err := response.EmptySyncResponse.Render(w)
if err != nil {
return err
}
// Send the response before replacing the daemon process.
f, ok := w.(http.Flusher)
if ok {
f.Flush()
} else {
return errors.New("http.ResponseWriter is not type http.Flusher")
}
return nil
})
}
// Get lock now we are on leader.
d.clusterMembershipMutex.Lock()
defer d.clusterMembershipMutex.Unlock()
// If we are removing the leader of a 2 node cluster, ensure the other node can be a leader.
if name == leaderInfo.Name && len(nodes) == 2 {
for i := range nodes {
if nodes[i].Address != leader && nodes[i].Role != db.RaftVoter {
// Promote the remaining node.
nodes[i].Role = db.RaftVoter
err := changeMemberRole(s, r, nodes[i].Address, nodes)
if err != nil {
return response.SmartError(fmt.Errorf("Unable to promote remaining cluster member to leader: %w", err))
}
break
}
}
}
logger.Info("Deleting member from cluster", logger.Ctx{"name": name, "force": force})
err = autoSyncImages(s.ShutdownCtx, s)
if err != nil {
if force == 0 {
return response.SmartError(fmt.Errorf("Failed to sync images: %w", err))
}
// If force is set, only show a warning instead of returning an error.
logger.Warn("Failed to sync images")
}
// First check that the node is clear from containers and images and
// make it leave the database cluster, if it's part of it.
address, err := cluster.Leave(s, d.gateway, name, force == 1, pending == 1)
if err != nil {
return response.SmartError(err)
}
if force != 1 {
// Try to gracefully delete all networks and storage pools on it.
// Delete all networks on this node
client, err := cluster.Connect(address, s.Endpoints.NetworkCert(), s.ServerCert(), r, true)
if err != nil {
return response.SmartError(err)
}
// Get a list of projects for networks.
var networkProjectNames []string
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
networkProjectNames, err = dbCluster.GetProjectNames(ctx, tx.Tx())
return err
})
if err != nil {
return response.SmartError(fmt.Errorf("Failed to load projects for networks: %w", err))
}
for _, networkProjectName := range networkProjectNames {
var networks []string
err := s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
networks, err = tx.GetNetworks(ctx, networkProjectName)
return err
})
if err != nil {
return response.SmartError(err)
}
for _, name := range networks {
err := client.UseProject(networkProjectName).DeleteNetwork(name)
if err != nil {
return response.SmartError(err)
}
}
}
var pools []string
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
// Delete all the pools on this node
pools, err = tx.GetStoragePoolNames(ctx)
return err
})
if err != nil && !response.IsNotFoundError(err) {
return response.SmartError(err)
}
for _, name := range pools {
err := client.DeleteStoragePool(name)
if err != nil {
return response.SmartError(err)
}
}
}
// Remove node from the database
err = cluster.Purge(s.DB.Cluster, name, pending == 1)
if err != nil {
return response.SmartError(fmt.Errorf("Failed to remove member from database: %w", err))
}
err = rebalanceMemberRoles(s, d.gateway, r, nil)
if err != nil {
logger.Warnf("Failed to rebalance dqlite nodes: %v", err)
}
// If this leader node removed itself, just disable clustering.
if address == localClusterAddress {
return clusterPutDisable(d, r, api.ClusterPut{})
} else if force != 1 {
// Try to gracefully reset the database on the node.
client, err := cluster.Connect(address, s.Endpoints.NetworkCert(), s.ServerCert(), r, true)
if err != nil {
return response.SmartError(err)
}
put := api.ClusterPut{}
put.Enabled = false
_, err = client.UpdateCluster(put, "")
if err != nil {
return response.SmartError(fmt.Errorf("Failed to cleanup the member: %w", err))
}
}
// Refresh the trusted certificate cache now that the member certificate has been removed.
// We do not need to notify the other members here because the next heartbeat will trigger member change
// detection and updateCertificateCache is called as part of that.
s.UpdateCertificateCache()
// Ensure all images are available after this node has been deleted.
err = autoSyncImages(s.ShutdownCtx, s)
if err != nil {
logger.Warn("Failed to sync images")
}
requestor := request.CreateRequestor(r)
s.Events.SendLifecycle(request.ProjectParam(r), lifecycle.ClusterMemberRemoved.Event(name, requestor, nil))
return response.EmptySyncResponse
}
func internalClusterPostAccept(d *Daemon, r *http.Request) response.Response {
s := d.State()
req := internalClusterPostAcceptRequest{}
// Parse the request
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
return response.BadRequest(err)
}
// Quick checks.
if req.Name == "" {
return response.BadRequest(errors.New("No name provided"))
}
// Redirect all requests to the leader, which is the one
// knowing what nodes are part of the raft cluster.
localClusterAddress := s.LocalConfig.ClusterAddress()
leader, err := s.Cluster.LeaderAddress()
if err != nil {
return response.InternalError(err)
}
if localClusterAddress != leader {
logger.Debugf("Redirect member accept request to %s", leader)
if leader == "" {
return response.SmartError(errors.New("Unable to find leader address"))
}
url := &url.URL{
Scheme: "https",
Path: "/internal/cluster/accept",
Host: leader,
}
return response.SyncResponseRedirect(url.String())
}
// Get lock now we are on leader.
d.clusterMembershipMutex.Lock()
defer d.clusterMembershipMutex.Unlock()
// Make sure we have all the expected storage pools.
err = clusterCheckStoragePoolsMatch(r.Context(), s.DB.Cluster, req.StoragePools)
if err != nil {
return response.SmartError(err)
}
// Make sure we have all the expected networks.
err = clusterCheckNetworksMatch(r.Context(), s.DB.Cluster, req.Networks)
if err != nil {
return response.SmartError(err)
}
nodes, err := cluster.Accept(s, d.gateway, req.Name, req.Address, req.Schema, req.API, req.Architecture)
if err != nil {
return response.BadRequest(err)
}
accepted := internalClusterPostAcceptResponse{
RaftNodes: make([]internalRaftNode, len(nodes)),
PrivateKey: s.Endpoints.NetworkPrivateKey(),
}
for i, node := range nodes {
accepted.RaftNodes[i].ID = node.ID
accepted.RaftNodes[i].Address = node.Address
accepted.RaftNodes[i].Role = int(node.Role)
}
return response.SyncResponse(true, accepted)
}
// A request for the /internal/cluster/accept endpoint.
type internalClusterPostAcceptRequest struct {
Name string `json:"name" yaml:"name"`
Address string `json:"address" yaml:"address"`
Schema int `json:"schema" yaml:"schema"`
API int `json:"api" yaml:"api"`
StoragePools []api.StoragePool `json:"storage_pools" yaml:"storage_pools"`
Networks []api.InitNetworksProjectPost `json:"networks" yaml:"networks"`
Architecture int `json:"architecture" yaml:"architecture"`
}
// A Response for the /internal/cluster/accept endpoint.
type internalClusterPostAcceptResponse struct {
RaftNodes []internalRaftNode `json:"raft_nodes" yaml:"raft_nodes"`
PrivateKey []byte `json:"private_key" yaml:"private_key"`
}
// Represent a node that is part of the dqlite raft cluster.
type internalRaftNode struct {
ID uint64 `json:"id" yaml:"id"`
Address string `json:"address" yaml:"address"`
Role int `json:"role" yaml:"role"`
Name string `json:"name" yaml:"name"`
}
// Used to update the cluster after a database node has been removed, and
// possibly promote another one as database node.
func internalClusterPostRebalance(d *Daemon, r *http.Request) response.Response {
s := d.State()
// Redirect all requests to the leader, which is the one with with
// up-to-date knowledge of what nodes are part of the raft cluster.
localClusterAddress := s.LocalConfig.ClusterAddress()
leader, err := s.Cluster.LeaderAddress()
if err != nil {
return response.InternalError(err)
}
if localClusterAddress != leader {
logger.Debugf("Redirect cluster rebalance request to %s", leader)
url := &url.URL{
Scheme: "https",
Path: "/internal/cluster/rebalance",
Host: leader,
}
return response.SyncResponseRedirect(url.String())
}
// Get lock now we are on leader.
d.clusterMembershipMutex.Lock()
defer d.clusterMembershipMutex.Unlock()
err = rebalanceMemberRoles(s, d.gateway, r, nil)
if err != nil {
return response.SmartError(err)
}
return response.SyncResponse(true, nil)
}
// Check if there's a dqlite node whose role should be changed, and post a
// change role request if so.
func rebalanceMemberRoles(s *state.State, gateway *cluster.Gateway, r *http.Request, unavailableMembers []string) error {
if s.ShutdownCtx.Err() != nil {
return nil
}
again:
address, nodes, err := cluster.Rebalance(s, gateway, unavailableMembers)
if err != nil {
return err
}
if address == "" {
// Nothing to do.
return nil
}
// Process demotions of offline nodes immediately.
for _, node := range nodes {
if node.Address != address {
continue
}
reachable := cluster.HasConnectivity(s.Endpoints.NetworkCert(), s.ServerCert(), address, true)
if node.Role != db.RaftSpare {
if !reachable {
// The server isn't ready to be promoted yet, try again next time.
return nil
}
logger.Info("Promoting cluster member", logger.Ctx{"name": node.Name, "role": node.Role})
break
}
if reachable {
// Don't demote reachable servers.
break
}
logger.Info("Demoting cluster member", logger.Ctx{"name": node.Name, "role": node.Role})
err := gateway.DemoteOfflineNode(node.ID)
if err != nil {
return fmt.Errorf("Failed to demote cluster member %q: %w", node.Name, err)
}
goto again
}
// Then handle the promotions.
err = changeMemberRole(s, r, address, nodes)
if err != nil {
return err
}
goto again
}
// Check if there are nodes not part of the raft configuration and add them in
// case.
func upgradeNodesWithoutRaftRole(s *state.State, gateway *cluster.Gateway) error {
if s.ShutdownCtx.Err() != nil {
return nil
}
var members []db.NodeInfo
err := s.DB.Cluster.Transaction(context.Background(), func(ctx context.Context, tx *db.ClusterTx) error {
var err error
members, err = tx.GetNodes(ctx)
if err != nil {
return fmt.Errorf("Failed getting cluster members: %w", err)
}
return nil
})
if err != nil {
return err
}
return cluster.UpgradeMembersWithoutRole(gateway, members)
}
// Post a change role request to the member with the given address. The nodes
// slice contains details about all members, including the one being changed.
func changeMemberRole(s *state.State, r *http.Request, address string, nodes []db.RaftNode) error {
post := &internalClusterPostAssignRequest{}
for _, node := range nodes {
post.RaftNodes = append(post.RaftNodes, internalRaftNode{
ID: node.ID,
Address: node.Address,
Role: int(node.Role),
Name: node.Name,
})
}
client, err := cluster.Connect(address, s.Endpoints.NetworkCert(), s.ServerCert(), r, true)
if err != nil {
return err
}
_, _, err = client.RawQuery("POST", "/internal/cluster/assign", post, "")
if err != nil {
return err
}
return nil
}
// Try to handover the role of this member to another one.
func handoverMemberRole(s *state.State, gateway *cluster.Gateway) error {
// If we aren't clustered, there's nothing to do.
if !s.ServerClustered {
return nil
}
// Figure out our own cluster address.
localClusterAddress := s.LocalConfig.ClusterAddress()
post := &internalClusterPostHandoverRequest{
Address: localClusterAddress,
}
logCtx := logger.Ctx{"address": localClusterAddress}
// Find the cluster leader.
findLeader:
leader, err := s.Cluster.LeaderAddress()
if err != nil {
return err
}
if leader == "" {
return errors.New("No leader address found")
}
if leader == localClusterAddress {
logger.Info("Transferring leadership", logCtx)
err := gateway.TransferLeadership()
if err != nil {
return fmt.Errorf("Failed to transfer leadership: %w", err)
}
goto findLeader
}
logger.Info("Handing over cluster member role", logCtx)
client, err := cluster.Connect(leader, s.Endpoints.NetworkCert(), s.ServerCert(), nil, true)
if err != nil {
return fmt.Errorf("Failed handing over cluster member role: %w", err)
}
_, _, err = client.RawQuery("POST", "/internal/cluster/handover", post, "")
if err != nil {
return err
}
return nil
}
// Used to assign a new role to a the local dqlite node.
func internalClusterPostAssign(d *Daemon, r *http.Request) response.Response {
s := d.State()
req := internalClusterPostAssignRequest{}
// Parse the request
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
return response.BadRequest(err)
}
// Quick checks.
if len(req.RaftNodes) == 0 {
return response.BadRequest(errors.New("No raft members provided"))
}
nodes := make([]db.RaftNode, len(req.RaftNodes))
for i, node := range req.RaftNodes {
nodes[i].ID = node.ID
nodes[i].Address = node.Address
nodes[i].Role = db.RaftRole(node.Role)
nodes[i].Name = node.Name
}
err = cluster.Assign(s, d.gateway, nodes)
if err != nil {
return response.SmartError(err)
}
return response.SyncResponse(true, nil)
}
// A request for the /internal/cluster/assign endpoint.
type internalClusterPostAssignRequest struct {
RaftNodes []internalRaftNode `json:"raft_nodes" yaml:"raft_nodes"`
}
// Used to to transfer the responsibilities of a member to another one.
func internalClusterPostHandover(d *Daemon, r *http.Request) response.Response {
s := d.State()
req := internalClusterPostHandoverRequest{}
// Parse the request
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
return response.BadRequest(err)
}
// Quick checks.
if req.Address == "" {
return response.BadRequest(errors.New("No id provided"))
}
// Redirect all requests to the leader, which is the one with
// authoritative knowledge of the current raft configuration.
localClusterAddress := s.LocalConfig.ClusterAddress()
leader, err := s.Cluster.LeaderAddress()
if err != nil {
return response.InternalError(err)
}
if leader == "" {
return response.SmartError(errors.New("No leader address found"))
}
if localClusterAddress != leader {
logger.Debugf("Redirect handover request to %s", leader)
url := &url.URL{
Scheme: "https",
Path: "/internal/cluster/handover",
Host: leader,
}
return response.SyncResponseRedirect(url.String())
}
// Get lock now we are on leader.
d.clusterMembershipMutex.Lock()
defer d.clusterMembershipMutex.Unlock()
target, nodes, err := cluster.Handover(s, d.gateway, req.Address)
if err != nil {
return response.SmartError(err)
}
// If there's no other member we can promote, there's nothing we can
// do, just return.
if target == "" {
goto out
}
logger.Info("Promoting member during handover", logger.Ctx{"address": localClusterAddress, "losingAddress": req.Address, "candidateAddress": target})
err = changeMemberRole(s, r, target, nodes)
if err != nil {
return response.SmartError(err)
}
// Demote the member that is handing over.
for i, node := range nodes {
if node.Address == req.Address {
nodes[i].Role = db.RaftSpare
}
}
logger.Info("Demoting member during handover", logger.Ctx{"address": localClusterAddress, "losingAddress": req.Address})
err = changeMemberRole(s, r, req.Address, nodes)
if err != nil {
return response.SmartError(err)
}
out:
return response.SyncResponse(true, nil)
}
// A request for the /internal/cluster/handover endpoint.
type internalClusterPostHandoverRequest struct {
// Address of the server whose role should be transferred.
Address string `json:"address" yaml:"address"`
}
func clusterCheckStoragePoolsMatch(ctx context.Context, clusterDB *db.Cluster, reqPools []api.StoragePool) error {
return clusterDB.Transaction(ctx, func(ctx context.Context, tx *db.ClusterTx) error {
poolNames, err := tx.GetCreatedStoragePoolNames(ctx)
if err != nil && !response.IsNotFoundError(err) {
return err
}
for _, name := range poolNames {
found := false
for _, reqPool := range reqPools {
if reqPool.Name != name {
continue
}
found = true
var pool *api.StoragePool
_, pool, _, err = tx.GetStoragePoolInAnyState(ctx, name)
if err != nil {
return err
}
if pool.Driver != reqPool.Driver {
return fmt.Errorf("Mismatching driver for storage pool %s", name)
}
// Exclude the keys which are node-specific.
exclude := db.NodeSpecificStorageConfig
err = localUtil.CompareConfigs(pool.Config, reqPool.Config, exclude)
if err != nil {
return fmt.Errorf("Mismatching config for storage pool %s: %w", name, err)
}
break
}
if !found {
return fmt.Errorf("Missing storage pool %s", name)
}
}
return nil
})
}
func clusterCheckNetworksMatch(ctx context.Context, clusterDB *db.Cluster, reqNetworks []api.InitNetworksProjectPost) error {
return clusterDB.Transaction(ctx, func(ctx context.Context, tx *db.ClusterTx) error {
// Get a list of projects for networks.
networkProjectNames, err := dbCluster.GetProjectNames(ctx, tx.Tx())
if err != nil {
return fmt.Errorf("Failed to load projects for networks: %w", err)
}
for _, networkProjectName := range networkProjectNames {
networkNames, err := tx.GetCreatedNetworkNamesByProject(ctx, networkProjectName)
if err != nil && !response.IsNotFoundError(err) {
return err
}
for _, networkName := range networkNames {
_, network, _, err := tx.GetNetworkInAnyState(ctx, networkProjectName, networkName)
if err != nil {
return err
}
// OVN networks don't need local creation.
if network.Type == "ovn" {
continue
}
// Check that the network is present locally.
found := false
for _, reqNetwork := range reqNetworks {
if reqNetwork.Name != networkName || reqNetwork.Project != networkProjectName {
continue
}
found = true
if reqNetwork.Type != network.Type {
return fmt.Errorf("Mismatching type for network %q in project %q", networkName, networkProjectName)
}
// Exclude the keys which are node-specific.
networkConfigWithoutNodeSpecific := db.StripNodeSpecificNetworkConfig(network.Config)
reqNetworkConfigwithoutNodeSpecific := db.StripNodeSpecificNetworkConfig(reqNetwork.Config)
err = localUtil.CompareConfigs(networkConfigWithoutNodeSpecific, reqNetworkConfigwithoutNodeSpecific, nil)
if err != nil {
return fmt.Errorf("Mismatching config for network %q in project %q: %w", network.Name, networkProjectName, err)
}
break
}
if !found {
return fmt.Errorf("Missing network %q in project %q", networkName, networkProjectName)
}
}
}
return nil
})
}
// Used as low-level recovering helper.
func internalClusterRaftNodeDelete(d *Daemon, r *http.Request) response.Response {
s := d.State()
address, err := url.PathUnescape(mux.Vars(r)["address"])
if err != nil {
return response.SmartError(err)
}
err = cluster.RemoveRaftNode(d.gateway, address)
if err != nil {
return response.SmartError(err)
}
err = rebalanceMemberRoles(s, d.gateway, r, nil)
if err != nil && !errors.Is(err, cluster.ErrNotLeader) {
logger.Warn("Could not rebalance cluster member roles after raft member removal", logger.Ctx{"err": err})
}
return response.SyncResponse(true, nil)
}
// swagger:operation GET /1.0/cluster/members/{name}/state cluster cluster_member_state_get
//
// Get state of the cluster member
//
// Gets state of a specific cluster member.
//
// ---
// produces:
// - application/json
// responses:
// "200":
// description: Cluster member state
// schema:
// type: object
// description: Sync response
// properties:
// type:
// type: string
// description: Response type
// example: sync
// status:
// type: string
// description: Status description
// example: Success
// status_code:
// type: integer
// description: Status code
// example: 200
// metadata:
// $ref: "#/definitions/ClusterMemberState"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func clusterNodeStateGet(d *Daemon, r *http.Request) response.Response {
memberName, err := url.PathUnescape(mux.Vars(r)["name"])
if err != nil {
return response.SmartError(err)
}
s := d.State()
// Forward request.
resp := forwardedResponseToNode(s, r, memberName)
if resp != nil {
return resp
}
memberState, err := cluster.MemberState(r.Context(), s, memberName)
if err != nil {
return response.SmartError(err)
}
return response.SyncResponse(true, memberState)
}
// swagger:operation POST /1.0/cluster/members/{name}/state cluster cluster_member_state_post
//
// Evacuate or restore a cluster member
//
// Evacuates or restores a cluster member.
//
// ---
// consumes:
// - application/json
// produces:
// - application/json
// parameters:
// - in: body
// name: cluster
// description: Cluster member state
// required: true
// schema:
// $ref: "#/definitions/ClusterMemberStatePost"
// responses:
// "202":
// $ref: "#/responses/Operation"
// "400":
// $ref: "#/responses/BadRequest"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func clusterNodeStatePost(d *Daemon, r *http.Request) response.Response {
name, err := url.PathUnescape(mux.Vars(r)["name"])
if err != nil {
return response.SmartError(err)
}
s := d.State()
// Forward request.
resp := forwardedResponseToNode(s, r, name)
if resp != nil {
return resp
}
// Parse the request.
req := api.ClusterMemberStatePost{}
err = json.NewDecoder(r.Body).Decode(&req)
if err != nil {
return response.BadRequest(err)
}
// Validate the overrides.
if req.Action == "evacuate" && req.Mode != "" {
// Use the validator from the instance logic.
validator := internalInstance.InstanceConfigKeysAny["cluster.evacuate"]
err = validator(req.Mode)
if err != nil {
return response.BadRequest(err)
}
}
if req.Action == "evacuate" {
stopFunc := func(inst instance.Instance, action string) error {
l := logger.AddContext(logger.Ctx{"project": inst.Project().Name, "instance": inst.Name()})
if action == "force-stop" {
// Handle forced shutdown.
err = inst.Stop(false)
if err != nil && !errors.Is(err, instanceDrivers.ErrInstanceIsStopped) {
return fmt.Errorf("Failed to force stop instance %q in project %q: %w", inst.Name(), inst.Project().Name, err)
}
} else if action == "stateful-stop" {
// Handle stateful stop.
err = inst.Stop(true)
if err != nil && !errors.Is(err, instanceDrivers.ErrInstanceIsStopped) {
return fmt.Errorf("Failed to stateful stop instance %q in project %q: %w", inst.Name(), inst.Project().Name, err)
}
} else {
// Get the shutdown timeout for the instance.
timeout := inst.ExpandedConfig()["boot.host_shutdown_timeout"]
val, err := strconv.Atoi(timeout)
if err != nil {
val = evacuateHostShutdownDefaultTimeout
}
// Start with a clean shutdown.
err = inst.Shutdown(time.Duration(val) * time.Second)
if err != nil {
l.Warn("Failed shutting down instance, forcing stop", logger.Ctx{"err": err})
// Fallback to forced stop.
err = inst.Stop(false)
if err != nil && !errors.Is(err, instanceDrivers.ErrInstanceIsStopped) {
return fmt.Errorf("Failed to stop instance %q in project %q: %w", inst.Name(), inst.Project().Name, err)
}
}
}
// Mark the instance as RUNNING in volatile so its state can be properly restored.
err = inst.VolatileSet(map[string]string{"volatile.last_state.power": instance.PowerStateRunning})
if err != nil {
l.Warn("Failed to set instance state to RUNNING", logger.Ctx{"err": err})
}
return nil
}
migrateFunc := func(ctx context.Context, s *state.State, inst instance.Instance, sourceMemberInfo *db.NodeInfo, targetMemberInfo *db.NodeInfo, live bool, startInstance bool, metadata map[string]any, op *operations.Operation) error {
// Migrate the instance.
req := api.InstancePost{
Migration: true,
Live: live,
}
err := migrateInstance(ctx, s, inst, req, sourceMemberInfo, targetMemberInfo, "", op)
if err != nil {
return fmt.Errorf("Failed to migrate instance %q in project %q: %w", inst.Name(), inst.Project().Name, err)
}
if !startInstance || live {
return nil
}
// Start it back up on target.
dest, err := cluster.Connect(targetMemberInfo.Address, s.Endpoints.NetworkCert(), s.ServerCert(), r, true)
if err != nil {
return fmt.Errorf("Failed to connect to destination %q for instance %q in project %q: %w", targetMemberInfo.Address, inst.Name(), inst.Project().Name, err)
}
dest = dest.UseProject(inst.Project().Name)
if metadata != nil && op != nil {
metadata["evacuation_progress"] = fmt.Sprintf("Starting %q in project %q", inst.Name(), inst.Project().Name)
_ = op.UpdateMetadata(metadata)
}
startOp, err := dest.UpdateInstanceState(inst.Name(), api.InstanceStatePut{Action: "start"}, "")
if err != nil {
return err
}
err = startOp.Wait()
if err != nil {
return err
}
return nil
}
run := func(op *operations.Operation) error {
return evacuateClusterMember(context.Background(), s, op, name, req.Mode, stopFunc, migrateFunc)
}
op, err := operations.OperationCreate(s, "", operations.OperationClassTask, operationtype.ClusterMemberEvacuate, nil, nil, run, nil, nil, r)
if err != nil {
return response.SmartError(err)
}
return operations.OperationResponse(op)
} else if req.Action == "restore" {
return restoreClusterMember(d, r)
}
return response.BadRequest(fmt.Errorf("Unknown action %q", req.Action))
}
|