1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503
|
package storage
import (
"archive/zip"
"bytes"
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"net/url"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"time"
"github.com/minio/minio-go/v7"
"golang.org/x/sync/errgroup"
"gopkg.in/yaml.v2"
incus "github.com/lxc/incus/v6/client"
internalInstance "github.com/lxc/incus/v6/internal/instance"
"github.com/lxc/incus/v6/internal/instancewriter"
internalIO "github.com/lxc/incus/v6/internal/io"
"github.com/lxc/incus/v6/internal/linux"
"github.com/lxc/incus/v6/internal/migration"
"github.com/lxc/incus/v6/internal/server/backup"
backupConfig "github.com/lxc/incus/v6/internal/server/backup/config"
"github.com/lxc/incus/v6/internal/server/cluster/request"
"github.com/lxc/incus/v6/internal/server/db"
"github.com/lxc/incus/v6/internal/server/db/cluster"
deviceConfig "github.com/lxc/incus/v6/internal/server/device/config"
"github.com/lxc/incus/v6/internal/server/instance"
"github.com/lxc/incus/v6/internal/server/instance/instancetype"
"github.com/lxc/incus/v6/internal/server/lifecycle"
"github.com/lxc/incus/v6/internal/server/locking"
localMigration "github.com/lxc/incus/v6/internal/server/migration"
"github.com/lxc/incus/v6/internal/server/operations"
"github.com/lxc/incus/v6/internal/server/project"
"github.com/lxc/incus/v6/internal/server/response"
"github.com/lxc/incus/v6/internal/server/state"
"github.com/lxc/incus/v6/internal/server/storage/drivers"
"github.com/lxc/incus/v6/internal/server/storage/memorypipe"
"github.com/lxc/incus/v6/internal/server/storage/s3"
"github.com/lxc/incus/v6/internal/server/storage/s3/miniod"
localUtil "github.com/lxc/incus/v6/internal/server/util"
internalUtil "github.com/lxc/incus/v6/internal/util"
"github.com/lxc/incus/v6/shared/api"
"github.com/lxc/incus/v6/shared/ioprogress"
"github.com/lxc/incus/v6/shared/logger"
"github.com/lxc/incus/v6/shared/revert"
"github.com/lxc/incus/v6/shared/units"
"github.com/lxc/incus/v6/shared/util"
)
var (
unavailablePools = make(map[string]struct{})
unavailablePoolsMu = sync.Mutex{}
)
// ConnectIfInstanceIsRemote is a reference to cluster.ConnectIfInstanceIsRemote.
//
//nolint:typecheck
var ConnectIfInstanceIsRemote func(s *state.State, projectName string, instName string, r *http.Request) (incus.InstanceServer, error)
// instanceDiskVolumeEffectiveFields fields from the instance disks that are applied to the volume's effective
// config (but not stored in the disk's volume database record).
var instanceDiskVolumeEffectiveFields = []string{
"size",
"size.state",
}
type backend struct {
driver drivers.Driver
id int64
db api.StoragePool
name string
state *state.State
logger logger.Logger
nodes map[int64]db.StoragePoolNode
}
// ID returns the storage pool ID.
func (b *backend) ID() int64 {
return b.id
}
// Name returns the storage pool name.
func (b *backend) Name() string {
return b.name
}
// Description returns the storage pool description.
func (b *backend) Description() string {
return b.db.Description
}
// Validate storage pool config.
func (b *backend) Validate(config map[string]string) error {
return b.Driver().Validate(config)
}
// Status returns the storage pool status.
func (b *backend) Status() string {
return b.db.Status
}
// LocalStatus returns storage pool status of the local cluster member.
func (b *backend) LocalStatus() string {
// Check if pool is unavailable locally and replace status if so.
// But don't modify b.db.Status as the status may be recovered later so we don't want to persist it here.
if !IsAvailable(b.name) {
return api.StoragePoolStatusUnvailable
}
node, exists := b.nodes[b.state.DB.Cluster.GetNodeID()]
if !exists {
return api.StoragePoolStatusUnknown
}
return db.StoragePoolStateToAPIStatus(node.State)
}
// isStatusReady returns an error if pool is not ready for use on this server.
func (b *backend) isStatusReady() error {
if b.Status() == api.StoragePoolStatusPending {
return errors.New("Specified pool is not fully created")
}
if b.LocalStatus() == api.StoragePoolStatusUnvailable {
return api.StatusErrorf(http.StatusServiceUnavailable, "Storage pool is unavailable on this server")
}
return nil
}
// ToAPI returns the storage pool as an API representation.
func (b *backend) ToAPI() api.StoragePool {
return b.db
}
// Driver returns the storage pool driver.
func (b *backend) Driver() drivers.Driver {
return b.driver
}
// MigrationTypes returns the migration transport method preferred when sending a migration, based
// on the migration method requested by the driver's ability. The copySnapshots argument indicates
// whether snapshots are migrated as well. clusterMove determines whether the migration is done
// within a cluster and storageMove determines whether the storage pool is changed by the migration.
// This method is used to determine whether to use optimized migration.
func (b *backend) MigrationTypes(contentType drivers.ContentType, refresh bool, copySnapshots bool, clusterMove bool, storageMove bool) []localMigration.Type {
return b.driver.MigrationTypes(contentType, refresh, copySnapshots, clusterMove, storageMove)
}
// Create creates the storage pool layout on the storage device.
// localOnly is used for clustering where only a single node should do remote storage setup.
func (b *backend) Create(clientType request.ClientType, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"config": b.db.Config, "description": b.db.Description, "clientType": clientType})
l.Debug("Create started")
defer l.Debug("Create finished")
// Validate config.
err := b.driver.Validate(b.db.Config)
if err != nil {
return err
}
reverter := revert.New()
defer reverter.Fail()
path := drivers.GetPoolMountPath(b.name)
if internalUtil.IsDir(path) {
return fmt.Errorf("Storage pool directory %q already exists", path)
}
// Create the storage path.
err = os.MkdirAll(path, 0o711)
if err != nil {
return fmt.Errorf("Failed to create storage pool directory %q: %w", path, err)
}
reverter.Add(func() { _ = os.RemoveAll(path) })
if b.driver.Info().Remote && clientType != request.ClientTypeNormal {
if !b.driver.Info().MountedRoot {
// Create the directory structure.
err = b.createStorageStructure(path)
if err != nil {
return err
}
}
// Dealing with a remote storage pool, we're done now.
reverter.Success()
return nil
}
// Create the storage pool on the storage device.
err = b.driver.Create()
if err != nil {
return err
}
reverter.Add(func() { _ = b.driver.Delete(op) })
// Mount the storage pool.
ourMount, err := b.driver.Mount()
if err != nil {
return err
}
// We expect the caller of create to mount the pool if needed, so we should unmount after
// storage struct has been created.
if ourMount {
defer func() { _, _ = b.driver.Unmount() }()
}
// Create the directory structure.
err = b.createStorageStructure(path)
if err != nil {
return err
}
reverter.Success()
return nil
}
// GetVolume returns a drivers.Volume containing copies of the supplied volume config and the pools config.
func (b *backend) GetVolume(volType drivers.VolumeType, contentType drivers.ContentType, volName string, volConfig map[string]string) drivers.Volume {
return drivers.NewVolume(b.driver, b.name, volType, contentType, volName, volConfig, b.db.Config).Clone()
}
// GetResources returns utilisation information about the pool.
func (b *backend) GetResources() (*api.ResourcesStoragePool, error) {
l := b.logger.AddContext(nil)
l.Debug("GetResources started")
defer l.Debug("GetResources finished")
if b.Status() == api.StoragePoolStatusPending {
return nil, errors.New("The pool is in pending state")
}
return b.driver.GetResources()
}
// IsUsed returns whether the storage pool is used by any volumes or profiles (excluding image volumes).
func (b *backend) IsUsed() (bool, error) {
usedBy, err := UsedBy(context.TODO(), b.state, b, true, true, db.StoragePoolVolumeTypeNameImage)
if err != nil {
return false, err
}
return len(usedBy) > 0, nil
}
// Update updates the pool config.
func (b *backend) Update(clientType request.ClientType, newDesc string, newConfig map[string]string, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"newDesc": newDesc, "newConfig": newConfig})
l.Debug("Update started")
defer l.Debug("Update finished")
// Validate config.
err := b.driver.Validate(newConfig)
if err != nil {
return err
}
// Diff the configurations.
changedConfig, userOnly := b.detectChangedConfig(b.db.Config, newConfig)
// Check if the pool source is being changed that the local state is still pending, otherwise prevent it.
_, sourceChanged := changedConfig["source"]
if sourceChanged && b.LocalStatus() != api.StoragePoolStatusPending {
return errors.New("Pool source cannot be changed when not in pending state")
}
// Prevent shrinking the storage pool.
newSize, sizeChanged := changedConfig["size"]
if sizeChanged {
oldSizeBytes, _ := units.ParseByteSizeString(b.db.Config["size"])
newSizeBytes, _ := units.ParseByteSizeString(newSize)
if newSizeBytes < oldSizeBytes {
return errors.New("Pool cannot be shrunk")
}
}
// Apply changes to local member if both global pool and node are not pending and non-user config changed.
// Otherwise just apply changes to DB (below) ready for the actual global create request to be initiated.
if len(changedConfig) > 0 && b.Status() != api.StoragePoolStatusPending && b.LocalStatus() != api.StoragePoolStatusPending && !userOnly {
err = b.driver.Update(changedConfig)
if err != nil {
return err
}
}
// Update the database if something changed and we're in ClientTypeNormal mode.
if clientType == request.ClientTypeNormal && (len(changedConfig) > 0 || newDesc != b.db.Description) {
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.UpdateStoragePool(ctx, b.name, newDesc, newConfig)
})
if err != nil {
return err
}
}
return nil
}
// warningsDelete deletes any persistent warnings for the pool.
func (b *backend) warningsDelete() error {
err := b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return cluster.DeleteWarnings(ctx, tx.Tx(), cluster.TypeStoragePool, int(b.ID()))
})
if err != nil {
return fmt.Errorf("Failed deleting persistent warnings: %w", err)
}
return nil
}
// Delete removes the pool.
func (b *backend) Delete(clientType request.ClientType, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"clientType": clientType})
l.Debug("Delete started")
defer l.Debug("Delete finished")
// Delete any persistent warnings for pool.
err := b.warningsDelete()
if err != nil {
return err
}
// If completely gone, just return
path := internalUtil.VarPath("storage-pools", b.name)
if !util.PathExists(path) {
return nil
}
if clientType != request.ClientTypeNormal && b.driver.Info().Remote {
if b.driver.Info().Deactivate || b.driver.Info().MountedRoot {
_, err := b.driver.Unmount()
if err != nil {
return err
}
}
if !b.driver.Info().MountedRoot {
// Remote storage may have leftover entries caused by
// volumes that were moved or delete while a particular system was offline.
err := os.RemoveAll(path)
if err != nil {
return err
}
}
} else {
// Remove any left over image volumes.
// This can occur during partial image unpack or if the storage pool has been recovered from an
// instance backup file and the image volume DB records were not restored.
// If non-image volumes exist, we don't delete the, even if they can then prevent the storage pool
// from being deleted, because they should not exist by this point and we don't want to end up
// removing an instance or custom volume accidentally.
// Errors listing volumes are ignored, as we should still try and delete the storage pool.
vols, _ := b.driver.ListVolumes()
for _, vol := range vols {
if vol.Type() == drivers.VolumeTypeImage {
err := b.driver.DeleteVolume(vol, op)
if err != nil {
return fmt.Errorf("Failed deleting left over image volume %q (%s): %w", vol.Name(), vol.ContentType(), err)
}
l.Warn("Deleted left over image volume", logger.Ctx{"volName": vol.Name(), "contentType": vol.ContentType()})
}
}
// Delete the low-level storage.
err := b.driver.Delete(op)
if err != nil {
return err
}
}
// Delete the mountpoint.
err = os.Remove(path)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf("Failed to remove directory %q: %w", path, err)
}
unavailablePoolsMu.Lock()
delete(unavailablePools, b.Name())
unavailablePoolsMu.Unlock()
return nil
}
// Mount mounts the storage pool.
func (b *backend) Mount() (bool, error) {
b.logger.Debug("Mount started")
defer b.logger.Debug("Mount finished")
reverter := revert.New()
defer reverter.Fail()
reverter.Add(func() {
unavailablePoolsMu.Lock()
unavailablePools[b.Name()] = struct{}{}
unavailablePoolsMu.Unlock()
})
path := drivers.GetPoolMountPath(b.name)
// Create the storage path if needed.
if !internalUtil.IsDir(path) {
err := os.MkdirAll(path, 0o711)
if err != nil {
return false, fmt.Errorf("Failed to create storage pool directory %q: %w", path, err)
}
}
ourMount, err := b.driver.Mount()
if err != nil {
return false, err
}
if ourMount {
reverter.Add(func() { _, _ = b.Unmount() })
}
// Create the directory structure (if needed) after mounted.
err = b.createStorageStructure(path)
if err != nil {
return false, err
}
reverter.Success()
// Ensure pool is marked as available now its mounted.
unavailablePoolsMu.Lock()
delete(unavailablePools, b.Name())
unavailablePoolsMu.Unlock()
return ourMount, nil
}
// Unmount unmounts the storage pool.
func (b *backend) Unmount() (bool, error) {
b.logger.Debug("Unmount started")
defer b.logger.Debug("Unmount finished")
return b.driver.Unmount()
}
// ApplyPatch runs the requested patch at both backend and driver level.
func (b *backend) ApplyPatch(name string) error {
b.logger.Info("Applying patch", logger.Ctx{"name": name})
// Run early backend patches.
patch, ok := earlyPatches[name]
if ok {
err := patch(b)
if err != nil {
return err
}
}
// Run the driver patch itself.
err := b.driver.ApplyPatch(name)
if err != nil {
return err
}
// Run late backend patches.
patch, ok = latePatches[name]
if ok {
err := patch(b)
if err != nil {
return err
}
}
return nil
}
// ensureInstanceSymlink creates a symlink in the instance directory to the instance's mount path
// if doesn't exist already.
func (b *backend) ensureInstanceSymlink(instanceType instancetype.Type, projectName string, instanceName string, mountPath string) error {
if internalInstance.IsSnapshot(instanceName) {
return errors.New("Instance must not be snapshot")
}
symlinkPath := InstancePath(instanceType, projectName, instanceName, false)
// Remove any old symlinks left over by previous bugs that may point to a different pool.
if util.PathExists(symlinkPath) {
err := os.Remove(symlinkPath)
if err != nil {
return fmt.Errorf("Failed to remove symlink %q: %w", symlinkPath, err)
}
}
// Create new symlink.
err := os.Symlink(mountPath, symlinkPath)
if err != nil {
return fmt.Errorf("Failed to create symlink from %q to %q: %w", mountPath, symlinkPath, err)
}
return nil
}
// removeInstanceSymlink removes a symlink in the instance directory to the instance's mount path.
func (b *backend) removeInstanceSymlink(instanceType instancetype.Type, projectName string, instanceName string) error {
symlinkPath := InstancePath(instanceType, projectName, instanceName, false)
if util.PathExists(symlinkPath) {
err := os.Remove(symlinkPath)
if err != nil {
return fmt.Errorf("Failed to remove symlink %q: %w", symlinkPath, err)
}
}
return nil
}
// ensureInstanceSnapshotSymlink creates a symlink in the snapshot directory to the instance's
// snapshot path if doesn't exist already.
func (b *backend) ensureInstanceSnapshotSymlink(instanceType instancetype.Type, projectName string, instanceName string) error {
// Check we can convert the instance to the volume type needed.
volType, err := InstanceTypeToVolumeType(instanceType)
if err != nil {
return err
}
parentName, _, _ := api.GetParentAndSnapshotName(instanceName)
snapshotSymlink := InstancePath(instanceType, projectName, parentName, true)
volStorageName := project.Instance(projectName, parentName)
snapshotTargetPath := drivers.GetVolumeSnapshotDir(b.name, volType, volStorageName)
// Remove any old symlinks left over by previous bugs that may point to a different pool.
if util.PathExists(snapshotSymlink) {
err = os.Remove(snapshotSymlink)
if err != nil {
return fmt.Errorf("Failed to remove symlink %q: %w", snapshotSymlink, err)
}
}
// Create new symlink.
err = os.Symlink(snapshotTargetPath, snapshotSymlink)
if err != nil {
return fmt.Errorf("Failed to create symlink from %q to %q: %w", snapshotTargetPath, snapshotSymlink, err)
}
return nil
}
// removeInstanceSnapshotSymlinkIfUnused removes the symlink in the snapshot directory to the
// instance's snapshot path if the snapshot path is missing. It is expected that the driver will
// remove the instance's snapshot path after the last snapshot is removed or the volume is deleted.
func (b *backend) removeInstanceSnapshotSymlinkIfUnused(instanceType instancetype.Type, projectName string, instanceName string) error {
// Check we can convert the instance to the volume type needed.
volType, err := InstanceTypeToVolumeType(instanceType)
if err != nil {
return err
}
parentName, _, _ := api.GetParentAndSnapshotName(instanceName)
snapshotSymlink := InstancePath(instanceType, projectName, parentName, true)
volStorageName := project.Instance(projectName, parentName)
snapshotTargetPath := drivers.GetVolumeSnapshotDir(b.name, volType, volStorageName)
// If snapshot parent directory doesn't exist, remove symlink.
if !util.PathExists(snapshotTargetPath) {
if util.PathExists(snapshotSymlink) {
err := os.Remove(snapshotSymlink)
if err != nil {
return fmt.Errorf("Failed to remove symlink %q: %w", snapshotSymlink, err)
}
}
}
return nil
}
// applyInstanceRootDiskOverrides applies the instance's root disk config to the volume's config.
func (b *backend) applyInstanceRootDiskOverrides(inst instance.Instance, vol *drivers.Volume) error {
_, rootDiskConf, err := internalInstance.GetRootDiskDevice(inst.ExpandedDevices().CloneNative())
if err != nil {
return err
}
for _, k := range instanceDiskVolumeEffectiveFields {
if rootDiskConf[k] != "" {
switch k {
case "size":
vol.SetConfigSize(rootDiskConf[k])
case "size.state":
vol.SetConfigStateSize(rootDiskConf[k])
default:
return fmt.Errorf("Unsupported instance disk volume override field %q", k)
}
}
}
return nil
}
// applyInstanceRootDiskInitialValues applies the instance's root disk initial config to the volume's config.
func (b *backend) applyInstanceRootDiskInitialValues(inst instance.Instance, volConfig map[string]string) error {
_, rootDiskConf, err := internalInstance.GetRootDiskDevice(inst.ExpandedDevices().CloneNative())
if err != nil {
return err
}
for k, v := range rootDiskConf {
prefix, newKey, found := strings.Cut(k, "initial.")
if found && prefix == "" {
volConfig[newKey] = v
}
}
return nil
}
// CreateInstance creates an empty instance.
func (b *backend) CreateInstance(inst instance.Instance, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": inst.Project().Name, "instance": inst.Name()})
l.Debug("CreateInstance started")
defer l.Debug("CreateInstance finished")
err := b.isStatusReady()
if err != nil {
return err
}
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return err
}
contentType := InstanceContentType(inst)
reverter := revert.New()
defer reverter.Fail()
volumeConfig := make(map[string]string)
err = b.applyInstanceRootDiskInitialValues(inst, volumeConfig)
if err != nil {
return err
}
// Validate config and create database entry for new storage volume.
err = VolumeDBCreate(b, inst.Project().Name, inst.Name(), "", volType, false, volumeConfig, inst.CreationDate(), time.Time{}, contentType, true, false)
if err != nil {
return err
}
reverter.Add(func() { _ = VolumeDBDelete(b, inst.Project().Name, inst.Name(), volType) })
// Record new volume with authorizer.
err = b.state.Authorizer.AddStoragePoolVolume(b.state.ShutdownCtx, inst.Project().Name, b.Name(), volType.Singular(), inst.Name(), "")
if err != nil {
logger.Error("Failed to add storage volume to authorizer", logger.Ctx{"name": inst.Name(), "type": volType, "pool": b.Name(), "project": inst.Project().Name, "error": err})
}
reverter.Add(func() {
_ = b.state.Authorizer.DeleteStoragePoolVolume(b.state.ShutdownCtx, inst.Project().Name, b.Name(), volType.Singular(), inst.Name(), "")
})
// Generate the effective root device volume for instance.
volStorageName := project.Instance(inst.Project().Name, inst.Name())
vol := b.GetVolume(volType, contentType, volStorageName, volumeConfig)
err = b.applyInstanceRootDiskOverrides(inst, &vol)
if err != nil {
return err
}
var filler *drivers.VolumeFiller
if inst.Type() == instancetype.Container {
filler = &drivers.VolumeFiller{
Fill: func(vol drivers.Volume, rootBlockPath string, allowUnsafeResize bool) (int64, error) {
// Create an empty rootfs.
err := os.Mkdir(filepath.Join(vol.MountPath(), "rootfs"), 0o755)
if err != nil && !os.IsExist(err) {
return 0, err
}
return 0, nil
},
}
}
err = b.driver.CreateVolume(vol, filler, op)
if err != nil {
return err
}
reverter.Add(func() { _ = b.DeleteInstance(inst, op) })
err = b.ensureInstanceSymlink(inst.Type(), inst.Project().Name, inst.Name(), vol.MountPath())
if err != nil {
return err
}
err = inst.DeferTemplateApply(instance.TemplateTriggerCreate)
if err != nil {
return err
}
reverter.Success()
return nil
}
// CreateInstanceFromBackup restores a backup file onto the storage device. Because the backup file
// is unpacked and restored onto the storage device before the instance is created in the database
// it is necessary to return two functions; a post hook that can be run once the instance has been
// created in the database to run any storage layer finalisations, and a revert hook that can be
// run if the instance database load process fails that will remove anything created thus far.
func (b *backend) CreateInstanceFromBackup(srcBackup backup.Info, srcData io.ReadSeeker, op *operations.Operation) (func(instance.Instance) error, revert.Hook, error) {
l := b.logger.AddContext(logger.Ctx{"project": srcBackup.Project, "instance": srcBackup.Name, "snapshots": srcBackup.Snapshots, "optimizedStorage": *srcBackup.OptimizedStorage})
l.Debug("CreateInstanceFromBackup started")
defer l.Debug("CreateInstanceFromBackup finished")
// Get the volume name on storage.
volStorageName := project.Instance(srcBackup.Project, srcBackup.Name)
// Get the instance type.
instanceType, err := instancetype.New(string(srcBackup.Type))
if err != nil {
return nil, nil, err
}
// Get the volume type.
volType, err := InstanceTypeToVolumeType(instanceType)
if err != nil {
return nil, nil, err
}
contentType := drivers.ContentTypeFS
if volType == drivers.VolumeTypeVM {
contentType = drivers.ContentTypeBlock
}
var volumeConfig map[string]string
if srcBackup.Config != nil && srcBackup.Config.Volume != nil {
volumeConfig = srcBackup.Config.Volume.Config
}
// Get instance root size information.
if srcBackup.Config != nil && srcBackup.Config.Container != nil {
_, rootConfig, err := internalInstance.GetRootDiskDevice(srcBackup.Config.Container.ExpandedDevices)
if err == nil && rootConfig["size"] != "" {
if volumeConfig == nil {
volumeConfig = map[string]string{}
}
volumeConfig["size"] = rootConfig["size"]
}
}
vol := b.GetVolume(volType, contentType, volStorageName, volumeConfig)
importRevert := revert.New()
defer importRevert.Fail()
// Unpack the backup into the new storage volume(s).
volPostHook, revertHook, err := b.driver.CreateVolumeFromBackup(vol, srcBackup, srcData, op)
if err != nil {
return nil, nil, err
}
if revertHook != nil {
importRevert.Add(revertHook)
}
err = b.ensureInstanceSymlink(instanceType, srcBackup.Project, srcBackup.Name, vol.MountPath())
if err != nil {
return nil, nil, err
}
importRevert.Add(func() {
_ = b.removeInstanceSymlink(instanceType, srcBackup.Project, srcBackup.Name)
})
if len(srcBackup.Snapshots) > 0 {
err = b.ensureInstanceSnapshotSymlink(instanceType, srcBackup.Project, srcBackup.Name)
if err != nil {
return nil, nil, err
}
importRevert.Add(func() {
_ = b.removeInstanceSnapshotSymlinkIfUnused(instanceType, srcBackup.Project, srcBackup.Name)
})
}
// Make sure the size isn't part of the instance volume after initial creation.
if volumeConfig != nil {
delete(volumeConfig, "size")
}
// Update information in the backup.yaml file.
err = vol.MountTask(func(mountPath string, op *operations.Operation) error {
return backup.UpdateInstanceConfig(b.state.DB.Cluster, srcBackup, mountPath)
}, op)
if err != nil {
return nil, nil, fmt.Errorf("Error updating backup file: %w", err)
}
// Create a post hook function that will use the instance (that will be created) to setup a new volume
// containing the instance's root disk device's config so that the driver's post hook function can access
// that config to perform any post instance creation setup.
postHook := func(inst instance.Instance) error {
l.Debug("CreateInstanceFromBackup post hook started")
defer l.Debug("CreateInstanceFromBackup post hook finished")
postHookRevert := revert.New()
defer postHookRevert.Fail()
// Create database entry for new storage volume.
var volumeDescription string
var volumeConfig map[string]string
volumeCreationDate := inst.CreationDate()
if srcBackup.Config != nil && srcBackup.Config.Volume != nil {
// If the backup restore interface provides volume config use it, otherwise use
// default volume config for the storage pool.
volumeDescription = srcBackup.Config.Volume.Description
volumeConfig = srcBackup.Config.Volume.Config
// Use volume's creation date if available.
if !srcBackup.Config.Volume.CreatedAt.IsZero() {
volumeCreationDate = srcBackup.Config.Volume.CreatedAt
}
}
// Validate config and create database entry for new storage volume.
// Strip unsupported config keys (in case the export was made from a different type of storage pool).
err = VolumeDBCreate(b, inst.Project().Name, inst.Name(), volumeDescription, volType, false, volumeConfig, volumeCreationDate, time.Time{}, contentType, true, true)
if err != nil {
return err
}
postHookRevert.Add(func() { _ = VolumeDBDelete(b, inst.Project().Name, inst.Name(), volType) })
// Record new volume with authorizer.
err = b.state.Authorizer.AddStoragePoolVolume(b.state.ShutdownCtx, inst.Project().Name, b.Name(), volType.Singular(), inst.Name(), "")
if err != nil {
logger.Error("Failed to add storage volume to authorizer", logger.Ctx{"name": inst.Name(), "type": volType, "pool": b.Name(), "project": inst.Project().Name, "error": err})
}
postHookRevert.Add(func() {
_ = b.state.Authorizer.DeleteStoragePoolVolume(b.state.ShutdownCtx, inst.Project().Name, b.Name(), volType.Singular(), inst.Name(), "")
})
for i, backupFileSnap := range srcBackup.Snapshots {
var volumeSnapDescription string
var volumeSnapConfig map[string]string
var volumeSnapExpiryDate time.Time
var volumeSnapCreationDate time.Time
// Check if snapshot volume config is available for restore and matches snapshot name.
if srcBackup.Config != nil {
if len(srcBackup.Config.Snapshots) >= i-1 && srcBackup.Config.Snapshots[i] != nil && srcBackup.Config.Snapshots[i].Name == backupFileSnap {
// Use instance snapshot's creation date if snap info available.
volumeSnapCreationDate = srcBackup.Config.Snapshots[i].CreatedAt
}
if len(srcBackup.Config.VolumeSnapshots) >= i-1 && srcBackup.Config.VolumeSnapshots[i] != nil && srcBackup.Config.VolumeSnapshots[i].Name == backupFileSnap {
// If the backup restore interface provides volume snapshot config use it,
// otherwise use default volume config for the storage pool.
volumeSnapDescription = srcBackup.Config.VolumeSnapshots[i].Description
volumeSnapConfig = srcBackup.Config.VolumeSnapshots[i].Config
if srcBackup.Config.VolumeSnapshots[i].ExpiresAt != nil {
volumeSnapExpiryDate = *srcBackup.Config.VolumeSnapshots[i].ExpiresAt
}
// Use volume's creation date if available.
if !srcBackup.Config.VolumeSnapshots[i].CreatedAt.IsZero() {
volumeSnapCreationDate = srcBackup.Config.VolumeSnapshots[i].CreatedAt
}
}
}
newSnapshotName := drivers.GetSnapshotVolumeName(inst.Name(), backupFileSnap)
// Validate config and create database entry for new storage volume.
// Strip unsupported config keys (in case the export was made from a different type of storage pool).
err = VolumeDBCreate(b, inst.Project().Name, newSnapshotName, volumeSnapDescription, volType, true, volumeSnapConfig, volumeSnapCreationDate, volumeSnapExpiryDate, contentType, true, true)
if err != nil {
return err
}
postHookRevert.Add(func() { _ = VolumeDBDelete(b, inst.Project().Name, newSnapshotName, volType) })
}
// Generate the effective root device volume for instance.
volStorageName := project.Instance(inst.Project().Name, inst.Name())
vol := b.GetVolume(volType, contentType, volStorageName, volumeConfig)
err = b.applyInstanceRootDiskOverrides(inst, &vol)
if err != nil {
return err
}
// Save any changes that have occurred to the instance's config to the on-disk backup.yaml file.
err = b.UpdateInstanceBackupFile(inst, false, op)
if err != nil {
return fmt.Errorf("Failed updating backup file: %w", err)
}
// If the driver returned a post hook, run it now.
if volPostHook != nil {
// Initialize new volume containing root disk config supplied in instance.
err = volPostHook(vol)
if err != nil {
return err
}
}
rootDiskConf := vol.Config()
// Apply quota config from root device if its set. Should be done after driver's post hook if set
// so that any volume initialisation has been completed first.
if rootDiskConf["size"] != "" {
size := rootDiskConf["size"]
l.Debug("Applying volume quota from root disk config", logger.Ctx{"size": size})
allowUnsafeResize := false
if vol.Type() == drivers.VolumeTypeContainer {
// Enable allowUnsafeResize for container imports so that filesystem resize
// safety checks are avoided in order to allow more imports to succeed when
// otherwise the pre-resize estimated checks of resize2fs would prevent
// import. If there is truly insufficient size to complete the import the
// resize will still fail, but its OK as we will then delete the volume
// rather than leaving it in a corrupted state. We don't need to do this
// for non-container volumes (nor should we) because block volumes won't
// error if we shrink them too much, and custom volumes can be created at
// the correct size immediately and don't need a post-import resize step.
allowUnsafeResize = true
}
err = b.driver.SetVolumeQuota(vol, size, allowUnsafeResize, op)
if err != nil {
// The restored volume can end up being larger than the root disk config's size
// property due to the block boundary rounding some storage drivers use. As such
// if the restored volume is larger than the config's size and it cannot be shrunk
// to the equivalent size on the target storage driver, don't fail as the backup
// has still been restored successfully.
if errors.Is(err, drivers.ErrCannotBeShrunk) {
l.Warn("Could not apply volume quota from root disk config as restored volume cannot be shrunk", logger.Ctx{"size": size})
} else {
return fmt.Errorf("Failed applying volume quota to root disk: %w", err)
}
}
// Apply the filesystem volume quota (only when main volume is block).
if vol.IsVMBlock() {
vmStateSize := rootDiskConf["size.state"]
// Apply default VM config filesystem size if main volume size is specified and
// no custom vmStateSize is specified. This way if the main volume size is empty
// (i.e removing quota) then this will also pass empty quota for the config
// filesystem volume as well, allowing a former quota to be removed from both
// volumes.
if vmStateSize == "" && size != "" {
vmStateSize = b.driver.Info().DefaultVMBlockFilesystemSize
}
l.Debug("Applying filesystem volume quota from root disk config", logger.Ctx{"size.state": vmStateSize})
fsVol := vol.NewVMBlockFilesystemVolume()
err := b.driver.SetVolumeQuota(fsVol, vmStateSize, allowUnsafeResize, op)
if errors.Is(err, drivers.ErrCannotBeShrunk) {
l.Warn("Could not apply VM filesystem volume quota from root disk config as restored volume cannot be shrunk", logger.Ctx{"size": vmStateSize})
} else if err != nil {
return fmt.Errorf("Failed applying filesystem volume quota to root disk: %w", err)
}
}
}
postHookRevert.Success()
return nil
}
importRevert.Success()
return postHook, revertHook, nil
}
// CreateInstanceFromCopy copies an instance volume and optionally its snapshots to new volume(s).
func (b *backend) CreateInstanceFromCopy(inst instance.Instance, src instance.Instance, snapshots bool, allowInconsistent bool, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": inst.Project().Name, "instance": inst.Name(), "src": src.Name(), "snapshots": snapshots})
l.Debug("CreateInstanceFromCopy started")
defer l.Debug("CreateInstanceFromCopy finished")
err := b.isStatusReady()
if err != nil {
return err
}
if inst.Type() != src.Type() {
return errors.New("Instance types must match")
}
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return err
}
contentType := InstanceContentType(inst)
// Get the source storage pool.
srcPool, err := LoadByInstance(b.state, src)
if err != nil {
return err
}
srcPoolBackend, ok := srcPool.(*backend)
if !ok {
return errors.New("Source pool is not a backend")
}
// Check source volume exists, and get its config.
srcConfig, err := srcPool.GenerateInstanceBackupConfig(src, snapshots, op)
if err != nil {
return fmt.Errorf("Failed generating instance copy config: %w", err)
}
// If we are copying snapshots, retrieve a list of snapshots from source volume.
var snapshotNames []string
if snapshots {
snapshotNames = make([]string, 0, len(srcConfig.VolumeSnapshots))
for _, snapshot := range srcConfig.VolumeSnapshots {
snapshotNames = append(snapshotNames, snapshot.Name)
}
}
volStorageName := project.Instance(inst.Project().Name, inst.Name())
vol := b.GetVolume(volType, contentType, volStorageName, srcConfig.Volume.Config)
volExists, err := b.driver.HasVolume(vol)
if err != nil {
return err
}
if volExists {
return errors.New("Cannot create volume, already exists on target storage")
}
// Setup reverter.
reverter := revert.New()
defer reverter.Fail()
// Some driver backing stores require that running instances be frozen during copy.
if !src.IsSnapshot() && srcPoolBackend.driver.Info().RunningCopyFreeze && src.IsRunning() && !src.IsFrozen() && !allowInconsistent {
b.logger.Info("Freezing instance for consistent copy")
err = src.Freeze()
if err != nil {
return err
}
defer func() { _ = src.Unfreeze() }()
// Attempt to sync the filesystem.
_ = linux.SyncFS(src.RootfsPath())
}
reverter.Add(func() { _ = b.DeleteInstance(inst, op) })
if b.Name() == srcPool.Name() {
l.Debug("CreateInstanceFromCopy same-pool mode detected")
// Get the src volume name on storage.
srcVolStorageName := project.Instance(src.Project().Name, src.Name())
srcVol := b.GetVolume(volType, contentType, srcVolStorageName, srcConfig.Volume.Config)
// Validate config and create database entry for new storage volume.
err = VolumeDBCreate(b, inst.Project().Name, inst.Name(), "", vol.Type(), false, vol.Config(), inst.CreationDate(), time.Time{}, contentType, false, true)
if err != nil {
return err
}
reverter.Add(func() { _ = VolumeDBDelete(b, inst.Project().Name, inst.Name(), volType) })
// Record new volume with authorizer.
err = b.state.Authorizer.AddStoragePoolVolume(b.state.ShutdownCtx, inst.Project().Name, b.Name(), volType.Singular(), inst.Name(), "")
if err != nil {
logger.Error("Failed to add storage volume to authorizer", logger.Ctx{"name": inst.Name(), "type": volType, "pool": b.Name(), "project": inst.Project().Name, "error": err})
}
reverter.Add(func() {
_ = b.state.Authorizer.DeleteStoragePoolVolume(b.state.ShutdownCtx, inst.Project().Name, b.Name(), volType.Singular(), inst.Name(), "")
})
// Create database entries for new storage volume snapshots.
for i, snapName := range snapshotNames {
newSnapshotName := drivers.GetSnapshotVolumeName(inst.Name(), snapName)
var volumeSnapExpiryDate time.Time
if srcConfig.VolumeSnapshots[i].ExpiresAt != nil {
volumeSnapExpiryDate = *srcConfig.VolumeSnapshots[i].ExpiresAt
}
// Validate config and create database entry for new storage volume.
err = VolumeDBCreate(b, inst.Project().Name, newSnapshotName, srcConfig.VolumeSnapshots[i].Description, vol.Type(), true, srcConfig.VolumeSnapshots[i].Config, srcConfig.VolumeSnapshots[i].CreatedAt, volumeSnapExpiryDate, vol.ContentType(), false, true)
if err != nil {
return err
}
reverter.Add(func() { _ = VolumeDBDelete(b, inst.Project().Name, newSnapshotName, vol.Type()) })
}
// Generate the effective root device volume for instance.
err = b.applyInstanceRootDiskOverrides(inst, &vol)
if err != nil {
return err
}
err = b.driver.CreateVolumeFromCopy(vol, srcVol, snapshots, allowInconsistent, op)
if err != nil {
return err
}
} else {
// We are copying volumes between storage pools so use migration system as it will
// be able to negotiate a common transfer method between pool types.
l.Debug("CreateInstanceFromCopy cross-pool mode detected")
// Negotiate the migration type to use.
offeredTypes := srcPool.MigrationTypes(contentType, false, snapshots, false, true)
offerHeader := localMigration.TypesToHeader(offeredTypes...)
migrationTypes, err := localMigration.MatchTypes(offerHeader, FallbackMigrationType(contentType), b.MigrationTypes(contentType, false, snapshots, false, true))
if err != nil {
return fmt.Errorf("Failed to negotiate copy migration type: %w", err)
}
var srcVolumeSize int64
// For VMs, get source volume size so that target can create the volume the same size.
if src.Type() == instancetype.VM {
srcVolumeSize, err = InstanceDiskBlockSize(srcPool, src, op)
if err != nil {
return fmt.Errorf("Failed getting source disk size: %w", err)
}
}
var migrationSnapshots []*migration.Snapshot
if snapshots {
migrationSnapshots, err = VolumeSnapshotsToMigrationSnapshots(srcConfig.VolumeSnapshots, inst.Project().Name, srcPool, contentType, volType, src.Name())
if err != nil {
return err
}
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Run sender and receiver in separate go routines to prevent deadlocks.
g, ctx := errgroup.WithContext(ctx)
// Use in-memory pipe pair to simulate a connection between the sender and receiver.
// Use context from error group so that if either side fails the pipes are closed.
aEnd, bEnd := memorypipe.NewPipePair(ctx)
// Start each side of the migration concurrently and collect any errors.
g.Go(func() error {
return srcPool.MigrateInstance(src, aEnd, &localMigration.VolumeSourceArgs{
IndexHeaderVersion: localMigration.IndexHeaderVersion,
Name: src.Name(),
Snapshots: snapshotNames,
MigrationType: migrationTypes[0],
TrackProgress: true, // Do use a progress tracker on sender.
AllowInconsistent: allowInconsistent,
VolumeOnly: !snapshots,
Info: &localMigration.Info{Config: srcConfig},
StorageMove: true,
}, op)
})
g.Go(func() error {
return b.CreateInstanceFromMigration(inst, bEnd, localMigration.VolumeTargetArgs{
IndexHeaderVersion: localMigration.IndexHeaderVersion,
Name: inst.Name(),
Snapshots: migrationSnapshots,
MigrationType: migrationTypes[0],
VolumeSize: srcVolumeSize, // Block size setting override.
TrackProgress: false, // Do not use a progress tracker on receiver.
VolumeOnly: !snapshots,
StoragePool: srcPool.Name(),
}, op)
})
err = g.Wait()
if err != nil {
return fmt.Errorf("Create instance volume from copy failed: %w", err)
}
}
// Setup the symlinks.
err = b.ensureInstanceSymlink(inst.Type(), inst.Project().Name, inst.Name(), vol.MountPath())
if err != nil {
return err
}
if len(snapshotNames) > 0 {
err = b.ensureInstanceSnapshotSymlink(inst.Type(), inst.Project().Name, inst.Name())
if err != nil {
return err
}
}
reverter.Success()
return nil
}
// RefreshCustomVolume refreshes custom volumes (and optionally snapshots) during the custom volume copy operations.
// Snapshots that are not present in the source but are in the destination are removed from the
// destination if snapshots are included in the synchronization.
func (b *backend) RefreshCustomVolume(projectName string, srcProjectName string, volName string, desc string, config map[string]string, srcPoolName, srcVolName string, snapshots bool, excludeOlder bool, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": projectName, "srcProjectName": srcProjectName, "volName": volName, "desc": desc, "config": config, "srcPoolName": srcPoolName, "srcVolName": srcVolName, "snapshots": snapshots})
l.Debug("RefreshCustomVolume started")
defer l.Debug("RefreshCustomVolume finished")
err := b.isStatusReady()
if err != nil {
return err
}
if srcProjectName == "" {
srcProjectName = projectName
}
// Setup the source pool backend instance.
var srcPool Pool
if b.name == srcPoolName {
srcPool = b // Source and target are in the same pool so share pool var.
} else {
// Source is in a different pool to target, so load the pool.
srcPool, err = LoadByName(b.state, srcPoolName)
if err != nil {
return err
}
}
// Check source volume exists and is custom type, and get its config.
srcConfig, err := srcPool.GenerateCustomVolumeBackupConfig(srcProjectName, srcVolName, snapshots, op)
if err != nil {
return fmt.Errorf("Failed generating volume refresh config: %w", err)
}
// Use the source volume's config if not supplied.
if config == nil {
config = srcConfig.Volume.Config
}
// Use the source volume's description if not supplied.
if desc == "" {
desc = srcConfig.Volume.Description
}
contentDBType, err := VolumeContentTypeNameToContentType(srcConfig.Volume.ContentType)
if err != nil {
return err
}
// Get the source volume's content type.
contentType, err := VolumeDBContentTypeToContentType(contentDBType)
if err != nil {
return err
}
if contentType != drivers.ContentTypeFS && contentType != drivers.ContentTypeBlock {
return fmt.Errorf("Volume of content type %q cannot be refreshed", contentType)
}
storagePoolSupported := slices.Contains(b.Driver().Info().VolumeTypes, drivers.VolumeTypeCustom)
if !storagePoolSupported {
return errors.New("Storage pool does not support custom volume type")
}
reverter := revert.New()
defer reverter.Fail()
// Only send the snapshots that the target needs when refreshing.
// There is currently no recorded creation timestamp, so we can only detect changes based on name.
var snapshotNames []string
if snapshots {
// Compare snapshots.
sourceSnapshotComparable := make([]ComparableSnapshot, 0, len(srcConfig.VolumeSnapshots))
for _, sourceSnap := range srcConfig.VolumeSnapshots {
sourceSnapshotComparable = append(sourceSnapshotComparable, ComparableSnapshot{
Name: sourceSnap.Name,
CreationDate: sourceSnap.CreatedAt,
})
}
targetSnaps, err := VolumeDBSnapshotsGet(b, projectName, volName, drivers.VolumeTypeCustom)
if err != nil {
return err
}
targetSnapshotsComparable := make([]ComparableSnapshot, 0, len(targetSnaps))
for _, targetSnap := range targetSnaps {
_, targetSnapName, _ := api.GetParentAndSnapshotName(targetSnap.Name)
targetSnapshotsComparable = append(targetSnapshotsComparable, ComparableSnapshot{
Name: targetSnapName,
CreationDate: targetSnap.CreationDate,
})
}
syncSourceSnapshotIndexes, deleteTargetSnapshotIndexes := CompareSnapshots(sourceSnapshotComparable, targetSnapshotsComparable, excludeOlder)
// Delete extra snapshots first.
for _, deleteTargetSnapIndex := range deleteTargetSnapshotIndexes {
err = b.DeleteCustomVolumeSnapshot(projectName, targetSnaps[deleteTargetSnapIndex].Name, op)
if err != nil {
return err
}
}
// Ensure that only the requested snapshots are included in the source config.
allSnapshots := srcConfig.VolumeSnapshots
srcConfig.VolumeSnapshots = make([]*api.StorageVolumeSnapshot, 0, len(syncSourceSnapshotIndexes))
for _, syncSourceSnapIndex := range syncSourceSnapshotIndexes {
snapshotNames = append(snapshotNames, allSnapshots[syncSourceSnapIndex].Name)
srcConfig.VolumeSnapshots = append(srcConfig.VolumeSnapshots, allSnapshots[syncSourceSnapIndex])
}
}
volStorageName := project.StorageVolume(projectName, volName)
vol := b.GetVolume(drivers.VolumeTypeCustom, contentType, volStorageName, config)
// Get the src volume name on storage.
srcVolStorageName := project.StorageVolume(srcProjectName, srcVolName)
srcVol := srcPool.GetVolume(drivers.VolumeTypeCustom, contentType, srcVolStorageName, srcConfig.Volume.Config)
if srcPool == b {
l.Debug("RefreshCustomVolume same-pool mode detected")
// Only refresh the snapshots that the target needs.
srcSnapVols := make([]drivers.Volume, 0, len(srcConfig.VolumeSnapshots))
for _, srcSnap := range srcConfig.VolumeSnapshots {
newSnapshotName := drivers.GetSnapshotVolumeName(volName, srcSnap.Name)
snapExpiryDate := time.Time{}
if srcSnap.ExpiresAt != nil {
snapExpiryDate = *srcSnap.ExpiresAt
}
// Validate config and create database entry for new storage volume from source volume config.
err = VolumeDBCreate(b, projectName, newSnapshotName, srcSnap.Description, drivers.VolumeTypeCustom, true, srcSnap.Config, srcSnap.CreatedAt, snapExpiryDate, contentType, false, true)
if err != nil {
return err
}
reverter.Add(func() { _ = VolumeDBDelete(b, projectName, newSnapshotName, vol.Type()) })
// Generate source snapshot volumes list.
srcSnapVolumeName := drivers.GetSnapshotVolumeName(srcVolName, srcSnap.Name)
srcSnapVolStorageName := project.StorageVolume(projectName, srcSnapVolumeName)
srcSnapVol := srcPool.GetVolume(drivers.VolumeTypeCustom, contentType, srcSnapVolStorageName, srcSnap.Config)
srcSnapVols = append(srcSnapVols, srcSnapVol)
}
err = b.driver.RefreshVolume(vol, srcVol, srcSnapVols, false, op)
if err != nil {
return err
}
} else {
l.Debug("RefreshCustomVolume cross-pool mode detected")
// Negotiate the migration type to use.
offeredTypes := srcPool.MigrationTypes(contentType, true, snapshots, false, true)
offerHeader := localMigration.TypesToHeader(offeredTypes...)
migrationTypes, err := localMigration.MatchTypes(offerHeader, FallbackMigrationType(contentType), b.MigrationTypes(contentType, true, snapshots, false, true))
if err != nil {
return fmt.Errorf("Failed to negotiate copy migration type: %w", err)
}
var volSize int64
if contentType == drivers.ContentTypeBlock {
err = srcVol.MountTask(func(mountPath string, op *operations.Operation) error {
srcPoolBackend, ok := srcPool.(*backend)
if !ok {
return errors.New("Pool is not a backend")
}
volDiskPath, err := srcPoolBackend.driver.GetVolumeDiskPath(srcVol)
if err != nil {
return err
}
volSize, err = drivers.BlockDiskSizeBytes(volDiskPath)
if err != nil {
return err
}
return nil
}, nil)
if err != nil {
return err
}
}
var migrationSnapshots []*migration.Snapshot
if snapshots {
migrationSnapshots, err = VolumeSnapshotsToMigrationSnapshots(srcConfig.VolumeSnapshots, projectName, srcPool, contentType, drivers.VolumeTypeCustom, srcVolName)
if err != nil {
return err
}
}
ctx, cancel := context.WithCancel(context.Background())
// Use in-memory pipe pair to simulate a connection between the sender and receiver.
aEnd, bEnd := memorypipe.NewPipePair(ctx)
// Run sender and receiver in separate go routines to prevent deadlocks.
aEndErrCh := make(chan error, 1)
bEndErrCh := make(chan error, 1)
go func() {
err := srcPool.MigrateCustomVolume(srcProjectName, aEnd, &localMigration.VolumeSourceArgs{
IndexHeaderVersion: localMigration.IndexHeaderVersion,
Name: srcVolName,
Snapshots: snapshotNames,
MigrationType: migrationTypes[0],
TrackProgress: true, // Do use a progress tracker on sender.
ContentType: string(contentType),
Info: &localMigration.Info{Config: srcConfig},
StorageMove: true,
}, op)
if err != nil {
cancel()
}
aEndErrCh <- err
}()
go func() {
err := b.CreateCustomVolumeFromMigration(projectName, bEnd, localMigration.VolumeTargetArgs{
IndexHeaderVersion: localMigration.IndexHeaderVersion,
Name: volName,
Description: desc,
Config: config,
Snapshots: migrationSnapshots,
MigrationType: migrationTypes[0],
TrackProgress: false, // Do not use a progress tracker on receiver.
ContentType: string(contentType),
VolumeSize: volSize, // Block size setting override.
Refresh: true,
StoragePool: srcPoolName,
}, op)
if err != nil {
cancel()
}
bEndErrCh <- err
}()
// Capture errors from the sender and receiver from their result channels.
errs := []error{}
aEndErr := <-aEndErrCh
if aEndErr != nil {
_ = aEnd.Close()
errs = append(errs, aEndErr)
}
bEndErr := <-bEndErrCh
if bEndErr != nil {
errs = append(errs, bEndErr)
}
cancel()
if len(errs) > 0 {
return fmt.Errorf("Refresh custom volume from copy failed: %v", errs)
}
}
reverter.Success()
return nil
}
// RefreshInstance synchronises one instance's volume (and optionally snapshots) over another.
// Snapshots that are not present in the source but are in the destination are removed from the
// destination if snapshots are included in the synchronisation. An empty srcSnapshots argument
// indicates a volume-only refresh.
func (b *backend) RefreshInstance(inst instance.Instance, src instance.Instance, srcSnapshots []instance.Instance, allowInconsistent bool, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": inst.Project().Name, "instance": inst.Name(), "src": src.Name(), "srcSnapshots": len(srcSnapshots)})
l.Debug("RefreshInstance started")
defer l.Debug("RefreshInstance finished")
// This indicates whether or not it's a volume-only refresh.
snapshots := len(srcSnapshots) > 0
if inst.Type() != src.Type() {
return errors.New("Instance types must match")
}
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return err
}
contentType := InstanceContentType(inst)
// Load storage volume from database.
dbVol, err := VolumeDBGet(b, inst.Project().Name, inst.Name(), volType)
if err != nil {
return err
}
// Generate the effective root device volume for instance.
volStorageName := project.Instance(inst.Project().Name, inst.Name())
vol := b.GetVolume(volType, contentType, volStorageName, dbVol.Config)
err = b.applyInstanceRootDiskOverrides(inst, &vol)
if err != nil {
return err
}
// Get the source storage pool.
srcPool, err := LoadByInstance(b.state, src)
if err != nil {
return err
}
srcPoolBackend, ok := srcPool.(*backend)
if !ok {
return errors.New("Source pool is not a backend")
}
// Check source volume exists, and get its config.
srcConfig, err := srcPool.GenerateInstanceBackupConfig(src, snapshots, op)
if err != nil {
return fmt.Errorf("Failed generating instance refresh config: %w", err)
}
// Ensure that only the requested snapshots are included in the source config.
allSnapshots := srcConfig.VolumeSnapshots
srcConfig.VolumeSnapshots = make([]*api.StorageVolumeSnapshot, 0, len(srcSnapshots))
for i := range allSnapshots {
found := false
for _, srcSnapshot := range srcSnapshots {
_, srcSnapshotName, _ := api.GetParentAndSnapshotName(srcSnapshot.Name())
if srcSnapshotName == allSnapshots[i].Name {
found = true
break
}
}
if found {
srcConfig.VolumeSnapshots = append(srcConfig.VolumeSnapshots, allSnapshots[i])
}
}
// Get source volume construct.
srcVolStorageName := project.Instance(src.Project().Name, src.Name())
srcVol := b.GetVolume(volType, contentType, srcVolStorageName, srcConfig.Volume.Config)
// Get source snapshot volume constructs.
srcSnapVols := make([]drivers.Volume, 0, len(srcConfig.VolumeSnapshots))
snapshotNames := make([]string, 0, len(srcConfig.VolumeSnapshots))
for i := range srcConfig.VolumeSnapshots {
newSnapshotName := drivers.GetSnapshotVolumeName(src.Name(), srcConfig.VolumeSnapshots[i].Name)
snapVolStorageName := project.Instance(src.Project().Name, newSnapshotName)
srcSnapVol := srcPool.GetVolume(volType, contentType, snapVolStorageName, srcConfig.VolumeSnapshots[i].Config)
srcSnapVols = append(srcSnapVols, srcSnapVol)
snapshotNames = append(snapshotNames, srcConfig.VolumeSnapshots[i].Name)
}
reverter := revert.New()
defer reverter.Fail()
// Some driver backing stores require that running instances be frozen during copy.
if !src.IsSnapshot() && srcPoolBackend.driver.Info().RunningCopyFreeze && src.IsRunning() && !src.IsFrozen() && !allowInconsistent {
b.logger.Info("Freezing instance for consistent refresh")
err = src.Freeze()
if err != nil {
return err
}
defer func() { _ = src.Unfreeze() }()
// Attempt to sync the filesystem.
_ = linux.SyncFS(src.RootfsPath())
}
if b.Name() == srcPool.Name() {
l.Debug("RefreshInstance same-pool mode detected")
// Create database entries for new storage volume snapshots.
for i := range srcConfig.VolumeSnapshots {
newSnapshotName := drivers.GetSnapshotVolumeName(inst.Name(), srcConfig.VolumeSnapshots[i].Name)
var volumeSnapExpiryDate time.Time
if srcConfig.VolumeSnapshots[i].ExpiresAt != nil {
volumeSnapExpiryDate = *srcConfig.VolumeSnapshots[i].ExpiresAt
}
// Validate config and create database entry for new storage volume.
err = VolumeDBCreate(b, inst.Project().Name, newSnapshotName, srcConfig.VolumeSnapshots[i].Description, volType, true, srcConfig.VolumeSnapshots[i].Config, srcConfig.VolumeSnapshots[i].CreatedAt, volumeSnapExpiryDate, contentType, false, true)
if err != nil {
return err
}
reverter.Add(func() { _ = VolumeDBDelete(b, inst.Project().Name, newSnapshotName, volType) })
}
err = b.driver.RefreshVolume(vol, srcVol, srcSnapVols, allowInconsistent, op)
if err != nil {
return err
}
} else {
// We are copying volumes between storage pools so use migration system as it will
// be able to negotiate a common transfer method between pool types.
l.Debug("RefreshInstance cross-pool mode detected")
// Negotiate the migration type to use.
offeredTypes := srcPool.MigrationTypes(contentType, true, snapshots, false, true)
offerHeader := localMigration.TypesToHeader(offeredTypes...)
migrationTypes, err := localMigration.MatchTypes(offerHeader, FallbackMigrationType(contentType), b.MigrationTypes(contentType, true, snapshots, false, true))
if err != nil {
return fmt.Errorf("Failed to negotiate copy migration type: %w", err)
}
var srcVolumeSize int64
// For VMs, get source volume size so that target can create the volume the same size.
if src.Type() == instancetype.VM {
srcVolumeSize, err = InstanceDiskBlockSize(srcPool, src, op)
if err != nil {
return fmt.Errorf("Failed getting source disk size: %w", err)
}
}
migrationSnapshots, err := VolumeSnapshotsToMigrationSnapshots(srcConfig.VolumeSnapshots, src.Project().Name, srcPool, contentType, volType, src.Name())
if err != nil {
return err
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Run sender and receiver in separate go routines to prevent deadlocks.
g, ctx := errgroup.WithContext(ctx)
// Use in-memory pipe pair to simulate a connection between the sender and receiver.
// Use context from error group so that if either side fails the pipes are closed.
aEnd, bEnd := memorypipe.NewPipePair(ctx)
// Start each side of the migration concurrently and collect any errors.
g.Go(func() error {
return srcPool.MigrateInstance(src, aEnd, &localMigration.VolumeSourceArgs{
IndexHeaderVersion: localMigration.IndexHeaderVersion,
Name: src.Name(),
Snapshots: snapshotNames,
MigrationType: migrationTypes[0],
TrackProgress: true, // Do use a progress tracker on sender.
AllowInconsistent: allowInconsistent,
Refresh: true, // Indicate to sender to use incremental streams.
Info: &localMigration.Info{Config: srcConfig},
VolumeOnly: !snapshots,
StorageMove: true,
}, op)
})
g.Go(func() error {
return b.CreateInstanceFromMigration(inst, bEnd, localMigration.VolumeTargetArgs{
IndexHeaderVersion: localMigration.IndexHeaderVersion,
Name: inst.Name(),
Snapshots: migrationSnapshots,
MigrationType: migrationTypes[0],
Refresh: true, // Indicate to receiver volume should exist.
VolumeSize: srcVolumeSize,
TrackProgress: false, // Do not use a progress tracker on receiver.
VolumeOnly: !snapshots,
StoragePool: srcPool.Name(),
}, op)
})
err = g.Wait()
if err != nil {
return fmt.Errorf("Create instance volume from copy failed: %w", err)
}
}
err = b.ensureInstanceSymlink(inst.Type(), inst.Project().Name, inst.Name(), vol.MountPath())
if err != nil {
return err
}
err = inst.DeferTemplateApply(instance.TemplateTriggerCopy)
if err != nil {
return err
}
reverter.Success()
return nil
}
// imageFiller returns a function that can be used as a filler function with CreateVolume().
// The function returned will unpack the specified image archive into the specified mount path
// provided, and for VM images, a raw root block path is required to unpack the qcow2 image into.
func (b *backend) imageFiller(fingerprint string, op *operations.Operation) func(vol drivers.Volume, rootBlockPath string, allowUnsafeResize bool) (int64, error) {
return func(vol drivers.Volume, rootBlockPath string, allowUnsafeResize bool) (int64, error) {
var tracker *ioprogress.ProgressTracker
if op != nil { // Not passed when being done as part of pre-migration setup.
metadata := make(map[string]any)
tracker = &ioprogress.ProgressTracker{
Handler: func(percent, speed int64) {
operations.SetProgressMetadata(metadata, "create_instance_from_image_unpack", "Unpacking image", percent, 0, speed)
_ = op.UpdateMetadata(metadata)
},
}
}
imageFile := internalUtil.VarPath("images", fingerprint)
return ImageUnpack(imageFile, vol, rootBlockPath, b.state.OS, allowUnsafeResize, tracker)
}
}
// isoFiller returns a function that can be used as a filler function with CreateVolume().
// The function returned will copy the ISO content into the specified mount path
// provided.
func (b *backend) isoFiller(data io.Reader) func(vol drivers.Volume, rootBlockPath string, allowUnsafeResize bool) (int64, error) {
return func(vol drivers.Volume, rootBlockPath string, allowUnsafeResize bool) (int64, error) {
f, err := os.OpenFile(rootBlockPath, os.O_CREATE|os.O_WRONLY, 0o600)
if err != nil {
return -1, err
}
defer func() { _ = f.Close() }()
return io.Copy(f, data)
}
}
// CreateInstanceFromImage creates a new volume for an instance populated with the image requested.
// On failure caller is expected to call DeleteInstance() to clean up.
func (b *backend) CreateInstanceFromImage(inst instance.Instance, fingerprint string, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": inst.Project().Name, "instance": inst.Name()})
l.Debug("CreateInstanceFromImage started")
defer l.Debug("CreateInstanceFromImage finished")
err := b.isStatusReady()
if err != nil {
return err
}
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return err
}
contentType := InstanceContentType(inst)
reverter := revert.New()
defer reverter.Fail()
volumeConfig := make(map[string]string)
err = b.applyInstanceRootDiskInitialValues(inst, volumeConfig)
if err != nil {
return err
}
// Determine whether an optimized image should be used.
useOptimizedImage, err := b.shouldUseOptimizedImage(fingerprint, contentType, volumeConfig, op)
if err != nil {
return err
}
// Validate config and create database entry for new storage volume.
err = VolumeDBCreate(b, inst.Project().Name, inst.Name(), "", volType, false, volumeConfig, inst.CreationDate(), time.Time{}, contentType, true, false)
if err != nil {
return err
}
reverter.Add(func() { _ = VolumeDBDelete(b, inst.Project().Name, inst.Name(), volType) })
// Record new volume with authorizer.
err = b.state.Authorizer.AddStoragePoolVolume(b.state.ShutdownCtx, inst.Project().Name, b.Name(), volType.Singular(), inst.Name(), "")
if err != nil {
logger.Error("Failed to add storage volume to authorizer", logger.Ctx{"name": inst.Name(), "type": volType, "pool": b.Name(), "project": inst.Project().Name, "error": err})
}
reverter.Add(func() {
_ = b.state.Authorizer.DeleteStoragePoolVolume(b.state.ShutdownCtx, inst.Project().Name, b.Name(), volType.Singular(), inst.Name(), "")
})
// Generate the effective root device volume for instance.
volStorageName := project.Instance(inst.Project().Name, inst.Name())
vol := b.GetVolume(volType, contentType, volStorageName, volumeConfig)
err = b.applyInstanceRootDiskOverrides(inst, &vol)
if err != nil {
return err
}
// Leave reverting on failure to caller, they are expected to call DeleteInstance().
// If the driver doesn't support optimized image volumes or the optimized image volume should not be used,
// create a new empty volume and populate it with the contents of the image archive.
if !useOptimizedImage {
volFiller := drivers.VolumeFiller{
Fingerprint: fingerprint,
Fill: b.imageFiller(fingerprint, op),
}
err = b.driver.CreateVolume(vol, &volFiller, op)
if err != nil {
return err
}
} else {
// If the driver supports optimized images then ensure the optimized image volume has been created
// for the images's fingerprint and that it matches the pool's current volume settings, and if not
// recreating using the pool's current volume settings.
err = b.EnsureImage(fingerprint, op)
if err != nil {
return err
}
// Try and load existing volume config on this storage pool so we can compare filesystems if needed.
imgDBVol, err := VolumeDBGet(b, api.ProjectDefaultName, fingerprint, drivers.VolumeTypeImage)
if err != nil {
return err
}
imgVol := b.GetVolume(drivers.VolumeTypeImage, contentType, fingerprint, imgDBVol.Config)
// Derive the volume size to use for a new volume when copying from a source volume.
// Where possible (if the source volume has a volatile.rootfs.size property), it checks that the
// source volume isn't larger than the volume's "size" and the pool's "volume.size" setting.
l.Debug("Checking volume size")
newVolSize, err := vol.ConfigSizeFromSource(imgVol)
if err != nil {
return err
}
// Set the derived size directly as the "size" property on the new volume so that it is applied.
vol.SetConfigSize(newVolSize)
l.Debug("Set new volume size", logger.Ctx{"size": newVolSize})
// Proceed to create a new volume by copying the optimized image volume.
err = b.driver.CreateVolumeFromCopy(vol, imgVol, false, false, op)
// If the driver returns ErrCannotBeShrunk, this means that the cached volume that the new volume
// is to be created from is larger than the requested new volume size, and cannot be shrunk.
// So we unpack the image directly into a new volume rather than use the optimized snapsot.
// This is slower but allows for individual volumes to be created from an image that are smaller
// than the pool's volume settings.
if errors.Is(err, drivers.ErrCannotBeShrunk) {
l.Debug("Cached image volume is larger than new volume and cannot be shrunk, creating non-optimized volume")
volFiller := drivers.VolumeFiller{
Fingerprint: fingerprint,
Fill: b.imageFiller(fingerprint, op),
}
err = b.driver.CreateVolume(vol, &volFiller, op)
if err != nil {
return err
}
} else if err != nil {
return err
}
}
err = b.ensureInstanceSymlink(inst.Type(), inst.Project().Name, inst.Name(), vol.MountPath())
if err != nil {
return err
}
err = inst.DeferTemplateApply(instance.TemplateTriggerCreate)
if err != nil {
return err
}
reverter.Success()
return nil
}
// CreateInstanceFromMigration receives an instance being migrated.
// The args.Name and args.Config fields are ignored and, instance properties are used instead.
func (b *backend) CreateInstanceFromMigration(inst instance.Instance, conn io.ReadWriteCloser, args localMigration.VolumeTargetArgs, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": inst.Project().Name, "instance": inst.Name(), "args": fmt.Sprintf("%+v", args)})
l.Debug("CreateInstanceFromMigration started")
defer l.Debug("CreateInstanceFromMigration finished")
err := b.isStatusReady()
if err != nil {
return err
}
if args.Config != nil {
return errors.New("Migration VolumeTargetArgs.Config cannot be set for instances")
}
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return err
}
contentType := InstanceContentType(inst)
// Receive index header from source if applicable and respond confirming receipt.
// This will also communicate the args.Refresh setting back to the source (in case it was changed by the
// caller if the instance DB record already exists).
srcInfo, err := b.migrationIndexHeaderReceive(l, args.IndexHeaderVersion, conn, args.Refresh)
if err != nil {
return err
}
// Now that we got the source details, validate against the instance limits.
_, rootDiskConf, err := internalInstance.GetRootDiskDevice(inst.ExpandedDevices().CloneNative())
if err != nil {
return err
}
if rootDiskConf["size"] != "" {
rootDiskConfBytes, err := units.ParseByteSizeString(rootDiskConf["size"])
if err != nil {
return err
}
// Compare volume size with configured root size.
// Add a 4MiB allowed extra to account for round to nearest extent (16k on ZFS, 4MiB on LVM).
if args.VolumeSize > (rootDiskConfBytes + (4 * 1024 * 1024)) {
return errors.New("The configured target instance root disk size is smaller than the migration source")
}
}
var volumeDescription string
var volumeConfig map[string]string
// Check if the volume exists in database
dbVol, err := VolumeDBGet(b, inst.Project().Name, inst.Name(), volType)
if err != nil && !response.IsNotFoundError(err) {
return err
}
// Prefer using existing volume config (to allow mounting existing volume correctly).
if dbVol != nil {
volumeConfig = dbVol.Config
volumeDescription = dbVol.Description
} else if srcInfo != nil && srcInfo.Config != nil && srcInfo.Config.Volume != nil {
volumeConfig = srcInfo.Config.Volume.Config
volumeDescription = srcInfo.Config.Volume.Description
} else {
volumeConfig = make(map[string]string)
volumeDescription = args.Description
}
volStorageName := project.Instance(inst.Project().Name, inst.Name())
vol := b.GetVolume(volType, contentType, volStorageName, volumeConfig)
// Ensure storage volume settings are honored when doing migration.
// This is only done for non-optimized migration because some storage volume settings,
// in particular block mode, cannot be honored when doing optimized migration.
if args.MigrationType.FSType == migration.MigrationFSType_RSYNC || args.MigrationType.FSType == migration.MigrationFSType_BLOCK_AND_RSYNC {
vol.SetHasSource(false)
err = b.driver.FillVolumeConfig(vol)
if err != nil {
return fmt.Errorf("Failed filling volume config: %w", err)
}
}
// Check if the volume exists on storage.
volExists, err := b.driver.HasVolume(vol)
if err != nil {
return err
}
// Check for inconsistencies between database and storage before continuing.
if dbVol == nil && volExists {
return errors.New("Volume already exists on storage but not in database")
}
if dbVol != nil && !volExists {
return errors.New("Volume exists in database but not on storage")
}
// Consistency check for refresh mode.
// We expect that the args.Refresh setting will have already been set to false by the caller as part of
// detecting if the instance DB record exists or not. If we get here then something has gone wrong.
if args.Refresh && !volExists {
return errors.New("Cannot refresh volume, doesn't exist on migration target storage")
}
reverter := revert.New()
defer reverter.Fail()
isRemoteClusterMove := args.ClusterMoveSourceName != "" && b.driver.Info().Remote
if !args.Refresh {
if volExists {
if !isRemoteClusterMove {
return errors.New("Cannot create volume, already exists on migration target storage")
}
} else {
// Validate config and create database entry for new storage volume if not refreshing.
// Strip unsupported config keys (in case the export was made from a different type of storage pool).
err = VolumeDBCreate(b, inst.Project().Name, inst.Name(), volumeDescription, volType, false, vol.Config(), inst.CreationDate(), time.Time{}, contentType, true, true)
if err != nil {
return err
}
reverter.Add(func() { _ = VolumeDBDelete(b, inst.Project().Name, inst.Name(), volType) })
// Record new volume with authorizer.
err = b.state.Authorizer.AddStoragePoolVolume(b.state.ShutdownCtx, inst.Project().Name, b.Name(), volType.Singular(), inst.Name(), "")
if err != nil {
logger.Error("Failed to add storage volume to authorizer", logger.Ctx{"name": inst.Name(), "type": volType, "pool": b.Name(), "project": inst.Project().Name, "error": err})
}
reverter.Add(func() {
_ = b.state.Authorizer.DeleteStoragePoolVolume(b.state.ShutdownCtx, inst.Project().Name, b.Name(), volType.Singular(), inst.Name(), "")
})
}
}
// Create new volume database records when the storage pool is changed or
// when it is not a remote cluster move.
if !isRemoteClusterMove || args.StoragePool != "" {
for i, snapshot := range args.Snapshots {
snapName := snapshot.GetName()
newSnapshotName := drivers.GetSnapshotVolumeName(inst.Name(), snapName)
snapConfig := vol.Config() // Use parent volume config by default.
snapDescription := volumeDescription // Use parent volume description by default.
snapExpiryDate := time.Time{}
snapCreationDate := time.Time{}
// If the source snapshot config is available, use that.
if srcInfo != nil && srcInfo.Config != nil {
if len(srcInfo.Config.Snapshots) >= i-1 && srcInfo.Config.Snapshots[i] != nil && srcInfo.Config.Snapshots[i].Name == snapName {
// Use instance snapshot's creation date if snap info available.
snapCreationDate = srcInfo.Config.Snapshots[i].CreatedAt
}
if len(srcInfo.Config.VolumeSnapshots) >= i-1 && srcInfo.Config.VolumeSnapshots[i] != nil && srcInfo.Config.VolumeSnapshots[i].Name == snapName {
// Check if snapshot volume config is available then use it.
snapDescription = srcInfo.Config.VolumeSnapshots[i].Description
snapConfig = srcInfo.Config.VolumeSnapshots[i].Config
if srcInfo.Config.VolumeSnapshots[i].ExpiresAt != nil {
snapExpiryDate = *srcInfo.Config.VolumeSnapshots[i].ExpiresAt
}
// Use volume's creation date if available.
if !srcInfo.Config.VolumeSnapshots[i].CreatedAt.IsZero() {
snapCreationDate = srcInfo.Config.VolumeSnapshots[i].CreatedAt
}
}
}
// Validate config and create database entry for new storage volume.
// Strip unsupported config keys (in case the export was made from a different type of storage pool).
err = VolumeDBCreate(b, inst.Project().Name, newSnapshotName, snapDescription, volType, true, snapConfig, snapCreationDate, snapExpiryDate, contentType, true, true)
if err != nil {
return err
}
reverter.Add(func() { _ = VolumeDBDelete(b, inst.Project().Name, newSnapshotName, volType) })
}
}
// Generate the effective root device volume for instance.
err = b.applyInstanceRootDiskOverrides(inst, &vol)
if err != nil {
return err
}
// Override args.Name and args.Config to ensure volume is created based on instance.
args.Config = vol.Config()
args.Name = inst.Name()
projectName := inst.Project().Name
// If migration header supplies a volume size, then use that as block volume size instead of pool default.
// This way if the volume being received is larger than the pool default size, the block volume created
// will still be able to accommodate it.
if args.VolumeSize > 0 && contentType == drivers.ContentTypeBlock {
b.logger.Debug("Setting volume size from offer header", logger.Ctx{"size": args.VolumeSize})
args.Config["size"] = fmt.Sprintf("%d", args.VolumeSize)
} else if args.Config["size"] != "" {
b.logger.Debug("Using volume size from root disk config", logger.Ctx{"size": args.Config["size"]})
}
var preFiller drivers.VolumeFiller
if !args.Refresh && !isRemoteClusterMove {
// If the negotiated migration method is rsync and the instance's base image is
// already on the host then setup a pre-filler that will unpack the local image
// to try and speed up the rsync of the incoming volume by avoiding the need to
// transfer the base image files too.
if args.MigrationType.FSType == migration.MigrationFSType_RSYNC {
fingerprint := inst.ExpandedConfig()["volatile.base_image"]
imageExists := false
if fingerprint != "" {
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Confirm that the image is present in the project.
_, _, err = tx.GetImage(ctx, fingerprint, cluster.ImageFilter{Project: &projectName})
return err
})
if err != nil && !response.IsNotFoundError(err) {
return err
}
// Make sure that the image is available locally too (not guaranteed in clusters).
imageExists = err == nil && util.PathExists(internalUtil.VarPath("images", fingerprint))
}
if imageExists {
l.Debug("Using optimised migration from existing image", logger.Ctx{"fingerprint": fingerprint})
// Populate the volume filler with the fingerprint and image filler
// function that can be used by the driver to pre-populate the
// volume with the contents of the image.
preFiller = drivers.VolumeFiller{
Fingerprint: fingerprint,
Fill: b.imageFiller(fingerprint, op),
}
// Ensure if the image doesn't yet exist on a driver which supports
// optimized storage, then it gets created first.
err = b.EnsureImage(preFiller.Fingerprint, op)
if err != nil {
return err
}
}
}
}
err = b.driver.CreateVolumeFromMigration(vol, conn, args, &preFiller, op)
if err != nil {
return err
}
if !isRemoteClusterMove {
reverter.Add(func() { _ = b.DeleteInstance(inst, op) })
}
err = b.ensureInstanceSymlink(inst.Type(), inst.Project().Name, inst.Name(), vol.MountPath())
if err != nil {
return err
}
if len(args.Snapshots) > 0 {
err = b.ensureInstanceSnapshotSymlink(inst.Type(), inst.Project().Name, inst.Name())
if err != nil {
return err
}
}
reverter.Success()
return nil
}
// RenameInstance renames the instance's root volume and any snapshot volumes.
func (b *backend) RenameInstance(inst instance.Instance, newName string, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": inst.Project().Name, "instance": inst.Name(), "newName": newName})
l.Debug("RenameInstance started")
defer l.Debug("RenameInstance finished")
if inst.IsSnapshot() {
return errors.New("Instance cannot be a snapshot")
}
if internalInstance.IsSnapshot(newName) {
return errors.New("New name cannot be a snapshot")
}
// Check we can convert the instance to the volume types needed.
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return err
}
volDBType, err := VolumeTypeToDBType(volType)
if err != nil {
return err
}
reverter := revert.New()
defer reverter.Fail()
volume, err := VolumeDBGet(b, inst.Project().Name, inst.Name(), volType)
if err != nil && !response.IsNotFoundError(err) {
return err
}
var snapshots []string
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
var err error
// Get any snapshots the instance has in the format <instance name>/<snapshot name>.
snapshots, err = tx.GetInstanceSnapshotsNames(ctx, inst.Project().Name, inst.Name())
return err
})
if err != nil {
return err
}
if len(snapshots) > 0 {
reverter.Add(func() {
_ = b.removeInstanceSnapshotSymlinkIfUnused(inst.Type(), inst.Project().Name, newName)
_ = b.ensureInstanceSnapshotSymlink(inst.Type(), inst.Project().Name, inst.Name())
})
}
// Rename each snapshot DB record to have the new parent volume prefix.
for _, srcSnapshot := range snapshots {
_, snapName, _ := api.GetParentAndSnapshotName(srcSnapshot)
newSnapVolName := drivers.GetSnapshotVolumeName(newName, snapName)
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.RenameStoragePoolVolume(ctx, inst.Project().Name, srcSnapshot, newSnapVolName, volDBType, b.ID())
})
if err != nil {
return err
}
reverter.Add(func() {
_ = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.RenameStoragePoolVolume(ctx, inst.Project().Name, newSnapVolName, srcSnapshot, volDBType, b.ID())
})
})
}
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Rename the parent volume DB record.
return tx.RenameStoragePoolVolume(ctx, inst.Project().Name, inst.Name(), newName, volDBType, b.ID())
})
if err != nil {
return err
}
reverter.Add(func() {
_ = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.RenameStoragePoolVolume(ctx, inst.Project().Name, newName, inst.Name(), volDBType, b.ID())
})
})
// Rename the volume and its snapshots on the storage device.
volStorageName := project.Instance(inst.Project().Name, inst.Name())
newVolStorageName := project.Instance(inst.Project().Name, newName)
contentType := InstanceContentType(inst)
vol := b.GetVolume(volType, contentType, volStorageName, volume.Config)
err = b.driver.RenameVolume(vol, newVolStorageName, op)
if err != nil {
return err
}
reverter.Add(func() {
// There's no need to pass config as it's not needed when renaming a volume.
newVol := b.GetVolume(volType, contentType, newVolStorageName, nil)
_ = b.driver.RenameVolume(newVol, volStorageName, op)
})
// Remove old instance symlink and create new one.
err = b.removeInstanceSymlink(inst.Type(), inst.Project().Name, inst.Name())
if err != nil {
return err
}
reverter.Add(func() {
_ = b.ensureInstanceSymlink(inst.Type(), inst.Project().Name, inst.Name(), drivers.GetVolumeMountPath(b.name, volType, volStorageName))
})
err = b.ensureInstanceSymlink(inst.Type(), inst.Project().Name, newName, drivers.GetVolumeMountPath(b.name, volType, newVolStorageName))
if err != nil {
return err
}
reverter.Add(func() {
_ = b.removeInstanceSymlink(inst.Type(), inst.Project().Name, newName)
})
// Remove old instance snapshot symlink and create a new one if needed.
err = b.removeInstanceSnapshotSymlinkIfUnused(inst.Type(), inst.Project().Name, inst.Name())
if err != nil {
return err
}
if len(snapshots) > 0 {
err = b.ensureInstanceSnapshotSymlink(inst.Type(), inst.Project().Name, newName)
if err != nil {
return err
}
}
// Record volume rename with authorizer.
err = b.state.Authorizer.RenameStoragePoolVolume(b.state.ShutdownCtx, inst.Project().Name, b.Name(), vol.Type().Singular(), inst.Name(), newName, "")
if err != nil {
logger.Error("Failed to rename storage volume in authorizer", logger.Ctx{"name": inst.Name(), "newName": newName, "type": vol.Type(), "pool": b.Name(), "project": inst.Project().Name, "error": err})
}
reverter.Success()
return nil
}
// DeleteInstance removes the instance's root volume (all snapshots need to be removed first).
func (b *backend) DeleteInstance(inst instance.Instance, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": inst.Project().Name, "instance": inst.Name()})
l.Debug("DeleteInstance started")
defer l.Debug("DeleteInstance finished")
if inst.IsSnapshot() {
return errors.New("Instance must not be a snapshot")
}
// Check we can convert the instance to the volume types needed.
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return err
}
// Get any snapshot volume DB records that the instance has.
dbVolSnaps, err := VolumeDBSnapshotsGet(b, inst.Project().Name, inst.Name(), volType)
if err != nil {
return err
}
// Check all snapshots are already removed.
if len(dbVolSnaps) > 0 {
return errors.New("Cannot remove an instance volume that has snapshots")
}
// Get the volume name on storage.
volStorageName := project.Instance(inst.Project().Name, inst.Name())
contentType := InstanceContentType(inst)
// There's no need to pass config as it's not needed when deleting a volume.
vol := b.GetVolume(volType, contentType, volStorageName, nil)
// Delete the volume from the storage device. Must come after snapshots are removed.
// Must come before DB VolumeDBDelete so that the volume ID is still available.
l.Debug("Deleting instance volume", logger.Ctx{"volName": volStorageName})
volExists, err := b.driver.HasVolume(vol)
if err != nil {
return err
}
if volExists {
err = b.driver.DeleteVolume(vol, op)
if err != nil {
return fmt.Errorf("Error deleting storage volume: %w", err)
}
}
// Remove symlinks.
err = b.removeInstanceSymlink(inst.Type(), inst.Project().Name, inst.Name())
if err != nil {
return err
}
err = b.removeInstanceSnapshotSymlinkIfUnused(inst.Type(), inst.Project().Name, inst.Name())
if err != nil {
return err
}
// Remove the volume record from the database.
err = VolumeDBDelete(b, inst.Project().Name, inst.Name(), vol.Type())
if err != nil {
return err
}
// Record volume deletion with authorizer.
err = b.state.Authorizer.DeleteStoragePoolVolume(b.state.ShutdownCtx, inst.Project().Name, b.Name(), vol.Type().Singular(), inst.Name(), "")
if err != nil {
logger.Error("Failed to remove storage volume from authorizer", logger.Ctx{"name": inst.Name(), "type": vol.Type(), "pool": b.Name(), "project": inst.Project().Name, "error": err})
}
return nil
}
// UpdateInstance updates an instance volume's config.
func (b *backend) UpdateInstance(inst instance.Instance, newDesc string, newConfig map[string]string, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": inst.Project().Name, "instance": inst.Name(), "newDesc": newDesc, "newConfig": newConfig})
l.Debug("UpdateInstance started")
defer l.Debug("UpdateInstance finished")
if inst.IsSnapshot() {
return errors.New("Instance cannot be a snapshot")
}
// Check we can convert the instance to the volume types needed.
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return err
}
volDBType, err := VolumeTypeToDBType(volType)
if err != nil {
return err
}
volStorageName := project.Instance(inst.Project().Name, inst.Name())
contentType := InstanceContentType(inst)
// Validate config.
newVol := b.GetVolume(volType, contentType, volStorageName, newConfig)
err = b.driver.ValidateVolume(newVol, false)
if err != nil {
return err
}
// Get current config to compare what has changed.
curVol, err := VolumeDBGet(b, inst.Project().Name, inst.Name(), volType)
if err != nil {
return err
}
// Apply config changes if there are any.
changedConfig, userOnly := b.detectChangedConfig(curVol.Config, newConfig)
if len(changedConfig) != 0 {
// Check that the volume's size property isn't being changed.
if changedConfig["size"] != "" {
return errors.New(`Instance volume "size" property cannot be changed`)
}
// Check that the volume's size.state property isn't being changed.
if changedConfig["size.state"] != "" {
return errors.New(`Instance volume "size.state" property cannot be changed`)
}
// Check that the volume's block.filesystem property isn't being changed.
if changedConfig["block.filesystem"] != "" {
return errors.New(`Instance volume "block.filesystem" property cannot be changed`)
}
// Load storage volume from database.
dbVol, err := VolumeDBGet(b, inst.Project().Name, inst.Name(), volType)
if err != nil {
return err
}
// Generate the effective root device volume for instance.
volStorageName := project.Instance(inst.Project().Name, inst.Name())
curVol := b.GetVolume(volType, contentType, volStorageName, dbVol.Config)
err = b.applyInstanceRootDiskOverrides(inst, &curVol)
if err != nil {
return err
}
if !userOnly {
err = b.driver.UpdateVolume(curVol, changedConfig)
if err != nil {
return err
}
}
}
// Update the database if something changed.
if len(changedConfig) != 0 || newDesc != curVol.Description {
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.UpdateStoragePoolVolume(ctx, inst.Project().Name, inst.Name(), volDBType, b.ID(), newDesc, newConfig)
})
if err != nil {
return err
}
}
b.state.Events.SendLifecycle(inst.Project().Name, lifecycle.StorageVolumeUpdated.Event(newVol, string(newVol.Type()), inst.Project().Name, op, nil))
return nil
}
// UpdateInstanceSnapshot updates an instance snapshot volume's description.
// Volume config is not allowed to be updated and will return an error.
func (b *backend) UpdateInstanceSnapshot(inst instance.Instance, newDesc string, newConfig map[string]string, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": inst.Project().Name, "instance": inst.Name(), "newDesc": newDesc, "newConfig": newConfig})
l.Debug("UpdateInstanceSnapshot started")
defer l.Debug("UpdateInstanceSnapshot finished")
if !inst.IsSnapshot() {
return errors.New("Instance must be a snapshot")
}
// Check we can convert the instance to the volume types needed.
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return err
}
return b.updateVolumeDescriptionOnly(inst.Project().Name, inst.Name(), volType, newDesc, newConfig, op)
}
// MigrateInstance sends an instance volume for migration.
// The args.Name field is ignored and the name of the instance is used instead.
func (b *backend) MigrateInstance(inst instance.Instance, conn io.ReadWriteCloser, args *localMigration.VolumeSourceArgs, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": inst.Project().Name, "instance": inst.Name(), "args": fmt.Sprintf("%+v", args)})
l.Debug("MigrateInstance started")
defer l.Debug("MigrateInstance finished")
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return err
}
contentType := InstanceContentType(inst)
if len(args.Snapshots) > 0 && args.FinalSync {
return errors.New("Snapshots should not be transferred during final sync")
}
if args.Info == nil {
return errors.New("Migration info required")
}
if args.Info.Config == nil || args.Info.Config.Volume == nil || args.Info.Config.Volume.Config == nil {
return errors.New("Volume config is required")
}
if len(args.Snapshots) != len(args.Info.Config.VolumeSnapshots) {
return fmt.Errorf("Requested snapshots count (%d) doesn't match volume snapshot config count (%d)", len(args.Snapshots), len(args.Info.Config.VolumeSnapshots))
}
// Load storage volume from database.
dbVol, err := VolumeDBGet(b, inst.Project().Name, inst.Name(), volType)
if err != nil {
return err
}
// Generate the effective root device volume for instance.
volStorageName := project.Instance(inst.Project().Name, inst.Name())
vol := b.GetVolume(volType, contentType, volStorageName, dbVol.Config)
err = b.applyInstanceRootDiskOverrides(inst, &vol)
if err != nil {
return err
}
args.Name = inst.Name() // Override args.Name to ensure instance volume is sent.
// Send migration index header frame with volume info and wait for receipt if not doing final sync.
if !args.FinalSync {
resp, err := b.migrationIndexHeaderSend(l, args.IndexHeaderVersion, conn, args.Info)
if err != nil {
return err
}
if resp.Refresh != nil {
args.Refresh = *resp.Refresh
}
}
// Detect if source pool driver doesn't support cheap temporary snapshots that allow consistent copy when
// running, or if the negotiated protocol is VM non-optimized, meaning a complete raw copy of the active
// volume is being sent.
// TODO this can be relaxed in the future if the storage drivers that have RunningCopyFreeze=false make
// temporary snapshots for block volumes too. But for now this is not the case and we must detect when a
// generic migration transfer protocol has been negotiated between source and target pools.
runningCopyFreeze := b.driver.Info().RunningCopyFreeze || args.MigrationType.FSType == migration.MigrationFSType_BLOCK_AND_RSYNC
// Freeze the instance if not already frozen/stopped, allowInconsistent is not enabled and when its not
// possible to make a consistent copy with the instance running.
if !inst.IsSnapshot() && runningCopyFreeze && inst.IsRunning() && !inst.IsFrozen() && !args.AllowInconsistent {
b.logger.Info("Freezing instance for consistent migration transfer")
err = inst.Freeze()
if err != nil {
return err
}
defer func() { _ = inst.Unfreeze() }()
// Attempt to sync the filesystem.
_ = linux.SyncFS(inst.RootfsPath())
}
err = b.driver.MigrateVolume(vol, conn, args, op)
if err != nil {
return err
}
return nil
}
// CleanupInstancePaths removes any remaining mount paths and symlinks for the instance and its snapshots.
func (b *backend) CleanupInstancePaths(inst instance.Instance, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": inst.Project().Name, "instance": inst.Name()})
l.Debug("CleanupInstancePaths started")
defer l.Debug("CleanupInstancePaths finished")
if inst.IsSnapshot() {
return errors.New("Instance must not be a snapshot")
}
// Check we can convert the instance to the volume types needed.
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return err
}
// Get the volume name on storage.
volStorageName := project.Instance(inst.Project().Name, inst.Name())
contentType := InstanceContentType(inst)
// There's no need to pass config as it's not needed when deleting a volume.
vol := b.GetVolume(volType, contentType, volStorageName, nil)
// Remove empty snapshot mount paths.
snapshotDir := drivers.GetVolumeSnapshotDir(b.Name(), vol.Type(), vol.Name())
ents, err := os.ReadDir(snapshotDir)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf("Failed listing instance snapshots directory %q: %w", snapshotDir, err)
}
for _, ent := range ents {
filePath := filepath.Join(snapshotDir, ent.Name())
fileInfo, err := os.Stat(filePath)
if err != nil {
return err
}
if !fileInfo.IsDir() {
continue
}
// Remove empty snapshot mount path.
err = os.Remove(filePath)
if err != nil {
return fmt.Errorf("Failed removing instance snapshot mount path %q: %w", filePath, err)
}
}
err = os.Remove(snapshotDir)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf("Failed removing instance snapshots directory %q: %w", snapshotDir, err)
}
// Remove empty mount path.
err = os.Remove(vol.MountPath())
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf("Failed removing instance mount path %q: %w", vol.MountPath(), err)
}
// Remove symlinks.
err = b.removeInstanceSymlink(inst.Type(), inst.Project().Name, inst.Name())
if err != nil {
return fmt.Errorf("Failed removing instance symlink: %w", err)
}
err = b.removeInstanceSnapshotSymlinkIfUnused(inst.Type(), inst.Project().Name, inst.Name())
if err != nil {
return fmt.Errorf("Failed removing instance snapshots symlink: %w", err)
}
return nil
}
// BackupInstance creates an instance backup.
func (b *backend) BackupInstance(inst instance.Instance, tarWriter *instancewriter.InstanceTarWriter, optimized bool, snapshots bool, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": inst.Project().Name, "instance": inst.Name(), "optimized": optimized, "snapshots": snapshots})
l.Debug("BackupInstance started")
defer l.Debug("BackupInstance finished")
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return err
}
contentType := InstanceContentType(inst)
// Load storage volume from database.
dbVol, err := VolumeDBGet(b, inst.Project().Name, inst.Name(), volType)
if err != nil {
return err
}
// Generate the effective root device volume for instance.
volStorageName := project.Instance(inst.Project().Name, inst.Name())
vol := b.GetVolume(volType, contentType, volStorageName, dbVol.Config)
err = b.applyInstanceRootDiskOverrides(inst, &vol)
if err != nil {
return err
}
// Ensure the backup file reflects current config.
err = b.UpdateInstanceBackupFile(inst, snapshots, op)
if err != nil {
return err
}
var snapNames []string
if snapshots {
// Get snapshots in age order, oldest first, and pass names to storage driver.
instSnapshots, err := inst.Snapshots()
if err != nil {
return err
}
snapNames = make([]string, 0, len(instSnapshots))
for _, instSnapshot := range instSnapshots {
_, snapName, _ := api.GetParentAndSnapshotName(instSnapshot.Name())
snapNames = append(snapNames, snapName)
}
}
err = b.driver.BackupVolume(vol, tarWriter, optimized, snapNames, op)
if err != nil {
return err
}
return nil
}
// GetInstanceUsage returns the disk usage of the instance's root volume.
func (b *backend) GetInstanceUsage(inst instance.Instance) (*VolumeUsage, error) {
l := b.logger.AddContext(logger.Ctx{"project": inst.Project().Name, "instance": inst.Name()})
l.Debug("GetInstanceUsage started")
defer l.Debug("GetInstanceUsage finished")
err := b.isStatusReady()
if err != nil {
return nil, err
}
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return nil, err
}
contentType := InstanceContentType(inst)
val := VolumeUsage{}
// There's no need to pass config as it's not needed when retrieving the volume usage.
volStorageName := project.Instance(inst.Project().Name, inst.Name())
vol := b.GetVolume(volType, contentType, volStorageName, nil)
// Get the usage.
size, err := b.driver.GetVolumeUsage(vol)
if err != nil {
return nil, err
}
val.Used = size
// Get the total size.
_, rootDiskConf, err := internalInstance.GetRootDiskDevice(inst.ExpandedDevices().CloneNative())
if err != nil {
return nil, err
}
sizeStr, ok := rootDiskConf["size"]
if !ok && volType == drivers.VolumeTypeVM {
sizeStr = drivers.DefaultBlockSize
}
if sizeStr != "" {
total, err := units.ParseByteSizeString(sizeStr)
if err != nil {
return nil, err
}
if total >= 0 {
val.Total = total
}
}
return &val, nil
}
// SetInstanceQuota sets the quota on the instance's root volume.
// Returns ErrInUse if the instance is running and the storage driver doesn't support online resizing.
func (b *backend) SetInstanceQuota(inst instance.Instance, size string, vmStateSize string, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": inst.Project().Name, "instance": inst.Name(), "size": size, "vm_state_size": vmStateSize})
l.Debug("SetInstanceQuota started")
defer l.Debug("SetInstanceQuota finished")
// Check we can convert the instance to the volume type needed.
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return err
}
contentVolume := InstanceContentType(inst)
volStorageName := project.Instance(inst.Project().Name, inst.Name())
// Load storage volume from database.
dbVol, err := VolumeDBGet(b, inst.Project().Name, inst.Name(), volType)
if err != nil {
return err
}
// Apply the main volume quota.
// There's no need to pass config as it's not needed when setting quotas.
vol := b.GetVolume(volType, contentVolume, volStorageName, dbVol.Config)
err = b.driver.SetVolumeQuota(vol, size, false, op)
if err != nil {
return err
}
// Apply the filesystem volume quota (only when main volume is block).
if vol.IsVMBlock() {
// Apply default VM config filesystem size if main volume size is specified and no custom
// vmStateSize is specified. This way if the main volume size is empty (i.e removing quota) then
// this will also pass empty quota for the config filesystem volume as well, allowing a former
// quota to be removed from both volumes.
if vmStateSize == "" && size != "" {
vmStateSize = b.driver.Info().DefaultVMBlockFilesystemSize
}
fsVol := vol.NewVMBlockFilesystemVolume()
err := b.driver.SetVolumeQuota(fsVol, vmStateSize, false, op)
if err != nil {
return err
}
}
return nil
}
// MountInstance mounts the instance's root volume.
func (b *backend) MountInstance(inst instance.Instance, op *operations.Operation) (*MountInfo, error) {
l := b.logger.AddContext(logger.Ctx{"project": inst.Project().Name, "instance": inst.Name()})
l.Debug("MountInstance started")
defer l.Debug("MountInstance finished")
err := b.isStatusReady()
if err != nil {
return nil, err
}
reverter := revert.New()
defer reverter.Fail()
// Check we can convert the instance to the volume type needed.
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return nil, err
}
contentType := InstanceContentType(inst)
// Get the volume.
var vol drivers.Volume
volStorageName := project.Instance(inst.Project().Name, inst.Name())
if inst.ID() > -1 {
// Load storage volume from database.
dbVol, err := VolumeDBGet(b, inst.Project().Name, inst.Name(), volType)
if err != nil {
return nil, err
}
// Generate the effective root device volume for instance.
vol = b.GetVolume(volType, contentType, volStorageName, dbVol.Config)
err = b.applyInstanceRootDiskOverrides(inst, &vol)
if err != nil {
return nil, err
}
} else {
contentType := InstanceContentType(inst)
vol = b.GetVolume(volType, contentType, volStorageName, nil)
}
err = b.driver.MountVolume(vol, op)
if err != nil {
return nil, err
}
reverter.Add(func() { _, _ = b.driver.UnmountVolume(vol, false, op) })
diskPath, err := b.getInstanceDisk(inst)
if err != nil && !errors.Is(err, drivers.ErrNotSupported) {
return nil, fmt.Errorf("Failed getting disk path: %w", err)
}
mountInfo := &MountInfo{
DiskPath: diskPath,
}
reverter.Success() // From here on it is up to caller to call UnmountInstance() when done.
// Handle delegation.
if b.driver.CanDelegateVolume(vol) {
mountInfo.PostHooks = append(mountInfo.PostHooks, func(inst instance.Instance) error {
pid := inst.InitPID()
// Only apply to running instances.
if pid < 1 {
return nil
}
return b.driver.DelegateVolume(vol, pid)
})
}
return mountInfo, nil
}
// UnmountInstance unmounts the instance's root volume.
func (b *backend) UnmountInstance(inst instance.Instance, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": inst.Project().Name, "instance": inst.Name()})
l.Debug("UnmountInstance started")
defer l.Debug("UnmountInstance finished")
// Check we can convert the instance to the volume type needed.
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return err
}
contentType := InstanceContentType(inst)
// Get the volume.
var vol drivers.Volume
volStorageName := project.Instance(inst.Project().Name, inst.Name())
if inst.ID() > -1 {
// Load storage volume from database.
dbVol, err := VolumeDBGet(b, inst.Project().Name, inst.Name(), volType)
if err != nil {
return err
}
// Generate the effective root device volume for instance.
vol = b.GetVolume(volType, contentType, volStorageName, dbVol.Config)
err = b.applyInstanceRootDiskOverrides(inst, &vol)
if err != nil {
return err
}
} else {
vol = b.GetVolume(volType, contentType, volStorageName, nil)
}
_, err = b.driver.UnmountVolume(vol, false, op)
return err
}
// getInstanceDisk returns the location of the disk.
func (b *backend) getInstanceDisk(inst instance.Instance) (string, error) {
if inst.Type() != instancetype.VM {
return "", drivers.ErrNotSupported
}
// Check we can convert the instance to the volume type needed.
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return "", err
}
contentType := InstanceContentType(inst)
volStorageName := project.Instance(inst.Project().Name, inst.Name())
// Get the volume.
// There's no need to pass config as it's not needed when getting the
// location of the disk block device.
vol := b.GetVolume(volType, contentType, volStorageName, nil)
// Get the location of the disk block device.
diskPath, err := b.driver.GetVolumeDiskPath(vol)
if err != nil {
return "", err
}
return diskPath, nil
}
// CacheInstanceSnapshots instructs the driver to pre-fetch and cache details on all snapshots.
// This is used to significantly accelerate listing of issues with a lot of snapshots.
func (b *backend) CacheInstanceSnapshots(inst instance.ConfigReader) error {
l := b.logger.AddContext(logger.Ctx{"project": inst.Project().Name, "instance": inst.Name()})
l.Debug("CacheInstanceSnapshots started")
defer l.Debug("CacheInstanceSnapshots finished")
// Check we can convert the instance to the volume type needed.
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return err
}
contentVolume := InstanceContentType(inst)
volStorageName := project.Instance(inst.Project().Name, inst.Name())
// Load storage volume from database.
dbVol, err := VolumeDBGet(b, inst.Project().Name, inst.Name(), volType)
if err != nil {
return err
}
// Apply the main volume quota.
// There's no need to pass config as it's not needed when setting quotas.
vol := b.GetVolume(volType, contentVolume, volStorageName, dbVol.Config)
err = b.driver.CacheVolumeSnapshots(vol)
if err != nil {
return err
}
return nil
}
// CreateInstanceSnapshot creates a snapshot of an instance volume.
func (b *backend) CreateInstanceSnapshot(inst instance.Instance, src instance.Instance, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": inst.Project().Name, "instance": inst.Name(), "src": src.Name()})
l.Debug("CreateInstanceSnapshot started")
defer l.Debug("CreateInstanceSnapshot finished")
if inst.Type() != src.Type() {
return errors.New("Instance types must match")
}
if !inst.IsSnapshot() {
return errors.New("Instance must be a snapshot")
}
if src.IsSnapshot() {
return errors.New("Source instance cannot be a snapshot")
}
// Check we can convert the instance to the volume type needed.
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return err
}
contentType := InstanceContentType(inst)
// Load storage volume from database.
srcDBVol, err := VolumeDBGet(b, src.Project().Name, src.Name(), volType)
if err != nil {
return err
}
reverter := revert.New()
defer reverter.Fail()
// Validate config and create database entry for new storage volume.
err = VolumeDBCreate(b, inst.Project().Name, inst.Name(), srcDBVol.Description, volType, true, srcDBVol.Config, inst.CreationDate(), time.Time{}, contentType, false, true)
if err != nil {
return err
}
reverter.Add(func() { _ = VolumeDBDelete(b, inst.Project().Name, inst.Name(), volType) })
// Some driver backing stores require that running instances be frozen during snapshot.
if b.driver.Info().RunningCopyFreeze && src.IsRunning() && !src.IsFrozen() {
// Freeze the processes.
err = src.Freeze()
if err != nil {
return err
}
defer func() { _ = src.Unfreeze() }()
// Attempt to sync the filesystem.
_ = linux.SyncFS(src.RootfsPath())
}
volStorageName := project.Instance(inst.Project().Name, inst.Name())
// Get the volume.
// There's no need to pass config as it's not needed when creating volume snapshots.
vol := b.GetVolume(volType, contentType, volStorageName, nil)
// Lock this operation to ensure that the only one snapshot is made at the time.
// Other operations will wait for this one to finish.
unlock, err := locking.Lock(context.TODO(), drivers.OperationLockName("CreateInstanceSnapshot", b.name, vol.Type(), contentType, src.Name()))
if err != nil {
return err
}
defer unlock()
err = b.driver.CreateVolumeSnapshot(vol, op)
if err != nil {
return err
}
err = b.ensureInstanceSnapshotSymlink(inst.Type(), inst.Project().Name, inst.Name())
if err != nil {
return err
}
reverter.Success()
return nil
}
// RenameInstanceSnapshot renames an instance snapshot.
func (b *backend) RenameInstanceSnapshot(inst instance.Instance, newName string, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": inst.Project().Name, "instance": inst.Name(), "newName": newName})
l.Debug("RenameInstanceSnapshot started")
defer l.Debug("RenameInstanceSnapshot finished")
reverter := revert.New()
defer reverter.Fail()
if !inst.IsSnapshot() {
return errors.New("Instance must be a snapshot")
}
if internalInstance.IsSnapshot(newName) {
return errors.New("New name cannot be a snapshot")
}
// Check we can convert the instance to the volume types needed.
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return err
}
volDBType, err := VolumeTypeToDBType(volType)
if err != nil {
return err
}
parentName, oldSnapshotName, isSnap := api.GetParentAndSnapshotName(inst.Name())
if !isSnap {
return errors.New("Volume name must be a snapshot")
}
contentType := InstanceContentType(inst)
volStorageName := project.Instance(inst.Project().Name, inst.Name())
// Rename storage volume snapshot. No need to pass config as it's not needed when renaming a volume.
snapVol := b.GetVolume(volType, contentType, volStorageName, nil)
err = b.driver.RenameVolumeSnapshot(snapVol, newName, op)
if err != nil {
return err
}
newVolName := drivers.GetSnapshotVolumeName(parentName, newName)
reverter.Add(func() {
// Revert rename. No need to pass config as it's not needed when renaming a volume.
newSnapVol := b.GetVolume(volType, contentType, project.Instance(inst.Project().Name, newVolName), nil)
_ = b.driver.RenameVolumeSnapshot(newSnapVol, oldSnapshotName, op)
})
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Rename DB volume record.
return tx.RenameStoragePoolVolume(ctx, inst.Project().Name, inst.Name(), newVolName, volDBType, b.ID())
})
if err != nil {
return err
}
reverter.Add(func() {
_ = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Rename DB volume record back.
return tx.RenameStoragePoolVolume(ctx, inst.Project().Name, newVolName, inst.Name(), volDBType, b.ID())
})
})
// Ensure the backup file reflects current config.
err = b.UpdateInstanceBackupFile(inst, true, op)
if err != nil {
return err
}
reverter.Success()
return nil
}
// DeleteInstanceSnapshot removes the snapshot volume for the supplied snapshot instance.
func (b *backend) DeleteInstanceSnapshot(inst instance.Instance, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": inst.Project().Name, "instance": inst.Name()})
l.Debug("DeleteInstanceSnapshot started")
defer l.Debug("DeleteInstanceSnapshot finished")
parentName, snapName, isSnap := api.GetParentAndSnapshotName(inst.Name())
if !inst.IsSnapshot() || !isSnap {
return errors.New("Instance must be a snapshot")
}
// Check we can convert the instance to the volume types needed.
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return err
}
contentType := InstanceContentType(inst)
// Get the parent volume name on storage.
parentStorageName := project.Instance(inst.Project().Name, parentName)
// Delete the snapshot from the storage device.
// Must come before DB VolumeDBDelete so that the volume ID is still available.
l.Debug("Deleting instance snapshot volume", logger.Ctx{"volName": parentStorageName, "snapshotName": snapName})
snapVolName := drivers.GetSnapshotVolumeName(parentStorageName, snapName)
// There's no need to pass config as it's not needed when deleting a volume snapshot.
vol := b.GetVolume(volType, contentType, snapVolName, nil)
volExists, err := b.driver.HasVolume(vol)
if err != nil {
return err
}
if volExists {
err = b.driver.DeleteVolumeSnapshot(vol, op)
if err != nil {
return err
}
}
// Delete symlink if needed.
err = b.removeInstanceSnapshotSymlinkIfUnused(inst.Type(), inst.Project().Name, inst.Name())
if err != nil {
return err
}
// Remove the snapshot volume record from the database if exists.
err = VolumeDBDelete(b, inst.Project().Name, inst.Name(), vol.Type())
if err != nil {
return err
}
return nil
}
// RestoreInstanceSnapshot restores an instance snapshot.
func (b *backend) RestoreInstanceSnapshot(inst instance.Instance, src instance.Instance, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": inst.Project().Name, "instance": inst.Name(), "src": src.Name()})
l.Debug("RestoreInstanceSnapshot started")
defer l.Debug("RestoreInstanceSnapshot finished")
reverter := revert.New()
defer reverter.Fail()
if inst.Type() != src.Type() {
return errors.New("Instance types must match")
}
if inst.IsSnapshot() {
return errors.New("Instance must not be snapshot")
}
if !src.IsSnapshot() {
return errors.New("Source instance must be a snapshot")
}
// Target instance must not be running.
if inst.IsRunning() {
return errors.New("Instance must not be running to restore")
}
// Check we can convert the instance to the volume type needed.
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return err
}
contentType := InstanceContentType(inst)
// Load storage volume from database.
dbVol, err := VolumeDBGet(b, inst.Project().Name, inst.Name(), volType)
if err != nil {
return err
}
// Generate the effective root device volume for instance.
volStorageName := project.Instance(inst.Project().Name, inst.Name())
vol := b.GetVolume(volType, contentType, volStorageName, dbVol.Config)
err = b.applyInstanceRootDiskOverrides(inst, &vol)
if err != nil {
return err
}
_, snapshotName, isSnap := api.GetParentAndSnapshotName(src.Name())
if !isSnap {
return errors.New("Volume name must be a snapshot")
}
srcDBVol, err := VolumeDBGet(b, src.Project().Name, src.Name(), volType)
if err != nil {
return err
}
// Restore snapshot volume config if different.
changedConfig, _ := b.detectChangedConfig(dbVol.Config, srcDBVol.Config)
if len(changedConfig) != 0 || dbVol.Description != srcDBVol.Description {
volDBType, err := VolumeTypeToDBType(volType)
if err != nil {
return err
}
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.UpdateStoragePoolVolume(ctx, inst.Project().Name, inst.Name(), volDBType, b.ID(), srcDBVol.Description, srcDBVol.Config)
})
if err != nil {
return err
}
reverter.Add(func() {
_ = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.UpdateStoragePoolVolume(ctx, inst.Project().Name, inst.Name(), volDBType, b.ID(), dbVol.Description, dbVol.Config)
})
})
}
err = b.driver.RestoreVolume(vol, snapshotName, op)
if err != nil {
var snapErr drivers.ErrDeleteSnapshots
if errors.As(err, &snapErr) {
// We need to delete some snapshots and try again.
snaps, err := inst.Snapshots()
if err != nil {
return err
}
// Go through all the snapshots.
for _, snap := range snaps {
_, snapName, _ := api.GetParentAndSnapshotName(snap.Name())
if !slices.Contains(snapErr.Snapshots, snapName) {
continue
}
// Delete snapshot instance if listed in the error as one that needs removing.
err := snap.Delete(true)
if err != nil {
return err
}
}
// Now try restoring again.
err = b.driver.RestoreVolume(vol, snapshotName, op)
if err != nil {
return err
}
return nil
}
return err
}
reverter.Success()
return nil
}
// MountInstanceSnapshot mounts an instance snapshot. It is mounted as read only so that the
// snapshot cannot be modified.
func (b *backend) MountInstanceSnapshot(inst instance.Instance, op *operations.Operation) (*MountInfo, error) {
l := b.logger.AddContext(logger.Ctx{"project": inst.Project().Name, "instance": inst.Name()})
l.Debug("MountInstanceSnapshot started")
defer l.Debug("MountInstanceSnapshot finished")
if !inst.IsSnapshot() {
return nil, errors.New("Instance must be a snapshot")
}
// Check we can convert the instance to the volume type needed.
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return nil, err
}
// Load storage volume from database.
dbVol, err := VolumeDBGet(b, inst.Project().Name, inst.Name(), volType)
if err != nil {
return nil, err
}
contentType := InstanceContentType(inst)
// Generate the effective root device volume for instance.
volStorageName := project.Instance(inst.Project().Name, inst.Name())
vol := b.GetVolume(volType, contentType, volStorageName, dbVol.Config)
err = b.applyInstanceRootDiskOverrides(inst, &vol)
if err != nil {
return nil, err
}
err = b.driver.MountVolumeSnapshot(vol, op)
if err != nil {
return nil, err
}
diskPath, err := b.getInstanceDisk(inst)
if err != nil && !errors.Is(err, drivers.ErrNotSupported) {
return nil, fmt.Errorf("Failed getting disk path: %w", err)
}
mountInfo := &MountInfo{
DiskPath: diskPath,
}
return mountInfo, nil
}
// UnmountInstanceSnapshot unmounts an instance snapshot.
func (b *backend) UnmountInstanceSnapshot(inst instance.Instance, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": inst.Project().Name, "instance": inst.Name()})
l.Debug("UnmountInstanceSnapshot started")
defer l.Debug("UnmountInstanceSnapshot finished")
if !inst.IsSnapshot() {
return errors.New("Instance must be a snapshot")
}
// Check we can convert the instance to the volume type needed.
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return err
}
contentType := InstanceContentType(inst)
// Load storage volume from database.
dbVol, err := VolumeDBGet(b, inst.Project().Name, inst.Name(), volType)
if err != nil {
return err
}
// Generate the effective root device volume for instance.
volStorageName := project.Instance(inst.Project().Name, inst.Name())
vol := b.GetVolume(volType, contentType, volStorageName, dbVol.Config)
err = b.applyInstanceRootDiskOverrides(inst, &vol)
if err != nil {
return err
}
_, err = b.driver.UnmountVolumeSnapshot(vol, op)
return err
}
// EnsureImage creates an optimized volume of the image if supported by the storage pool driver and the volume
// doesn't already exist. If the volume already exists then it is checked to ensure it matches the pools current
// volume settings ("volume.size" and "block.filesystem" if applicable). If not the optimized volume is removed
// and regenerated to apply the pool's current volume settings.
func (b *backend) EnsureImage(fingerprint string, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"fingerprint": fingerprint})
l.Debug("EnsureImage started")
defer l.Debug("EnsureImage finished")
err := b.isStatusReady()
if err != nil {
return err
}
if !b.driver.Info().OptimizedImages {
return nil // Nothing to do for drivers that don't support optimized images volumes.
}
// We need to lock this operation to ensure that the image is not being created multiple times.
// Uses a lock name of "EnsureImage_<fingerprint>" to avoid deadlocking with CreateVolume below that also
// establishes a lock on the volume type & name if it needs to mount the volume before filling.
unlock, err := locking.Lock(context.TODO(), drivers.OperationLockName("EnsureImage", b.name, drivers.VolumeTypeImage, "", fingerprint))
if err != nil {
return err
}
defer unlock()
var image *api.Image
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Load image info from database.
_, image, err = tx.GetImageFromAnyProject(ctx, fingerprint)
return err
})
if err != nil {
return err
}
// Derive content type from image type. Image types are not the same as instance types, so don't use
// instance type constants for comparison.
contentType := drivers.ContentTypeFS
if image.Type == "virtual-machine" {
contentType = drivers.ContentTypeBlock
}
// Try and load any existing volume config on this storage pool so we can compare filesystems if needed.
imgDBVol, err := VolumeDBGet(b, api.ProjectDefaultName, fingerprint, drivers.VolumeTypeImage)
if err != nil && !response.IsNotFoundError(err) {
return err
}
// Create the new image volume. No config for an image volume so set to nil.
// Pool config values will be read by the underlying driver if needed.
imgVol := b.GetVolume(drivers.VolumeTypeImage, contentType, fingerprint, nil)
// If an existing DB row was found, check if filesystem is the same as the current pool's filesystem.
// If not we need to delete the existing cached image volume and re-create using new filesystem.
// We need to do this for VM block images too, as they create a filesystem based config volume too.
if imgDBVol != nil {
// Generate a temporary volume instance that represents how a new volume using pool defaults would
// be configured.
tmpImgVol := imgVol.Clone()
err := b.Driver().FillVolumeConfig(tmpImgVol)
if err != nil {
return err
}
// Add existing image volume's config to imgVol.
imgVol = b.GetVolume(drivers.VolumeTypeImage, contentType, fingerprint, imgDBVol.Config)
// Check if the volume's block backed mode differs from the pool's current setting for new volumes.
blockModeChanged := tmpImgVol.IsBlockBacked() != imgVol.IsBlockBacked()
// Check if the volume is block backed and its filesystem is different from the pool's current
// setting for new volumes.
blockFSChanged := imgVol.IsBlockBacked() && imgVol.Config()["block.filesystem"] != tmpImgVol.Config()["block.filesystem"]
// If the existing image volume no longer matches the pool's settings for new volumes then we need
// to delete and re-create it.
if blockModeChanged || blockFSChanged {
if blockModeChanged {
l.Debug("Block mode has changed, regenerating image volume")
} else {
l.Debug("Block volume filesystem of pool has changed since cached image volume created, regenerating image volume")
}
err = b.DeleteImage(fingerprint, op)
if err != nil {
return err
}
// Reset img volume variables as we just deleted the old one.
imgDBVol = nil
imgVol = b.GetVolume(drivers.VolumeTypeImage, contentType, fingerprint, nil)
}
}
// Check if we already have a suitable volume on storage device.
volExists, err := b.driver.HasVolume(imgVol)
if err != nil {
return err
}
if volExists {
if imgDBVol != nil {
// Work out what size the image volume should be as if we were creating from scratch.
// This takes into account the existing volume's "volatile.rootfs.size" setting if set so
// as to avoid trying to shrink a larger image volume back to the default size when it is
// allowed to be larger than the default as the pool doesn't specify a volume.size.
l.Debug("Checking image volume size")
newVolSize, err := imgVol.ConfigSizeFromSource(imgVol)
if err != nil {
return err
}
imgVol.SetConfigSize(newVolSize)
// Try applying the current size policy to the existing volume. If it is the same the
// driver should make no changes, and if not then attempt to resize it to the new policy.
l.Debug("Setting image volume size", logger.Ctx{"size": imgVol.ConfigSize()})
err = b.driver.SetVolumeQuota(imgVol, imgVol.ConfigSize(), false, op)
if errors.Is(err, drivers.ErrCannotBeShrunk) || errors.Is(err, drivers.ErrNotSupported) {
// If the driver cannot resize the existing image volume to the new policy size
// then delete the image volume and try to recreate using the new policy settings.
l.Debug("Volume size of pool has changed since cached image volume created and cached volume cannot be resized, regenerating image volume")
err = b.DeleteImage(fingerprint, op)
if err != nil {
return err
}
// Reset img volume variables as we just deleted the old one.
imgDBVol = nil
imgVol = b.GetVolume(drivers.VolumeTypeImage, contentType, fingerprint, nil)
} else if err != nil {
return err
} else {
// We already have a valid volume at the correct size, just return.
return nil
}
} else {
// We have an unrecorded on-disk volume, assume it's a partial unpack and delete it.
// This can occur if Incus process exits unexpectedly during an image unpack or if the
// storage pool has been recovered (which would not recreate the image volume DB records).
l.Warn("Deleting leftover/partially unpacked image volume")
err = b.driver.DeleteVolume(imgVol, op)
if err != nil {
return fmt.Errorf("Failed deleting leftover/partially unpacked image volume: %w", err)
}
}
}
volFiller := drivers.VolumeFiller{
Fingerprint: fingerprint,
Fill: b.imageFiller(fingerprint, op),
}
reverter := revert.New()
defer reverter.Fail()
// Validate config and create database entry for new storage volume.
err = VolumeDBCreate(b, api.ProjectDefaultName, fingerprint, "", drivers.VolumeTypeImage, false, imgVol.Config(), time.Now().UTC(), time.Time{}, contentType, false, false)
if err != nil {
return err
}
reverter.Add(func() { _ = VolumeDBDelete(b, api.ProjectDefaultName, fingerprint, drivers.VolumeTypeImage) })
// Record new volume with authorizer.
var location string
if b.state.ServerClustered && !b.Driver().Info().Remote {
location = b.state.ServerName
}
// Record new volume with authorizer.
err = b.state.Authorizer.AddStoragePoolVolume(b.state.ShutdownCtx, api.ProjectDefaultName, b.Name(), drivers.VolumeTypeImage.Singular(), fingerprint, location)
if err != nil {
logger.Error("Failed to add storage volume to authorizer", logger.Ctx{"name": fingerprint, "type": drivers.VolumeTypeImage, "pool": b.Name(), "project": api.ProjectDefaultName, "error": err})
}
reverter.Add(func() {
_ = b.state.Authorizer.DeleteStoragePoolVolume(b.state.ShutdownCtx, api.ProjectDefaultName, b.Name(), drivers.VolumeTypeImage.Singular(), fingerprint, location)
})
err = b.driver.CreateVolume(imgVol, &volFiller, op)
if err != nil {
return err
}
reverter.Add(func() { _ = b.driver.DeleteVolume(imgVol, op) })
// If the volume filler has recorded the size of the unpacked volume, then store this in the image DB row.
if volFiller.Size != 0 {
imgVol.Config()["volatile.rootfs.size"] = fmt.Sprintf("%d", volFiller.Size)
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.UpdateStoragePoolVolume(ctx, api.ProjectDefaultName, fingerprint, db.StoragePoolVolumeTypeImage, b.id, "", imgVol.Config())
})
if err != nil {
return err
}
}
reverter.Success()
return nil
}
// shouldUseOptimizedImage determines if an optimized image should be used based on the provided volume config.
// It returns true if the volume config aligns with the pool's default configuration, and an optimized image does
// not exist or also matches the pool's default configuration.
func (b *backend) shouldUseOptimizedImage(fingerprint string, contentType drivers.ContentType, volConfig map[string]string, op *operations.Operation) (bool, error) {
canOptimizeImage := b.driver.Info().OptimizedImages
// If the volume config is empty, the default pool configuration is used, making the driver's support
// for optimized images the determining factor. However, an optimized image cannot be utilized if the
// driver lacks support for it.
if !canOptimizeImage || len(volConfig) == 0 {
return canOptimizeImage, nil
}
// Create the image volume with the provided volume config.
newImgVol := b.GetVolume(drivers.VolumeTypeImage, contentType, fingerprint, volConfig)
err := b.Driver().FillVolumeConfig(newImgVol)
if err != nil {
return false, err
}
// Create the image volume with pool's default settings.
poolDefaultImgVol := b.GetVolume(drivers.VolumeTypeImage, contentType, fingerprint, nil)
err = b.Driver().FillVolumeConfig(poolDefaultImgVol)
if err != nil {
return false, err
}
// If the new volume's config doesn't match the pool's default configuration, don't use an optimized image.
if !volumeConfigsMatch(newImgVol, poolDefaultImgVol) {
return false, nil
}
// Load existing optimized image, if it exists.
imgDBVol, err := VolumeDBGet(b, api.ProjectDefaultName, fingerprint, drivers.VolumeTypeImage)
if err != nil && !response.IsNotFoundError(err) {
return false, err
}
if imgDBVol != nil {
// Ensure existing optimized image's config matches the pool's default configuration.
imgVol := b.GetVolume(drivers.VolumeTypeImage, contentType, fingerprint, imgDBVol.Config)
if !volumeConfigsMatch(newImgVol, imgVol) {
return false, nil
}
}
return true, nil
}
// volumeConfigsMatch checks if the block-backed modes of two volumes match, and if they are block-backed, ensures
// their filesystem configurations are also identical.
func volumeConfigsMatch(vol1, vol2 drivers.Volume) bool {
blockModeChanged := vol1.IsBlockBacked() != vol2.IsBlockBacked()
blockFSChanged := vol1.IsBlockBacked() && vol1.Config()["block.filesystem"] != vol2.Config()["block.filesystem"]
// TODO: Temporary workaround for zfs.blocksize issue:
// When zfs.blocksize changes, a new optimized image isn't generated. This ensures we don't use an
// optimized image if initial.zfs.blocksize differs from the default pool settings.
//
// Note: If initial.zfs.blocksize is set to 8KiB and volume.zfs.blocksize is unset (defaults to 8KiB),
// they're considered unequal ("" != "8KiB"), preventing the use of a matching optimized image.
blockSizeChanged := vol1.IsBlockBacked() && vol1.Config()["zfs.blocksize"] != vol2.Config()["zfs.blocksize"]
return !blockModeChanged && !blockFSChanged && !blockSizeChanged
}
// DeleteImage removes an image from the database and underlying storage device if needed.
func (b *backend) DeleteImage(fingerprint string, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"fingerprint": fingerprint})
l.Debug("DeleteImage started")
defer l.Debug("DeleteImage finished")
// We need to lock this operation to ensure that the image is not being deleted multiple times.
unlock, err := locking.Lock(context.TODO(), drivers.OperationLockName("DeleteImage", b.name, drivers.VolumeTypeImage, "", fingerprint))
if err != nil {
return err
}
defer unlock()
// Load the storage volume in order to get the volume config which is needed for some drivers.
imgDBVol, err := VolumeDBGet(b, api.ProjectDefaultName, fingerprint, drivers.VolumeTypeImage)
if err != nil {
return err
}
// Get the content type.
dbContentType, err := VolumeContentTypeNameToContentType(imgDBVol.ContentType)
if err != nil {
return err
}
contentType, err := VolumeDBContentTypeToContentType(dbContentType)
if err != nil {
return err
}
vol := b.GetVolume(drivers.VolumeTypeImage, contentType, fingerprint, imgDBVol.Config)
volExists, err := b.driver.HasVolume(vol)
if err != nil {
return err
}
if volExists {
err = b.driver.DeleteVolume(vol, op)
if err != nil {
return err
}
}
err = VolumeDBDelete(b, api.ProjectDefaultName, fingerprint, vol.Type())
if err != nil {
return err
}
// Record volume deletion with authorizer.
var location string
if b.state.ServerClustered && !b.Driver().Info().Remote {
location = b.state.ServerName
}
err = b.state.Authorizer.DeleteStoragePoolVolume(b.state.ShutdownCtx, api.ProjectDefaultName, b.Name(), vol.Type().Singular(), fingerprint, location)
if err != nil {
logger.Error("Failed to remove storage volume from authorizer", logger.Ctx{"name": fingerprint, "type": vol.Type(), "pool": b.Name(), "project": api.ProjectDefaultName, "error": err})
}
b.state.Events.SendLifecycle(api.ProjectDefaultName, lifecycle.StorageVolumeDeleted.Event(vol, string(vol.Type()), api.ProjectDefaultName, op, nil))
return nil
}
// updateVolumeDescriptionOnly is a helper function used when handling update requests for volumes
// that only allow their descriptions to be updated. If any config supplied differs from the
// current volume's config then an error is returned.
func (b *backend) updateVolumeDescriptionOnly(projectName string, volName string, volType drivers.VolumeType, newDesc string, newConfig map[string]string, op *operations.Operation) error {
volDBType, err := VolumeTypeToDBType(volType)
if err != nil {
return err
}
// Get current config to compare what has changed.
curVol, err := VolumeDBGet(b, projectName, volName, volType)
if err != nil {
return err
}
if newConfig != nil {
changedConfig, _ := b.detectChangedConfig(curVol.Config, newConfig)
if len(changedConfig) != 0 {
return errors.New("Volume config is not editable")
}
}
// Update the database if description changed. Use current config.
if newDesc != curVol.Description {
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.UpdateStoragePoolVolume(ctx, projectName, volName, volDBType, b.ID(), newDesc, curVol.Config)
})
if err != nil {
return err
}
}
// Get content type.
dbContentType, err := VolumeContentTypeNameToContentType(curVol.ContentType)
if err != nil {
return err
}
contentType, err := VolumeDBContentTypeToContentType(dbContentType)
if err != nil {
return err
}
// Validate config.
vol := b.GetVolume(drivers.VolumeType(curVol.Type), contentType, volName, newConfig)
if !vol.IsSnapshot() {
b.state.Events.SendLifecycle(projectName, lifecycle.StorageVolumeUpdated.Event(vol, string(vol.Type()), projectName, op, nil))
} else {
b.state.Events.SendLifecycle(projectName, lifecycle.StorageVolumeSnapshotUpdated.Event(vol, string(vol.Type()), projectName, op, nil))
}
return nil
}
// UpdateImage updates image config.
func (b *backend) UpdateImage(fingerprint, newDesc string, newConfig map[string]string, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"fingerprint": fingerprint, "newDesc": newDesc, "newConfig": newConfig})
l.Debug("UpdateImage started")
defer l.Debug("UpdateImage finished")
return b.updateVolumeDescriptionOnly(api.ProjectDefaultName, fingerprint, drivers.VolumeTypeImage, newDesc, newConfig, op)
}
// CreateBucket creates an object bucket.
func (b *backend) CreateBucket(projectName string, bucket api.StorageBucketsPost, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": projectName, "bucketName": bucket.Name, "desc": bucket.Description, "config": bucket.Config})
l.Debug("CreateBucket started")
defer l.Debug("CreateBucket finished")
err := b.isStatusReady()
if err != nil {
return err
}
if !b.Driver().Info().Buckets {
return errors.New("Storage pool does not support buckets")
}
// Must be defined before revert so that its not cancelled by time reverter.Fail runs.
ctx, ctxCancel := context.WithTimeout(context.TODO(), time.Duration(time.Second*30))
defer ctxCancel()
// Validate config and create database entry for new storage bucket.
reverter := revert.New()
defer reverter.Fail()
memberSpecific := !b.Driver().Info().Remote // Member specific if storage pool isn't remote.
bucketID, err := BucketDBCreate(context.TODO(), b, projectName, memberSpecific, &bucket)
if err != nil {
return err
}
reverter.Add(func() { _ = BucketDBDelete(context.TODO(), b, bucketID) })
bucketVolName := project.StorageVolume(projectName, bucket.Name)
bucketVol := b.GetVolume(drivers.VolumeTypeBucket, drivers.ContentTypeFS, bucketVolName, bucket.Config)
// Create the bucket on the storage device.
if memberSpecific {
// Handle common MinIO implementation for local storage drivers.
err := b.driver.CreateVolume(bucketVol, nil, op)
if err != nil {
return err
}
reverter.Add(func() { _ = b.driver.DeleteVolume(bucketVol, op) })
// Start minio process.
minioProc, err := b.ActivateBucket(projectName, bucket.Name, op)
if err != nil {
return err
}
s3Client, err := minioProc.S3Client()
if err != nil {
return err
}
bucketExists, err := s3Client.BucketExists(ctx, bucket.Name)
if err != nil {
return fmt.Errorf("Failed checking if bucket exists: %w", err)
}
if bucketExists {
return api.StatusErrorf(http.StatusConflict, "A bucket for that name already exists")
}
// Create new bucket.
err = s3Client.MakeBucket(ctx, bucket.Name, minio.MakeBucketOptions{})
if err != nil {
return fmt.Errorf("Failed creating bucket: %w", err)
}
reverter.Add(func() { _ = s3Client.RemoveBucket(ctx, bucket.Name) })
} else {
// Handle per-driver implementation for remote storage drivers.
err = b.driver.CreateBucket(bucketVol, op)
if err != nil {
return err
}
}
reverter.Success()
return nil
}
// UpdateBucket updates an object bucket.
func (b *backend) UpdateBucket(projectName string, bucketName string, bucket api.StorageBucketPut, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": projectName, "bucketName": bucketName, "desc": bucket.Description, "config": bucket.Config})
l.Debug("UpdateBucket started")
defer l.Debug("UpdateBucket finished")
err := b.isStatusReady()
if err != nil {
return err
}
if !b.Driver().Info().Buckets {
return errors.New("Storage pool does not support buckets")
}
memberSpecific := !b.Driver().Info().Remote // Member specific if storage pool isn't remote.
// Get current config to compare what has changed.
var curBucket *db.StorageBucket
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
curBucket, err = tx.GetStoragePoolBucket(ctx, b.id, projectName, memberSpecific, bucketName)
return err
})
if err != nil {
return err
}
bucketVolName := project.StorageVolume(projectName, curBucket.Name)
curBucketVol := b.GetVolume(drivers.VolumeTypeBucket, drivers.ContentTypeFS, bucketVolName, curBucket.Config)
// Validate config.
newBucketVol := b.GetVolume(drivers.VolumeTypeBucket, drivers.ContentTypeFS, bucketVolName, bucket.Config)
err = b.driver.ValidateBucket(newBucketVol)
if err != nil {
return err
}
err = b.driver.ValidateVolume(newBucketVol, false)
if err != nil {
return err
}
curBucketEtagHash, err := localUtil.EtagHash(curBucket.Etag())
if err != nil {
return err
}
newBucket := api.StorageBucket{
Name: curBucket.Name,
StorageBucketPut: bucket,
}
newBucketEtagHash, err := localUtil.EtagHash(newBucket.Etag())
if err != nil {
return err
}
if curBucketEtagHash == newBucketEtagHash {
return nil // Nothing has changed.
}
changedConfig, userOnly := b.detectChangedConfig(curBucket.Config, bucket.Config)
if len(changedConfig) > 0 && !userOnly {
if memberSpecific {
// Stop MinIO process if running so volume can be resized if needed.
minioProc, err := miniod.Get(curBucketVol.Name())
if err != nil {
return err
}
if minioProc != nil {
err = minioProc.Stop(context.Background())
if err != nil {
return fmt.Errorf("Failed stopping bucket: %w", err)
}
}
err = b.driver.UpdateVolume(curBucketVol, changedConfig)
if err != nil {
return err
}
} else {
// Handle per-driver implementation for remote storage drivers.
err = b.driver.UpdateBucket(curBucketVol, changedConfig)
if err != nil {
return err
}
}
}
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Update the database record.
return tx.UpdateStoragePoolBucket(ctx, b.id, curBucket.ID, &bucket)
})
if err != nil {
return err
}
return nil
}
// DeleteBucket deletes an object bucket.
func (b *backend) DeleteBucket(projectName string, bucketName string, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": projectName, "bucketName": bucketName})
l.Debug("DeleteBucket started")
defer l.Debug("DeleteBucket finished")
err := b.isStatusReady()
if err != nil {
return err
}
if !b.Driver().Info().Buckets {
return errors.New("Storage pool does not support buckets")
}
memberSpecific := !b.Driver().Info().Remote // Member specific if storage pool isn't remote.
var bucket *db.StorageBucket
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
bucket, err = tx.GetStoragePoolBucket(ctx, b.id, projectName, memberSpecific, bucketName)
return err
})
if err != nil {
return err
}
bucketVolName := project.StorageVolume(projectName, bucket.Name)
bucketVol := b.GetVolume(drivers.VolumeTypeBucket, drivers.ContentTypeFS, bucketVolName, bucket.Config)
if memberSpecific {
// Handle common MinIO implementation for local storage drivers.
// Stop MinIO process if running.
minioProc, err := miniod.Get(bucketVolName)
if err != nil {
return err
}
if minioProc != nil {
err = minioProc.Stop(context.Background())
if err != nil {
return fmt.Errorf("Failed stopping bucket: %w", err)
}
}
vol := b.GetVolume(drivers.VolumeTypeBucket, drivers.ContentTypeFS, bucketVolName, nil)
err = b.driver.DeleteVolume(vol, op)
if err != nil {
return err
}
} else {
// Handle per-driver implementation for remote storage drivers.
err = b.driver.DeleteBucket(bucketVol, op)
if err != nil {
return err
}
}
_ = BucketDBDelete(context.TODO(), b, bucket.ID)
if err != nil {
return err
}
return nil
}
// ImportBucket takes an existing bucket on the storage backend and ensures that the DB records
// are restored as needed to make it operational with Incus.
// Used during the recovery import stage.
func (b *backend) ImportBucket(projectName string, poolVol *backupConfig.Config, op *operations.Operation) (revert.Hook, error) {
if poolVol.Bucket == nil {
return nil, errors.New("Invalid pool bucket config supplied")
}
l := b.logger.AddContext(logger.Ctx{"project": projectName, "bucketName": poolVol.Bucket.Name})
l.Debug("ImportBucket started")
defer l.Debug("ImportBucket finished")
reverter := revert.New()
defer reverter.Fail()
// Copy bucket config from backup file if present (so BucketDBCreate can safely modify the copy if needed).
bucketConfig := util.CloneMap(poolVol.Bucket.Config)
bucket := &api.StorageBucketsPost{
Name: poolVol.Bucket.Name,
StorageBucketPut: poolVol.Bucket.StorageBucketPut,
}
// Validate config and create database entry for restored bucket.
bucketID, err := BucketDBCreate(b.state.ShutdownCtx, b, projectName, true, bucket)
if err != nil {
return nil, err
}
reverter.Add(func() { _ = BucketDBDelete(b.state.ShutdownCtx, b, bucketID) })
// Get the bucket name on storage.
storageBucketName := project.StorageVolume(projectName, bucket.Name)
storageBucket := b.GetVolume(drivers.VolumeTypeBucket, drivers.ContentTypeFS, storageBucketName, bucketConfig)
err = b.driver.ValidateVolume(storageBucket, false)
if err != nil {
return nil, err
}
memberSpecific := !b.Driver().Info().Remote // Member specific if storage pool isn't remote.
if memberSpecific {
// Handle common MinIO implementation for local storage drivers.
// Extract existing bucket keys from MinIO.
keys, err := b.recoverMinIOKeys(projectName, bucket.Name, op)
if err != nil {
return nil, err
}
// Insert keys into the database.
for _, key := range keys {
var keyID int64
err := b.state.DB.Cluster.Transaction(b.state.ShutdownCtx, func(ctx context.Context, tx *db.ClusterTx) error {
keyID, err = tx.CreateStoragePoolBucketKey(ctx, bucketID, key)
return err
})
if err != nil {
return nil, err
}
reverter.Add(func() {
_ = b.state.DB.Cluster.Transaction(b.state.ShutdownCtx, func(ctx context.Context, tx *db.ClusterTx) error {
return tx.DeleteStoragePoolBucketKey(ctx, bucketID, keyID)
})
})
}
} else {
return nil, errors.New("Importing buckets from a remote storage is not supported")
}
cleanup := reverter.Clone().Fail
reverter.Success()
return cleanup, nil
}
// recoverMinIOKeys retrieves existing bucket keys from MinIO for each service account associated with the given bucket.
func (b *backend) recoverMinIOKeys(projectName string, bucketName string, op *operations.Operation) ([]api.StorageBucketKeysPost, error) {
// Start minio process.
minioProc, err := b.ActivateBucket(projectName, bucketName, op)
if err != nil {
return nil, err
}
// Initialize minio client object.
adminClient, err := minioProc.AdminClient()
if err != nil {
return nil, err
}
ctx, ctxCancel := context.WithTimeout(b.state.ShutdownCtx, time.Duration(time.Second*30))
defer ctxCancel()
// Export IAM data (response is ZIP file).
iamBytes, err := adminClient.ExportIAM(ctx)
if err != nil {
return nil, err
}
iamZipReader, err := zip.NewReader(bytes.NewReader(iamBytes), int64(len(iamBytes)))
if err != nil {
return nil, err
}
// We are interested only in a json file that contains service accounts.
// Find that file and extract service accounts.
svcAccounts := map[string]miniod.AddServiceAccountResp{}
for _, file := range iamZipReader.File {
if file.Name != "iam-assets/svcaccts.json" {
continue
}
f, err := file.Open()
if err != nil {
return nil, err
}
defer f.Close()
fContent, err := io.ReadAll(f)
if err != nil {
return nil, err
}
err = json.Unmarshal(fContent, &svcAccounts)
if err != nil {
return nil, err
}
break
}
var recoveredKeys []api.StorageBucketKeysPost
// Extract bucket keys for each service account.
for _, creds := range svcAccounts {
svcAccountInfo, err := adminClient.InfoServiceAccount(ctx, creds.AccessKey)
if err != nil {
return nil, err
}
jsonBytes, err := json.Marshal(svcAccountInfo.Policy)
if err != nil {
return nil, err
}
bucketRole, err := s3.BucketPolicyRole(bucketName, string(jsonBytes))
if err != nil {
return nil, err
}
key := api.StorageBucketKeysPost{
Name: creds.AccessKey,
StorageBucketKeyPut: api.StorageBucketKeyPut{
Description: "Recovered bucket key",
Role: bucketRole,
AccessKey: creds.AccessKey,
SecretKey: creds.SecretKey,
},
}
recoveredKeys = append(recoveredKeys, key)
}
return recoveredKeys, nil
}
// CreateBucketKey creates an object bucket key.
func (b *backend) CreateBucketKey(projectName string, bucketName string, key api.StorageBucketKeysPost, op *operations.Operation) (*api.StorageBucketKey, error) {
l := b.logger.AddContext(logger.Ctx{"project": projectName, "bucketName": bucketName, "keyName": key.Name, "desc": key.Description, "role": key.Role})
l.Debug("CreateBucketKey started")
defer l.Debug("CreateBucketKey finished")
err := b.isStatusReady()
if err != nil {
return nil, err
}
if !b.Driver().Info().Buckets {
return nil, errors.New("Storage pool does not support buckets")
}
// Must be defined before revert so that its not cancelled by time reverter.Fail runs.
ctx, ctxCancel := context.WithTimeout(context.TODO(), time.Duration(time.Second*30))
defer ctxCancel()
reverter := revert.New()
defer reverter.Fail()
memberSpecific := !b.Driver().Info().Remote // Member specific if storage pool isn't remote.
var bucket *db.StorageBucket
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
bucket, err = tx.GetStoragePoolBucket(ctx, b.id, projectName, memberSpecific, bucketName)
return err
})
if err != nil {
return nil, err
}
bucketVolName := project.StorageVolume(projectName, bucket.Name)
bucketVol := b.GetVolume(drivers.VolumeTypeBucket, drivers.ContentTypeFS, bucketVolName, bucket.Config)
// Create the bucket key on the storage device.
creds := drivers.S3Credentials{
AccessKey: key.AccessKey,
SecretKey: key.SecretKey,
}
err = b.driver.ValidateBucketKey(key.Name, creds, key.Role)
if err != nil {
return nil, err
}
var newCreds *drivers.S3Credentials
if memberSpecific {
// Handle common MinIO implementation for local storage drivers.
// Start minio process.
minioProc, err := b.ActivateBucket(projectName, bucket.Name, op)
if err != nil {
return nil, err
}
bucketPolicy, err := s3.BucketPolicy(bucket.Name, key.Role)
if err != nil {
return nil, err
}
adminClient, err := minioProc.AdminClient()
if err != nil {
return nil, err
}
adminCreds, err := adminClient.AddServiceAccount(ctx, minioProc.AdminUser(), key.AccessKey, key.SecretKey, bucketPolicy)
if err != nil {
return nil, err
}
reverter.Add(func() { _ = adminClient.DeleteServiceAccount(ctx, adminCreds.AccessKey) })
newCreds = &drivers.S3Credentials{
AccessKey: adminCreds.AccessKey,
SecretKey: adminCreds.SecretKey,
}
} else {
// Handle per-driver implementation for remote storage drivers.
newCreds, err = b.driver.CreateBucketKey(bucketVol, key.Name, creds, key.Role, op)
if err != nil {
return nil, err
}
reverter.Add(func() { _ = b.driver.DeleteBucketKey(bucketVol, key.Name, op) })
}
key.AccessKey = newCreds.AccessKey
key.SecretKey = newCreds.SecretKey
newKey := api.StorageBucketKey{
Name: key.Name,
StorageBucketKeyPut: api.StorageBucketKeyPut{
Description: key.Description,
Role: key.Role,
AccessKey: key.AccessKey,
SecretKey: key.SecretKey,
},
}
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
_, err = tx.CreateStoragePoolBucketKey(ctx, bucket.ID, key)
return err
})
if err != nil {
return nil, err
}
reverter.Success()
return &newKey, err
}
func (b *backend) UpdateBucketKey(projectName string, bucketName string, keyName string, key api.StorageBucketKeyPut, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": projectName, "bucketName": bucketName, "keyName": keyName, "desc": key.Description, "role": key.Role})
l.Debug("UpdateBucketKey started")
defer l.Debug("UpdateBucketKey finished")
err := b.isStatusReady()
if err != nil {
return err
}
if !b.Driver().Info().Buckets {
return errors.New("Storage pool does not support buckets")
}
// Must be defined before revert so that its not cancelled by time reverter.Fail runs.
ctx, ctxCancel := context.WithTimeout(context.TODO(), time.Duration(time.Second*30))
defer ctxCancel()
memberSpecific := !b.Driver().Info().Remote // Member specific if storage pool isn't remote.
// Get current config to compare what has changed.
var bucket *db.StorageBucket
var curBucketKey *db.StorageBucketKey
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
bucket, err = tx.GetStoragePoolBucket(ctx, b.id, projectName, memberSpecific, bucketName)
if err != nil {
return err
}
curBucketKey, err = tx.GetStoragePoolBucketKey(ctx, bucket.ID, keyName)
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
curBucketKeyEtagHash, err := localUtil.EtagHash(curBucketKey.Etag())
if err != nil {
return err
}
newBucketKey := api.StorageBucketKey{
Name: curBucketKey.Name,
StorageBucketKeyPut: key,
}
newBucketKeyEtagHash, err := localUtil.EtagHash(newBucketKey.Etag())
if err != nil {
return err
}
if curBucketKeyEtagHash == newBucketKeyEtagHash {
return nil // Nothing has changed.
}
bucketVolName := project.StorageVolume(projectName, bucket.Name)
bucketVol := b.GetVolume(drivers.VolumeTypeBucket, drivers.ContentTypeFS, bucketVolName, bucket.Config)
creds := drivers.S3Credentials{
AccessKey: newBucketKey.AccessKey,
SecretKey: newBucketKey.SecretKey,
}
err = b.driver.ValidateBucketKey(keyName, creds, key.Role)
if err != nil {
return err
}
if memberSpecific {
// Handle common MinIO implementation for local storage drivers.
// Start minio process.
minioProc, err := b.ActivateBucket(projectName, bucket.Name, op)
if err != nil {
return err
}
bucketPolicy, err := s3.BucketPolicy(bucket.Name, key.Role)
if err != nil {
return err
}
adminClient, err := minioProc.AdminClient()
if err != nil {
return err
}
// Delete service account if exists (this allows changing the access key).
_ = adminClient.DeleteServiceAccount(ctx, curBucketKey.AccessKey)
newCreds, err := adminClient.AddServiceAccount(ctx, minioProc.AdminUser(), creds.AccessKey, creds.SecretKey, bucketPolicy)
if err != nil {
return err
}
if creds.SecretKey != "" && newCreds.AccessKey != creds.SecretKey {
// There seems to be a bug in MinIO where if the AccessKey isn't specified for a new
// service account but a secret key is, *both* the AccessKey and the SecreyKey are randomly
// generated, even though it should only have been the AccessKey.
// So detect this and update the SecretKey back to what it should have been.
err := adminClient.UpdateServiceAccount(ctx, newCreds.AccessKey, creds.SecretKey, bucketPolicy)
if err != nil {
return err
}
newCreds.SecretKey = creds.SecretKey
}
key.AccessKey = newCreds.AccessKey
key.SecretKey = newCreds.SecretKey
} else {
// Handle per-driver implementation for remote storage drivers.
newCreds, err := b.driver.UpdateBucketKey(bucketVol, keyName, creds, key.Role, op)
if err != nil {
return err
}
key.AccessKey = newCreds.AccessKey
key.SecretKey = newCreds.SecretKey
}
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Update the database record.
return tx.UpdateStoragePoolBucketKey(ctx, bucket.ID, curBucketKey.ID, &key)
})
if err != nil {
return err
}
return nil
}
// DeleteBucketKey deletes an object bucket key.
func (b *backend) DeleteBucketKey(projectName string, bucketName string, keyName string, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": projectName, "bucketName": bucketName, "keyName": keyName})
l.Debug("DeleteBucketKey started")
defer l.Debug("DeleteBucketKey finished")
err := b.isStatusReady()
if err != nil {
return err
}
if !b.Driver().Info().Buckets {
return errors.New("Storage pool does not support buckets")
}
// Must be defined before revert so that its not cancelled by time reverter.Fail runs.
ctx, ctxCancel := context.WithTimeout(context.TODO(), time.Duration(time.Second*30))
defer ctxCancel()
memberSpecific := !b.Driver().Info().Remote // Member specific if storage pool isn't remote.
var bucket *db.StorageBucket
var bucketKey *db.StorageBucketKey
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
bucket, err = tx.GetStoragePoolBucket(ctx, b.id, projectName, memberSpecific, bucketName)
if err != nil {
return err
}
bucketKey, err = tx.GetStoragePoolBucketKey(ctx, bucket.ID, keyName)
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
if memberSpecific {
// Handle common MinIO implementation for local storage drivers.
// Start minio process.
minioProc, err := b.ActivateBucket(projectName, bucket.Name, op)
if err != nil {
return err
}
adminClient, err := minioProc.AdminClient()
if err != nil {
return err
}
err = adminClient.DeleteServiceAccount(ctx, bucketKey.AccessKey)
if err != nil {
return err
}
} else {
// Handle per-driver implementation for remote storage drivers.
bucketVolName := project.StorageVolume(projectName, bucket.Name)
bucketVol := b.GetVolume(drivers.VolumeTypeBucket, drivers.ContentTypeFS, bucketVolName, bucket.Config)
// Delete the bucket key from the storage device.
err = b.driver.DeleteBucketKey(bucketVol, keyName, op)
if err != nil {
return err
}
}
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.DeleteStoragePoolBucketKey(ctx, bucket.ID, bucketKey.ID)
})
if err != nil {
return fmt.Errorf("Failed deleting bucket key from database: %w", err)
}
return nil
}
// ActivateBucket mounts the local bucket volume and returns the MinIO S3 process for it.
func (b *backend) ActivateBucket(projectName string, bucketName string, op *operations.Operation) (*miniod.Process, error) {
if !b.Driver().Info().Buckets {
return nil, errors.New("Storage pool does not support buckets")
}
if b.Driver().Info().Remote {
return nil, errors.New("Remote buckets cannot be activated")
}
bucketVolName := project.StorageVolume(projectName, bucketName)
bucketVol := b.GetVolume(drivers.VolumeTypeBucket, drivers.ContentTypeFS, bucketVolName, nil)
return miniod.EnsureRunning(b.state, bucketVol)
}
// GetBucketURL returns S3 URL for bucket.
func (b *backend) GetBucketURL(bucketName string) *url.URL {
err := b.isStatusReady()
if err != nil {
return nil
}
if !b.Driver().Info().Buckets {
return nil
}
memberSpecific := !b.Driver().Info().Remote // Member specific if storage pool isn't remote.
if memberSpecific {
// Handle common MinIO implementation for local storage drivers.
// Check that the storage buckets listener is configured via core.storage_buckets_address.
storageBucketsAddress := b.state.Endpoints.StorageBucketsAddress()
if storageBucketsAddress == "" {
return nil
}
return &api.NewURL().Scheme("https").Host(storageBucketsAddress).Path(bucketName).URL
}
// Handle per-driver implementation for remote storage drivers.
return b.driver.GetBucketURL(bucketName)
}
// CreateCustomVolume creates an empty custom volume.
func (b *backend) CreateCustomVolume(projectName string, volName string, desc string, config map[string]string, contentType drivers.ContentType, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": projectName, "volName": volName, "desc": desc, "config": config, "contentType": contentType})
l.Debug("CreateCustomVolume started")
defer l.Debug("CreateCustomVolume finished")
err := b.isStatusReady()
if err != nil {
return err
}
// Get the volume name on storage.
volStorageName := project.StorageVolume(projectName, volName)
vol := b.GetVolume(drivers.VolumeTypeCustom, contentType, volStorageName, config)
storagePoolSupported := slices.Contains(b.Driver().Info().VolumeTypes, drivers.VolumeTypeCustom)
if !storagePoolSupported {
return errors.New("Storage pool does not support custom volume type")
}
reverter := revert.New()
defer reverter.Fail()
// Validate config and create database entry for new storage volume.
err = VolumeDBCreate(b, projectName, volName, desc, vol.Type(), false, vol.Config(), time.Now().UTC(), time.Time{}, vol.ContentType(), false, false)
if err != nil {
return err
}
reverter.Add(func() { _ = VolumeDBDelete(b, projectName, volName, vol.Type()) })
// Create the empty custom volume on the storage device.
err = b.driver.CreateVolume(vol, nil, op)
if err != nil {
return err
}
eventCtx := logger.Ctx{"type": vol.Type()}
var location string
if b.state.ServerClustered && !b.Driver().Info().Remote {
eventCtx["location"] = b.state.ServerName
location = b.state.ServerName
}
// Record new volume with authorizer.
err = b.state.Authorizer.AddStoragePoolVolume(b.state.ShutdownCtx, projectName, b.Name(), vol.Type().Singular(), volName, location)
if err != nil {
logger.Error("Failed to add storage volume to authorizer", logger.Ctx{"name": volName, "type": vol.Type(), "pool": b.Name(), "project": projectName, "error": err})
}
b.state.Events.SendLifecycle(projectName, lifecycle.StorageVolumeCreated.Event(vol, string(vol.Type()), projectName, op, eventCtx))
reverter.Success()
return nil
}
// CreateCustomVolumeFromCopy creates a custom volume from an existing custom volume.
// It copies the snapshots from the source volume by default, but can be disabled if requested.
func (b *backend) CreateCustomVolumeFromCopy(projectName string, srcProjectName string, volName string, desc string, config map[string]string, srcPoolName, srcVolName string, snapshots bool, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": projectName, "srcProjectName": srcProjectName, "volName": volName, "desc": desc, "config": config, "srcPoolName": srcPoolName, "srcVolName": srcVolName, "snapshots": snapshots})
l.Debug("CreateCustomVolumeFromCopy started")
defer l.Debug("CreateCustomVolumeFromCopy finished")
err := b.isStatusReady()
if err != nil {
return err
}
if srcProjectName == "" {
srcProjectName = projectName
}
// Setup the source pool backend instance.
var srcPool Pool
if b.name == srcPoolName {
srcPool = b // Source and target are in the same pool so share pool var.
} else {
// Source is in a different pool to target, so load the pool.
srcPool, err = LoadByName(b.state, srcPoolName)
if err != nil {
return err
}
}
// Check source volume exists and is custom type, and get its config.
srcConfig, err := srcPool.GenerateCustomVolumeBackupConfig(srcProjectName, srcVolName, snapshots, op)
if err != nil {
return fmt.Errorf("Failed generating volume copy config: %w", err)
}
// Use the source volume's config if not supplied.
if config == nil {
config = srcConfig.Volume.Config
}
// Use the source volume's description if not supplied.
if desc == "" {
desc = srcConfig.Volume.Description
}
contentDBType, err := VolumeContentTypeNameToContentType(srcConfig.Volume.ContentType)
if err != nil {
return err
}
// Get the source volume's content type.
contentType, err := VolumeDBContentTypeToContentType(contentDBType)
if err != nil {
return err
}
storagePoolSupported := slices.Contains(b.Driver().Info().VolumeTypes, drivers.VolumeTypeCustom)
if !storagePoolSupported {
return errors.New("Storage pool does not support custom volume type")
}
// If we are copying snapshots, retrieve a list of snapshots from source volume.
var snapshotNames []string
if snapshots {
snapshotNames = make([]string, 0, len(srcConfig.VolumeSnapshots))
for _, snapshot := range srcConfig.VolumeSnapshots {
snapshotNames = append(snapshotNames, snapshot.Name)
}
}
reverter := revert.New()
defer reverter.Fail()
// Get the src volume name on storage.
srcVolStorageName := project.StorageVolume(srcProjectName, srcVolName)
srcVol := srcPool.GetVolume(drivers.VolumeTypeCustom, contentType, srcVolStorageName, srcConfig.Volume.Config)
// If the source and target are in the same pool then use CreateVolumeFromCopy rather than
// migration system as it will be quicker.
if srcPool == b {
l.Debug("CreateCustomVolumeFromCopy same-pool mode detected")
// Get the volume name on storage.
volStorageName := project.StorageVolume(projectName, volName)
vol := b.GetVolume(drivers.VolumeTypeCustom, contentType, volStorageName, config)
// Validate config and create database entry for new storage volume.
err = VolumeDBCreate(b, projectName, volName, desc, vol.Type(), false, vol.Config(), time.Now().UTC(), time.Time{}, vol.ContentType(), false, true)
if err != nil {
return err
}
reverter.Add(func() { _ = VolumeDBDelete(b, projectName, volName, vol.Type()) })
// Create database entries for new storage volume snapshots.
for i, snapName := range snapshotNames {
newSnapshotName := drivers.GetSnapshotVolumeName(volName, snapName)
var volumeSnapExpiryDate time.Time
if srcConfig.VolumeSnapshots[i].ExpiresAt != nil {
volumeSnapExpiryDate = *srcConfig.VolumeSnapshots[i].ExpiresAt
}
// Validate config and create database entry for new storage volume.
err = VolumeDBCreate(b, projectName, newSnapshotName, srcConfig.VolumeSnapshots[i].Description, vol.Type(), true, srcConfig.VolumeSnapshots[i].Config, srcConfig.VolumeSnapshots[i].CreatedAt, volumeSnapExpiryDate, vol.ContentType(), false, true)
if err != nil {
return err
}
reverter.Add(func() { _ = VolumeDBDelete(b, projectName, newSnapshotName, vol.Type()) })
}
err = b.driver.CreateVolumeFromCopy(vol, srcVol, snapshots, false, op)
if err != nil {
return err
}
eventCtx := logger.Ctx{"type": vol.Type()}
var location string
if b.state.ServerClustered && !b.Driver().Info().Remote {
eventCtx["location"] = b.state.ServerName
location = b.state.ServerName
}
// Record new volume with authorizer.
err = b.state.Authorizer.AddStoragePoolVolume(b.state.ShutdownCtx, projectName, b.Name(), vol.Type().Singular(), volName, location)
if err != nil {
logger.Error("Failed to add storage volume to authorizer", logger.Ctx{"name": volName, "type": vol.Type(), "pool": b.Name(), "project": projectName, "error": err})
}
b.state.Events.SendLifecycle(projectName, lifecycle.StorageVolumeCreated.Event(vol, string(vol.Type()), projectName, op, eventCtx))
reverter.Success()
return nil
}
// We are copying volumes between storage pools so use migration system as it will be able
// to negotiate a common transfer method between pool types.
l.Debug("CreateCustomVolumeFromCopy cross-pool mode detected")
// Negotiate the migration type to use.
offeredTypes := srcPool.MigrationTypes(contentType, false, snapshots, false, true)
offerHeader := localMigration.TypesToHeader(offeredTypes...)
migrationTypes, err := localMigration.MatchTypes(offerHeader, FallbackMigrationType(contentType), b.MigrationTypes(contentType, false, snapshots, false, true))
if err != nil {
return fmt.Errorf("Failed to negotiate copy migration type: %w", err)
}
// If we're copying block volumes, the target block volume needs to be
// at least the size of the source volume, otherwise we'll run into
// "no space left on device".
var volSize int64
if drivers.IsContentBlock(contentType) {
err = srcVol.MountTask(func(mountPath string, op *operations.Operation) error {
srcPoolBackend, ok := srcPool.(*backend)
if !ok {
return errors.New("Pool is not a backend")
}
volDiskPath, err := srcPoolBackend.driver.GetVolumeDiskPath(srcVol)
if err != nil {
return err
}
volSize, err = drivers.BlockDiskSizeBytes(volDiskPath)
if err != nil {
return err
}
return nil
}, nil)
if err != nil {
return err
}
}
var migrationSnapshots []*migration.Snapshot
if snapshots {
migrationSnapshots, err = VolumeSnapshotsToMigrationSnapshots(srcConfig.VolumeSnapshots, srcProjectName, srcPool, contentType, drivers.VolumeTypeCustom, srcVolName)
if err != nil {
return err
}
}
ctx, cancel := context.WithCancel(context.Background())
// Use in-memory pipe pair to simulate a connection between the sender and receiver.
aEnd, bEnd := memorypipe.NewPipePair(ctx)
// Run sender and receiver in separate go routines to prevent deadlocks.
aEndErrCh := make(chan error, 1)
bEndErrCh := make(chan error, 1)
go func() {
err := srcPool.MigrateCustomVolume(srcProjectName, aEnd, &localMigration.VolumeSourceArgs{
IndexHeaderVersion: localMigration.IndexHeaderVersion,
Name: srcVolName,
Snapshots: snapshotNames,
MigrationType: migrationTypes[0],
TrackProgress: true, // Do use a progress tracker on sender.
ContentType: string(contentType),
Info: &localMigration.Info{Config: srcConfig},
VolumeOnly: !snapshots,
StorageMove: true,
}, op)
if err != nil {
cancel()
}
aEndErrCh <- err
}()
go func() {
err := b.CreateCustomVolumeFromMigration(projectName, bEnd, localMigration.VolumeTargetArgs{
IndexHeaderVersion: localMigration.IndexHeaderVersion,
Name: volName,
Description: desc,
Config: config,
Snapshots: migrationSnapshots,
MigrationType: migrationTypes[0],
TrackProgress: false, // Do not use a progress tracker on receiver.
ContentType: string(contentType),
VolumeSize: volSize, // Block size setting override.
VolumeOnly: !snapshots,
StoragePool: srcPool.Name(),
}, op)
if err != nil {
cancel()
}
bEndErrCh <- err
}()
// Capture errors from the sender and receiver from their result channels.
errs := []error{}
aEndErr := <-aEndErrCh
if aEndErr != nil {
_ = aEnd.Close()
errs = append(errs, aEndErr)
}
bEndErr := <-bEndErrCh
if bEndErr != nil {
errs = append(errs, bEndErr)
}
cancel()
if len(errs) > 0 {
return fmt.Errorf("Create custom volume from copy failed: %v", errs)
}
reverter.Success()
return nil
}
// migrationIndexHeaderSend sends the migration index header to target and waits for confirmation of receipt.
func (b *backend) migrationIndexHeaderSend(l logger.Logger, indexHeaderVersion uint32, conn io.ReadWriteCloser, info *localMigration.Info) (*localMigration.InfoResponse, error) {
infoResp := localMigration.InfoResponse{}
// Send migration index header frame to target if applicable and wait for receipt.
if indexHeaderVersion > 0 {
headerJSON, err := json.Marshal(info)
if err != nil {
return nil, fmt.Errorf("Failed encoding migration index header: %w", err)
}
_, err = conn.Write(headerJSON)
if err != nil {
return nil, fmt.Errorf("Failed sending migration index header: %w", err)
}
err = conn.Close() // End the frame.
if err != nil {
return nil, fmt.Errorf("Failed closing migration index header frame: %w", err)
}
l.Debug("Sent migration index header, waiting for response", logger.Ctx{"version": indexHeaderVersion})
respBuf, err := io.ReadAll(conn)
if err != nil {
return nil, fmt.Errorf("Failed reading migration index header: %w", err)
}
err = json.Unmarshal(respBuf, &infoResp)
if err != nil {
return nil, fmt.Errorf("Failed decoding migration index header response: %w", err)
}
if infoResp.Err() != nil {
return nil, fmt.Errorf("Failed negotiating migration options: %w", err)
}
l.Debug("Received migration index header response", logger.Ctx{"response": fmt.Sprintf("%+v", infoResp), "version": indexHeaderVersion})
}
return &infoResp, nil
}
// migrationIndexHeaderReceive receives migration index header from source and sends confirmation of receipt.
// Returns the received source index header info.
func (b *backend) migrationIndexHeaderReceive(l logger.Logger, indexHeaderVersion uint32, conn io.ReadWriteCloser, refresh bool) (*localMigration.Info, error) {
info := localMigration.Info{}
// Receive index header from source if applicable and respond confirming receipt.
if indexHeaderVersion > 0 {
l.Debug("Waiting for migration index header", logger.Ctx{"version": indexHeaderVersion})
buf, err := io.ReadAll(conn)
if err != nil {
return nil, fmt.Errorf("Failed reading migration index header: %w", err)
}
err = json.Unmarshal(buf, &info)
if err != nil {
return nil, fmt.Errorf("Failed decoding migration index header: %w", err)
}
l.Debug("Received migration index header, sending response", logger.Ctx{"version": indexHeaderVersion})
infoResp := localMigration.InfoResponse{StatusCode: http.StatusOK, Refresh: &refresh}
headerJSON, err := json.Marshal(infoResp)
if err != nil {
return nil, fmt.Errorf("Failed encoding migration index header response: %w", err)
}
_, err = conn.Write(headerJSON)
if err != nil {
return nil, fmt.Errorf("Failed sending migration index header response: %w", err)
}
err = conn.Close() // End the frame.
if err != nil {
return nil, fmt.Errorf("Failed closing migration index header response frame: %w", err)
}
l.Debug("Sent migration index header response", logger.Ctx{"version": indexHeaderVersion})
}
return &info, nil
}
// MigrateCustomVolume sends a volume for migration.
func (b *backend) MigrateCustomVolume(projectName string, conn io.ReadWriteCloser, args *localMigration.VolumeSourceArgs, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": projectName, "volName": args.Name, "args": fmt.Sprintf("%+v", args)})
l.Debug("MigrateCustomVolume started")
defer l.Debug("MigrateCustomVolume finished")
// Get the volume name on storage.
volStorageName := project.StorageVolume(projectName, args.Name)
dbContentType, err := VolumeContentTypeNameToContentType(args.ContentType)
if err != nil {
return err
}
contentType, err := VolumeDBContentTypeToContentType(dbContentType)
if err != nil {
return err
}
if args.Info == nil {
return errors.New("Migration info required")
}
if args.Info.Config == nil || args.Info.Config.Volume == nil || args.Info.Config.Volume.Config == nil {
return errors.New("Volume config is required")
}
if len(args.Snapshots) != len(args.Info.Config.VolumeSnapshots) {
return fmt.Errorf("Requested snapshots count (%d) doesn't match volume snapshot config count (%d)", len(args.Snapshots), len(args.Info.Config.VolumeSnapshots))
}
// Send migration index header frame with volume info and wait for receipt.
resp, err := b.migrationIndexHeaderSend(l, args.IndexHeaderVersion, conn, args.Info)
if err != nil {
return err
}
if resp.Refresh != nil {
args.Refresh = *resp.Refresh
}
vol := b.GetVolume(drivers.VolumeTypeCustom, contentType, volStorageName, args.Info.Config.Volume.Config)
err = b.driver.MigrateVolume(vol, conn, args, op)
if err != nil {
return err
}
return nil
}
// CreateCustomVolumeFromMigration receives a volume being migrated.
func (b *backend) CreateCustomVolumeFromMigration(projectName string, conn io.ReadWriteCloser, args localMigration.VolumeTargetArgs, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": projectName, "volName": args.Name, "args": fmt.Sprintf("%+v", args)})
l.Debug("CreateCustomVolumeFromMigration started")
defer l.Debug("CreateCustomVolumeFromMigration finished")
err := b.isStatusReady()
if err != nil {
return err
}
storagePoolSupported := slices.Contains(b.Driver().Info().VolumeTypes, drivers.VolumeTypeCustom)
if !storagePoolSupported {
return errors.New("Storage pool does not support custom volume type")
}
var volumeConfig map[string]string
// Check if the volume exists in database.
dbVol, err := VolumeDBGet(b, projectName, args.Name, drivers.VolumeTypeCustom)
if err != nil && !response.IsNotFoundError(err) {
return err
}
// Prefer using existing volume config (to allow mounting existing volume correctly).
if dbVol != nil {
volumeConfig = dbVol.Config
} else {
volumeConfig = args.Config
}
// Check if the volume exists on storage.
volStorageName := project.StorageVolume(projectName, args.Name)
vol := b.GetVolume(drivers.VolumeTypeCustom, drivers.ContentType(args.ContentType), volStorageName, volumeConfig)
volExists, err := b.driver.HasVolume(vol)
if err != nil {
return err
}
// Check for inconsistencies between database and storage before continuing.
if dbVol == nil && volExists {
return errors.New("Volume already exists on storage but not in database")
}
if dbVol != nil && !volExists {
return errors.New("Volume exists in database but not on storage")
}
// Disable refresh mode if volume doesn't exist yet.
// Unlike in CreateInstanceFromMigration there is no existing check for if the volume exists, so we must do
// it here and disable refresh mode if the volume doesn't exist.
if args.Refresh && !volExists {
args.Refresh = false
} else if !args.Refresh && volExists {
return errors.New("Cannot create volume, already exists on migration target storage")
}
// VolumeSize is set to the actual size of the underlying block device.
// The target should use this value if present, otherwise it might get an error like
// "no space left on device".
if args.VolumeSize > 0 {
vol.SetConfigSize(fmt.Sprintf("%d", args.VolumeSize))
}
// Receive index header from source if applicable and respond confirming receipt.
// This will also let the source know whether to actually perform a refresh, as the target
// will set Refresh to false if the volume doesn't exist.
srcInfo, err := b.migrationIndexHeaderReceive(l, args.IndexHeaderVersion, conn, args.Refresh)
if err != nil {
return err
}
reverter := revert.New()
defer reverter.Fail()
if !args.Refresh {
// Validate config and create database entry for new storage volume.
// Strip unsupported config keys (in case the export was made from a different type of storage pool).
err = VolumeDBCreate(b, projectName, args.Name, args.Description, vol.Type(), false, vol.Config(), time.Now().UTC(), time.Time{}, vol.ContentType(), true, true)
if err != nil {
return err
}
reverter.Add(func() { _ = VolumeDBDelete(b, projectName, args.Name, vol.Type()) })
}
if len(args.Snapshots) > 0 {
// Create database entries for new storage volume snapshots.
for _, snapshot := range args.Snapshots {
snapName := snapshot.GetName()
newSnapshotName := drivers.GetSnapshotVolumeName(args.Name, snapName)
snapConfig := vol.Config() // Use parent volume config by default.
snapDescription := args.Description
snapExpiryDate := time.Time{}
snapCreationDate := time.Time{}
// If the source snapshot config is available, use that.
if srcInfo != nil && srcInfo.Config != nil {
for _, srcSnap := range srcInfo.Config.VolumeSnapshots {
if srcSnap.Name != snapName {
continue
}
snapConfig = srcSnap.Config
snapDescription = srcSnap.Description
if srcSnap.ExpiresAt != nil {
snapExpiryDate = *srcSnap.ExpiresAt
}
snapCreationDate = srcSnap.CreatedAt
break
}
}
// Validate config and create database entry for new storage volume.
// Strip unsupported config keys (in case the export was made from a different type of storage pool).
err = VolumeDBCreate(b, projectName, newSnapshotName, snapDescription, vol.Type(), true, snapConfig, snapCreationDate, snapExpiryDate, vol.ContentType(), true, true)
if err != nil {
return err
}
reverter.Add(func() { _ = VolumeDBDelete(b, projectName, newSnapshotName, vol.Type()) })
}
}
err = b.driver.CreateVolumeFromMigration(vol, conn, args, nil, op)
if err != nil {
return err
}
eventCtx := logger.Ctx{"type": vol.Type()}
var location string
if b.state.ServerClustered && !b.Driver().Info().Remote {
eventCtx["location"] = b.state.ServerName
location = b.state.ServerName
}
// Record new volume with authorizer.
err = b.state.Authorizer.AddStoragePoolVolume(b.state.ShutdownCtx, projectName, b.Name(), vol.Type().Singular(), args.Name, location)
if err != nil {
logger.Error("Failed to add storage volume to authorizer", logger.Ctx{"name": args.Name, "type": vol.Type(), "pool": b.Name(), "project": projectName, "error": err})
}
b.state.Events.SendLifecycle(projectName, lifecycle.StorageVolumeCreated.Event(vol, string(vol.Type()), projectName, op, eventCtx))
reverter.Success()
return nil
}
// RenameCustomVolume renames a custom volume and its snapshots.
func (b *backend) RenameCustomVolume(projectName string, volName string, newVolName string, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": projectName, "volName": volName, "newVolName": newVolName})
l.Debug("RenameCustomVolume started")
defer l.Debug("RenameCustomVolume finished")
if internalInstance.IsSnapshot(volName) {
return errors.New("Volume name cannot be a snapshot")
}
if internalInstance.IsSnapshot(newVolName) {
return errors.New("New volume name cannot be a snapshot")
}
reverter := revert.New()
defer reverter.Fail()
volume, err := VolumeDBGet(b, projectName, volName, drivers.VolumeTypeCustom)
if err != nil {
return err
}
// Rename each snapshot to have the new parent volume prefix.
snapshots, err := VolumeDBSnapshotsGet(b, projectName, volName, drivers.VolumeTypeCustom)
if err != nil {
return err
}
for _, srcSnapshot := range snapshots {
_, snapName, _ := api.GetParentAndSnapshotName(srcSnapshot.Name)
newSnapVolName := drivers.GetSnapshotVolumeName(newVolName, snapName)
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.RenameStoragePoolVolume(ctx, projectName, srcSnapshot.Name, newSnapVolName, db.StoragePoolVolumeTypeCustom, b.ID())
})
if err != nil {
return err
}
reverter.Add(func() {
_ = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.RenameStoragePoolVolume(ctx, projectName, newSnapVolName, srcSnapshot.Name, db.StoragePoolVolumeTypeCustom, b.ID())
})
})
}
var backups []db.StoragePoolVolumeBackup
// Rename each backup to have the new parent volume prefix.
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
var err error
backups, err = tx.GetStoragePoolVolumeBackups(ctx, projectName, volName, b.ID())
return err
})
if err != nil {
return err
}
for _, br := range backups {
backupRow := br // Local var for revert.
_, backupName, _ := api.GetParentAndSnapshotName(backupRow.Name)
newVolBackupName := drivers.GetSnapshotVolumeName(newVolName, backupName)
volBackup := backup.NewVolumeBackup(b.state, projectName, b.name, volName, backupRow.ID, backupRow.Name, backupRow.CreationDate, backupRow.ExpiryDate, backupRow.VolumeOnly, backupRow.OptimizedStorage)
err = volBackup.Rename(newVolBackupName)
if err != nil {
return fmt.Errorf("Failed renaming backup %q to %q: %w", backupRow.Name, newVolBackupName, err)
}
reverter.Add(func() {
_ = volBackup.Rename(backupRow.Name)
})
}
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.RenameStoragePoolVolume(ctx, projectName, volName, newVolName, db.StoragePoolVolumeTypeCustom, b.ID())
})
if err != nil {
return err
}
reverter.Add(func() {
_ = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.RenameStoragePoolVolume(ctx, projectName, newVolName, volName, db.StoragePoolVolumeTypeCustom, b.ID())
})
})
// Get the volume name on storage.
volStorageName := project.StorageVolume(projectName, volName)
newVolStorageName := project.StorageVolume(projectName, newVolName)
vol := b.GetVolume(drivers.VolumeTypeCustom, drivers.ContentType(volume.ContentType), volStorageName, volume.Config)
err = b.driver.RenameVolume(vol, newVolStorageName, op)
if err != nil {
return err
}
var location string
if b.state.ServerClustered && !b.Driver().Info().Remote {
location = b.state.ServerName
}
err = b.state.Authorizer.RenameStoragePoolVolume(b.state.ShutdownCtx, projectName, b.Name(), vol.Type().Singular(), volName, newVolStorageName, location)
if err != nil {
logger.Error("Failed to rename storage volume in authorizer", logger.Ctx{"old_name": volName, "new_name": newVolStorageName, "type": vol.Type(), "pool": b.Name(), "project": projectName, "error": err})
}
vol = b.GetVolume(drivers.VolumeTypeCustom, drivers.ContentType(volume.ContentType), newVolStorageName, nil)
b.state.Events.SendLifecycle(projectName, lifecycle.StorageVolumeRenamed.Event(vol, string(vol.Type()), projectName, op, logger.Ctx{"old_name": volName}))
reverter.Success()
return nil
}
// detectChangedConfig returns the config that has changed between current and new config maps.
// Also returns a boolean indicating whether all of the changed keys start with "user.".
// Deleted keys will be returned as having an empty string value.
func (b *backend) detectChangedConfig(curConfig, newConfig map[string]string) (map[string]string, bool) {
// Diff the configurations.
changedConfig := make(map[string]string)
userOnly := true
for key := range curConfig {
if curConfig[key] != newConfig[key] {
if !strings.HasPrefix(key, "user.") {
userOnly = false
}
changedConfig[key] = newConfig[key] // Will be empty string on deleted keys.
}
}
for key := range newConfig {
if curConfig[key] != newConfig[key] {
if !strings.HasPrefix(key, "user.") {
userOnly = false
}
changedConfig[key] = newConfig[key]
}
}
return changedConfig, userOnly
}
// UpdateCustomVolume applies the supplied config to the custom volume.
func (b *backend) UpdateCustomVolume(projectName string, volName string, newDesc string, newConfig map[string]string, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": projectName, "volName": volName, "newDesc": newDesc, "newConfig": newConfig})
l.Debug("UpdateCustomVolume started")
defer l.Debug("UpdateCustomVolume finished")
if internalInstance.IsSnapshot(volName) {
return errors.New("Volume name cannot be a snapshot")
}
// Get the volume name on storage.
volStorageName := project.StorageVolume(projectName, volName)
// Get current config to compare what has changed.
curVol, err := VolumeDBGet(b, projectName, volName, drivers.VolumeTypeCustom)
if err != nil {
return err
}
// Get content type.
dbContentType, err := VolumeContentTypeNameToContentType(curVol.ContentType)
if err != nil {
return err
}
contentType, err := VolumeDBContentTypeToContentType(dbContentType)
if err != nil {
return err
}
// Validate config.
newVol := b.GetVolume(drivers.VolumeTypeCustom, contentType, volStorageName, newConfig)
err = b.driver.ValidateVolume(newVol, false)
if err != nil {
return err
}
// Apply config changes if there are any.
changedConfig, userOnly := b.detectChangedConfig(curVol.Config, newConfig)
if len(changedConfig) != 0 {
// Forbid changing the config for ISO custom volumes as they are read-only.
if contentType == drivers.ContentTypeISO {
return errors.New("Custom ISO volume config cannot be changed")
}
// Check that the volume's block.filesystem property isn't being changed.
if changedConfig["block.filesystem"] != "" {
return errors.New(`Custom volume "block.filesystem" property cannot be changed`)
}
// Check for config changing that is not allowed when running instances are using it.
if changedConfig["security.shifted"] != "" {
err = VolumeUsedByInstanceDevices(b.state, b.name, projectName, &curVol.StorageVolume, true, func(dbInst db.InstanceArgs, project api.Project, usedByDevices []string) error {
inst, err := instance.Load(b.state, dbInst, project)
if err != nil {
return err
}
// Confirm that no running instances are using it when changing shifted state.
if inst.IsRunning() && changedConfig["security.shifted"] != "" {
return errors.New("Cannot modify shifting with running instances using the volume")
}
return nil
})
if err != nil {
return err
}
}
sharedVolume, ok := changedConfig["security.shared"]
if ok && util.IsFalseOrEmpty(sharedVolume) {
var usedByProfileDevices []api.Profile
err = VolumeUsedByProfileDevices(b.state, b.name, projectName, &curVol.StorageVolume, func(profileID int64, profile api.Profile, project api.Project, usedByDevices []string) error {
usedByProfileDevices = append(usedByProfileDevices, profile)
return nil
})
if err != nil {
return err
}
if len(usedByProfileDevices) > 0 {
return errors.New("Cannot un-share custom storage block volume if attached to profile")
}
var usedByInstanceDevices []string
err = VolumeUsedByInstanceDevices(b.state, b.name, projectName, &curVol.StorageVolume, true, func(inst db.InstanceArgs, project api.Project, usedByDevices []string) error {
usedByInstanceDevices = append(usedByInstanceDevices, inst.Name)
return nil
})
if err != nil {
return err
}
if len(usedByInstanceDevices) > 1 {
return errors.New("Cannot un-share custom storage block volume if attached to more than one instance")
}
}
curVol := b.GetVolume(drivers.VolumeTypeCustom, contentType, volStorageName, curVol.Config)
if !userOnly {
err = b.driver.UpdateVolume(curVol, changedConfig)
if err != nil {
return err
}
}
}
// Unset idmap keys if volume is unmapped.
if util.IsTrue(newConfig["security.unmapped"]) {
delete(newConfig, "volatile.idmap.last")
delete(newConfig, "volatile.idmap.next")
}
// Notify instances of disk size changes as needed.
newSize, ok := changedConfig["size"]
if ok && newSize != "" && contentType == drivers.ContentTypeBlock {
// Get the disk size in bytes.
size, err := units.ParseByteSizeString(changedConfig["size"])
if err != nil {
return err
}
type instDevice struct {
args db.InstanceArgs
devices []string
}
instDevices := []instDevice{}
err = VolumeUsedByInstanceDevices(b.state, b.name, projectName, &curVol.StorageVolume, true, func(dbInst db.InstanceArgs, project api.Project, usedByDevices []string) error {
if dbInst.Type != instancetype.VM {
return nil
}
instDevices = append(instDevices, instDevice{args: dbInst, devices: usedByDevices})
return nil
})
if err != nil {
return err
}
for _, entry := range instDevices {
c, err := ConnectIfInstanceIsRemote(b.state, entry.args.Project, entry.args.Name, nil)
if err != nil {
return err
}
if c != nil {
// Send a remote notification.
devs := []string{}
for _, devName := range entry.devices {
devs = append(devs, fmt.Sprintf("%s:%d", devName, size))
}
uri := fmt.Sprintf("/internal/virtual-machines/%d/onresize?devices=%s", entry.args.ID, strings.Join(devs, ","))
_, _, err := c.RawQuery("GET", uri, nil, "")
if err != nil {
return err
}
} else {
// Update the local instance.
inst, err := instance.LoadByProjectAndName(b.state, entry.args.Project, entry.args.Name)
if err != nil {
return err
}
if !inst.IsRunning() {
continue
}
for _, devName := range entry.devices {
runConf := deviceConfig.RunConfig{}
runConf.Mounts = []deviceConfig.MountEntryItem{
{
DevName: devName,
Size: size,
},
}
err = inst.DeviceEventHandler(&runConf)
if err != nil {
return err
}
}
}
}
}
// Update the database if something changed.
if len(changedConfig) != 0 || newDesc != curVol.Description {
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.UpdateStoragePoolVolume(ctx, projectName, volName, db.StoragePoolVolumeTypeCustom, b.ID(), newDesc, newConfig)
})
if err != nil {
return err
}
}
b.state.Events.SendLifecycle(projectName, lifecycle.StorageVolumeUpdated.Event(newVol, string(newVol.Type()), projectName, op, nil))
return nil
}
// UpdateCustomVolumeSnapshot updates the description of a custom volume snapshot.
// Volume config is not allowed to be updated and will return an error.
func (b *backend) UpdateCustomVolumeSnapshot(projectName string, volName string, newDesc string, newConfig map[string]string, newExpiryDate time.Time, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": projectName, "volName": volName, "newDesc": newDesc, "newConfig": newConfig, "newExpiryDate": newExpiryDate})
l.Debug("UpdateCustomVolumeSnapshot started")
defer l.Debug("UpdateCustomVolumeSnapshot finished")
if !internalInstance.IsSnapshot(volName) {
return errors.New("Volume must be a snapshot")
}
// Get current config to compare what has changed.
curVol, err := VolumeDBGet(b, projectName, volName, drivers.VolumeTypeCustom)
if err != nil {
return err
}
var curExpiryDate time.Time
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
curExpiryDate, err = tx.GetStorageVolumeSnapshotExpiry(ctx, curVol.ID)
return err
})
if err != nil {
return err
}
if newConfig != nil {
changedConfig, _ := b.detectChangedConfig(curVol.Config, newConfig)
if len(changedConfig) != 0 {
return errors.New("Volume config is not editable")
}
}
// Update the database if description changed. Use current config.
if newDesc != curVol.Description || newExpiryDate != curExpiryDate {
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.UpdateStorageVolumeSnapshot(ctx, projectName, volName, db.StoragePoolVolumeTypeCustom, b.ID(), newDesc, curVol.Config, newExpiryDate)
})
if err != nil {
return err
}
}
vol := b.GetVolume(drivers.VolumeTypeCustom, drivers.ContentType(curVol.ContentType), curVol.Name, curVol.Config)
b.state.Events.SendLifecycle(projectName, lifecycle.StorageVolumeSnapshotUpdated.Event(vol, string(vol.Type()), projectName, op, nil))
return nil
}
// DeleteCustomVolume removes a custom volume and its snapshots.
func (b *backend) DeleteCustomVolume(projectName string, volName string, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": projectName, "volName": volName})
l.Debug("DeleteCustomVolume started")
defer l.Debug("DeleteCustomVolume finished")
_, _, isSnap := api.GetParentAndSnapshotName(volName)
if isSnap {
return errors.New("Volume name cannot be a snapshot")
}
// Retrieve a list of snapshots.
snapshots, err := VolumeDBSnapshotsGet(b, projectName, volName, drivers.VolumeTypeCustom)
if err != nil {
return err
}
// Remove each snapshot.
for _, snapshot := range snapshots {
err = b.DeleteCustomVolumeSnapshot(projectName, snapshot.Name, op)
if err != nil {
return err
}
}
// Get the volume name on storage.
volStorageName := project.StorageVolume(projectName, volName)
// Get the volume.
curVol, err := VolumeDBGet(b, projectName, volName, drivers.VolumeTypeCustom)
if err != nil {
return err
}
// Get the content type.
dbContentType, err := VolumeContentTypeNameToContentType(curVol.ContentType)
if err != nil {
return err
}
contentType, err := VolumeDBContentTypeToContentType(dbContentType)
if err != nil {
return err
}
// There's no need to pass config as it's not needed when deleting a volume.
vol := b.GetVolume(drivers.VolumeTypeCustom, contentType, volStorageName, nil)
// Delete the volume from the storage device. Must come after snapshots are removed.
volExists, err := b.driver.HasVolume(vol)
if err != nil {
return err
}
if volExists {
err = b.driver.DeleteVolume(vol, op)
if err != nil {
return err
}
}
// Remove backups directory for volume.
backupsPath := internalUtil.VarPath("backups", "custom", b.name, project.StorageVolume(projectName, volName))
if util.PathExists(backupsPath) {
err := os.RemoveAll(backupsPath)
if err != nil {
return err
}
}
// Finally, remove the volume record from the database.
err = VolumeDBDelete(b, projectName, volName, vol.Type())
if err != nil {
return err
}
var location string
if b.state.ServerClustered && !b.Driver().Info().Remote {
location = b.state.ServerName
}
// Record volume deletion with authorizer.
err = b.state.Authorizer.DeleteStoragePoolVolume(b.state.ShutdownCtx, projectName, b.Name(), vol.Type().Singular(), volName, location)
if err != nil {
logger.Error("Failed to remove storage volume from authorizer", logger.Ctx{"name": volName, "type": vol.Type(), "pool": b.Name(), "project": projectName, "error": err})
}
b.state.Events.SendLifecycle(projectName, lifecycle.StorageVolumeDeleted.Event(vol, string(vol.Type()), projectName, op, nil))
return nil
}
// GetCustomVolumeDisk returns the location of the disk.
func (b *backend) GetCustomVolumeDisk(projectName, volName string) (string, error) {
volume, err := VolumeDBGet(b, projectName, volName, drivers.VolumeTypeCustom)
if err != nil {
return "", err
}
// Get the volume name on storage.
volStorageName := project.StorageVolume(projectName, volName)
// There's no need to pass config as it's not needed when getting the volume usage.
vol := b.GetVolume(drivers.VolumeTypeCustom, drivers.ContentType(volume.ContentType), volStorageName, nil)
return b.driver.GetVolumeDiskPath(vol)
}
// GetCustomVolumeUsage returns the disk space used by the custom volume.
func (b *backend) GetCustomVolumeUsage(projectName, volName string) (*VolumeUsage, error) {
err := b.isStatusReady()
if err != nil {
return nil, err
}
volume, err := VolumeDBGet(b, projectName, volName, drivers.VolumeTypeCustom)
if err != nil {
return nil, err
}
val := VolumeUsage{}
// Get the volume name on storage.
volStorageName := project.StorageVolume(projectName, volName)
// There's no need to pass config as it's not needed when getting the volume usage.
vol := b.GetVolume(drivers.VolumeTypeCustom, drivers.ContentType(volume.ContentType), volStorageName, nil)
// Get the usage.
size, err := b.driver.GetVolumeUsage(vol)
if err != nil {
return nil, err
}
val.Used = size
// Get the total size.
sizeStr, ok := vol.Config()["size"]
if ok {
total, err := units.ParseByteSizeString(sizeStr)
if err != nil {
return nil, err
}
if total >= 0 {
val.Total = total
}
}
return &val, nil
}
// MountCustomVolume mounts a custom volume.
func (b *backend) MountCustomVolume(projectName, volName string, op *operations.Operation) (*MountInfo, error) {
l := b.logger.AddContext(logger.Ctx{"project": projectName, "volName": volName})
l.Debug("MountCustomVolume started")
defer l.Debug("MountCustomVolume finished")
err := b.isStatusReady()
if err != nil {
return nil, err
}
volume, err := VolumeDBGet(b, projectName, volName, drivers.VolumeTypeCustom)
if err != nil {
return nil, err
}
// Get the volume name on storage.
volStorageName := project.StorageVolume(projectName, volName)
vol := b.GetVolume(drivers.VolumeTypeCustom, drivers.ContentType(volume.ContentType), volStorageName, volume.Config)
// Perform the mount.
mountInfo := &MountInfo{}
err = b.driver.MountVolume(vol, op)
if err != nil {
return nil, err
}
// Handle delegation.
if b.driver.CanDelegateVolume(vol) {
mountInfo.PostHooks = append(mountInfo.PostHooks, func(inst instance.Instance) error {
pid := inst.InitPID()
// Only apply to running instances.
if pid < 1 {
return nil
}
return b.driver.DelegateVolume(vol, pid)
})
}
return mountInfo, nil
}
// UnmountCustomVolume unmounts a custom volume.
func (b *backend) UnmountCustomVolume(projectName, volName string, op *operations.Operation) (bool, error) {
l := b.logger.AddContext(logger.Ctx{"project": projectName, "volName": volName})
l.Debug("UnmountCustomVolume started")
defer l.Debug("UnmountCustomVolume finished")
volume, err := VolumeDBGet(b, projectName, volName, drivers.VolumeTypeCustom)
if err != nil {
return false, err
}
// Get the volume name on storage.
volStorageName := project.StorageVolume(projectName, volName)
vol := b.GetVolume(drivers.VolumeTypeCustom, drivers.ContentType(volume.ContentType), volStorageName, volume.Config)
return b.driver.UnmountVolume(vol, false, op)
}
// ImportCustomVolume takes an existing custom volume on the storage backend and ensures that the DB records,
// volume directories and symlinks are restored as needed to make it operational with Incus.
// Used during the recovery import stage.
func (b *backend) ImportCustomVolume(projectName string, poolVol *backupConfig.Config, op *operations.Operation) (revert.Hook, error) {
if poolVol.Volume == nil {
return nil, errors.New("Invalid pool volume config supplied")
}
l := b.logger.AddContext(logger.Ctx{"project": projectName, "volName": poolVol.Volume.Name})
l.Debug("ImportCustomVolume started")
defer l.Debug("ImportCustomVolume finished")
reverter := revert.New()
defer reverter.Fail()
// Copy volume config from backup file if present (so VolumeDBCreate can safely modify the copy if needed).
volumeConfig := util.CloneMap(poolVol.Volume.Config)
// Validate config and create database entry for restored storage volume.
err := VolumeDBCreate(b, projectName, poolVol.Volume.Name, poolVol.Volume.Description, drivers.VolumeTypeCustom, false, volumeConfig, poolVol.Volume.CreatedAt, time.Time{}, drivers.ContentType(poolVol.Volume.ContentType), false, true)
if err != nil {
return nil, err
}
reverter.Add(func() { _ = VolumeDBDelete(b, projectName, poolVol.Volume.Name, drivers.VolumeTypeCustom) })
// Create the storage volume snapshot DB records.
for _, poolVolSnap := range poolVol.VolumeSnapshots {
fullSnapName := drivers.GetSnapshotVolumeName(poolVol.Volume.Name, poolVolSnap.Name)
// Copy volume config from backup file if present
// (so VolumeDBCreate can safely modify the copy if needed).
snapVolumeConfig := util.CloneMap(poolVolSnap.Config)
// Validate config and create database entry for restored storage volume.
err = VolumeDBCreate(b, projectName, fullSnapName, poolVolSnap.Description, drivers.VolumeTypeCustom, true, snapVolumeConfig, poolVolSnap.CreatedAt, time.Time{}, drivers.ContentType(poolVolSnap.ContentType), false, true)
if err != nil {
return nil, err
}
reverter.Add(func() { _ = VolumeDBDelete(b, projectName, fullSnapName, drivers.VolumeTypeCustom) })
}
// Get the volume name on storage.
volStorageName := project.StorageVolume(projectName, poolVol.Volume.Name)
vol := b.GetVolume(drivers.VolumeTypeCustom, drivers.ContentType(poolVol.Volume.ContentType), volStorageName, volumeConfig)
// Create the mount path if needed.
err = vol.EnsureMountPath(false)
if err != nil {
return nil, err
}
// Create snapshot mount paths and snapshot parent directory if needed.
for _, poolVolSnap := range poolVol.VolumeSnapshots {
l.Debug("Ensuring instance snapshot mount path", logger.Ctx{"snapshot": poolVolSnap.Name})
snapVol, err := vol.NewSnapshot(poolVolSnap.Name)
if err != nil {
return nil, err
}
err = snapVol.EnsureMountPath(false)
if err != nil {
return nil, err
}
}
cleanup := reverter.Clone().Fail
reverter.Success()
return cleanup, err
}
// CreateCustomVolumeSnapshot creates a snapshot of a custom volume.
func (b *backend) CreateCustomVolumeSnapshot(projectName, volName string, newSnapshotName string, newExpiryDate time.Time, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": projectName, "volName": volName, "newSnapshotName": newSnapshotName, "newExpiryDate": newExpiryDate})
l.Debug("CreateCustomVolumeSnapshot started")
defer l.Debug("CreateCustomVolumeSnapshot finished")
if internalInstance.IsSnapshot(volName) {
return errors.New("Volume does not support snapshots")
}
if internalInstance.IsSnapshot(newSnapshotName) {
return errors.New("Snapshot name is not a valid snapshot name")
}
fullSnapshotName := drivers.GetSnapshotVolumeName(volName, newSnapshotName)
// Check snapshot volume doesn't exist already.
volume, err := VolumeDBGet(b, projectName, fullSnapshotName, drivers.VolumeTypeCustom)
if err != nil && !response.IsNotFoundError(err) {
return err
} else if volume != nil {
return api.StatusErrorf(http.StatusConflict, "Snapshot by that name already exists")
}
// Load parent volume information and check it exists.
parentVol, err := VolumeDBGet(b, projectName, volName, drivers.VolumeTypeCustom)
if err != nil {
if response.IsNotFoundError(err) {
return api.StatusErrorf(http.StatusNotFound, "Parent volume doesn't exist")
}
return err
}
volDBContentType, err := VolumeContentTypeNameToContentType(parentVol.ContentType)
if err != nil {
return err
}
contentType, err := VolumeDBContentTypeToContentType(volDBContentType)
if err != nil {
return err
}
if contentType != drivers.ContentTypeFS && contentType != drivers.ContentTypeBlock {
return fmt.Errorf("Volume of content type %q does not support snapshots", contentType)
}
reverter := revert.New()
defer reverter.Fail()
// Validate config and create database entry for new storage volume.
// Copy volume config from parent.
err = VolumeDBCreate(b, projectName, fullSnapshotName, parentVol.Description, drivers.VolumeTypeCustom, true, parentVol.Config, time.Now().UTC(), newExpiryDate, drivers.ContentType(parentVol.ContentType), false, true)
if err != nil {
return err
}
reverter.Add(func() { _ = VolumeDBDelete(b, projectName, fullSnapshotName, drivers.VolumeTypeCustom) })
// Get the volume name on storage.
volStorageName := project.StorageVolume(projectName, fullSnapshotName)
vol := b.GetVolume(drivers.VolumeTypeCustom, contentType, volStorageName, parentVol.Config)
// Lock this operation to ensure that the only one snapshot is made at the time.
// Other operations will wait for this one to finish.
unlock, err := locking.Lock(context.TODO(), drivers.OperationLockName("CreateCustomVolumeSnapshot", b.name, vol.Type(), contentType, volName))
if err != nil {
return err
}
defer unlock()
// Create the snapshot on the storage device.
err = b.driver.CreateVolumeSnapshot(vol, op)
if err != nil {
return err
}
b.state.Events.SendLifecycle(projectName, lifecycle.StorageVolumeSnapshotCreated.Event(vol, string(vol.Type()), projectName, op, logger.Ctx{"type": vol.Type()}))
reverter.Success()
return nil
}
// RenameCustomVolumeSnapshot renames a custom volume.
func (b *backend) RenameCustomVolumeSnapshot(projectName, volName string, newSnapshotName string, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": projectName, "volName": volName, "newSnapshotName": newSnapshotName})
l.Debug("RenameCustomVolumeSnapshot started")
defer l.Debug("RenameCustomVolumeSnapshot finished")
parentName, oldSnapshotName, isSnap := api.GetParentAndSnapshotName(volName)
if !isSnap {
return errors.New("Volume name must be a snapshot")
}
if internalInstance.IsSnapshot(newSnapshotName) {
return errors.New("Invalid new snapshot name")
}
volume, err := VolumeDBGet(b, projectName, volName, drivers.VolumeTypeCustom)
if err != nil {
return err
}
// Get the volume name on storage.
volStorageName := project.StorageVolume(projectName, volName)
// There's no need to pass config as it's not needed when renaming a volume.
vol := b.GetVolume(drivers.VolumeTypeCustom, drivers.ContentType(volume.ContentType), volStorageName, nil)
err = b.driver.RenameVolumeSnapshot(vol, newSnapshotName, op)
if err != nil {
return err
}
newVolName := drivers.GetSnapshotVolumeName(parentName, newSnapshotName)
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.RenameStoragePoolVolume(ctx, projectName, volName, newVolName, db.StoragePoolVolumeTypeCustom, b.ID())
})
if err != nil {
// Get the volume name on storage.
newVolStorageName := project.StorageVolume(projectName, newVolName)
// Revert rename.
newVol := b.GetVolume(drivers.VolumeTypeCustom, drivers.ContentType(volume.ContentType), newVolStorageName, nil)
_ = b.driver.RenameVolumeSnapshot(newVol, oldSnapshotName, op)
return err
}
b.state.Events.SendLifecycle(projectName, lifecycle.StorageVolumeSnapshotRenamed.Event(vol, string(vol.Type()), projectName, op, logger.Ctx{"old_name": oldSnapshotName}))
return nil
}
// DeleteCustomVolumeSnapshot removes a custom volume snapshot.
func (b *backend) DeleteCustomVolumeSnapshot(projectName, volName string, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": projectName, "volName": volName})
l.Debug("DeleteCustomVolumeSnapshot started")
defer l.Debug("DeleteCustomVolumeSnapshot finished")
isSnap := internalInstance.IsSnapshot(volName)
if !isSnap {
return errors.New("Volume name must be a snapshot")
}
// Get the volume.
volume, err := VolumeDBGet(b, projectName, volName, drivers.VolumeTypeCustom)
if err != nil {
return err
}
// Get the content type.
dbContentType, err := VolumeContentTypeNameToContentType(volume.ContentType)
if err != nil {
return err
}
contentType, err := VolumeDBContentTypeToContentType(dbContentType)
if err != nil {
return err
}
// Get the volume name on storage.
volStorageName := project.StorageVolume(projectName, volName)
// There's no need to pass config as it's not needed when deleting a volume snapshot.
vol := b.GetVolume(drivers.VolumeTypeCustom, contentType, volStorageName, nil)
// Delete the snapshot from the storage device.
// Must come before DB VolumeDBDelete so that the volume ID is still available.
volExists, err := b.driver.HasVolume(vol)
if err != nil {
return err
}
if volExists {
err := b.driver.DeleteVolumeSnapshot(vol, op)
if err != nil {
return err
}
}
// Remove the snapshot volume record from the database.
err = VolumeDBDelete(b, projectName, volName, vol.Type())
if err != nil {
return err
}
b.state.Events.SendLifecycle(projectName, lifecycle.StorageVolumeSnapshotDeleted.Event(vol, string(vol.Type()), projectName, op, nil))
return nil
}
// RestoreCustomVolume restores a custom volume from a snapshot.
func (b *backend) RestoreCustomVolume(projectName, volName string, snapshotName string, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": projectName, "volName": volName, "snapshotName": snapshotName})
l.Debug("RestoreCustomVolume started")
defer l.Debug("RestoreCustomVolume finished")
// Quick checks.
if internalInstance.IsSnapshot(volName) {
return errors.New("Volume cannot be snapshot")
}
if internalInstance.IsSnapshot(snapshotName) {
return errors.New("Invalid snapshot name")
}
// Get current volume.
curVol, err := VolumeDBGet(b, projectName, volName, drivers.VolumeTypeCustom)
if err != nil {
return err
}
// Check that the volume isn't in use by running instances.
err = VolumeUsedByInstanceDevices(b.state, b.Name(), projectName, &curVol.StorageVolume, true, func(dbInst db.InstanceArgs, project api.Project, usedByDevices []string) error {
inst, err := instance.Load(b.state, dbInst, project)
if err != nil {
return err
}
if inst.IsRunning() {
return errors.New("Cannot restore custom volume used by running instances")
}
return nil
})
if err != nil {
return err
}
dbContentType, err := VolumeContentTypeNameToContentType(curVol.ContentType)
if err != nil {
return err
}
contentType, err := VolumeDBContentTypeToContentType(dbContentType)
if err != nil {
return err
}
// Get the volume name on storage.
volStorageName := project.StorageVolume(projectName, volName)
vol := b.GetVolume(drivers.VolumeTypeCustom, contentType, volStorageName, curVol.Config)
err = b.driver.RestoreVolume(vol, snapshotName, op)
if err != nil {
var snapErr drivers.ErrDeleteSnapshots
if errors.As(err, &snapErr) {
// We need to delete some snapshots and try again.
for _, snapName := range snapErr.Snapshots {
err := b.DeleteCustomVolumeSnapshot(projectName, fmt.Sprintf("%s/%s", volName, snapName), op)
if err != nil {
return err
}
}
// Now try again.
err = b.driver.RestoreVolume(vol, snapshotName, op)
if err != nil {
return err
}
}
return err
}
b.state.Events.SendLifecycle(projectName, lifecycle.StorageVolumeRestored.Event(vol, string(vol.Type()), projectName, op, logger.Ctx{"snapshot": snapshotName}))
return nil
}
func (b *backend) createStorageStructure(path string) error {
for _, volType := range b.driver.Info().VolumeTypes {
for _, name := range drivers.BaseDirectories[volType] {
path := filepath.Join(path, name)
err := os.MkdirAll(path, 0o711)
if err != nil && !os.IsExist(err) {
return fmt.Errorf("Failed to create directory %q: %w", path, err)
}
}
}
return nil
}
// GenerateBucketBackupConfig returns the backup config entry for this bucket.
func (b *backend) GenerateBucketBackupConfig(projectName string, bucketName string, op *operations.Operation) (*backupConfig.Config, error) {
bucket, err := BucketDBGet(b, projectName, bucketName, true)
if err != nil {
return nil, err
}
dbBucketKeys, err := BucketKeysDBGet(b, bucket.ID)
if err != nil {
return nil, err
}
var bucketKeys []*api.StorageBucketKey
for _, key := range dbBucketKeys {
bucketKeys = append(bucketKeys, &key.StorageBucketKey)
}
config := &backupConfig.Config{
Bucket: &bucket.StorageBucket,
BucketKeys: bucketKeys,
}
return config, nil
}
// GenerateCustomVolumeBackupConfig returns the backup config entry for this volume.
func (b *backend) GenerateCustomVolumeBackupConfig(projectName string, volName string, snapshots bool, op *operations.Operation) (*backupConfig.Config, error) {
vol, err := VolumeDBGet(b, projectName, volName, drivers.VolumeTypeCustom)
if err != nil {
return nil, err
}
if vol.Type != db.StoragePoolVolumeTypeNameCustom {
return nil, fmt.Errorf("Unsupported volume type %q", vol.Type)
}
config := &backupConfig.Config{
Volume: &vol.StorageVolume,
}
if snapshots {
dbVolSnaps, err := VolumeDBSnapshotsGet(b, projectName, vol.Name, drivers.VolumeTypeCustom)
if err != nil {
return nil, err
}
config.VolumeSnapshots = make([]*api.StorageVolumeSnapshot, 0, len(dbVolSnaps))
for i := range dbVolSnaps {
_, snapName, _ := api.GetParentAndSnapshotName(dbVolSnaps[i].Name)
snapshot := api.StorageVolumeSnapshot{
StorageVolumeSnapshotPut: api.StorageVolumeSnapshotPut{
Description: dbVolSnaps[i].Description,
ExpiresAt: &dbVolSnaps[i].ExpiryDate,
},
Name: snapName, // Snapshot only name, not full name.
Config: dbVolSnaps[i].Config,
ContentType: dbVolSnaps[i].ContentType,
CreatedAt: dbVolSnaps[i].CreationDate,
}
config.VolumeSnapshots = append(config.VolumeSnapshots, &snapshot)
}
}
return config, nil
}
// GenerateInstanceBackupConfig returns the backup config entry for this instance.
// The Container field is only populated for non-snapshot instances.
func (b *backend) GenerateInstanceBackupConfig(inst instance.Instance, snapshots bool, op *operations.Operation) (*backupConfig.Config, error) {
// Generate the YAML.
ci, _, err := inst.Render()
if err != nil {
return nil, fmt.Errorf("Failed to render instance metadata: %w", err)
}
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return nil, err
}
volume, err := VolumeDBGet(b, inst.Project().Name, inst.Name(), volType)
if err != nil {
return nil, err
}
config := &backupConfig.Config{
Pool: &b.db,
Volume: &volume.StorageVolume,
}
// Add profiles from instance.
instProfiles := inst.Profiles()
config.Profiles = make([]*api.Profile, len(instProfiles))
for i := range instProfiles {
config.Profiles[i] = &instProfiles[i]
}
// Only populate Container field for non-snapshot instances.
if !inst.IsSnapshot() {
config.Container = ci.(*api.Instance)
if snapshots {
snapshots, err := inst.Snapshots()
if err != nil {
return nil, fmt.Errorf("Failed to get snapshots: %w", err)
}
config.Snapshots = make([]*api.InstanceSnapshot, 0, len(snapshots))
for _, s := range snapshots {
si, _, err := s.Render()
if err != nil {
return nil, err
}
config.Snapshots = append(config.Snapshots, si.(*api.InstanceSnapshot))
}
dbVolSnaps, err := VolumeDBSnapshotsGet(b, inst.Project().Name, inst.Name(), volType)
if err != nil {
return nil, err
}
if len(snapshots) != len(dbVolSnaps) {
return nil, errors.New("Instance snapshot record count doesn't match instance snapshot volume record count")
}
config.VolumeSnapshots = make([]*api.StorageVolumeSnapshot, 0, len(dbVolSnaps))
for i := range dbVolSnaps {
foundInstanceSnapshot := false
for _, snap := range snapshots {
if snap.Name() == dbVolSnaps[i].Name {
foundInstanceSnapshot = true
break
}
}
if !foundInstanceSnapshot {
return nil, fmt.Errorf("Instance snapshot record missing for %q", dbVolSnaps[i].Name)
}
_, snapName, _ := api.GetParentAndSnapshotName(dbVolSnaps[i].Name)
config.VolumeSnapshots = append(config.VolumeSnapshots, &api.StorageVolumeSnapshot{
StorageVolumeSnapshotPut: api.StorageVolumeSnapshotPut{
Description: dbVolSnaps[i].Description,
ExpiresAt: &dbVolSnaps[i].ExpiryDate,
},
Name: snapName,
Config: dbVolSnaps[i].Config,
ContentType: dbVolSnaps[i].ContentType,
CreatedAt: dbVolSnaps[i].CreationDate,
})
}
}
}
return config, nil
}
// UpdateInstanceBackupFile writes the instance's config to the backup.yaml file on the storage device.
func (b *backend) UpdateInstanceBackupFile(inst instance.Instance, snapshots bool, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": inst.Project().Name, "instance": inst.Name()})
l.Debug("UpdateInstanceBackupFile started")
defer l.Debug("UpdateInstanceBackupFile finished")
// We only write backup files out for actual instances.
if inst.IsSnapshot() {
return nil
}
config, err := b.GenerateInstanceBackupConfig(inst, snapshots, op)
if err != nil {
return err
}
data, err := yaml.Marshal(config)
if err != nil {
return err
}
// Get the volume name on storage.
volStorageName := project.Instance(inst.Project().Name, inst.Name())
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return err
}
contentType := InstanceContentType(inst)
vol := b.GetVolume(volType, contentType, volStorageName, config.Volume.Config)
// Only need to activate and mount the VM's config volume.
if inst.Type() == instancetype.VM {
vol = vol.NewVMBlockFilesystemVolume()
}
// Update pool information in the backup.yaml file.
err = vol.MountTask(func(mountPath string, op *operations.Operation) error {
// Write the YAML
path := filepath.Join(inst.Path(), "backup.yaml")
f, err := os.Create(path)
if err != nil {
return fmt.Errorf("Failed to create file %q: %w", path, err)
}
err = f.Chmod(0o400)
if err != nil {
return err
}
err = internalIO.WriteAll(f, data)
if err != nil {
return err
}
return f.Close()
}, op)
return err
}
// CheckInstanceBackupFileSnapshots compares the snapshots on the storage device to those defined in the backup
// config supplied and returns an error if they do not match (if deleteMissing argument is false).
// If deleteMissing argument is true, then any snapshots that exist on the storage device but not in the backup
// config are removed from the storage device, and any snapshots that exist in the backup config but do not exist
// on the storage device are ignored. The remaining set of snapshots that exist on both the storage device and the
// backup config are returned. They set can be used to re-create the snapshot database entries when importing.
func (b *backend) CheckInstanceBackupFileSnapshots(backupConf *backupConfig.Config, projectName string, deleteMissing bool, op *operations.Operation) ([]*api.InstanceSnapshot, error) {
l := b.logger.AddContext(logger.Ctx{"project": projectName, "instance": backupConf.Container.Name, "deleteMissing": deleteMissing})
l.Debug("CheckInstanceBackupFileSnapshots started")
defer l.Debug("CheckInstanceBackupFileSnapshots finished")
instType, err := instancetype.New(string(backupConf.Container.Type))
if err != nil {
return nil, err
}
volType, err := InstanceTypeToVolumeType(instType)
if err != nil {
return nil, err
}
// Get the volume name on storage.
volStorageName := project.Instance(projectName, backupConf.Container.Name)
contentType := drivers.ContentTypeFS
if volType == drivers.VolumeTypeVM {
contentType = drivers.ContentTypeBlock
}
// We don't need to use the volume's config for mounting so set to nil.
vol := b.GetVolume(volType, contentType, volStorageName, nil)
// Get a list of snapshots that exist on storage device.
driverSnapshots, err := vol.Snapshots(op)
if err != nil {
return nil, err
}
if len(backupConf.Snapshots) != len(driverSnapshots) {
if !deleteMissing {
return nil, fmt.Errorf("Snapshot count in backup config (%d) and storage device (%d) are different: %w", len(backupConf.Snapshots), len(driverSnapshots), ErrBackupSnapshotsMismatch)
}
}
// Check (and optionally delete) snapshots that do not exist in backup config.
for _, driverSnapVol := range driverSnapshots {
_, driverSnapOnly, _ := api.GetParentAndSnapshotName(driverSnapVol.Name())
inBackupFile := false
for _, backupFileSnap := range backupConf.Snapshots {
backupFileSnapOnly := backupFileSnap.Name
if driverSnapOnly == backupFileSnapOnly {
inBackupFile = true
break
}
}
if inBackupFile {
continue
}
if !deleteMissing {
return nil, fmt.Errorf("Snapshot %q exists on storage device but not in backup config: %w", driverSnapOnly, ErrBackupSnapshotsMismatch)
}
err = b.driver.DeleteVolumeSnapshot(driverSnapVol, op)
if err != nil {
return nil, fmt.Errorf("Failed to delete snapshot %q: %w", driverSnapOnly, err)
}
l.Warn("Deleted snapshot as not present in backup config", logger.Ctx{"snapshot": driverSnapOnly})
}
// Check the snapshots in backup config exist on storage device.
existingSnapshots := []*api.InstanceSnapshot{}
for _, backupFileSnap := range backupConf.Snapshots {
backupFileSnapOnly := backupFileSnap.Name
onStorageDevice := false
for _, driverSnapVol := range driverSnapshots {
_, driverSnapOnly, _ := api.GetParentAndSnapshotName(driverSnapVol.Name())
if driverSnapOnly == backupFileSnapOnly {
onStorageDevice = true
break
}
}
if !onStorageDevice {
if !deleteMissing {
return nil, fmt.Errorf("Snapshot %q exists in backup config but not on storage device: %w", backupFileSnapOnly, ErrBackupSnapshotsMismatch)
}
l.Warn("Skipped snapshot in backup config as not present on storage device", logger.Ctx{"snapshot": backupFileSnap})
continue // Skip snapshots missing on storage device.
}
existingSnapshots = append(existingSnapshots, backupFileSnap)
}
return existingSnapshots, nil
}
// ListUnknownVolumes returns volumes that exist on the storage pool but don't have records in the database.
// Returns the unknown volumes parsed/generated backup config in a slice (keyed on project name).
func (b *backend) ListUnknownVolumes(op *operations.Operation) (map[string][]*backupConfig.Config, error) {
// Get a list of volumes on the storage pool. We only expect to get 1 volume per logical Incus volume.
// So for VMs we only expect to get the block volume for a VM and not its filesystem one too. This way we
// can operate on the volume using the existing storage pool functions and let the pool then handle the
// associated filesystem volume as needed.
poolVols, err := b.driver.ListVolumes()
if err != nil {
return nil, fmt.Errorf("Failed getting pool volumes: %w", err)
}
projectVols := make(map[string][]*backupConfig.Config)
for _, poolVol := range poolVols {
volType := poolVol.Type()
// If the storage driver has returned a filesystem volume for a VM, this is a break of protocol.
if volType == drivers.VolumeTypeVM && poolVol.ContentType() == drivers.ContentTypeFS {
return nil, fmt.Errorf("Storage driver returned unexpected VM volume with filesystem content type (%q)", poolVol.Name())
}
if volType == drivers.VolumeTypeVM || volType == drivers.VolumeTypeContainer {
err = b.detectUnknownInstanceVolume(&poolVol, projectVols, op)
if err != nil {
return nil, err
}
} else if volType == drivers.VolumeTypeCustom {
err = b.detectUnknownCustomVolume(&poolVol, projectVols, op)
if err != nil {
return nil, err
}
} else if volType == drivers.VolumeTypeBucket {
err = b.detectUnknownBuckets(&poolVol, projectVols, op)
if err != nil {
return nil, err
}
}
}
return projectVols, nil
}
// detectUnknownInstanceVolume detects if a volume is unknown and if so attempts to mount the volume and parse the
// backup stored on it. It then runs a series of consistency checks that compare the contents of the backup file to
// the state of the volume on disk, and if all checks out, it adds the parsed backup file contents to projectVols.
func (b *backend) detectUnknownInstanceVolume(vol *drivers.Volume, projectVols map[string][]*backupConfig.Config, op *operations.Operation) error {
volType := vol.Type()
projectName, instName := project.InstanceParts(vol.Name())
var instID int
var instSnapshots []string
err := b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
var err error
// Check if an entry for the instance already exists in the DB.
instID, err = tx.GetInstanceID(ctx, projectName, instName)
if err != nil && !response.IsNotFoundError(err) {
return err
}
instSnapshots, err = tx.GetInstanceSnapshotsNames(ctx, projectName, instName)
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
// Check if any entry for the instance volume already exists in the DB.
// This will return no record for any temporary pool structs being used (as ID is -1).
volume, err := VolumeDBGet(b, projectName, instName, volType)
if err != nil && !response.IsNotFoundError(err) {
return err
}
if instID > 0 && volume != nil {
return nil // Instance record and storage record already exists in DB, no recovery needed.
} else if instID > 0 {
return fmt.Errorf("Instance %q in project %q already has instance DB record", instName, projectName)
} else if volume != nil {
return fmt.Errorf("Instance %q in project %q already has storage DB record", instName, projectName)
}
backupYamlPath := filepath.Join(vol.MountPath(), "backup.yaml")
var backupConf *backupConfig.Config
// If the instance is running, it should already be mounted, so check if the backup file
// is already accessible, and if so parse it directly, without disturbing the mount count.
if util.PathExists(backupYamlPath) {
backupConf, err = backup.ParseConfigYamlFile(backupYamlPath)
if err != nil {
return fmt.Errorf("Failed parsing backup file %q: %w", backupYamlPath, err)
}
} else {
// If backup file not accessible, we take this to mean the instance isn't running
// and so we need to mount the volume to access the backup file and then unmount.
// This will also create the mount path if needed.
err = vol.MountTask(func(_ string, _ *operations.Operation) error {
backupConf, err = backup.ParseConfigYamlFile(backupYamlPath)
if err != nil {
return fmt.Errorf("Failed parsing backup file %q: %w", backupYamlPath, err)
}
return nil
}, op)
if err != nil {
return err
}
}
// Run some consistency checks on the backup file contents.
if backupConf.Pool != nil {
if backupConf.Pool.Name != b.name {
return fmt.Errorf("Instance %q in project %q has pool name mismatch in its backup file (%q doesn't match's pool's %q)", instName, projectName, backupConf.Pool.Name, b.name)
}
if backupConf.Pool.Driver != b.Driver().Info().Name {
return fmt.Errorf("Instance %q in project %q has pool driver mismatch in its backup file (%q doesn't match's pool's %q)", instName, projectName, backupConf.Pool.Driver, b.Driver().Name())
}
}
if backupConf.Container == nil {
return fmt.Errorf("Instance %q in project %q has no instance information in its backup file", instName, projectName)
}
if instName != backupConf.Container.Name {
return fmt.Errorf("Instance %q in project %q has a different instance name in its backup file (%q)", instName, projectName, backupConf.Container.Name)
}
apiInstType, err := VolumeTypeToAPIInstanceType(volType)
if err != nil {
return fmt.Errorf("Failed checking instance type for instance %q in project %q: %w", instName, projectName, err)
}
if apiInstType != api.InstanceType(backupConf.Container.Type) {
return fmt.Errorf("Instance %q in project %q has a different instance type in its backup file (%q)", instName, projectName, backupConf.Container.Type)
}
if backupConf.Volume == nil {
return fmt.Errorf("Instance %q in project %q has no volume information in its backup file", instName, projectName)
}
if instName != backupConf.Volume.Name {
return fmt.Errorf("Instance %q in project %q has a different volume name in its backup file (%q)", instName, projectName, backupConf.Volume.Name)
}
instVolDBType, err := VolumeTypeNameToDBType(backupConf.Volume.Type)
if err != nil {
return fmt.Errorf("Failed checking instance volume type for instance %q in project %q: %w", instName, projectName, err)
}
instVolType, err := VolumeDBTypeToType(instVolDBType)
if err != nil {
return fmt.Errorf("Failed checking instance volume type for instance %q in project %q: %w", instName, projectName, err)
}
if volType != instVolType {
return fmt.Errorf("Instance %q in project %q has a different volume type in its backup file (%q)", instName, projectName, backupConf.Volume.Type)
}
// Add to volume to unknown volumes list for the project.
if projectVols[projectName] == nil {
projectVols[projectName] = []*backupConfig.Config{backupConf}
} else {
projectVols[projectName] = append(projectVols[projectName], backupConf)
}
// Check snapshots are consistent between storage layer and backup config file.
_, err = b.CheckInstanceBackupFileSnapshots(backupConf, projectName, false, nil)
if err != nil {
return fmt.Errorf("Instance %q in project %q has snapshot inconsistency: %w", instName, projectName, err)
}
// Check there are no existing DB records present for snapshots.
for _, snapshot := range backupConf.Snapshots {
fullSnapshotName := drivers.GetSnapshotVolumeName(instName, snapshot.Name)
// Check if an entry for the instance already exists in the DB.
if slices.Contains(instSnapshots, fullSnapshotName) {
return fmt.Errorf("Instance %q snapshot %q in project %q already has instance DB record", instName, snapshot.Name, projectName)
}
// Check if any entry for the instance snapshot volume already exists in the DB.
// This will return no record for any temporary pool structs being used (as ID is -1).
volume, err := VolumeDBGet(b, projectName, fullSnapshotName, volType)
if err != nil && !response.IsNotFoundError(err) {
return err
} else if volume != nil {
return fmt.Errorf("Instance %q snapshot %q in project %q already has storage DB record", instName, snapshot.Name, projectName)
}
}
return nil
}
// detectUnknownCustomVolume detects if a volume is unknown and if so attempts to discover the filesystem of the
// volume (for filesystem volumes). It then runs a series of consistency checks, and if all checks out, it adds
// generates a simulated backup config for the custom volume and adds it to projectVols.
func (b *backend) detectUnknownCustomVolume(vol *drivers.Volume, projectVols map[string][]*backupConfig.Config, op *operations.Operation) error {
volType := vol.Type()
projectName, volName := project.StorageVolumeParts(vol.Name())
// Check if any entry for the custom volume already exists in the DB.
// This will return no record for any temporary pool structs being used (as ID is -1).
volume, err := VolumeDBGet(b, projectName, volName, volType)
if err != nil && !response.IsNotFoundError(err) {
return err
} else if volume != nil {
return nil // Storage record already exists in DB, no recovery needed.
}
// Get a list of snapshots that exist on storage device.
snapshots, err := b.driver.VolumeSnapshots(*vol, op)
if err != nil {
return err
}
contentType := vol.ContentType()
var apiContentType string
if contentType == drivers.ContentTypeBlock {
apiContentType = db.StoragePoolVolumeContentTypeNameBlock
} else if contentType == drivers.ContentTypeISO {
apiContentType = db.StoragePoolVolumeContentTypeNameISO
} else if contentType == drivers.ContentTypeFS {
apiContentType = db.StoragePoolVolumeContentTypeNameFS
// Detect block volume filesystem (by mounting it (if not already) with filesystem probe mode).
if vol.IsBlockBacked() {
var blockFS string
mountPath := vol.MountPath()
if linux.IsMountPoint(mountPath) {
blockFS, err = linux.DetectFilesystem(mountPath)
if err != nil {
return err
}
} else {
err = vol.MountTask(func(mountPath string, op *operations.Operation) error {
blockFS, err = linux.DetectFilesystem(mountPath)
if err != nil {
return err
}
return nil
}, op)
if err != nil {
return err
}
}
// Record detected filesystem in config.
vol.Config()["block.filesystem"] = blockFS
}
} else {
return fmt.Errorf("Unknown custom volume content type %q", contentType)
}
// This may not always be the correct thing to do, but seeing as we don't know what the volume's config
// was lets take a best guess that it was the default config.
err = b.driver.FillVolumeConfig(*vol)
if err != nil {
return fmt.Errorf("Failed filling custom volume default config: %w", err)
}
// Check the filesystem detected is valid for the storage driver.
err = b.driver.ValidateVolume(*vol, false)
if err != nil {
return fmt.Errorf("Failed custom volume validation: %w", err)
}
backupConf := &backupConfig.Config{
Volume: &api.StorageVolume{
Name: volName,
Type: db.StoragePoolVolumeTypeNameCustom,
ContentType: apiContentType,
StorageVolumePut: api.StorageVolumePut{
Config: vol.Config(),
},
},
}
// Populate snapshot volumes.
for _, snapOnlyName := range snapshots {
backupConf.VolumeSnapshots = append(backupConf.VolumeSnapshots, &api.StorageVolumeSnapshot{
Name: snapOnlyName, // Snapshot only name, not full name.
Config: vol.Config(), // Have to assume the snapshot volume config is same as parent.
ContentType: apiContentType,
})
}
// Add to volume to unknown volumes list for the project.
if projectVols[projectName] == nil {
projectVols[projectName] = []*backupConfig.Config{backupConf}
} else {
projectVols[projectName] = append(projectVols[projectName], backupConf)
}
return nil
}
// detectUnknownBuckets detects if a bucket is unknown and if so attempts to discover the filesystem of the
// bucket. It then runs a series of consistency checks, and if all checks out, it generates a simulated backup
// config for the bucket and adds it to projectVols.
func (b *backend) detectUnknownBuckets(vol *drivers.Volume, projectVols map[string][]*backupConfig.Config, op *operations.Operation) error {
projectName, bucketName := project.StorageVolumeParts(vol.Name())
// Check if any entry for the bucket already exists in the DB.
bucket, err := BucketDBGet(b, projectName, bucketName, true)
if err != nil && !response.IsNotFoundError(err) {
return err
} else if bucket != nil {
return nil // Storage record already exists in DB, no recovery needed.
}
// This may not always be the correct thing to do, but seeing as we don't know what the volume's config
// was lets take a best guess that it was the default config.
err = b.driver.FillVolumeConfig(*vol)
if err != nil {
return fmt.Errorf("Failed filling bucket default config: %w", err)
}
// Check the detected filesystem is valid for the storage driver.
err = b.driver.ValidateVolume(*vol, false)
if err != nil {
return fmt.Errorf("Failed bucket validation: %w", err)
}
backupConf := &backupConfig.Config{
Bucket: &api.StorageBucket{
StorageBucketPut: api.StorageBucketPut{
Config: vol.Config(),
},
Name: bucketName,
},
}
// Add the bucket to unknown volumes list for the project.
if projectVols[projectName] == nil {
projectVols[projectName] = []*backupConfig.Config{backupConf}
} else {
projectVols[projectName] = append(projectVols[projectName], backupConf)
}
return nil
}
// ImportInstance takes an existing instance volume on the storage backend and ensures that the volume directories
// and symlinks are restored as needed to make it operational with Incus. Used during the recovery import stage.
// If the instance exists on the local cluster member then the local mount status is restored as needed.
// If the optional poolVol argument is provided then it is used to create the storage volume database records.
func (b *backend) ImportInstance(inst instance.Instance, poolVol *backupConfig.Config, op *operations.Operation) (revert.Hook, error) {
l := b.logger.AddContext(logger.Ctx{"project": inst.Project().Name, "instance": inst.Name()})
l.Debug("ImportInstance started")
defer l.Debug("ImportInstance finished")
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return nil, err
}
var snapshots []string
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
var err error
// Get any snapshots the instance has in the format <instance name>/<snapshot name>.
snapshots, err = tx.GetInstanceSnapshotsNames(ctx, inst.Project().Name, inst.Name())
return err
})
if err != nil {
return nil, err
}
contentType := InstanceContentType(inst)
reverter := revert.New()
defer reverter.Fail()
var volumeConfig map[string]string
// Create storage volume database records if in recover mode.
if poolVol != nil {
creationDate := inst.CreationDate()
// Copy volume config from backup file config if present,
// so VolumeDBCreate can safely modify the copy if needed.
if poolVol.Volume != nil {
volumeConfig = util.CloneMap(poolVol.Volume.Config)
if !poolVol.Volume.CreatedAt.IsZero() {
creationDate = poolVol.Volume.CreatedAt
}
}
// Validate config and create database entry for recovered storage volume.
err = VolumeDBCreate(b, inst.Project().Name, inst.Name(), "", volType, false, volumeConfig, creationDate, time.Time{}, contentType, false, true)
if err != nil {
return nil, err
}
reverter.Add(func() { _ = VolumeDBDelete(b, inst.Project().Name, inst.Name(), volType) })
if len(snapshots) > 0 && len(poolVol.VolumeSnapshots) > 0 {
// Create storage volume snapshot DB records from the entries in the backup file config.
for _, poolVolSnap := range poolVol.VolumeSnapshots {
fullSnapName := drivers.GetSnapshotVolumeName(inst.Name(), poolVolSnap.Name)
// Copy volume config from backup file if present,
// so VolumeDBCreate can safely modify the copy if needed.
snapVolumeConfig := util.CloneMap(poolVolSnap.Config)
// Validate config and create database entry for recovered storage volume.
err = VolumeDBCreate(b, inst.Project().Name, fullSnapName, poolVolSnap.Description, volType, true, snapVolumeConfig, poolVolSnap.CreatedAt, time.Time{}, contentType, false, true)
if err != nil {
return nil, err
}
reverter.Add(func() { _ = VolumeDBDelete(b, inst.Project().Name, fullSnapName, volType) })
}
} else {
b.logger.Warn("Missing volume snapshot info in backup config, using parent volume config")
// Create storage volume snapshot DB records based on instance snapshot list, as the
// backup config doesn't contain the required info. This is needed because there was a
// historical bug that meant that the instance's backup file didn't store the storage
// volume snapshot info.
for _, i := range snapshots {
fullSnapName := i // Local var for revert.
// Validate config and create database entry for new storage volume.
// Use parent volume config.
err = VolumeDBCreate(b, inst.Project().Name, fullSnapName, "", volType, true, volumeConfig, time.Time{}, time.Time{}, contentType, false, true)
if err != nil {
return nil, err
}
reverter.Add(func() { _ = VolumeDBDelete(b, inst.Project().Name, fullSnapName, volType) })
}
}
}
// Generate the effective root device volume for instance.
volStorageName := project.Instance(inst.Project().Name, inst.Name())
vol := b.GetVolume(volType, contentType, volStorageName, volumeConfig)
err = b.applyInstanceRootDiskOverrides(inst, &vol)
if err != nil {
return nil, err
}
err = vol.EnsureMountPath(false)
if err != nil {
return nil, err
}
// Only attempt to restore mount status on instance's local cluster member.
if inst.Location() == b.state.ServerName {
l.Debug("Restoring local instance mount status")
if inst.IsRunning() {
// If the instance is running then this implies the volume is mounted, but if the Incus
// daemon has been restarted since the DB records were removed then there will be no mount
// reference counter showing the volume is in use. If this is the case then call mount the
// volume to increment the reference counter.
if !vol.MountInUse() {
_, err = b.MountInstance(inst, op)
if err != nil {
return nil, fmt.Errorf("Failed mounting instance: %w", err)
}
}
} else {
// If the instance isn't running then try and unmount it to ensure consistent state after
// import.
err = b.UnmountInstance(inst, op)
if err != nil {
return nil, fmt.Errorf("Failed unmounting instance: %w", err)
}
}
}
// Create symlink.
err = b.ensureInstanceSymlink(inst.Type(), inst.Project().Name, inst.Name(), vol.MountPath())
if err != nil {
return nil, err
}
reverter.Add(func() {
// Remove symlinks.
_ = b.removeInstanceSymlink(inst.Type(), inst.Project().Name, inst.Name())
_ = b.removeInstanceSnapshotSymlinkIfUnused(inst.Type(), inst.Project().Name, inst.Name())
})
// Create snapshot mount paths and snapshot symlink if needed.
if len(snapshots) > 0 {
for _, snapName := range snapshots {
_, snapOnlyName, _ := api.GetParentAndSnapshotName(snapName)
l.Debug("Ensuring instance snapshot mount path", logger.Ctx{"snapshot": snapOnlyName})
snapVol, err := vol.NewSnapshot(snapOnlyName)
if err != nil {
return nil, err
}
err = snapVol.EnsureMountPath(false)
if err != nil {
return nil, err
}
}
err = b.ensureInstanceSnapshotSymlink(inst.Type(), inst.Project().Name, inst.Name())
if err != nil {
return nil, err
}
}
cleanup := reverter.Clone().Fail
reverter.Success()
return cleanup, err
}
func (b *backend) BackupCustomVolume(projectName string, volName string, tarWriter *instancewriter.InstanceTarWriter, optimized bool, snapshots bool, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": projectName, "volume": volName, "optimized": optimized, "snapshots": snapshots})
l.Debug("BackupCustomVolume started")
defer l.Debug("BackupCustomVolume finished")
volume, err := VolumeDBGet(b, projectName, volName, drivers.VolumeTypeCustom)
if err != nil {
return err
}
// Get the volume name on storage.
volStorageName := project.StorageVolume(projectName, volume.Name)
contentDBType, err := VolumeContentTypeNameToContentType(volume.ContentType)
if err != nil {
return err
}
contentType, err := VolumeDBContentTypeToContentType(contentDBType)
if err != nil {
return err
}
if contentType != drivers.ContentTypeFS && contentType != drivers.ContentTypeBlock {
return fmt.Errorf("Volume of content type %q cannot be backed up", contentType)
}
var snapNames []string
if snapshots {
// Get snapshots in age order, oldest first, and pass names to storage driver.
volSnaps, err := VolumeDBSnapshotsGet(b, projectName, volName, drivers.VolumeTypeCustom)
if err != nil {
return err
}
snapNames = make([]string, 0, len(volSnaps))
for _, volSnap := range volSnaps {
_, snapName, _ := api.GetParentAndSnapshotName(volSnap.Name)
snapNames = append(snapNames, snapName)
}
}
vol := b.GetVolume(drivers.VolumeTypeCustom, drivers.ContentType(volume.ContentType), volStorageName, volume.Config)
err = b.driver.BackupVolume(vol, tarWriter, optimized, snapNames, op)
if err != nil {
return err
}
return nil
}
func (b *backend) CreateCustomVolumeFromISO(projectName string, volName string, srcData io.ReadSeeker, size int64, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": projectName, "volume": volName})
l.Debug("CreateCustomVolumeFromISO started")
defer l.Debug("CreateCustomVolumeFromISO finished")
// Check whether we are allowed to create volumes.
req := api.StorageVolumesPost{
Name: volName,
StorageVolumePut: api.StorageVolumePut{
Config: map[string]string{
"size": fmt.Sprintf("%d", size),
},
},
}
err := b.state.DB.Cluster.Transaction(b.state.ShutdownCtx, func(ctx context.Context, tx *db.ClusterTx) error {
return project.AllowVolumeCreation(tx, projectName, b.name, req)
})
if err != nil {
return fmt.Errorf("Failed checking volume creation allowed: %w", err)
}
reverter := revert.New()
defer reverter.Fail()
// Get the volume name on storage.
volStorageName := project.StorageVolume(projectName, volName)
vol := b.GetVolume(drivers.VolumeTypeCustom, drivers.ContentTypeISO, volStorageName, req.Config)
volExists, err := b.driver.HasVolume(vol)
if err != nil {
return err
}
if volExists {
return errors.New("Cannot create volume, already exists on target storage")
}
// Validate config and create database entry for new storage volume.
err = VolumeDBCreate(b, projectName, volName, "", vol.Type(), false, vol.Config(), time.Now(), time.Time{}, vol.ContentType(), true, true)
if err != nil {
return fmt.Errorf("Failed creating database entry for custom volume: %w", err)
}
reverter.Add(func() { _ = VolumeDBDelete(b, projectName, volName, vol.Type()) })
_, err = srcData.Seek(0, io.SeekStart)
if err != nil {
return err
}
volFiller := drivers.VolumeFiller{
Fill: b.isoFiller(srcData),
}
// Unpack the ISO into the new storage volume(s).
err = b.driver.CreateVolume(vol, &volFiller, op)
if err != nil {
return fmt.Errorf("Failed creating volume: %w", err)
}
eventCtx := logger.Ctx{"type": vol.Type()}
if !b.Driver().Info().Remote {
eventCtx["location"] = b.state.ServerName
}
var location string
if b.state.ServerClustered && !b.Driver().Info().Remote {
location = b.state.ServerName
}
// Record new volume with authorizer.
err = b.state.Authorizer.AddStoragePoolVolume(b.state.ShutdownCtx, projectName, b.Name(), vol.Type().Singular(), volName, location)
if err != nil {
logger.Error("Failed to add storage volume to authorizer", logger.Ctx{"name": volName, "type": vol.Type(), "pool": b.Name(), "project": projectName, "error": err})
}
b.state.Events.SendLifecycle(projectName, lifecycle.StorageVolumeCreated.Event(vol, string(vol.Type()), projectName, op, eventCtx))
reverter.Success()
return nil
}
func (b *backend) CreateCustomVolumeFromBackup(srcBackup backup.Info, srcData io.ReadSeeker, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": srcBackup.Project, "volume": srcBackup.Name, "snapshots": srcBackup.Snapshots, "optimizedStorage": *srcBackup.OptimizedStorage})
l.Debug("CreateCustomVolumeFromBackup started")
defer l.Debug("CreateCustomVolumeFromBackup finished")
if srcBackup.Config == nil || srcBackup.Config.Volume == nil {
return errors.New("Valid volume config not found in index")
}
if len(srcBackup.Snapshots) != len(srcBackup.Config.VolumeSnapshots) {
return errors.New("Valid volume snapshot config not found in index")
}
// Check whether we are allowed to create volumes.
req := api.StorageVolumesPost{
StorageVolumePut: api.StorageVolumePut{
Config: srcBackup.Config.Volume.Config,
},
Name: srcBackup.Name,
}
err := b.state.DB.Cluster.Transaction(b.state.ShutdownCtx, func(ctx context.Context, tx *db.ClusterTx) error {
return project.AllowVolumeCreation(tx, srcBackup.Project, b.name, req)
})
if err != nil {
return fmt.Errorf("Failed checking volume creation allowed: %w", err)
}
reverter := revert.New()
defer reverter.Fail()
// Get the volume name on storage.
volStorageName := project.StorageVolume(srcBackup.Project, srcBackup.Name)
vol := b.GetVolume(drivers.VolumeTypeCustom, drivers.ContentType(srcBackup.Config.Volume.ContentType), volStorageName, srcBackup.Config.Volume.Config)
// Check if the volume exists in database.
dbVol, err := VolumeDBGet(b, srcBackup.Project, srcBackup.Name, vol.Type())
if err != nil && !response.IsNotFoundError(err) {
return err
}
if dbVol != nil {
return fmt.Errorf("Volume %q already exists in pool %q", srcBackup.Name, b.name)
}
// Validate config and create database entry for new storage volume.
// Strip unsupported config keys (in case the export was made from a different type of storage pool).
err = VolumeDBCreate(b, srcBackup.Project, srcBackup.Name, srcBackup.Config.Volume.Description, vol.Type(), false, vol.Config(), srcBackup.Config.Volume.CreatedAt, time.Time{}, vol.ContentType(), true, true)
if err != nil {
return err
}
reverter.Add(func() { _ = VolumeDBDelete(b, srcBackup.Project, srcBackup.Name, vol.Type()) })
// Create database entries for new storage volume snapshots.
for _, s := range srcBackup.Config.VolumeSnapshots {
snapshot := s // Local var for revert.
snapName := snapshot.Name
// Due to a historical bug, the volume snapshot names were sometimes written in their full form
// (<parent>/<snap>) rather than the expected snapshot name only form, so we need to handle both.
if internalInstance.IsSnapshot(snapshot.Name) {
_, snapName, _ = api.GetParentAndSnapshotName(snapshot.Name)
}
fullSnapName := drivers.GetSnapshotVolumeName(srcBackup.Name, snapName)
snapVolStorageName := project.StorageVolume(srcBackup.Project, fullSnapName)
snapVol := b.GetVolume(drivers.VolumeTypeCustom, drivers.ContentType(srcBackup.Config.Volume.ContentType), snapVolStorageName, snapshot.Config)
// Validate config and create database entry for new storage volume.
// Strip unsupported config keys (in case the export was made from a different type of storage pool).
err = VolumeDBCreate(b, srcBackup.Project, fullSnapName, snapshot.Description, snapVol.Type(), true, snapVol.Config(), snapshot.CreatedAt, *snapshot.ExpiresAt, snapVol.ContentType(), true, true)
if err != nil {
return err
}
reverter.Add(func() { _ = VolumeDBDelete(b, srcBackup.Project, fullSnapName, snapVol.Type()) })
}
// Unpack the backup into the new storage volume(s).
volPostHook, revertHook, err := b.driver.CreateVolumeFromBackup(vol, srcBackup, srcData, op)
if err != nil {
return err
}
if revertHook != nil {
reverter.Add(revertHook)
}
// If the driver returned a post hook, return error as custom volumes don't need post hooks and we expect
// the storage driver to understand this distinction and ensure that all activities done in the postHook
// normally are done in CreateVolumeFromBackup as the DB record is created ahead of time.
if volPostHook != nil {
return errors.New("Custom volume restore doesn't support post hooks")
}
eventCtx := logger.Ctx{"type": vol.Type()}
if !b.Driver().Info().Remote {
eventCtx["location"] = b.state.ServerName
}
var location string
if b.state.ServerClustered && !b.Driver().Info().Remote {
location = b.state.ServerName
}
// Record new volume with authorizer.
err = b.state.Authorizer.AddStoragePoolVolume(b.state.ShutdownCtx, srcBackup.Project, b.Name(), vol.Type().Singular(), srcBackup.Name, location)
if err != nil {
logger.Error("Failed to add storage volume to authorizer", logger.Ctx{"name": srcBackup.Name, "type": vol.Type(), "pool": b.Name(), "project": srcBackup.Project, "error": err})
}
b.state.Events.SendLifecycle(srcBackup.Project, lifecycle.StorageVolumeCreated.Event(vol, string(vol.Type()), srcBackup.Project, op, eventCtx))
reverter.Success()
return nil
}
// BackupBucket backups up a bucket to a tarball.
func (b *backend) BackupBucket(projectName string, bucketName string, tarWriter *instancewriter.InstanceTarWriter, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": projectName, "bucket": bucketName})
l.Debug("BackupBucket started")
defer l.Debug("BackupBucket finished")
err := b.isStatusReady()
if err != nil {
return err
}
if !b.Driver().Info().Buckets {
return errors.New("Storage pool does not support buckets")
}
memberSpecific := !b.Driver().Info().Remote // Member specific if storage pool isn't remote.
var bucket *db.StorageBucket
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
bucket, err = tx.GetStoragePoolBucket(ctx, b.id, projectName, memberSpecific, bucketName)
return err
})
if err != nil {
return err
}
backupKey, err := b.getFirstReadStorageBucketPoolKey(bucket.ID)
if err != nil {
return err
}
bucketURL := b.GetBucketURL(bucket.Name)
if bucketURL == nil {
return errors.New("The server is lacking a storage buckets listener address")
}
transferManager := s3.NewTransferManager(bucketURL, backupKey.AccessKey, backupKey.SecretKey)
err = transferManager.DownloadAllFiles(bucket.Name, tarWriter)
if err != nil {
return err
}
return nil
}
// CreateBucketFromBackup creates a bucket from a tarball.
func (b *backend) CreateBucketFromBackup(srcBackup backup.Info, srcData io.ReadSeeker, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": srcBackup.Project, "bucket": srcBackup.Name})
l.Debug("CreateBucketFromBackup started")
defer l.Debug("CreateBucketFromBackup finished")
err := b.isStatusReady()
if err != nil {
return err
}
if !b.Driver().Info().Buckets {
return errors.New("Storage pool does not support buckets")
}
reverter := revert.New()
defer reverter.Fail()
bucketRequest := api.StorageBucketsPost{
Name: srcBackup.Name,
StorageBucketPut: srcBackup.Config.Bucket.StorageBucketPut,
}
// Create the bucket to import.
err = b.CreateBucket(srcBackup.Project, bucketRequest, op)
if err != nil {
return err
}
reverter.Add(func() { _ = b.DeleteBucket(srcBackup.Project, bucketRequest.Name, op) })
// Upload all keys from the backup.
for _, bucketKey := range srcBackup.Config.BucketKeys {
bucketKeyRequest := api.StorageBucketKeysPost{
Name: bucketKey.Name,
StorageBucketKeyPut: bucketKey.StorageBucketKeyPut,
}
_, err := b.CreateBucketKey(srcBackup.Project, srcBackup.Name, bucketKeyRequest, op)
if err != nil {
return err
}
}
// Upload all files from the backup.
backupKey, err := b.getFirstAdminStorageBucketPoolKey(srcBackup.Project, srcBackup.Name)
if err != nil {
return err
}
bucketURL := b.GetBucketURL(srcBackup.Name)
if bucketURL == nil {
return errors.New("The server is lacking a storage buckets listener address")
}
transferManager := s3.NewTransferManager(bucketURL, backupKey.AccessKey, backupKey.SecretKey)
err = transferManager.UploadAllFiles(srcBackup.Name, srcData)
if err != nil {
return err
}
reverter.Success()
return nil
}
func (b *backend) getFirstReadStorageBucketPoolKey(bucketID int64) (*db.StorageBucketKey, error) {
var backupKey *db.StorageBucketKey
err := b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
bucketKeys, err := tx.GetStoragePoolBucketKeys(ctx, bucketID)
bucketKeysLen := len(bucketKeys)
if (err == nil && bucketKeysLen <= 0) || errors.Is(err, sql.ErrNoRows) {
return api.StatusErrorf(http.StatusNotFound, "Storage bucket key not found")
} else if err != nil {
return err
}
backupKey = bucketKeys[0]
return nil
})
if err != nil {
return nil, err
}
return backupKey, nil
}
func (b *backend) getFirstAdminStorageBucketPoolKey(projectName string, bucketName string) (*db.StorageBucketKey, error) {
memberSpecific := !b.Driver().Info().Remote // Member specific if storage pool isn't remote.
var bucket *db.StorageBucket
err := b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
var err error
bucket, err = tx.GetStoragePoolBucket(ctx, b.id, projectName, memberSpecific, bucketName)
return err
})
if err != nil {
return nil, err
}
var bucketKey *db.StorageBucketKey
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
bucketKeys, err := tx.GetStoragePoolBucketKeys(ctx, bucket.ID)
bucketKeysLen := len(bucketKeys)
if (err == nil && bucketKeysLen <= 0) || errors.Is(err, sql.ErrNoRows) {
return api.StatusErrorf(http.StatusNotFound, "Storage bucket key not found")
} else if err != nil {
return err
}
for _, key := range bucketKeys {
if key.Role == "admin" {
bucketKey = key
break
}
}
if bucketKey == nil {
return api.StatusErrorf(http.StatusNotFound, "No storage bucket admin key found")
}
return nil
})
if err != nil {
return nil, err
}
return bucketKey, nil
}
|