1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229
|
package drivers
import (
"bufio"
"bytes"
"compress/gzip"
"context"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"database/sql"
"embed"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"maps"
"math"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"slices"
"sort"
"strconv"
"strings"
"time"
"unsafe"
"github.com/flosch/pongo2"
"github.com/google/uuid"
"github.com/gorilla/websocket"
"github.com/kballard/go-shellquote"
"github.com/mdlayher/vsock"
"github.com/pkg/sftp"
"golang.org/x/sync/errgroup"
"golang.org/x/sys/unix"
"google.golang.org/protobuf/proto"
"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"
"github.com/lxc/incus/v6/internal/jmap"
"github.com/lxc/incus/v6/internal/linux"
"github.com/lxc/incus/v6/internal/migration"
"github.com/lxc/incus/v6/internal/ports"
"github.com/lxc/incus/v6/internal/server/apparmor"
"github.com/lxc/incus/v6/internal/server/cgroup"
"github.com/lxc/incus/v6/internal/server/db"
dbCluster "github.com/lxc/incus/v6/internal/server/db/cluster"
"github.com/lxc/incus/v6/internal/server/device"
deviceConfig "github.com/lxc/incus/v6/internal/server/device/config"
"github.com/lxc/incus/v6/internal/server/device/nictype"
"github.com/lxc/incus/v6/internal/server/instance"
"github.com/lxc/incus/v6/internal/server/instance/drivers/cfg"
"github.com/lxc/incus/v6/internal/server/instance/drivers/edk2"
"github.com/lxc/incus/v6/internal/server/instance/drivers/qemudefault"
"github.com/lxc/incus/v6/internal/server/instance/drivers/qmp"
"github.com/lxc/incus/v6/internal/server/instance/instancetype"
"github.com/lxc/incus/v6/internal/server/instance/operationlock"
"github.com/lxc/incus/v6/internal/server/lifecycle"
"github.com/lxc/incus/v6/internal/server/metrics"
localMigration "github.com/lxc/incus/v6/internal/server/migration"
"github.com/lxc/incus/v6/internal/server/network"
"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/scriptlet"
scriptletLoad "github.com/lxc/incus/v6/internal/server/scriptlet/load"
"github.com/lxc/incus/v6/internal/server/state"
storagePools "github.com/lxc/incus/v6/internal/server/storage"
storageDrivers "github.com/lxc/incus/v6/internal/server/storage/drivers"
pongoTemplate "github.com/lxc/incus/v6/internal/server/template"
localUtil "github.com/lxc/incus/v6/internal/server/util"
localvsock "github.com/lxc/incus/v6/internal/server/vsock"
internalUtil "github.com/lxc/incus/v6/internal/util"
"github.com/lxc/incus/v6/internal/version"
"github.com/lxc/incus/v6/shared/api"
agentAPI "github.com/lxc/incus/v6/shared/api/agent"
"github.com/lxc/incus/v6/shared/ioprogress"
"github.com/lxc/incus/v6/shared/logger"
"github.com/lxc/incus/v6/shared/osarch"
"github.com/lxc/incus/v6/shared/resources"
"github.com/lxc/incus/v6/shared/revert"
"github.com/lxc/incus/v6/shared/subprocess"
localtls "github.com/lxc/incus/v6/shared/tls"
"github.com/lxc/incus/v6/shared/units"
"github.com/lxc/incus/v6/shared/util"
)
// incus-agent files
//
//go:embed agent-loader/*
var incusAgentLoader embed.FS
// qemuSerialChardevName is used to communicate state with QEMU via QMP.
const qemuSerialChardevName = "qemu_serial-chardev"
// qemuPCIDeviceIDStart is the first PCI slot used for user configurable devices.
const qemuPCIDeviceIDStart = 4
// qemuDeviceIDPrefix used as part of the name given QEMU devices generated from user added devices.
const qemuDeviceIDPrefix = "dev-incus_"
// qemuNetDevIDPrefix used as part of the name given QEMU netdevs generated from user added devices.
const qemuNetDevIDPrefix = "incus_"
// qemuBlockDevIDPrefix used as part of the name given QEMU blockdevs generated from user added devices.
const qemuBlockDevIDPrefix = "incus_"
// qemuMigrationNBDExportName is the name of the disk device export by the migration NBD server.
const qemuMigrationNBDExportName = "incus_root"
// qemuSparseUSBPorts is the amount of sparse USB ports for VMs.
// 4 are reserved, and the other 4 can be used for any USB device.
const qemuSparseUSBPorts = 8
var errQemuAgentOffline = errors.New("VM agent isn't currently running")
type monitorHook func(m *qmp.Monitor) error
// qemuLoad creates a Qemu instance from the supplied InstanceArgs.
func qemuLoad(s *state.State, args db.InstanceArgs, p api.Project) (instance.Instance, error) {
// Create the instance struct.
d := qemuInstantiate(s, args, nil, p)
// Expand config and devices.
err := d.expandConfig()
if err != nil {
return nil, err
}
return d, nil
}
// qemuInstantiate creates a Qemu struct without expanding config. The expandedDevices argument is
// used during device config validation when the devices have already been expanded and we do not
// have access to the profiles used to do it. This can be safely passed as nil if not required.
func qemuInstantiate(s *state.State, args db.InstanceArgs, expandedDevices deviceConfig.Devices, p api.Project) *qemu {
d := &qemu{
common: common{
state: s,
architecture: args.Architecture,
creationDate: args.CreationDate,
dbType: args.Type,
description: args.Description,
ephemeral: args.Ephemeral,
expiryDate: args.ExpiryDate,
id: args.ID,
lastUsedDate: args.LastUsedDate,
localConfig: args.Config,
localDevices: args.Devices,
logger: logger.AddContext(logger.Ctx{"instanceType": args.Type, "instance": args.Name, "project": args.Project}),
name: args.Name,
node: args.Node,
profiles: args.Profiles,
project: p,
isSnapshot: args.Snapshot,
stateful: args.Stateful,
},
}
// Get the architecture name.
archName, err := osarch.ArchitectureName(d.architecture)
if err == nil {
d.architectureName = archName
}
// Cleanup the zero values.
if d.expiryDate.IsZero() {
d.expiryDate = time.Time{}
}
if d.creationDate.IsZero() {
d.creationDate = time.Time{}
}
if d.lastUsedDate.IsZero() {
d.lastUsedDate = time.Time{}
}
// This is passed during expanded config validation.
if expandedDevices != nil {
d.expandedDevices = expandedDevices
}
return d
}
// qemuCreate creates a new storage volume record and returns an initialized Instance.
// Returns a revert fail function that can be used to undo this function if a subsequent step fails.
func qemuCreate(s *state.State, args db.InstanceArgs, p api.Project, op *operations.Operation) (instance.Instance, revert.Hook, error) {
reverter := revert.New()
defer reverter.Fail()
// Create the instance struct.
d := &qemu{
common: common{
state: s,
op: op,
architecture: args.Architecture,
creationDate: args.CreationDate,
dbType: args.Type,
description: args.Description,
ephemeral: args.Ephemeral,
expiryDate: args.ExpiryDate,
id: args.ID,
lastUsedDate: args.LastUsedDate,
localConfig: args.Config,
localDevices: args.Devices,
logger: logger.AddContext(logger.Ctx{"instanceType": args.Type, "instance": args.Name, "project": args.Project}),
name: args.Name,
node: args.Node,
profiles: args.Profiles,
project: p,
isSnapshot: args.Snapshot,
stateful: args.Stateful,
},
}
// Get the architecture name.
archName, err := osarch.ArchitectureName(d.architecture)
if err == nil {
d.architectureName = archName
}
// Cleanup the zero values.
if d.expiryDate.IsZero() {
d.expiryDate = time.Time{}
}
if d.creationDate.IsZero() {
d.creationDate = time.Time{}
}
if d.lastUsedDate.IsZero() {
d.lastUsedDate = time.Time{}
}
if args.Snapshot {
d.logger.Info("Creating instance snapshot", logger.Ctx{"ephemeral": d.ephemeral})
} else {
d.logger.Info("Creating instance", logger.Ctx{"ephemeral": d.ephemeral})
}
// Load the config.
err = d.init()
if err != nil {
return nil, nil, fmt.Errorf("Failed to expand config: %w", err)
}
// When not a snapshot, perform full validation.
if !args.Snapshot {
// Validate expanded config (allows mixed instance types for profiles).
err = instance.ValidConfig(s.OS, d.expandedConfig, true, instancetype.Any)
if err != nil {
return nil, nil, fmt.Errorf("Invalid config: %w", err)
}
err = instance.ValidDevices(s, d.project, d.Type(), d.localDevices, d.expandedDevices)
if err != nil {
return nil, nil, fmt.Errorf("Invalid devices: %w", err)
}
}
// Retrieve the instance's storage pool.
_, rootDiskDevice, err := d.getRootDiskDevice()
if err != nil {
return nil, nil, fmt.Errorf("Failed getting root disk: %w", err)
}
if rootDiskDevice["pool"] == "" {
return nil, nil, errors.New("The instance's root device is missing the pool property")
}
// Initialize the storage pool.
d.storagePool, err = storagePools.LoadByName(d.state, rootDiskDevice["pool"])
if err != nil {
return nil, nil, fmt.Errorf("Failed loading storage pool: %w", err)
}
volType, err := storagePools.InstanceTypeToVolumeType(d.Type())
if err != nil {
return nil, nil, err
}
storagePoolSupported := slices.Contains(d.storagePool.Driver().Info().VolumeTypes, volType)
if !storagePoolSupported {
return nil, nil, errors.New("Storage pool does not support instance type")
}
if !d.IsSnapshot() {
// Add devices to instance.
cleanup, err := d.devicesAdd(d, false)
if err != nil {
return nil, nil, err
}
reverter.Add(cleanup)
}
if d.isSnapshot {
d.logger.Info("Created instance snapshot", logger.Ctx{"ephemeral": d.ephemeral})
} else {
d.logger.Info("Created instance", logger.Ctx{"ephemeral": d.ephemeral})
}
if d.isSnapshot {
d.state.Events.SendLifecycle(d.project.Name, lifecycle.InstanceSnapshotCreated.Event(d, nil))
} else {
err = d.state.Authorizer.AddInstance(d.state.ShutdownCtx, d.project.Name, d.Name())
if err != nil {
logger.Error("Failed to add instance to authorizer", logger.Ctx{"name": d.Name(), "project": d.project.Name, "error": err})
}
reverter.Add(func() { _ = d.state.Authorizer.DeleteInstance(d.state.ShutdownCtx, d.project.Name, d.Name()) })
d.state.Events.SendLifecycle(d.project.Name, lifecycle.InstanceCreated.Event(d, map[string]any{
"type": api.InstanceTypeVM,
"storage-pool": d.storagePool.Name(),
"location": d.Location(),
}))
}
cleanup := reverter.Clone().Fail
reverter.Success()
return d, cleanup, err
}
// qemu is the QEMU virtual machine driver.
type qemu struct {
common
// Cached handles.
// Do not use these variables directly, instead use their associated get functions so they
// will be initialized on demand.
architectureName string
// Stateful migration streams.
migrationReceiveStateful map[string]io.ReadWriteCloser
// Keep a reference to the console socket when switching backends, so we can properly cleanup when switching back to a ring buffer.
consoleSocket *net.UnixListener
consoleSocketFile *os.File
// Keep a record of QEMU configuration.
cmdArgs []string
conf []cfg.Section
}
// qmpConnect connects to the QMP monitor.
func (d *qemu) qmpConnect() (*qmp.Monitor, error) {
return qmp.Connect(d.monitorPath(), qemuSerialChardevName, d.getMonitorEventHandler(), d.QMPLogFilePath(), qemuDetachDisk(d.state, d.id))
}
// getAgentClient returns the current agent client handle.
// Callers should check that the instance is running (and therefore mounted) before calling this function,
// otherwise the qmp.Connect call will fail to use the monitor socket file.
func (d *qemu) getAgentClient() (*http.Client, error) {
if d.isWindows() {
// Get known network details.
networks, err := d.getNetworkState()
if err != nil {
return nil, errQemuAgentOffline
}
// The connection uses mutual authentication, so use the server's key & cert for client.
agentCert, _, clientCert, clientKey, err := d.generateAgentCert()
if err != nil {
return nil, err
}
// Get the TLS configuration.
tlsConfig, err := localtls.GetTLSConfigMem(clientCert, clientKey, "", agentCert, false)
if err != nil {
return nil, err
}
// Setup an HTTPS client.
client := &http.Client{}
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
// Replicate the headers.
req.Header = via[len(via)-1].Header
return nil
}
for _, netInterface := range networks {
for _, address := range netInterface.Addresses {
if address.Scope != "global" {
continue
}
networkAddress := net.JoinHostPort(address.Address, strconv.Itoa(ports.HTTPSDefaultPort))
client.Transport = &http.Transport{
TLSClientConfig: tlsConfig,
DialContext: func(_ context.Context, network, addr string) (net.Conn, error) {
return net.DialTimeout("tcp", networkAddress, 100*time.Millisecond)
},
DisableKeepAlives: true,
ExpectContinueTimeout: time.Second * 3,
ResponseHeaderTimeout: time.Second * 3600,
TLSHandshakeTimeout: time.Second * 3,
}
_, err := client.Get("https://agent/")
if err == nil {
return client, nil
}
}
}
return nil, errQemuAgentOffline
}
// Check if the agent is running.
monitor, err := d.qmpConnect()
if err != nil {
return nil, err
}
if !monitor.AgenStarted() {
return nil, errQemuAgentOffline
}
// The connection uses mutual authentication, so use the server's key & cert for client.
agentCert, _, clientCert, clientKey, err := d.generateAgentCert()
if err != nil {
return nil, err
}
// Existing vsock ID from volatile.
vsockID, err := d.getVsockID()
if err != nil {
return nil, err
}
agent, err := localvsock.HTTPClient(vsockID, ports.HTTPSDefaultPort, clientCert, clientKey, agentCert)
if err != nil {
return nil, err
}
return agent, nil
}
func (d *qemu) getMonitorEventHandler() func(event string, data map[string]any) {
// Create local variables from instance properties we need so as not to keep references to instance around
// after we have returned the callback function.
instProject := d.Project()
instanceName := d.Name()
state := d.state
return func(event string, data map[string]any) {
if !slices.Contains([]string{qmp.EventVMShutdown, qmp.EventAgentStarted, qmp.EventRTCChange}, event) {
return // Don't bother loading the instance from DB if we aren't going to handle the event.
}
var err error
var d *qemu // Redefine d as local variable inside callback to avoid keeping references around.
inst := instanceRefGet(instProject.Name, instanceName)
if inst == nil {
inst, err = instance.LoadByProjectAndName(state, instProject.Name, instanceName)
if err != nil {
l := logger.AddContext(logger.Ctx{"project": instProject.Name, "instance": instanceName})
// If DB not available, try loading from backup file.
l.Warn("Failed loading instance from database to handle monitor event, trying backup file", logger.Ctx{"err": err})
instancePath := filepath.Join(internalUtil.VarPath("virtual-machines"), project.Instance(instProject.Name, instanceName))
inst, err = instance.LoadFromBackup(state, instProject.Name, instancePath, false)
if err != nil {
l.Error("Failed loading instance to handle monitor event", logger.Ctx{"err": err})
return
}
}
}
d = inst.(*qemu)
switch event {
case qmp.EventAgentStarted:
d.logger.Debug("Instance agent started")
err := d.advertiseVsockAddress()
if err != nil {
d.logger.Warn("Failed to advertise vsock address to instance agent", logger.Ctx{"err": err})
return
}
case qmp.EventVMShutdown:
target := "stop"
entry, ok := data["reason"]
if ok && entry == "guest-reset" {
target = "reboot"
}
if entry == qmp.EventVMShutdownReasonDisconnect {
d.logger.Warn("Instance stopped", logger.Ctx{"target": target, "reason": data["reason"]})
} else {
d.logger.Debug("Instance stopped", logger.Ctx{"target": target, "reason": data["reason"]})
}
err = d.onStop(target)
if err != nil {
d.logger.Error("Failed to cleanly stop instance", logger.Ctx{"err": err})
return
}
case qmp.EventRTCChange:
val, ok := data["offset"].(float64)
if !ok {
d.logger.Debug("No offset in data", logger.Ctx{"data": data})
return
}
err = d.onRTCChange(int(val))
if err != nil {
d.logger.Error("Failed to apply rtc change", logger.Ctx{"offset": val, "err": err})
}
}
}
}
// mount the instance's config volume if needed.
func (d *qemu) mount() (*storagePools.MountInfo, error) {
var pool storagePools.Pool
pool, err := d.getStoragePool()
if err != nil {
return nil, err
}
if d.IsSnapshot() {
mountInfo, err := pool.MountInstanceSnapshot(d, nil)
if err != nil {
return nil, err
}
return mountInfo, nil
}
mountInfo, err := pool.MountInstance(d, nil)
if err != nil {
return nil, err
}
return mountInfo, nil
}
// unmount the instance's config volume if needed.
func (d *qemu) unmount() error {
pool, err := d.getStoragePool()
if err != nil {
return err
}
err = pool.UnmountInstance(d, nil)
if err != nil {
return err
}
return nil
}
// generateAgentCert creates the necessary server key and certificate if needed.
func (d *qemu) generateAgentCert() (string, string, string, string, error) {
agentCertFile := filepath.Join(d.Path(), "agent.crt")
agentKeyFile := filepath.Join(d.Path(), "agent.key")
clientCertFile := filepath.Join(d.Path(), "agent-client.crt")
clientKeyFile := filepath.Join(d.Path(), "agent-client.key")
// Create server certificate.
err := localtls.FindOrGenCert(agentCertFile, agentKeyFile, false, false)
if err != nil {
return "", "", "", "", err
}
// Create client certificate.
err = localtls.FindOrGenCert(clientCertFile, clientKeyFile, true, false)
if err != nil {
return "", "", "", "", err
}
// Read all the files
agentCert, err := os.ReadFile(agentCertFile)
if err != nil {
return "", "", "", "", err
}
agentKey, err := os.ReadFile(agentKeyFile)
if err != nil {
return "", "", "", "", err
}
clientCert, err := os.ReadFile(clientCertFile)
if err != nil {
return "", "", "", "", err
}
clientKey, err := os.ReadFile(clientKeyFile)
if err != nil {
return "", "", "", "", err
}
return string(agentCert), string(agentKey), string(clientCert), string(clientKey), nil
}
// Freeze freezes the instance.
func (d *qemu) Freeze() error {
// Connect to the monitor.
monitor, err := d.qmpConnect()
if err != nil {
return err
}
// Send the stop command.
err = monitor.Pause()
if err != nil {
return err
}
d.state.Events.SendLifecycle(d.project.Name, lifecycle.InstancePaused.Event(d, nil))
return nil
}
// configDriveMountPath returns the path for the config drive bind mount.
func (d *qemu) configDriveMountPath() string {
return filepath.Join(d.DevicesPath(), "config.mount")
}
// configDriveMountPathClear attempts to unmount the config drive bind mount and remove the directory.
func (d *qemu) configDriveMountPathClear() error {
return device.DiskMountClear(d.configDriveMountPath())
}
// pidWait waits for the QEMU process to exit. Does this in a way that doesn't require the process to be a
// parent of the QEMU process (in order to allow for the daemon to be restarted after the VM was started).
// Returns true if process stopped, false if timeout was exceeded.
func (d *qemu) pidWait(timeout time.Duration) bool {
waitUntil := time.Now().Add(timeout)
for {
pid, _ := d.pid()
if pid <= 0 {
break
}
if time.Now().After(waitUntil) {
return false
}
time.Sleep(time.Millisecond * time.Duration(250))
}
return true
}
// onStop is run when the instance stops.
func (d *qemu) onStop(target string) error {
d.logger.Debug("onStop hook started", logger.Ctx{"target": target})
defer d.logger.Debug("onStop hook finished", logger.Ctx{"target": target})
// Create/pick up operation.
op, err := d.onStopOperationSetup(target)
if err != nil {
return err
}
// Unlock on return
defer op.Done(nil)
// Set operation if missing.
if d.op == nil {
d.op = op.GetOperation()
}
// Wait for QEMU process to end (to avoiding racing start when restarting).
// Wait up to 5 minutes to allow for flushing any pending data to disk.
d.logger.Debug("Waiting for VM process to finish")
waitTimeout := time.Minute * 5
if d.pidWait(waitTimeout) {
d.logger.Debug("VM process finished")
} else {
// Log a warning, but continue clean up as best we can.
d.logger.Error("VM process failed to stop", logger.Ctx{"timeout": waitTimeout})
}
// Record power state.
err = d.VolatileSet(map[string]string{
"volatile.last_state.power": instance.PowerStateStopped,
"volatile.last_state.ready": "false",
})
if err != nil {
// Don't return an error here as we still want to cleanup the instance even if DB not available.
d.logger.Error("Failed recording last power state", logger.Ctx{"err": err})
}
// Cleanup.
d.cleanupDevices() // Must be called before unmount.
_ = os.Remove(d.pidFilePath())
_ = os.Remove(d.monitorPath())
_ = os.Remove(d.spicePath())
// Stop the storage for the instance.
err = d.unmount()
if err != nil && !errors.Is(err, storageDrivers.ErrInUse) {
err = fmt.Errorf("Failed unmounting instance: %w", err)
op.Done(err)
return err
}
// Unload the apparmor profile
err = apparmor.InstanceUnload(d.state.OS, d)
if err != nil {
op.Done(err)
return err
}
// Determine if instance should be auto-restarted.
var autoRestart bool
if target != "reboot" && op.GetInstanceInitiated() && d.shouldAutoRestart() {
autoRestart = true
// Mark current shutdown as complete.
op.Done(nil)
// Create a new restart operation.
op, err = operationlock.CreateWaitGet(d.Project().Name, d.Name(), d.op, operationlock.ActionRestart, nil, true, false)
if err == nil {
defer op.Done(nil)
} else {
d.logger.Error("Failed to setup new restart operation", logger.Ctx{"err": err})
}
}
// Log and emit lifecycle if not user triggered.
if target != "reboot" && !autoRestart && op.Action() != operationlock.ActionMigrate {
if op.GetInstanceInitiated() {
d.state.Events.SendLifecycle(d.project.Name, lifecycle.InstanceShutdown.Event(d, nil))
} else {
d.state.Events.SendLifecycle(d.project.Name, lifecycle.InstanceStopped.Event(d, nil))
}
}
// Reboot the instance.
if target == "reboot" || autoRestart {
err = d.Start(false)
if err != nil {
op.Done(err)
return err
}
d.state.Events.SendLifecycle(d.project.Name, lifecycle.InstanceRestarted.Event(d, nil))
} else if d.ephemeral {
// Destroy ephemeral virtual machines.
err = d.delete(true)
if err != nil {
op.Done(err)
return err
}
}
return nil
}
// Shutdown shuts the instance down.
func (d *qemu) Shutdown(timeout time.Duration) error {
d.logger.Debug("Shutdown started", logger.Ctx{"timeout": timeout})
defer d.logger.Debug("Shutdown finished", logger.Ctx{"timeout": timeout})
// Must be run prior to creating the operation lock.
statusCode := d.statusCode()
if !d.isRunningStatusCode(statusCode) {
if statusCode == api.Error {
return fmt.Errorf("The instance cannot be cleanly shutdown as in %s status", statusCode)
}
return ErrInstanceIsStopped
}
// Save the console log from ring buffer before the instance is shutdown. Must be run prior to creating the operation lock.
_, err := d.ConsoleLog()
if err != nil {
return err
}
// Setup a new operation.
// Allow inheriting of ongoing restart operation (we are called from restartCommon).
// Allow reuse when creating a new stop operation. This allows the Stop() function to inherit operation.
// Allow reuse of a reusable ongoing stop operation as Shutdown() may be called earlier, which allows reuse
// of its operations. This allow for multiple Shutdown() attempts.
op, err := operationlock.CreateWaitGet(d.Project().Name, d.Name(), d.op, operationlock.ActionStop, []operationlock.Action{operationlock.ActionRestart}, true, true)
if err != nil {
if errors.Is(err, operationlock.ErrNonReusuableSucceeded) {
// An existing matching operation has now succeeded, return.
return nil
}
return err
}
// If frozen, resume so the signal can be handled.
if d.IsFrozen() {
err := d.Unfreeze()
if err != nil {
return err
}
}
// Connect to the monitor.
monitor, err := d.qmpConnect()
if err != nil {
op.Done(err)
return err
}
// Indicate to the onStop hook that if the VM stops it was due to a clean shutdown because the VM responded
// to the powerdown request.
op.SetInstanceInitiated(true)
// Send the system_powerdown command.
err = monitor.Powerdown()
if err != nil {
if errors.Is(err, qmp.ErrMonitorDisconnect) {
op.Done(nil)
return nil
}
op.Done(err)
return err
}
// Wait 500ms for the first event to be received by the guest.
time.Sleep(500 * time.Millisecond)
// Attempt to send a second system_powerdown command (required to get Windows to shutdown).
_ = monitor.Powerdown()
d.logger.Debug("Shutdown request sent to instance")
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
// Wait for operation lock to be Done or context to timeout. The operation lock is normally completed by
// onStop which picks up the same lock and then marks it as Done after the instance stops and the devices
// have been cleaned up. However if the operation has failed for another reason we collect the error here.
err = op.Wait(ctx)
status := d.statusCode()
if status != api.Stopped {
errPrefix := fmt.Errorf("Failed shutting down instance, status is %q", status)
if err != nil {
return fmt.Errorf("%s: %w", errPrefix.Error(), err)
}
return errPrefix
}
// Now handle errors from shutdown sequence and return to caller if wasn't completed cleanly.
if err != nil {
return err
}
return nil
}
// Restart restart the instance.
func (d *qemu) Restart(timeout time.Duration) error {
return d.restartCommon(d, timeout)
}
// Rebuild rebuilds the instance using the supplied image fingerprint as source.
func (d *qemu) Rebuild(img *api.Image, op *operations.Operation) error {
return d.rebuildCommon(d, img, op)
}
// killQemuProcess kills specified process. Optimistically attempts to wait for the process to fully exit, but does
// not return an error if the Wait call fails. This is because this function is used in scenarios where the daemon has
// been restarted after the VM has been started and is no longer the parent of the QEMU process.
// The caller should use another method to ensure that the QEMU process has fully exited instead.
// Returns an error if the Kill signal couldn't be sent to the process (for any other reason apart from the process
// not existing).
func (d *qemu) killQemuProcess(pid int) error {
proc, err := os.FindProcess(pid)
if err != nil {
if errors.Is(err, os.ErrProcessDone) {
return nil
}
return err
}
err = proc.Kill()
if err != nil {
if errors.Is(err, os.ErrProcessDone) {
return nil
}
return err
}
// Wait for process to exit, but don't return an error if this fails as it may be called when the daemon isn't
// the parent of the process, and we have still sent the kill signal as per the function's description.
_, err = proc.Wait()
if err != nil {
if strings.Contains(err.Error(), "no child processes") {
return nil
}
d.logger.Warn("Failed to collect VM process exit status", logger.Ctx{"pid": pid, "err": err})
}
return nil
}
// restoreState restores the VM state from a file handle.
func (d *qemu) restoreStateHandle(ctx context.Context, monitor *qmp.Monitor, f *os.File) error {
err := monitor.SendFile("migration", f)
if err != nil {
return err
}
err = monitor.MigrateIncoming(ctx, "migration")
if err != nil {
return err
}
return nil
}
// restoreState restores VM state from state file or from migration source if d.migrationReceiveStateful set.
func (d *qemu) restoreState(monitor *qmp.Monitor) error {
if d.migrationReceiveStateful != nil {
stateConn := d.migrationReceiveStateful[api.SecretNameState]
if stateConn == nil {
return errors.New("Migration state connection is not initialized")
}
// Perform non-shared storage transfer if requested.
filesystemConn := d.migrationReceiveStateful[api.SecretNameFilesystem]
if filesystemConn != nil {
nbdConn, err := monitor.NBDServerStart()
if err != nil {
return fmt.Errorf("Failed starting NBD server: %w", err)
}
d.logger.Debug("Migration NBD server started")
defer func() {
_ = nbdConn.Close()
_ = monitor.NBDServerStop()
}()
err = monitor.NBDBlockExportAdd(qemuMigrationNBDExportName)
if err != nil {
return fmt.Errorf("Failed adding root disk to NBD server: %w", err)
}
go func() {
d.logger.Debug("Migration storage NBD export starting")
go func() { _, _ = io.Copy(filesystemConn, nbdConn) }()
_, _ = io.Copy(nbdConn, filesystemConn)
_ = nbdConn.Close()
d.logger.Debug("Migration storage NBD export finished")
}()
defer func() { _ = filesystemConn.Close() }()
}
// Receive checkpoint from QEMU process on source.
d.logger.Debug("Stateful migration checkpoint receive starting")
pipeRead, pipeWrite, err := os.Pipe()
if err != nil {
return err
}
go func() {
_, _ = io.Copy(pipeWrite, stateConn)
_ = pipeRead.Close()
_ = pipeWrite.Close()
}()
err = d.restoreStateHandle(context.Background(), monitor, pipeRead)
if err != nil {
return fmt.Errorf("Failed restoring checkpoint from source: %w", err)
}
d.logger.Debug("Stateful migration checkpoint receive finished")
} else {
statePath := d.StatePath()
d.logger.Debug("Stateful checkpoint restore starting", logger.Ctx{"source": statePath})
defer d.logger.Debug("Stateful checkpoint restore finished", logger.Ctx{"source": statePath})
stateFile, err := os.Open(statePath)
if err != nil {
return fmt.Errorf("Failed opening state file %q: %w", statePath, err)
}
defer func() { _ = stateFile.Close() }()
uncompressedState, err := gzip.NewReader(stateFile)
if err != nil {
return fmt.Errorf("Failed opening state gzip reader: %w", err)
}
defer func() { _ = uncompressedState.Close() }()
pipeRead, pipeWrite, err := os.Pipe()
if err != nil {
return err
}
go func() {
_, err := io.Copy(pipeWrite, uncompressedState)
if err != nil {
d.logger.Warn("Failed reading from state file", logger.Ctx{"path": statePath, "err": err})
}
_ = pipeRead.Close()
_ = pipeWrite.Close()
}()
err = d.restoreStateHandle(context.Background(), monitor, pipeRead)
if err != nil {
return fmt.Errorf("Failed restoring state from %q: %w", stateFile.Name(), err)
}
}
return nil
}
// saveStateHandle dumps the current VM state to a file handle.
// Once started, the VM is in a paused state and it's up to the caller to wait for the transfer to complete and
// resume or kill the VM guest.
func (d *qemu) saveStateHandle(monitor *qmp.Monitor, f *os.File) error {
// Send the target file to qemu.
err := monitor.SendFile("migration", f)
if err != nil {
return err
}
// Issue the migration command.
err = monitor.Migrate("migration")
if err != nil {
return err
}
return nil
}
// saveState dumps the current VM state to the state file.
// Once dumped, the VM is in a paused state and it's up to the caller to resume or kill it.
func (d *qemu) saveState(monitor *qmp.Monitor) error {
statePath := d.StatePath()
d.logger.Debug("Stateful checkpoint starting", logger.Ctx{"target": statePath})
defer d.logger.Debug("Stateful checkpoint finished", logger.Ctx{"target": statePath})
// Save the checkpoint to state file.
_ = os.Remove(statePath)
// Prepare the state file.
stateFile, err := os.Create(statePath)
if err != nil {
return err
}
defer func() { _ = stateFile.Close() }()
compressedState, err := gzip.NewWriterLevel(stateFile, gzip.BestSpeed)
if err != nil {
return err
}
defer func() { _ = compressedState.Close() }()
pipeRead, pipeWrite, err := os.Pipe()
if err != nil {
return err
}
defer func() {
_ = pipeRead.Close()
_ = pipeWrite.Close()
}()
go func() { _, _ = io.Copy(compressedState, pipeRead) }()
err = d.saveStateHandle(monitor, pipeWrite)
if err != nil {
return fmt.Errorf("Failed initializing state save to %q: %w", stateFile.Name(), err)
}
err = monitor.MigrateWait("completed")
if err != nil {
return fmt.Errorf("Failed saving state to %q: %w", stateFile.Name(), err)
}
return nil
}
// validateStartup checks any constraints that would prevent start up from succeeding under normal circumstances.
func (d *qemu) validateStartup(stateful bool, statusCode api.StatusCode) error {
err := d.common.validateStartup(stateful, statusCode)
if err != nil {
return err
}
// Cannot perform stateful start unless config is appropriately set.
if stateful && !d.CanLiveMigrate() {
return errors.New("Stateful start requires migration.stateful to be set to true")
}
// gendoc:generate(entity=image, group=requirements, key=requirements.secureboot)
//
// ---
// type: bool
// shortdesc: If set to `false`, indicates that the image cannot boot under secure boot.
//
// Ensure secureboot is turned off for images that are not secureboot enabled.
if util.IsFalse(d.localConfig["image.requirements.secureboot"]) && util.IsTrueOrEmpty(d.expandedConfig["security.secureboot"]) {
return errors.New("The image used by this instance is incompatible with secureboot. Please set security.secureboot=false on the instance")
}
// Ensure secureboot is turned off when CSM is on.
if util.IsTrue(d.expandedConfig["security.csm"]) && util.IsTrueOrEmpty(d.expandedConfig["security.secureboot"]) {
return errors.New("Secure boot can't be enabled while CSM is turned on. Please set security.secureboot=false on the instance")
}
// gendoc:generate(entity=image, group=requirements, key=requirements.cdrom_agent)
//
// ---
// type: bool
// shortdesc: If set to `true`, indicates that the VM requires an `agent:config` disk be added.
//
// Ensure an agent drive is present if the image requires it.
if util.IsTrue(d.localConfig["image.requirements.cdrom_agent"]) {
found := false
for _, dev := range d.expandedDevices {
if dev["type"] == "disk" && dev["source"] == "agent:config" {
found = true
break
}
}
if !found {
return errors.New("This virtual machine image requires an agent:config disk be added")
}
}
return nil
}
func (d *qemu) checkStateStorage() error {
// For some operations, the "size.state" of the instance root disk device must be larger than the instance memory.
// Otherwise, there will not be enough disk space to write the instance state to disk during any subsequent stops.
// (Only check when migration.stateful is true, otherwise the memory won't be dumped when this instance stops).
_, rootDiskDevice, err := d.getRootDiskDevice()
if err != nil {
return err
}
// Don't access d.storagePool directly since it isn't populated at this stage.
pool, err := d.getStoragePool()
if err != nil {
return err
}
stateDiskSizeStr := pool.Driver().Info().DefaultVMBlockFilesystemSize
if rootDiskDevice["size.state"] != "" {
stateDiskSizeStr = rootDiskDevice["size.state"]
}
stateDiskSize, err := units.ParseByteSizeString(stateDiskSizeStr)
if err != nil {
return err
}
memoryLimitStr := qemudefault.MemSize
if d.expandedConfig["limits.memory"] != "" {
memoryLimitStr = d.expandedConfig["limits.memory"]
}
memoryLimit, err := ParseMemoryStr(memoryLimitStr)
if err != nil {
return err
}
if stateDiskSize < memoryLimit {
return errors.New("Stateful stop and snapshots require the instance limits.memory be less than or equal to the root disk size.state property")
}
return nil
}
// Start starts the instance.
func (d *qemu) Start(stateful bool) error {
return d.start(stateful, nil)
}
// runStartupScriptlet runs startup scriptlets at config, early, pre-start and post-start stages.
func (d *qemu) runStartupScriptlet(monitor *qmp.Monitor, stage string) error {
_, ok := d.expandedConfig["raw.qemu.scriptlet"]
if ok {
// Render cannot return errors here.
render, _, _ := d.Render()
instanceData, ok := render.(*api.Instance)
if !ok {
return errors.New("Unexpected instance type")
}
err := scriptlet.QEMURun(logger.Log, instanceData, &d.cmdArgs, &d.conf, monitor, stage)
if err != nil {
err = fmt.Errorf("Failed running QEMU scriptlet at %s stage: %w", stage, err)
return err
}
}
return nil
}
// startupHook executes QMP commands and runs startup scriptlets at early, pre-start and post-start
// stages.
func (d *qemu) startupHook(monitor *qmp.Monitor, stage string) error {
commands, ok := d.expandedConfig["raw.qemu.qmp."+stage]
if ok {
var commandList []map[string]any
err := json.Unmarshal([]byte(commands), &commandList)
if err != nil {
err = fmt.Errorf("Failed to parse QMP commands at %s stage (expected JSON list of objects): %w", stage, err)
return err
}
for _, command := range commandList {
id := monitor.IncreaseID()
command["id"] = id
var jsonCommand []byte
jsonCommand, err = json.Marshal(command)
if err != nil {
err = fmt.Errorf("Failed to marshal command at %s stage: %w", stage, err)
return err
}
err = monitor.RunJSON(jsonCommand, nil, true, id)
if err != nil {
err = fmt.Errorf("Failed to run QMP command %s at %s stage: %w", jsonCommand, stage, err)
return err
}
}
}
return d.runStartupScriptlet(monitor, stage)
}
// start starts the instance and can use an existing InstanceOperation lock.
func (d *qemu) start(stateful bool, op *operationlock.InstanceOperation) error {
d.logger.Debug("Start started", logger.Ctx{"stateful": stateful})
defer d.logger.Debug("Start finished", logger.Ctx{"stateful": stateful})
// Check that we are startable before creating an operation lock.
// Must happen before creating operation Start lock to avoid the status check returning Stopped due to the
// existence of a Start operation lock.
err := d.validateStartup(stateful, d.statusCode())
if err != nil {
return err
}
// Setup a new operation if needed.
if op == nil {
op, err = operationlock.CreateWaitGet(d.Project().Name, d.Name(), d.op, operationlock.ActionStart, []operationlock.Action{operationlock.ActionRestart, operationlock.ActionRestore}, false, false)
if err != nil {
if errors.Is(err, operationlock.ErrNonReusuableSucceeded) {
// An existing matching operation has now succeeded, return.
return nil
}
return fmt.Errorf("Failed to create instance start operation: %w", err)
}
}
defer op.Done(err)
// Assign NUMA node(s) if needed.
if d.expandedConfig["limits.cpu.nodes"] == "balanced" {
err := d.balanceNUMANodes()
if err != nil {
op.Done(err)
return err
}
}
// Ensure the correct vhost_vsock kernel module is loaded before establishing the vsock.
err = linux.LoadModule("vhost_vsock")
if err != nil {
op.Done(err)
return err
}
reverter := revert.New()
defer reverter.Fail()
// Rotate the log files.
for _, logfile := range []string{d.LogFilePath(), d.ConsoleBufferLogPath(), d.QMPLogFilePath()} {
if util.PathExists(logfile) {
_ = os.Remove(logfile + ".old")
err := os.Rename(logfile, logfile+".old")
if err != nil && !errors.Is(err, fs.ErrNotExist) {
op.Done(err)
return err
}
}
}
// Remove old pid file if needed.
if util.PathExists(d.pidFilePath()) {
err = os.Remove(d.pidFilePath())
if err != nil {
op.Done(err)
return fmt.Errorf("Failed removing old PID file %q: %w", d.pidFilePath(), err)
}
}
// Cleanup old sockets.
for _, socketPath := range []string{d.consolePath(), d.spicePath(), d.monitorPath()} {
_ = os.Remove(socketPath)
}
// Mount the instance's config volume.
mountInfo, err := d.mount()
if err != nil {
op.Done(err)
return err
}
reverter.Add(func() { _ = d.unmount() })
// Define a set of files to open and pass their file descriptors to QEMU command.
fdFiles := make([]*os.File, 0)
// Ensure passed files are closed after start has returned (either because QEMU has started or on error).
defer func() {
for _, file := range fdFiles {
_ = file.Close()
}
}()
// New or existing vsock ID from volatile.
vsockID, vsockF, err := d.nextVsockID()
if err != nil {
return err
}
// Add allocated QEMU vhost file descriptor.
vsockFD := d.addFileDescriptor(&fdFiles, vsockF)
volatileSet := make(map[string]string)
// Update vsock ID in volatile if needed for recovery (do this before UpdateBackupFile() call).
oldVsockID := d.localConfig["volatile.vsock_id"]
newVsockID := strconv.FormatUint(uint64(vsockID), 10)
if oldVsockID != newVsockID {
volatileSet["volatile.vsock_id"] = newVsockID
}
// Generate UUID if not present (do this before UpdateBackupFile() call).
instUUID := d.localConfig["volatile.uuid"]
if instUUID == "" {
instUUID = uuid.New().String()
volatileSet["volatile.uuid"] = instUUID
}
// For a VM instance, we must also set the VM generation ID.
vmGenUUID := d.localConfig["volatile.uuid.generation"]
if vmGenUUID == "" {
vmGenUUID = instUUID
volatileSet["volatile.uuid.generation"] = vmGenUUID
}
// Generate the config drive.
err = d.generateConfigShare()
if err != nil {
op.Done(err)
return err
}
// Create all needed paths.
err = os.MkdirAll(d.LogPath(), 0o700)
if err != nil {
op.Done(err)
return err
}
err = os.MkdirAll(d.RunPath(), 0o700)
if err != nil {
op.Done(err)
return err
}
err = os.MkdirAll(d.DevicesPath(), 0o711)
if err != nil {
op.Done(err)
return err
}
err = os.MkdirAll(d.ShmountsPath(), 0o711)
if err != nil {
op.Done(err)
return err
}
// Copy EDK2 settings firmware to nvram file if needed.
// Set up EDK2 NVRAM when on EFI.
if d.architectureSupportsUEFI(d.architecture) {
fi, err := os.Lstat(d.nvramPath())
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return err
}
// Generate new NVRAM if missing, or if requested by the user or if the NVRAM file is of an invalid format (needs to be a valid symlink).
if util.IsTrue(d.localConfig["volatile.apply_nvram"]) || fi == nil || fi.Mode()&os.ModeSymlink != os.ModeSymlink {
err = d.setupNvram()
if err != nil {
op.Done(err)
return err
}
}
}
// Clear volatile.apply_nvram if set.
if d.localConfig["volatile.apply_nvram"] != "" {
volatileSet["volatile.apply_nvram"] = ""
}
// Apply any volatile changes that need to be made.
err = d.VolatileSet(volatileSet)
if err != nil {
err = fmt.Errorf("Failed setting volatile keys: %w", err)
op.Done(err)
return err
}
devConfs := make([]*deviceConfig.RunConfig, 0, len(d.expandedDevices))
postStartHooks := []func() error{}
sortedDevices := d.expandedDevices.Sorted()
startDevices := make([]device.Device, 0, len(sortedDevices))
// Load devices in sorted order, this ensures that device mounts are added in path order.
// Loading all devices first means that validation of all devices occurs before starting any of them.
for _, entry := range sortedDevices {
dev, err := d.deviceLoad(d, entry.Name, entry.Config)
if err != nil {
if errors.Is(err, device.ErrUnsupportedDevType) {
continue // Skip unsupported device (allows for mixed instance type profiles).
}
err = fmt.Errorf("Failed start validation for device %q: %w", entry.Name, err)
op.Done(err)
return err
}
// Run pre-start of check all devices before starting any device to avoid expensive revert.
err = dev.PreStartCheck()
if err != nil {
op.Done(err)
return fmt.Errorf("Failed pre-start check for device %q: %w", dev.Name(), err)
}
startDevices = append(startDevices, dev)
}
// Start devices in order.
for i := range startDevices {
dev := startDevices[i] // Local var for revert.
// Start the device.
runConf, err := d.deviceStart(dev, false)
if err != nil {
err = fmt.Errorf("Failed to start device %q: %w", dev.Name(), err)
op.Done(err)
return err
}
reverter.Add(func() {
err := d.deviceStop(dev, false, "")
if err != nil {
d.logger.Error("Failed to cleanup device", logger.Ctx{"device": dev.Name(), "err": err})
}
})
if runConf == nil {
continue
}
if runConf.Revert != nil {
reverter.Add(runConf.Revert)
}
// Add post-start hooks
if len(runConf.PostHooks) > 0 {
postStartHooks = append(postStartHooks, runConf.PostHooks...)
}
devConfs = append(devConfs, runConf)
}
// Setup the config drive readonly bind mount. Important that this come after the root disk device start.
// in order to allow unmounts triggered by deferred resizes of the root volume.
configMntPath := d.configDriveMountPath()
err = d.configDriveMountPathClear()
if err != nil {
err = fmt.Errorf("Failed cleaning config drive mount path %q: %w", configMntPath, err)
op.Done(err)
return err
}
err = os.Mkdir(configMntPath, 0o700)
if err != nil {
err = fmt.Errorf("Failed creating device mount path %q for config drive: %w", configMntPath, err)
op.Done(err)
return err
}
reverter.Add(func() { _ = d.configDriveMountPathClear() })
// Mount the config drive device as readonly. This way it will be readonly irrespective of whether its
// exported via 9p for virtio-fs.
configSrcPath := filepath.Join(d.Path(), "config")
err = device.DiskMount(configSrcPath, configMntPath, false, "", []string{"ro"}, "none")
if err != nil {
err = fmt.Errorf("Failed mounting device mount path %q for config drive: %w", configMntPath, err)
op.Done(err)
return err
}
// Get qemu configuration and check qemu is installed.
qemuPath, qemuBus, err := d.qemuArchConfig(d.architecture)
if err != nil {
op.Done(err)
return err
}
// Snapshot if needed.
snapName, expiry, err := d.getStartupSnapNameAndExpiry(d)
if err != nil {
err = fmt.Errorf("Failed getting startup snapshot info: %w", err)
op.Done(err)
return err
}
if snapName != "" && expiry != nil {
err := d.snapshot(snapName, *expiry, false)
if err != nil {
err = fmt.Errorf("Failed taking startup snapshot: %w", err)
op.Done(err)
return err
}
}
// Get CPU information.
cpuInfo, err := d.cpuTopology(d.expandedConfig["limits.cpu"])
if err != nil {
return err
}
// Determine additional CPU flags.
cpuExtensions := []string{}
if d.architecture == osarch.ARCH_64BIT_INTEL_X86 {
// If using Linux 5.10 or later, use HyperV optimizations.
minVer, _ := version.NewDottedVersion("5.10.0")
if d.state.OS.KernelVersion.Compare(minVer) >= 0 && !d.CanLiveMigrate() {
// x86_64 can use hv_time to improve Windows guest performance.
cpuExtensions = append(cpuExtensions, "hv_passthrough")
}
// x86_64 requires the use of topoext when SMT is used.
if cpuInfo.threads > 1 {
cpuExtensions = append(cpuExtensions, "topoext")
}
}
cpuType := "host"
// Get CPU flags if clustered and migration is enabled (x86_64 only for now).
if d.architecture == osarch.ARCH_64BIT_INTEL_X86 && d.state.ServerClustered && d.CanLiveMigrate() {
cpuFlags, err := GetClusterCPUFlags(context.TODO(), d.state, nil, "x86_64")
if err != nil {
op.Done(err)
return err
}
cpuType = "kvm64"
cpuExtensions = append(cpuExtensions, cpuFlags...)
}
// Get the feature flags.
info := DriverStatuses()[instancetype.VM].Info
_, nested := info.Features["nested"]
// Add +invtsc for fast TSC on x86 when not expected to be migratable and not nested.
if !nested && d.architecture == osarch.ARCH_64BIT_INTEL_X86 && !d.CanLiveMigrate() {
cpuExtensions = append(cpuExtensions, "migratable=no", "+invtsc")
}
if len(cpuExtensions) > 0 {
cpuType += "," + strings.Join(cpuExtensions, ",")
}
// Provide machine definition when restoring state.
var machineDefinition string
if stateful {
machineDefinition = d.localConfig["volatile.vm.definition"]
}
// Generate the QEMU configuration.
monHooks, err := d.generateQemuConfig(machineDefinition, strings.Split(cpuType, ",")[0], cpuInfo, mountInfo, qemuBus, vsockFD, devConfs, &fdFiles)
if err != nil {
op.Done(err)
return err
}
confFile := filepath.Join(d.RunPath(), "qemu.conf")
// Start QEMU.
qemuArgs := []string{
"-S",
"-name", d.Name(),
"-uuid", instUUID,
"-daemonize",
"-cpu", cpuType,
"-nographic",
"-serial", "chardev:console",
"-nodefaults",
"-no-user-config",
"-sandbox", "on,obsolete=deny,elevateprivileges=allow,spawn=allow,resourcecontrol=deny",
"-readconfig", confFile,
"-spice", d.spiceCmdlineConfig(),
"-pidfile", d.pidFilePath(),
"-D", d.LogFilePath(),
}
// If stateful, restore now.
if stateful {
if d.stateful {
qemuArgs = append(qemuArgs, "-incoming", "defer")
} else {
// No state to restore, just start as normal.
stateful = false
}
} else if d.stateful {
// Stateless start requested but state is present, delete it.
err := os.Remove(d.StatePath())
if err != nil && !errors.Is(err, fs.ErrNotExist) {
op.Done(err)
return err
}
d.stateful = false
err = d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.UpdateInstanceStatefulFlag(ctx, d.id, false)
})
if err != nil {
op.Done(err)
return fmt.Errorf("Error updating instance stateful flag: %w", err)
}
}
// APply the RTC configuration.
adjustment := d.getStartupRTCAdjustment()
base := time.Now().Add(adjustment)
if d.isWindows() {
// Set base to localtime on windows.
base = base.Local()
} else {
// set base to UTC on !windows.
base = base.UTC()
}
datetime := base.Format("2006-01-02T15:04:05")
qemuArgs = append(qemuArgs, "-rtc", fmt.Sprintf("base=%s", datetime))
// SMBIOS only on x86_64 and aarch64.
if d.architectureSupportsUEFI(d.architecture) {
qemuArgs = append(qemuArgs, "-smbios", "type=2,manufacturer=LinuxContainers,product=Incus")
for k, v := range d.expandedConfig {
if !strings.HasPrefix(k, "smbios11.") {
continue
}
qemuArgs = append(qemuArgs, "-smbios", fmt.Sprintf("type=11,value=%s=%s", strings.TrimPrefix(k, "smbios11."), qemuEscapeCmdline(v)))
}
}
// Attempt to drop privileges (doesn't work when restoring state).
if !stateful && d.state.OS.UnprivUser != "" {
qemuVer, _ := d.version()
qemuVer91, _ := version.NewDottedVersion("9.1.0")
// Since QEMU 9.1 the parameter `runas` has been marked as deprecated.
if qemuVer != nil && qemuVer.Compare(qemuVer91) >= 0 {
qemuArgs = append(qemuArgs, "-run-with", fmt.Sprintf("user=%s", d.state.OS.UnprivUser))
} else {
qemuArgs = append(qemuArgs, "-runas", d.state.OS.UnprivUser)
}
nvRAMPath := d.nvramPath()
if d.architectureSupportsUEFI(d.architecture) && util.PathExists(nvRAMPath) {
// Ensure UEFI nvram file is writable by the QEMU process.
// This is needed when doing stateful snapshots because the QEMU process will reopen the
// file for writing.
err = os.Chown(nvRAMPath, int(d.state.OS.UnprivUID), -1)
if err != nil {
op.Done(err)
return err
}
err = os.Chmod(nvRAMPath, 0o600)
if err != nil {
op.Done(err)
return err
}
}
// Change ownership of main instance directory.
err = os.Chown(d.Path(), int(d.state.OS.UnprivUID), -1)
if err != nil {
op.Done(err)
return fmt.Errorf("Failed to chown instance path: %w", err)
}
// Change ownership of config directory files so they are accessible to the
// unprivileged qemu process so that the 9p share can work.
//
// Security note: The 9P share will present the UID owner of these files on the host
// to the VM. In order to ensure that non-root users in the VM cannot access these
// files be sure to mount the 9P share in the VM with the "access=0" option to allow
// only root user in VM to access the mounted share.
err := filepath.Walk(filepath.Join(d.Path(), "config"),
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
err = os.Chown(path, int(d.state.OS.UnprivUID), -1)
if err != nil {
return err
}
return nil
})
if err != nil {
op.Done(err)
return err
}
}
// Handle hugepages on architectures where we don't set NUMA nodes.
if d.architecture != osarch.ARCH_64BIT_INTEL_X86 && util.IsTrue(d.expandedConfig["limits.memory.hugepages"]) {
hugetlb, err := localUtil.HugepagesPath()
if err != nil {
op.Done(err)
return err
}
qemuArgs = append(qemuArgs, "-mem-path", hugetlb, "-mem-prealloc")
}
if d.expandedConfig["raw.qemu"] != "" {
fields, err := shellquote.Split(d.expandedConfig["raw.qemu"])
if err != nil {
op.Done(err)
return err
}
qemuArgs = append(qemuArgs, fields...)
}
d.cmdArgs = qemuArgs
// Precompile the QEMU scriptlet
src, ok := d.expandedConfig["raw.qemu.scriptlet"]
if ok {
instanceName := d.Name()
err := scriptletLoad.QEMUSet(src, instanceName)
if err != nil {
err = fmt.Errorf("Failed loading QEMU scriptlet: %w", err)
return err
}
}
// Config startup hook.
err = d.runStartupScriptlet(nil, "config")
if err != nil {
op.Done(err)
return err
}
// Write the config file.
err = d.writeQemuConfigFile(confFile)
if err != nil {
op.Done(err)
return err
}
// Run the qemu command via forklimits so we can selectively increase ulimits.
forkLimitsCmd := []string{
"forklimits",
}
if !d.state.OS.RunningInUserNS {
// Required for PCI passthrough.
forkLimitsCmd = append(forkLimitsCmd, "limit=memlock:unlimited:unlimited")
}
for i := range fdFiles {
// Pass through any file descriptors as 3+i (as first 3 file descriptors are taken as standard).
forkLimitsCmd = append(forkLimitsCmd, fmt.Sprintf("fd=%d", 3+i))
}
// Log the QEMU command line.
fullCmd := append(forkLimitsCmd, "--", qemuPath)
fullCmd = append(fullCmd, d.cmdArgs...)
d.logger.Debug("Starting QEMU", logger.Ctx{"command": fullCmd})
// Setup background process.
p, err := subprocess.NewProcess(d.state.OS.ExecPath, fullCmd, d.EarlyLogFilePath(), d.EarlyLogFilePath())
if err != nil {
op.Done(err)
return err
}
// Load the AppArmor profile
err = apparmor.InstanceLoad(d.state.OS, d, []string{qemuPath})
if err != nil {
op.Done(err)
return err
}
p.SetApparmor(apparmor.InstanceProfileName(d))
// Update the backup.yaml file just before starting the instance process, but after all devices have been
// setup, so that the backup file contains the volatile keys used for this instance start, so that they can
// be used for instance cleanup.
err = d.UpdateBackupFile()
if err != nil {
err = fmt.Errorf("Failed updating backup file: %w", err)
op.Done(err)
return err
}
err = p.StartWithFiles(context.Background(), fdFiles)
if err != nil {
op.Done(err)
return err
}
_, err = p.Wait(context.Background())
if err != nil {
stderr, _ := os.ReadFile(d.EarlyLogFilePath())
err = fmt.Errorf("Failed to run: %s: %s: %w", strings.Join(p.Args, " "), string(stderr), err)
op.Done(err)
return err
}
pid, err := d.pid()
if err != nil || pid <= 0 {
d.logger.Error("Failed to get VM process ID", logger.Ctx{"err": err, "pid": pid})
op.Done(err)
return err
}
reverter.Add(func() {
_ = d.killQemuProcess(pid)
})
// Start QMP monitoring.
monitor, err := d.qmpConnect()
if err != nil {
op.Done(err)
return err
}
// Record the QEMU machine definition.
if !stateful {
definition, err := monitor.MachineDefinition()
if err != nil {
op.Done(err)
return err
}
err = d.VolatileSet(map[string]string{
"volatile.vm.definition": definition,
})
if err != nil {
op.Done(err)
return err
}
}
// Don't allow the monitor to trigger a disconnection shutdown event until cleanly started so that the
// onStop hook isn't triggered prematurely (as this function's reverter will clean up on failure to start).
monitor.SetOnDisconnectEvent(false)
// Early startup hook
err = d.startupHook(monitor, "early")
if err != nil {
op.Done(err)
return err
}
// Apply CPU pinning.
if cpuInfo.vcpus == nil {
if d.architectureSupportsCPUHotplug() && cpuInfo.cores > 1 {
// Hotplug the CPUs.
err := d.setCPUs(monitor, cpuInfo.cores)
if err != nil {
err = fmt.Errorf("Failed to add CPUs: %w", err)
op.Done(err)
return err
}
}
} else {
// Get the list of PIDs from the VM.
pids, err := monitor.GetCPUs()
if err != nil {
op.Done(err)
return err
}
// Confirm nothing weird is going on.
if len(cpuInfo.vcpus) != len(pids) {
err = errors.New("QEMU has less vCPUs than configured")
op.Done(err)
return err
}
// Apply the CPU pins.
for i, pid := range pids {
set := unix.CPUSet{}
set.Set(int(cpuInfo.vcpus[uint64(i)]))
// Apply the pin.
err := unix.SchedSetaffinity(pid, &set)
if err != nil {
op.Done(err)
return err
}
}
// Create a core scheduling group.
err = d.setCoreSched(pids)
if err != nil {
err = fmt.Errorf("Failed to allocate new core scheduling domain for vCPU threads: %w", err)
op.Done(err)
return err
}
}
// Run monitor hooks from devices.
for _, monHook := range monHooks {
err = monHook(monitor)
if err != nil {
op.Done(err)
return fmt.Errorf("Failed setting up device via monitor: %w", err)
}
}
// Pre-start startup hook
err = d.startupHook(monitor, "pre-start")
if err != nil {
op.Done(err)
return err
}
// Due to a bug in QEMU, devices added using QMP's device_add command do not have their bootindex option
// respected (even if added before emuation is started). To workaround this we must reset the VM in order
// for it to rebuild its boot config and to take into account the devices bootindex settings.
// This also means we cannot start the QEMU process with the -no-reboot flag, so we set the same reboot
// action below after this call.
err = monitor.Reset()
if err != nil {
op.Done(err)
return fmt.Errorf("Failed resetting VM: %w", err)
}
// Set the equivalent of the -no-reboot flag (which we can't set because of the reset bug above) via QMP.
// This ensures that if the guest initiates a reboot that the SHUTDOWN event is generated instead with the
// reason set to "guest-reset" so that the event handler returned from getMonitorEventHandler() can restart
// the guest instead.
actions := map[string]string{
"shutdown": "poweroff",
"reboot": "shutdown", // Don't reset on reboot. Let us handle reboots.
"panic": "pause", // Pause on panics to allow investigation.
}
err = monitor.SetAction(actions)
if err != nil {
op.Done(err)
return fmt.Errorf("Failed setting reboot action: %w", err)
}
// Restore the state.
if stateful {
err = d.restoreState(monitor)
if err != nil {
op.Done(err)
return err
}
}
// Start the VM.
err = monitor.Start()
if err != nil {
err = fmt.Errorf("Failed starting VM: %w", err)
op.Done(err)
return err
}
// Finish handling stateful start.
if stateful {
// Cleanup state.
_ = os.Remove(d.StatePath())
d.stateful = false
err = d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.UpdateInstanceStatefulFlag(ctx, d.id, false)
})
if err != nil {
op.Done(err)
return fmt.Errorf("Error updating instance stateful flag: %w", err)
}
}
// Record last start state.
err = d.recordLastState()
if err != nil {
op.Done(err)
return err
}
reverter.Success()
// Post-start startup hook
err = d.startupHook(monitor, "post-start")
if err != nil {
op.Done(err)
// Shut down the VM if the post-start commands fail.
_ = d.Stop(false)
return err
}
// Run any post-start hooks.
err = d.runHooks(postStartHooks)
if err != nil {
op.Done(err) // Must come before Stop() otherwise stop will not proceed.
// Shut down the VM if hooks fail.
_ = d.Stop(false)
return err
}
if op.Action() == "start" {
d.state.Events.SendLifecycle(d.project.Name, lifecycle.InstanceStarted.Event(d, nil))
}
// The VM started cleanly so now enable the unexpected disconnection event to ensure the onStop hook is
// run if QMP unexpectedly disconnects.
monitor.SetOnDisconnectEvent(true)
op.Done(nil)
return nil
}
func (d *qemu) setupSEV(fdFiles *[]*os.File) (*qemuSevOpts, error) {
if d.architecture != osarch.ARCH_64BIT_INTEL_X86 {
return nil, errors.New("AMD SEV support is only available on x86_64 systems")
}
// Get the QEMU features to check if AMD SEV is supported.
info := DriverStatuses()[instancetype.VM].Info
_, smeFound := info.Features["sme"] // codespell:ignore sme
sev, sevFound := info.Features["sev"]
if !smeFound || !sevFound {
return nil, errors.New("AMD SEV is not supported by the host")
}
// Get the SEV guest `cbitpos` and `reducedPhysBits`.
sevCapabilities, ok := sev.(qmp.AMDSEVCapabilities)
if !ok {
return nil, errors.New(`Failed to get the guest "sev" capabilities`)
}
cbitpos := sevCapabilities.CBitPos
reducedPhysBits := sevCapabilities.ReducedPhysBits
// Write user's dh-cert and session-data to file descriptors.
var dhCertFD, sessionDataFD int
if d.expandedConfig["security.sev.session.dh"] != "" {
dhCert, err := os.CreateTemp("", "incus_sev_dh_cert_")
if err != nil {
return nil, err
}
err = os.Remove(dhCert.Name())
if err != nil {
return nil, err
}
_, err = dhCert.WriteString(d.expandedConfig["security.sev.session.dh"])
if err != nil {
return nil, err
}
dhCertFD = d.addFileDescriptor(fdFiles, dhCert)
}
if d.expandedConfig["security.sev.session.data"] != "" {
sessionData, err := os.CreateTemp("", "incus_sev_session_data_")
if err != nil {
return nil, err
}
err = os.Remove(sessionData.Name())
if err != nil {
return nil, err
}
_, err = sessionData.WriteString(d.expandedConfig["security.sev.session.data"])
if err != nil {
return nil, err
}
sessionDataFD = d.addFileDescriptor(fdFiles, sessionData)
}
sevOpts := &qemuSevOpts{}
sevOpts.cbitpos = cbitpos
sevOpts.reducedPhysBits = reducedPhysBits
if dhCertFD > 0 && sessionDataFD > 0 {
sevOpts.dhCertFD = fmt.Sprintf("/proc/self/fd/%d", dhCertFD)
sevOpts.sessionDataFD = fmt.Sprintf("/proc/self/fd/%d", sessionDataFD)
}
if util.IsTrue(d.expandedConfig["security.sev.policy.es"]) {
_, sevES := info.Features["sev-es"]
if sevES {
// This bit mask is used to specify a guest policy. '0x5' is for SEV-ES. The details of the available policies can be found in the link below (see chapter 3)
// https://www.amd.com/system/files/TechDocs/55766_SEV-KM_API_Specification.pdf
sevOpts.policy = "0x5"
} else {
return nil, errors.New("AMD SEV-ES is not supported by the host")
}
} else {
// '0x1' is for a regular SEV policy.
sevOpts.policy = "0x1"
}
return sevOpts, nil
}
// getAgentConnectionInfo returns the connection info the agent needs to connect to the server.
func (d *qemu) getAgentConnectionInfo() (*agentAPI.API10Put, error) {
addr := d.state.Endpoints.VsockAddress()
if addr == nil {
return nil, nil
}
vsockaddr, ok := addr.(*vsock.Addr)
if !ok {
return nil, errors.New("Listen address is not vsock.Addr")
}
req := agentAPI.API10Put{
Certificate: string(d.state.Endpoints.NetworkCert().PublicKey()),
DevIncus: util.IsTrueOrEmpty(d.expandedConfig["security.guestapi"]),
CID: vsock.Host, // Always tell the agent to connect to the server using the Host Context ID to support nesting.
Port: vsockaddr.Port,
}
return &req, nil
}
// advertiseVsockAddress advertises the CID and port to the VM.
func (d *qemu) advertiseVsockAddress() error {
client, err := d.getAgentClient()
if err != nil {
return fmt.Errorf("Failed getting agent client handle: %w", err)
}
agentArgs := &incus.ConnectionArgs{
SkipGetEvents: true,
SkipGetServer: true,
}
agent, err := incus.ConnectIncusHTTP(agentArgs, client)
if err != nil {
return fmt.Errorf("Failed connecting to the agent: %w", err)
}
defer agent.Disconnect()
connInfo, err := d.getAgentConnectionInfo()
if err != nil {
return err
}
if connInfo == nil {
return nil
}
_, _, err = agent.RawQuery("PUT", "/1.0", connInfo, "")
if err != nil {
return fmt.Errorf("Failed sending host vsock information to the agent: %w", err)
}
return nil
}
// AgentCertificate returns the server certificate of the agent.
func (d *qemu) AgentCertificate() *x509.Certificate {
agentCert := filepath.Join(d.Path(), "config", "agent.crt")
if !util.PathExists(agentCert) {
return nil
}
cert, err := localtls.ReadCert(agentCert)
if err != nil {
return nil
}
return cert
}
func (d *qemu) architectureSupportsUEFI(arch int) bool {
return slices.Contains([]int{osarch.ARCH_64BIT_INTEL_X86, osarch.ARCH_64BIT_ARMV8_LITTLE_ENDIAN}, arch)
}
func (d *qemu) setupNvram() error {
var err error
d.logger.Debug("Generating NVRAM")
// Cleanup existing variables.
firmwares, err := edk2.GetArchitectureFirmwarePairs(d.architecture)
if err != nil {
return err
}
for _, firmwarePair := range firmwares {
err := os.Remove(filepath.Join(d.Path(), filepath.Base(firmwarePair.Vars)))
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return err
}
}
// Determine expected firmware.
if util.IsTrue(d.expandedConfig["security.csm"]) {
firmwares, err = edk2.GetArchitectureFirmwarePairsForUsage(d.architecture, edk2.CSM)
if err != nil {
return err
}
} else if util.IsTrueOrEmpty(d.expandedConfig["security.secureboot"]) {
firmwares, err = edk2.GetArchitectureFirmwarePairsForUsage(d.architecture, edk2.SECUREBOOT)
if err != nil {
return err
}
} else {
firmwares, err = edk2.GetArchitectureFirmwarePairsForUsage(d.architecture, edk2.GENERIC)
if err != nil {
return err
}
}
// Find the template file.
var efiVarsPath string
var efiVarsName string
for _, firmware := range firmwares {
varsPath, err := filepath.EvalSymlinks(firmware.Vars)
if err != nil {
continue
}
if util.PathExists(varsPath) {
efiVarsPath = varsPath
efiVarsName = filepath.Base(firmware.Vars)
break
}
}
if efiVarsPath == "" {
return fmt.Errorf("Couldn't find one of the required UEFI firmware files: %+v", firmwares)
}
// Copy the template.
err = internalUtil.FileCopy(efiVarsPath, filepath.Join(d.Path(), efiVarsName))
if err != nil {
return err
}
nvramPath := d.nvramPath()
// Handle the case where the firmware vars filename matches our internal one.
if efiVarsName == filepath.Base(nvramPath) {
return nil
}
// Generate a symlink.
// This is so qemu.nvram can always be assumed to be the EDK2 vars file.
// The real file name is then used to determine what firmware must be selected.
_ = os.Remove(nvramPath)
err = os.Symlink(efiVarsName, nvramPath)
if err != nil {
return err
}
return nil
}
func (d *qemu) qemuArchConfig(arch int) (string, string, error) {
if arch == osarch.ARCH_64BIT_INTEL_X86 {
path, err := exec.LookPath("qemu-system-x86_64")
if err != nil {
return "", "", err
}
return path, "pcie", nil
} else if arch == osarch.ARCH_64BIT_ARMV8_LITTLE_ENDIAN {
path, err := exec.LookPath("qemu-system-aarch64")
if err != nil {
return "", "", err
}
return path, "pcie", nil
} else if arch == osarch.ARCH_64BIT_POWERPC_LITTLE_ENDIAN {
path, err := exec.LookPath("qemu-system-ppc64")
if err != nil {
return "", "", err
}
return path, "pci", nil
} else if arch == osarch.ARCH_64BIT_S390_BIG_ENDIAN {
path, err := exec.LookPath("qemu-system-s390x")
if err != nil {
return "", "", err
}
return path, "ccw", nil
}
return "", "", errors.New("Architecture isn't supported for virtual machines")
}
// RegisterDevices calls the Register() function on all of the instance's devices.
func (d *qemu) RegisterDevices() {
d.devicesRegister(d)
}
func (d *qemu) saveConnectionInfo(connInfo *agentAPI.API10Put) error {
configDrivePath := filepath.Join(d.Path(), "config")
f, err := os.Create(filepath.Join(configDrivePath, "agent.conf"))
if err != nil {
return err
}
defer func() {
_ = f.Close()
}()
err = json.NewEncoder(f).Encode(connInfo)
if err != nil {
return err
}
return nil
}
// OnHook is the top-level hook handler.
func (d *qemu) OnHook(hookName string, args map[string]string) error {
return instance.ErrNotImplemented
}
// deviceStart loads a new device and calls its Start() function.
func (d *qemu) deviceStart(dev device.Device, instanceRunning bool) (*deviceConfig.RunConfig, error) {
configCopy := dev.Config()
l := d.logger.AddContext(logger.Ctx{"device": dev.Name(), "type": configCopy["type"]})
l.Debug("Starting device")
reverter := revert.New()
defer reverter.Fail()
if instanceRunning && !dev.CanHotPlug() {
return nil, errors.New("Device cannot be started when instance is running")
}
runConf, err := dev.Start()
if err != nil {
return nil, err
}
reverter.Add(func() {
runConf, _ := dev.Stop()
if runConf != nil {
_ = d.runHooks(runConf.PostHooks)
}
})
// If runConf supplied, perform any instance specific setup of device.
if runConf != nil {
// If instance is running and then live attach device.
if instanceRunning {
// Attach NIC to running instance.
if len(runConf.NetworkInterface) > 0 {
err = d.deviceAttachNIC(dev.Name(), configCopy, runConf)
if err != nil {
return nil, err
}
}
// Attach disk to running instance.
for _, mount := range runConf.Mounts {
if mount.FSType == "9p" {
err = d.deviceAttachPath(dev.Name(), configCopy, mount)
if err != nil {
return nil, err
}
} else if mount.TargetPath != "/" {
err = d.deviceAttachBlockDevice(dev.Name(), configCopy, mount)
if err != nil {
return nil, err
}
}
}
// Attach USB to running instance.
for _, usbDev := range runConf.USBDevice {
err = d.deviceAttachUSB(usbDev)
if err != nil {
return nil, err
}
}
// Attach PCI to running instance.
if len(runConf.PCIDevice) > 0 {
err = d.deviceAttachPCI(dev.Name(), configCopy, runConf.PCIDevice)
if err != nil {
return nil, err
}
}
// If running, run post start hooks now (if not, they will be run
// once the instance is started).
err = d.runHooks(runConf.PostHooks)
if err != nil {
return nil, err
}
}
}
reverter.Success()
return runConf, nil
}
func (d *qemu) deviceAttachPath(deviceName string, configCopy map[string]string, mount deviceConfig.MountEntryItem) error {
// Check if the agent is running.
monitor, err := d.qmpConnect()
if err != nil {
return fmt.Errorf("Failed to connect to QMP monitor: %w", err)
}
monHook, err := d.addDriveDirConfigVirtiofs(nil, nil, mount)
if err != nil {
return fmt.Errorf("Failed to add drive config: %w", err)
}
err = monHook(monitor)
if err != nil {
return fmt.Errorf("Failed to call monitor hook for block device: %w", err)
}
return nil
}
func (d *qemu) deviceAttachBlockDevice(deviceName string, configCopy map[string]string, mount deviceConfig.MountEntryItem) error {
// Check if the agent is running.
monitor, err := d.qmpConnect()
if err != nil {
return fmt.Errorf("Failed to connect to QMP monitor: %w", err)
}
monHook, err := d.addDriveConfig(nil, nil, mount)
if err != nil {
return fmt.Errorf("Failed to add drive config: %w", err)
}
err = monHook(monitor)
if err != nil {
return fmt.Errorf("Failed to call monitor hook for block device: %w", err)
}
return nil
}
func (d *qemu) deviceDetachPath(deviceName string, rawConfig deviceConfig.Device) error {
escapedDeviceName := linux.PathNameEncode(deviceName)
deviceID := fmt.Sprintf("%s%s", qemuDeviceIDPrefix, escapedDeviceName)
mountTag := fmt.Sprintf("incus_%s", deviceName)
// Check if the agent is running.
monitor, err := d.qmpConnect()
if err != nil {
return err
}
err = monitor.RemoveDevice(deviceID)
if err != nil {
return err
}
waitDuration := time.Duration(time.Second * time.Duration(10))
waitUntil := time.Now().Add(waitDuration)
for {
err = monitor.RemoveCharDevice(mountTag)
if err == nil {
break
}
if api.StatusErrorCheck(err, http.StatusLocked) {
time.Sleep(time.Second * time.Duration(2))
continue
}
if time.Now().After(waitUntil) {
return fmt.Errorf("Failed to detach path device after %v", waitDuration)
}
}
return nil
}
func (d *qemu) deviceDetachBlockDevice(deviceName string, rawConfig deviceConfig.Device) error {
// Check if the agent is running.
monitor, err := d.qmpConnect()
if err != nil {
return err
}
escapedDeviceName := linux.PathNameEncode(deviceName)
deviceID := fmt.Sprintf("%s%s", qemuDeviceIDPrefix, escapedDeviceName)
blockDevName := d.blockNodeName(escapedDeviceName)
err = monitor.RemoveFDFromFDSet(blockDevName)
if err != nil {
return err
}
err = monitor.RemoveDevice(deviceID)
if err != nil {
return err
}
waitDuration := time.Duration(time.Second * time.Duration(10))
waitUntil := time.Now().Add(waitDuration)
for {
err = monitor.RemoveBlockDevice(blockDevName)
if err == nil {
break
}
if api.StatusErrorCheck(err, http.StatusLocked) {
time.Sleep(time.Second * time.Duration(2))
continue
}
if time.Now().After(waitUntil) {
return fmt.Errorf("Failed to detach block device after %v", waitDuration)
}
}
return nil
}
// deviceAttachNIC live attaches a NIC device to the instance.
func (d *qemu) deviceAttachNIC(deviceName string, configCopy map[string]string, runConf *deviceConfig.RunConfig) error {
devName := ""
for _, dev := range runConf.NetworkInterface {
if dev.Key == "link" {
devName = dev.Value
break
}
}
if devName == "" {
return errors.New("Device didn't provide a link property to use")
}
_, qemuBus, err := d.qemuArchConfig(d.architecture)
if err != nil {
return err
}
// Check if the agent is running.
monitor, err := d.qmpConnect()
if err != nil {
return err
}
qemuDev := make(map[string]any)
if runConf.UseUSBBus {
qemuBus = "usb"
qemuDev["bus"] = "qemu_usb.0"
} else if slices.Contains([]string{"pcie", "pci"}, qemuBus) {
// Try to get a PCI address for hotplugging.
pciDeviceName, err := d.getPCIHotplug()
if err != nil {
return err
}
d.logger.Debug("Using PCI bus device to hotplug NIC into", logger.Ctx{"device": deviceName, "port": pciDeviceName})
qemuDev["bus"] = pciDeviceName
qemuDev["addr"] = "00.0"
}
monHook, err := d.addNetDevConfig(qemuBus, qemuDev, nil, runConf.NetworkInterface)
if err != nil {
return err
}
err = monHook(monitor)
if err != nil {
return err
}
return nil
}
func (d *qemu) getPCIHotplug() (string, error) {
// Check if the agent is running.
monitor, err := d.qmpConnect()
if err != nil {
return "", err
}
// Get the current PCI devices.
devices, err := monitor.QueryPCI()
if err != nil {
return "", err
}
for _, dev := range devices {
// Skip built-in devices.
if dev.DevID == "" || dev.DevID == "qemu_iommu" {
continue
}
// Skip used bridges.
if len(dev.Bridge.Devices) > 0 {
continue
}
// Found an empty slot.
return dev.DevID, nil
}
return "", errors.New("No available PCI hotplug slots could be found")
}
// deviceAttachPCI live attaches a generic PCI device to the instance.
func (d *qemu) deviceAttachPCI(deviceName string, configCopy map[string]string, pciConfig []deviceConfig.RunConfigItem) error {
reverter := revert.New()
defer reverter.Fail()
// Check if the agent is running.
monitor, err := d.qmpConnect()
if err != nil {
return err
}
// Get the device config.
var devName, pciSlotName, pciIOMMUGroup string
for _, pciItem := range pciConfig {
if pciItem.Key == "devName" {
devName = pciItem.Value
} else if pciItem.Key == "pciSlotName" {
pciSlotName = pciItem.Value
} else if pciItem.Key == "pciIOMMUGroup" {
pciIOMMUGroup = pciItem.Value
}
}
// PCIe and PCI require a port device name to hotplug the NIC into.
_, qemuBus, err := d.qemuArchConfig(d.architecture)
if err != nil {
return err
}
if !slices.Contains([]string{"pcie", "pci"}, qemuBus) {
return errors.New("Attempting PCI passthrough on a non-PCI system")
}
// Try to get a PCI address for hotplugging.
pciDeviceName, err := d.getPCIHotplug()
if err != nil {
return err
}
qemuDev := make(map[string]any)
escapedDeviceName := linux.PathNameEncode(devName)
d.logger.Debug("Using PCI bus device to hotplug NIC into", logger.Ctx{"device": deviceName, "port": pciDeviceName})
qemuDev["bus"] = pciDeviceName
qemuDev["addr"] = "00.0"
qemuDev["driver"] = "vfio-pci"
qemuDev["id"] = fmt.Sprintf("%s%s", qemuDeviceIDPrefix, escapedDeviceName)
qemuDev["host"] = pciSlotName
if d.state.OS.UnprivUser != "" {
if pciIOMMUGroup == "" {
return errors.New("No PCI IOMMU group supplied")
}
vfioGroupFile := fmt.Sprintf("/dev/vfio/%s", pciIOMMUGroup)
err := os.Chown(vfioGroupFile, int(d.state.OS.UnprivUID), -1)
if err != nil {
return fmt.Errorf("Failed to chown vfio group device %q: %w", vfioGroupFile, err)
}
}
err = monitor.AddDevice(qemuDev)
if err != nil {
return fmt.Errorf("Failed setting up device %q: %w", devName, err)
}
return nil
}
// deviceStop loads a new device and calls its Stop() function.
func (d *qemu) deviceStop(dev device.Device, instanceRunning bool, _ string) error {
configCopy := dev.Config()
l := d.logger.AddContext(logger.Ctx{"device": dev.Name(), "type": configCopy["type"]})
l.Debug("Stopping device")
if instanceRunning && !dev.CanHotPlug() {
return errors.New("Device cannot be stopped when instance is running")
}
runConf, err := dev.Stop()
if err != nil {
return err
}
if instanceRunning {
// Detach NIC from running instance.
if configCopy["type"] == "nic" {
for _, usbDev := range runConf.USBDevice {
err = d.deviceDetachUSB(usbDev)
if err != nil {
return err
}
}
err = d.deviceDetachNIC(dev.Name())
if err != nil {
return err
}
}
// Detach USB from running instance.
if configCopy["type"] == "usb" && runConf != nil {
for _, usbDev := range runConf.USBDevice {
err = d.deviceDetachUSB(usbDev)
if err != nil {
return err
}
}
}
// Detach disk from running instance.
if configCopy["type"] == "disk" {
if configCopy["path"] != "" {
err = d.deviceDetachPath(dev.Name(), configCopy)
if err != nil {
return err
}
} else {
err = d.deviceDetachBlockDevice(dev.Name(), configCopy)
if err != nil {
return err
}
}
}
// Detach generic PCI device from running instance.
if configCopy["type"] == "pci" {
err = d.deviceDetachPCI(dev.Name())
if err != nil {
return err
}
}
}
if runConf != nil {
// Run post stop hooks irrespective of run state of instance.
err = d.runHooks(runConf.PostHooks)
if err != nil {
return err
}
}
return nil
}
// deviceDetachNIC detaches a NIC device from a running instance.
func (d *qemu) deviceDetachNIC(deviceName string) error {
// Check if the agent is running.
monitor, err := d.qmpConnect()
if err != nil {
return err
}
escapedDeviceName := linux.PathNameEncode(deviceName)
deviceID := fmt.Sprintf("%s%s", qemuDeviceIDPrefix, escapedDeviceName)
netDevID := fmt.Sprintf("%s%s", qemuNetDevIDPrefix, escapedDeviceName)
// Request removal of device.
err = monitor.RemoveDevice(deviceID)
if err != nil {
return fmt.Errorf("Failed removing NIC device: %w", err)
}
err = monitor.RemoveNIC(netDevID)
if err != nil {
return err
}
_, qemuBus, err := d.qemuArchConfig(d.architecture)
if err != nil {
return err
}
if slices.Contains([]string{"pcie", "pci"}, qemuBus) {
// Wait until the device is actually removed (or we timeout waiting).
waitDuration := time.Duration(time.Second * time.Duration(10))
waitUntil := time.Now().Add(waitDuration)
for {
devExists, err := monitor.CheckPCIDevice(deviceID)
if err != nil {
return fmt.Errorf("Failed getting PCI devices to check for NIC detach: %w", err)
}
if !devExists {
break
}
if time.Now().After(waitUntil) {
return fmt.Errorf("Failed to detach NIC after %v", waitDuration)
}
d.logger.Debug("Waiting for NIC device to be detached", logger.Ctx{"device": deviceName})
time.Sleep(time.Second * time.Duration(2))
}
}
return nil
}
// deviceDetachPCI detaches a generic PCI device from a running instance.
func (d *qemu) deviceDetachPCI(deviceName string) error {
// Check if the agent is running.
monitor, err := d.qmpConnect()
if err != nil {
return err
}
escapedDeviceName := linux.PathNameEncode(deviceName)
deviceID := fmt.Sprintf("%s%s", qemuDeviceIDPrefix, escapedDeviceName)
// Request removal of device.
err = monitor.RemoveDevice(deviceID)
if err != nil {
return fmt.Errorf("Failed removing PCI device: %w", err)
}
_, qemuBus, err := d.qemuArchConfig(d.architecture)
if err != nil {
return err
}
if slices.Contains([]string{"pcie", "pci"}, qemuBus) {
// Wait until the device is actually removed (or we timeout waiting).
waitDuration := time.Duration(time.Second * time.Duration(10))
waitUntil := time.Now().Add(waitDuration)
for {
devExists, err := monitor.CheckPCIDevice(deviceID)
if err != nil {
return fmt.Errorf("Failed getting PCI devices to check for detach: %w", err)
}
if !devExists {
break
}
if time.Now().After(waitUntil) {
return fmt.Errorf("Failed to detach PCI device after %v", waitDuration)
}
d.logger.Debug("Waiting for PCI device to be detached", logger.Ctx{"device": deviceName})
time.Sleep(time.Second * time.Duration(2))
}
}
return nil
}
func (d *qemu) monitorPath() string {
return filepath.Join(d.RunPath(), "qemu.monitor")
}
func (d *qemu) nvramPath() string {
return filepath.Join(d.Path(), "qemu.nvram")
}
func (d *qemu) consolePath() string {
return filepath.Join(d.RunPath(), "qemu.console")
}
func (d *qemu) spicePath() string {
return filepath.Join(d.RunPath(), "qemu.spice")
}
func (d *qemu) spiceCmdlineConfig() string {
return fmt.Sprintf("unix=on,disable-ticketing=on,addr=%s", d.spicePath())
}
// generateConfigShare generates the config share directory that will be exported to the VM via
// a 9P share. Due to the unknown size of templates inside the images this directory is created
// inside the VM's config volume so that it can be restricted by quota.
// Requires the instance be mounted before calling this function.
func (d *qemu) generateConfigShare() error {
isWindows := d.isWindows()
configDrivePath := filepath.Join(d.Path(), "config")
// Create config drive dir if doesn't exist, if it does exist, leave it around so we don't regenerate all
// files causing unnecessary config drive snapshot usage.
err := os.MkdirAll(configDrivePath, 0o500)
if err != nil {
return err
}
if !isWindows {
// Add the VM agent loader.
agentSrcPath, _ := exec.LookPath("incus-agent")
if util.PathExists(os.Getenv("INCUS_AGENT_PATH")) {
// Install incus-agent script (loads from agent share).
agentFile, err := incusAgentLoader.ReadFile("agent-loader/incus-agent")
if err != nil {
return err
}
err = os.WriteFile(filepath.Join(configDrivePath, "incus-agent"), agentFile, 0o700)
if err != nil {
return err
}
if !isWindows {
// Legacy support.
_ = os.Remove(filepath.Join(configDrivePath, "lxd-agent"))
err = os.Symlink("incus-agent", filepath.Join(configDrivePath, "lxd-agent"))
if err != nil {
return err
}
}
} else if agentSrcPath != "" {
// Install agent into config drive dir if found.
agentSrcPath, err = filepath.EvalSymlinks(agentSrcPath)
if err != nil {
return err
}
agentSrcInfo, err := os.Stat(agentSrcPath)
if err != nil {
return fmt.Errorf("Failed getting info for incus-agent source %q: %w", agentSrcPath, err)
}
agentInstallPath := filepath.Join(configDrivePath, "incus-agent")
agentNeedsInstall := true
if util.PathExists(agentInstallPath) {
agentInstallInfo, err := os.Stat(agentInstallPath)
if err != nil {
return fmt.Errorf("Failed getting info for existing incus-agent install %q: %w", agentInstallPath, err)
}
if agentInstallInfo.ModTime().Equal(agentSrcInfo.ModTime()) && agentInstallInfo.Size() == agentSrcInfo.Size() {
agentNeedsInstall = false
}
}
// Only install the agent into config drive if the existing one is different to the source one.
// Otherwise we would end up copying it again and this can cause unnecessary snapshot usage.
if agentNeedsInstall {
d.logger.Debug("Installing incus-agent", logger.Ctx{"srcPath": agentSrcPath, "installPath": agentInstallPath})
err = internalUtil.FileCopy(agentSrcPath, agentInstallPath)
if err != nil {
return err
}
err = os.Chmod(agentInstallPath, 0o500)
if err != nil {
return err
}
err = os.Chown(agentInstallPath, 0, 0)
if err != nil {
return err
}
// Ensure we copy the source file's timestamps so they can be used for comparison later.
err = os.Chtimes(agentInstallPath, agentSrcInfo.ModTime(), agentSrcInfo.ModTime())
if err != nil {
return fmt.Errorf("Failed setting incus-agent timestamps: %w", err)
}
} else {
d.logger.Debug("Skipping incus-agent install as unchanged", logger.Ctx{"srcPath": agentSrcPath, "installPath": agentInstallPath})
}
// Legacy support.
_ = os.Remove(filepath.Join(configDrivePath, "lxd-agent"))
err = os.Symlink("incus-agent", filepath.Join(configDrivePath, "lxd-agent"))
if err != nil {
return err
}
} else {
d.logger.Warn("incus-agent not found, skipping its inclusion in the VM config drive", logger.Ctx{"err": err})
}
}
agentCert, agentKey, clientCert, _, err := d.generateAgentCert()
if err != nil {
return err
}
err = os.WriteFile(filepath.Join(configDrivePath, "server.crt"), []byte(clientCert), 0o400)
if err != nil {
return err
}
err = os.WriteFile(filepath.Join(configDrivePath, "agent.crt"), []byte(agentCert), 0o400)
if err != nil {
return err
}
err = os.WriteFile(filepath.Join(configDrivePath, "agent.key"), []byte(agentKey), 0o400)
if err != nil {
return err
}
if !isWindows {
// Systemd units.
err = os.MkdirAll(filepath.Join(configDrivePath, "systemd"), 0o500)
if err != nil {
return err
}
// Systemd unit for incus-agent. It ensures the incus-agent is copied from the shared filesystem before it is
// started. The service is triggered dynamically via udev rules when certain virtio-ports are detected,
// rather than being enabled at boot.
agentFile, err := incusAgentLoader.ReadFile("agent-loader/systemd/incus-agent.service")
if err != nil {
return err
}
err = os.WriteFile(filepath.Join(configDrivePath, "systemd", "incus-agent.service"), agentFile, 0o400)
if err != nil {
return err
}
// Setup script for incus-agent that is executed by the incus-agent systemd unit before incus-agent is started.
// The script sets up a temporary mount point, copies data from the mount (including incus-agent binary),
// and then unmounts it. It also ensures appropriate permissions for the Incus agent's runtime directory.
agentFile, err = incusAgentLoader.ReadFile("agent-loader/incus-agent-setup")
if err != nil {
return err
}
err = os.WriteFile(filepath.Join(configDrivePath, "systemd", "incus-agent-setup"), agentFile, 0o500)
if err != nil {
return err
}
err = os.MkdirAll(filepath.Join(configDrivePath, "udev"), 0o500)
if err != nil {
return err
}
// Udev rules to start the incus-agent.service when QEMU serial devices (symlinks in virtio-ports) appear.
agentFile, err = incusAgentLoader.ReadFile("agent-loader/systemd/incus-agent.rules")
if err != nil {
return err
}
err = os.WriteFile(filepath.Join(configDrivePath, "udev", "99-incus-agent.rules"), agentFile, 0o400)
if err != nil {
return err
}
// Install script for manual installs.
agentFile, err = incusAgentLoader.ReadFile("agent-loader/install.sh")
if err != nil {
return err
}
err = os.WriteFile(filepath.Join(configDrivePath, "install.sh"), agentFile, 0o700)
if err != nil {
return err
}
}
// Templated files.
templateFilesPath := filepath.Join(configDrivePath, "files")
// Clear path and recreate.
_ = os.RemoveAll(templateFilesPath)
err = os.MkdirAll(templateFilesPath, 0o500)
if err != nil {
return err
}
// Template anything that needs templating.
key := "volatile.apply_template"
if d.localConfig[key] != "" {
// Run any template that needs running.
err = d.templateApplyNow(instance.TemplateTrigger(d.localConfig[key]), templateFilesPath)
if err != nil {
return err
}
err := d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Remove the volatile key from the DB.
return tx.DeleteInstanceConfigKey(ctx, int64(d.id), key)
})
if err != nil {
return err
}
}
err = d.templateApplyNow("start", templateFilesPath)
if err != nil {
return err
}
// Copy the template metadata itself too.
metaPath := filepath.Join(d.Path(), "metadata.yaml")
if util.PathExists(metaPath) {
err = internalUtil.FileCopy(metaPath, filepath.Join(templateFilesPath, "metadata.yaml"))
if err != nil {
return err
}
}
if !isWindows {
// Clear NICConfigDir to ensure that no leftover configuration is erroneously applied by the agent.
nicConfigPath := filepath.Join(configDrivePath, deviceConfig.NICConfigDir)
_ = os.RemoveAll(nicConfigPath)
err = os.MkdirAll(nicConfigPath, 0o500)
if err != nil {
return err
}
// Add the NIC config.
if util.IsTrue(d.expandedConfig["agent.nic_config"]) {
sortedDevices := d.expandedDevices.Sorted()
for _, entry := range sortedDevices {
if entry.Config["type"] != "nic" {
continue // Only keep NIC devices.
}
dev, err := d.FillNetworkDevice(entry.Name, entry.Config)
if err != nil {
return err
}
err = d.writeNICDevConfig(dev["mtu"], entry.Name, dev["name"], dev["hwaddr"])
if err != nil {
return fmt.Errorf("Failed writing NIC config for device %q: %w", entry.Name, err)
}
}
}
// Writing the connection info the config drive allows the agent to start /dev/incus very
// early. This is important for systemd services which want or require /dev/incus/sock.
connInfo, err := d.getAgentConnectionInfo()
if err != nil {
return err
}
if connInfo != nil {
err = d.saveConnectionInfo(connInfo)
if err != nil {
return err
}
}
}
return nil
}
func (d *qemu) templateApplyNow(trigger instance.TemplateTrigger, path string) error {
// If there's no metadata, just return.
fname := filepath.Join(d.Path(), "metadata.yaml")
if !util.PathExists(fname) {
return nil
}
// Parse the metadata.
content, err := os.ReadFile(fname)
if err != nil {
return fmt.Errorf("Failed to read metadata: %w", err)
}
metadata := &api.ImageMetadata{}
err = yaml.Unmarshal(content, metadata)
if err != nil {
return fmt.Errorf("Could not parse %s: %w", fname, err)
}
// Figure out the instance architecture.
arch, err := osarch.ArchitectureName(d.architecture)
if err != nil {
arch, err = osarch.ArchitectureName(d.state.OS.Architectures[0])
if err != nil {
return fmt.Errorf("Failed to detect system architecture: %w", err)
}
}
// Generate the instance metadata.
instanceMeta := make(map[string]string)
instanceMeta["name"] = d.name
instanceMeta["type"] = "virtual-machine"
instanceMeta["architecture"] = arch
if d.ephemeral {
instanceMeta["ephemeral"] = "true"
} else {
instanceMeta["ephemeral"] = "false"
}
// Go through the templates.
for tplPath, tpl := range metadata.Templates {
err = func(tplPath string, tpl *api.ImageMetadataTemplate) error {
var w *os.File
// Check if the template should be applied now.
found := slices.Contains(tpl.When, string(trigger))
if !found {
return nil
}
// Create the file itself.
w, err = os.Create(filepath.Join(path, fmt.Sprintf("%s.out", tpl.Template)))
if err != nil {
return err
}
// Fix ownership and mode.
err = w.Chmod(0o644)
if err != nil {
return err
}
defer func() { _ = w.Close() }()
// Read the template.
tplString, err := os.ReadFile(filepath.Join(d.TemplatesPath(), tpl.Template))
if err != nil {
return fmt.Errorf("Failed to read template file: %w", err)
}
// Restrict filesystem access to within the instance's rootfs.
tplSet := pongo2.NewSet(fmt.Sprintf("%s-%s", d.name, tpl.Template), pongoTemplate.ChrootLoader{Path: d.TemplatesPath()})
tplRender, err := tplSet.FromString("{% autoescape off %}" + string(tplString) + "{% endautoescape %}")
if err != nil {
return fmt.Errorf("Failed to render template: %w", err)
}
configGet := func(confKey, confDefault *pongo2.Value) *pongo2.Value {
val, ok := d.expandedConfig[confKey.String()]
if !ok {
return confDefault
}
return pongo2.AsValue(strings.TrimRight(val, "\r\n"))
}
// Render the template.
err = tplRender.ExecuteWriter(pongo2.Context{
"trigger": trigger,
"path": tplPath,
"instance": instanceMeta,
"container": instanceMeta, // FIXME: remove once most images have moved away.
"config": d.expandedConfig,
"devices": d.expandedDevices,
"properties": tpl.Properties,
"config_get": configGet,
}, w)
if err != nil {
return err
}
return w.Close()
}(tplPath, tpl)
if err != nil {
return err
}
}
return nil
}
// deviceBootPriorities returns a map keyed on device name containing the boot index to use.
// Qemu tries to boot devices in order of boot index (lowest first).
func (d *qemu) deviceBootPriorities(base int) (map[string]int, error) {
type devicePrios struct {
Name string
BootPrio uint32
}
devices := []devicePrios{}
for _, dev := range d.expandedDevices.Sorted() {
if dev.Config["type"] != "disk" && dev.Config["type"] != "nic" {
continue
}
bootPrio := uint32(0) // Default to lowest priority.
if dev.Config["boot.priority"] != "" {
prio, err := strconv.ParseInt(dev.Config["boot.priority"], 10, 32)
if err != nil {
return nil, fmt.Errorf("Invalid boot.priority for device %q: %w", dev.Name, err)
}
bootPrio = uint32(prio)
} else if dev.Config["path"] == "/" {
bootPrio = 1 // Set boot priority of root disk higher than any device without a boot prio.
}
devices = append(devices, devicePrios{Name: dev.Name, BootPrio: bootPrio})
}
// Sort devices by priority (use SliceStable so that devices with the same boot priority stay in the same
// order each boot based on the device order provided by the d.expandedDevices.Sorted() function).
// This is important because as well as providing a predictable boot index order, the boot index number can
// also be used for other properties (such as disk SCSI ID) which can result in it being given different
// device names inside the guest based on the device order.
sort.SliceStable(devices, func(i, j int) bool { return devices[i].BootPrio > devices[j].BootPrio })
sortedDevs := make(map[string]int, len(devices))
for bootIndex, dev := range devices {
sortedDevs[dev.Name] = bootIndex + base
}
return sortedDevs, nil
}
// isWindows returns whether the VM is Windows.
func (d *qemu) isWindows() bool {
return strings.Contains(strings.ToLower(d.expandedConfig["image.os"]), "windows")
}
func (d *qemu) getStartupRTCAdjustment() time.Duration {
// Get the current values.
adjustment := d.parseRTC("volatile.vm.rtc_adjustment")
offset := d.parseRTC("volatile.vm.rtc_offset")
// Reset to handle new VM-generated updates.
adjustment += offset
offset = 0
changes := map[string]string{
"volatile.vm.rtc_adjustment": strconv.Itoa(adjustment),
"volatile.vm.rtc_offset": strconv.Itoa(offset),
}
err := d.VolatileSet(changes)
if err != nil {
d.logger.Error("Failed to set RTC change offset", logger.Ctx{"changes": changes, "err": err})
}
return time.Duration(adjustment) * time.Second
}
func (d *qemu) parseRTC(key string) int {
offset := 0
val, ok := d.localConfig[key]
if ok {
var err error
offset, err = strconv.Atoi(val)
if err != nil {
offset = 0
d.logger.Error("Failed to parse RTC volatile key")
}
}
return offset
}
// onRTCChange saves rtc change.
func (d *qemu) onRTCChange(change int) error {
offset := d.parseRTC("volatile.vm.rtc_offset")
if offset != change {
changes := map[string]string{"volatile.vm.rtc_offset": strconv.Itoa(change)}
err := d.VolatileSet(changes)
if err != nil {
d.logger.Error("Failed to set rtc change offset ", logger.Ctx{"changes": changes, "err": err})
}
return err
}
return nil
}
// generateQemuConfig generates the QEMU configuration.
func (d *qemu) generateQemuConfig(machineDefinition string, cpuType string, cpuInfo *cpuTopology, mountInfo *storagePools.MountInfo, busName string, vsockFD int, devConfs []*deviceConfig.RunConfig, fdFiles *[]*os.File) ([]monitorHook, error) {
var monHooks []monitorHook
isWindows := d.isWindows()
conf := qemuBase(&qemuBaseOpts{d.Architecture(), util.IsTrue(d.expandedConfig["security.iommu"]), machineDefinition})
err := d.addCPUMemoryConfig(&conf, cpuType, cpuInfo)
if err != nil {
return nil, err
}
// Parse raw.qemu.
rawOptions := []string{}
if d.expandedConfig["raw.qemu"] != "" {
rawOptions, err = shellquote.Split(d.expandedConfig["raw.qemu"])
if err != nil {
return nil, err
}
}
// Allow disabling the UEFI firmware.
if slices.Contains(rawOptions, "-bios") || slices.Contains(rawOptions, "-kernel") {
d.logger.Warn("Starting VM without default firmware (-bios or -kernel in raw.qemu)")
} else if d.architectureSupportsUEFI(d.architecture) {
// Open the UEFI NVRAM file and pass it via file descriptor to QEMU.
// This is so the QEMU process can still read/write the file after it has dropped its user privs.
nvRAMFile, err := os.Open(d.nvramPath())
if err != nil {
return nil, fmt.Errorf("Failed opening NVRAM file: %w", err)
}
// Determine expected firmware.
var firmwares []edk2.FirmwarePair
if util.IsTrue(d.expandedConfig["security.csm"]) {
firmwares, err = edk2.GetArchitectureFirmwarePairsForUsage(d.architecture, edk2.CSM)
if err != nil {
return nil, err
}
} else if util.IsTrueOrEmpty(d.expandedConfig["security.secureboot"]) {
firmwares, err = edk2.GetArchitectureFirmwarePairsForUsage(d.architecture, edk2.SECUREBOOT)
if err != nil {
return nil, err
}
} else {
firmwares, err = edk2.GetArchitectureFirmwarePairsForUsage(d.architecture, edk2.GENERIC)
if err != nil {
return nil, err
}
}
var efiCode string
for _, firmware := range firmwares {
if util.PathExists(filepath.Join(d.Path(), filepath.Base(firmware.Vars))) {
efiCode = firmware.Code
break
}
}
if efiCode == "" {
return nil, fmt.Errorf("Unable to locate matching firmware: %+v", firmwares)
}
driveFirmwareOpts := qemuDriveFirmwareOpts{
roPath: efiCode,
nvramPath: fmt.Sprintf("/dev/fd/%d", d.addFileDescriptor(fdFiles, nvRAMFile)),
}
conf = append(conf, qemuDriveFirmware(&driveFirmwareOpts)...)
}
// QMP socket.
conf = append(conf, qemuControlSocket(&qemuControlSocketOpts{d.monitorPath()})...)
// Console output.
conf = append(conf, qemuConsole()...)
// VM core info (memory dump).
conf = append(conf, qemuCoreInfo()...)
// Setup the bus allocator.
bus := qemuNewBus(busName, &conf)
// Add IOMMU.
if util.IsTrue(d.expandedConfig["security.iommu"]) && d.architectureSupportsUEFI(d.architecture) {
devBus, devAddr, multi := bus.allocateDirect()
iommuOpts := qemuDevOpts{
busName: bus.name,
devBus: devBus,
devAddr: devAddr,
multifunction: multi,
}
conf = append(conf, qemuIOMMU(&iommuOpts, isWindows)...)
}
// Now add the fixed set of devices. The multi-function groups used for these fixed internal devices are
// specifically chosen to ensure that we consume exactly 4 PCI bus ports (on PCIe bus). This ensures that
// the first user device NIC added will use the 5th PCI bus port and will be consistently named enp5s0
// on PCIe (which we need to maintain compatibility with network configuration in our existing VM images).
// It's also meant to group all low-bandwidth internal devices onto a single address. PCIe bus allows a
// total of 256 devices, but this assumes 32 chassis * 8 function. By using VFs for the internal fixed
// devices we avoid consuming a chassis for each one. See also the qemuPCIDeviceIDStart constant.
devBus, devAddr, multi := bus.allocate(busFunctionGroupGeneric)
balloonOpts := qemuDevOpts{
busName: bus.name,
devBus: devBus,
devAddr: devAddr,
multifunction: multi,
}
conf = append(conf, qemuBalloon(&balloonOpts)...)
devBus, devAddr, multi = bus.allocate(busFunctionGroupGeneric)
rngOpts := qemuDevOpts{
busName: bus.name,
devBus: devBus,
devAddr: devAddr,
multifunction: multi,
}
conf = append(conf, qemuRNG(&rngOpts)...)
devBus, devAddr, multi = bus.allocate(busFunctionGroupGeneric)
keyboardOpts := qemuDevOpts{
busName: bus.name,
devBus: devBus,
devAddr: devAddr,
multifunction: multi,
}
conf = append(conf, qemuKeyboard(&keyboardOpts)...)
devBus, devAddr, multi = bus.allocate(busFunctionGroupGeneric)
tabletOpts := qemuDevOpts{
busName: bus.name,
devBus: devBus,
devAddr: devAddr,
multifunction: multi,
}
conf = append(conf, qemuTablet(&tabletOpts)...)
// Windows doesn't support virtio-vsock.
if !isWindows {
// Existing vsock ID from volatile.
vsockID, err := d.getVsockID()
if err != nil {
return nil, err
}
devBus, devAddr, multi = bus.allocate(busFunctionGroupGeneric)
vsockOpts := qemuVsockOpts{
dev: qemuDevOpts{
busName: bus.name,
devBus: devBus,
devAddr: devAddr,
multifunction: multi,
},
vsockFD: vsockFD,
vsockID: vsockID,
}
conf = append(conf, qemuVsock(&vsockOpts)...)
}
devBus, devAddr, multi = bus.allocate(busFunctionGroupGeneric)
serialOpts := qemuSerialOpts{
dev: qemuDevOpts{
busName: bus.name,
devBus: devBus,
devAddr: devAddr,
multifunction: multi,
},
charDevName: qemuSerialChardevName,
ringbufSizeBytes: qmp.RingbufSize,
}
conf = append(conf, qemuSerial(&serialOpts)...)
// s390x doesn't really have USB.
if d.architecture != osarch.ARCH_64BIT_S390_BIG_ENDIAN {
devBus, devAddr, multi = bus.allocate(busFunctionGroupGeneric)
usbOpts := qemuUSBOpts{
devBus: devBus,
devAddr: devAddr,
multifunction: multi,
ports: qemuSparseUSBPorts,
}
conf = append(conf, qemuUSB(&usbOpts)...)
}
if util.IsTrue(d.expandedConfig["security.csm"]) {
// Allocate a regular entry to keep things aligned normally (avoid NICs getting a different name).
_, _, _ = bus.allocate(busFunctionGroupNone)
// Allocate a direct entry so the SCSI controller can be seen by seabios.
devBus, devAddr, multi = bus.allocateDirect()
} else {
devBus, devAddr, multi = bus.allocate(busFunctionGroupNone)
}
scsiOpts := qemuDevOpts{
busName: bus.name,
devBus: devBus,
devAddr: devAddr,
multifunction: multi,
}
conf = append(conf, qemuSCSI(&scsiOpts)...)
// Windows doesn't support virtio-9p.
if !isWindows {
// Always export the config directory as a 9p config drive, in case the host or VM guest doesn't support
// virtio-fs.
devBus, devAddr, multi = bus.allocate(busFunctionGroup9p)
driveConfig9pOpts := qemuDriveConfigOpts{
dev: qemuDevOpts{
busName: bus.name,
devBus: devBus,
devAddr: devAddr,
multifunction: multi,
},
name: "config",
protocol: "9p",
path: d.configDriveMountPath(),
}
conf = append(conf, qemuDriveConfig(&driveConfig9pOpts)...)
// Pass in the agents if INCUS_AGENT_PATH is set.
if util.PathExists(os.Getenv("INCUS_AGENT_PATH")) {
devBus, devAddr, multi = bus.allocate(busFunctionGroup9p)
driveConfig9pOpts := qemuDriveConfigOpts{
dev: qemuDevOpts{
busName: bus.name,
devBus: devBus,
devAddr: devAddr,
multifunction: multi,
},
name: "agent",
protocol: "9p",
path: os.Getenv("INCUS_AGENT_PATH"),
}
conf = append(conf, qemuDriveConfig(&driveConfig9pOpts)...)
}
}
// If user has requested AMD SEV, check if supported and add to QEMU config.
if util.IsTrue(d.expandedConfig["security.sev"]) {
sevOpts, err := d.setupSEV(fdFiles)
if err != nil {
return nil, err
}
if sevOpts != nil {
for i := range conf {
if conf[i].Name == "machine" {
conf[i].Entries["memory-encryption"] = "sev0"
break
}
}
conf = append(conf, qemuSEV(sevOpts)...)
}
}
if util.IsTrue(d.expandedConfig["security.csm"]) {
// Allocate a regular entry to keep things aligned normally (avoid NICs getting a different name).
_, _, _ = bus.allocate(busFunctionGroupNone)
// Allocate a direct entry so the GPU can be seen by seabios.
devBus, devAddr, multi = bus.allocateDirect()
} else {
devBus, devAddr, multi = bus.allocate(busFunctionGroupNone)
}
gpuOpts := qemuGpuOpts{
dev: qemuDevOpts{
busName: bus.name,
devBus: devBus,
devAddr: devAddr,
multifunction: multi,
},
architecture: d.Architecture(),
}
conf = append(conf, qemuGPU(&gpuOpts)...)
// Dynamic devices.
base := 0
if slices.Contains(rawOptions, "-kernel") {
base = 1
}
bootIndexes, err := d.deviceBootPriorities(base)
if err != nil {
return nil, fmt.Errorf("Error calculating boot indexes: %w", err)
}
// Record the mounts we are going to do inside the VM using the agent.
agentMounts := []instancetype.VMAgentMount{}
// These devices are sorted so that NICs are added first to ensure that the first NIC can use the 5th
// PCIe bus port and will be consistently named enp5s0 for compatibility with network configuration in our
// existing VM images. Even on non-PCIe buses having NICs first means that their names won't change when
// other devices are added.
for _, runConf := range devConfs {
// Add drive devices.
if len(runConf.Mounts) > 0 {
for _, drive := range runConf.Mounts {
var monHook monitorHook
// Check if the user has overridden the bus.
busName := "virtio-scsi"
for _, opt := range drive.Opts {
if !strings.HasPrefix(opt, "bus=") {
continue
}
busName = strings.TrimPrefix(opt, "bus=")
break
}
qemuDev := make(map[string]any)
if slices.Contains([]string{"9p", "nvme", "virtio-blk", "virtiofs"}, busName) {
// Allocate a PCI(e) port and write it to the config file so QMP can "hotplug" the
// drive into it later.
functionGroup := busFunctionGroupNone
if busName == "9p" {
functionGroup = busFunctionGroup9p
}
devBus, devAddr, multi := bus.allocate(functionGroup)
// Populate the qemu device with port info.
qemuDev["bus"] = devBus
qemuDev["addr"] = devAddr
qemuDev["multifunction"] = multi
}
if drive.TargetPath == "/" {
monHook, err = d.addRootDriveConfig(qemuDev, mountInfo, bootIndexes, drive)
} else if drive.FSType == "9p" {
if busName == "9p" {
conf = append(conf, d.driveDirConfig9p(qemuDev, bus.name, &agentMounts, drive)...)
} else {
monHook, err = d.addDriveDirConfigVirtiofs(qemuDev, &agentMounts, drive)
}
} else {
monHook, err = d.addDriveConfig(qemuDev, bootIndexes, drive)
}
if err != nil {
return nil, fmt.Errorf("Failed setting up disk device %q: %w", drive.DevName, err)
}
if monHook != nil {
monHooks = append(monHooks, monHook)
}
}
}
// Add network device.
if len(runConf.NetworkInterface) > 0 {
qemuDev := make(map[string]any)
busName := bus.name
if runConf.UseUSBBus {
busName = "usb"
qemuDev["bus"] = "qemu_usb.0"
} else if slices.Contains([]string{"pcie", "pci"}, busName) {
// Allocate a PCI(e) port and write it to the config file so QMP can "hotplug" the
// NIC into it later.
devBus, devAddr, multi := bus.allocate(busFunctionGroupNone)
// Populate the qemu device with port info.
qemuDev["bus"] = devBus
qemuDev["addr"] = devAddr
if multi {
qemuDev["multifunction"] = true
}
}
monHook, err := d.addNetDevConfig(busName, qemuDev, bootIndexes, runConf.NetworkInterface)
if err != nil {
return nil, err
}
monHooks = append(monHooks, monHook)
}
// Add GPU device.
if len(runConf.GPUDevice) > 0 {
err = d.addGPUDevConfig(&conf, bus, runConf.GPUDevice)
if err != nil {
return nil, err
}
}
// Add PCI device.
if len(runConf.PCIDevice) > 0 {
err = d.addPCIDevConfig(&conf, bus, runConf.PCIDevice)
if err != nil {
return nil, err
}
}
// Add USB devices.
for _, usbDev := range runConf.USBDevice {
monHook, err := d.addUSBDeviceConfig(usbDev)
if err != nil {
return nil, err
}
monHooks = append(monHooks, monHook)
}
// Add TPM device.
if len(runConf.TPMDevice) > 0 {
err = d.addTPMDeviceConfig(&conf, runConf.TPMDevice, fdFiles)
if err != nil {
return nil, err
}
}
}
// VM generation ID is only available on x86.
if d.architecture == osarch.ARCH_64BIT_INTEL_X86 {
err = d.addVmgenDeviceConfig(&conf, d.localConfig["volatile.uuid.generation"])
if err != nil {
return nil, err
}
}
// Allocate 8 PCI slots for hotplug devices.
for range 8 {
bus.allocate(busFunctionGroupNone)
}
if !d.isWindows() {
// Write the agent mount config.
agentMountJSON, err := json.Marshal(agentMounts)
if err != nil {
return nil, fmt.Errorf("Failed marshalling agent mounts to JSON: %w", err)
}
agentMountFile := filepath.Join(d.Path(), "config", "agent-mounts.json")
err = os.WriteFile(agentMountFile, agentMountJSON, 0o400)
if err != nil {
return nil, fmt.Errorf("Failed writing agent mounts file: %w", err)
}
}
// process any user-specified overrides
confOverride, ok := d.expandedConfig["raw.qemu.conf"]
if ok {
d.conf, err = qemuRawCfgOverride(conf, confOverride)
if err != nil {
return nil, err
}
} else {
d.conf = conf
}
return monHooks, nil
}
// writeQemuConfigFile writes the QEMU config file.
// It writes the config file inside the VM's log path.
func (d *qemu) writeQemuConfigFile(configPath string) error {
// Write the config file to disk.
sb := qemuStringifyCfg(d.conf...)
return os.WriteFile(configPath, []byte(sb.String()), 0o640)
}
// getCPUOpts retrieves configuration options for virtualized CPUs and memory.
func (d *qemu) getCPUOpts(cpuInfo *cpuTopology, memSizeBytes int64) (*qemuCPUOpts, error) {
// Figure out what memory object layout we're going to use.
// Before v6.0 or if version unknown, we use the "repeated" format, otherwise we use "indexed" format.
qemuMemObjectFormat := "repeated"
qemuVer6, _ := version.NewDottedVersion("6.0")
qemuVer, _ := d.version()
if qemuVer != nil && qemuVer.Compare(qemuVer6) >= 0 {
qemuMemObjectFormat = "indexed"
}
cpuOpts := qemuCPUOpts{
architecture: d.architectureName,
qemuMemObjectFormat: qemuMemObjectFormat,
}
hostNodes := []uint64{}
if cpuInfo.vcpus == nil {
// If not pinning, default to exposing cores.
// Only one CPU will be added here, as the others will be hotplugged during start.
if d.architectureSupportsCPUHotplug() {
cpuOpts.cpuCount = 1
cpuOpts.cpuCores = 1
// Expose the total requested by the user already so the hotplug limit can be set higher if needed.
cpuOpts.cpuRequested = cpuInfo.cores
} else {
cpuOpts.cpuCount = cpuInfo.cores
cpuOpts.cpuCores = cpuInfo.cores
}
cpuOpts.cpuSockets = 1
cpuOpts.cpuThreads = 1
hostNodes = []uint64{0}
// Handle NUMA restrictions.
numaNodes := d.expandedConfig["limits.cpu.nodes"]
if numaNodes != "" {
if numaNodes == "balanced" {
numaNodes = d.expandedConfig["volatile.cpu.nodes"]
}
// Parse the NUMA restriction.
numaNodeSet, err := resources.ParseNumaNodeSet(numaNodes)
if err != nil {
return nil, err
}
cpuOpts.memoryHostNodes = numaNodeSet
}
} else {
// Figure out socket-id/core-id/thread-id for all vcpus.
vcpuSocket := map[uint64]uint64{}
vcpuCore := map[uint64]uint64{}
vcpuThread := map[uint64]uint64{}
vcpu := uint64(0)
for i := range cpuInfo.sockets {
for j := range cpuInfo.cores {
for k := range cpuInfo.threads {
vcpuSocket[vcpu] = uint64(i)
vcpuCore[vcpu] = uint64(j)
vcpuThread[vcpu] = uint64(k)
vcpu++
}
}
}
// Prepare the NUMA map.
numa := []qemuNumaEntry{}
numaIDs := []uint64{}
numaNode := uint64(0)
for hostNode, entry := range cpuInfo.nodes {
hostNodes = append(hostNodes, hostNode)
numaIDs = append(numaIDs, numaNode)
for _, vcpu := range entry {
numa = append(numa, qemuNumaEntry{
node: numaNode,
socket: vcpuSocket[vcpu],
core: vcpuCore[vcpu],
thread: vcpuThread[vcpu],
})
}
numaNode++
}
// Prepare context.
cpuOpts.cpuCount = len(cpuInfo.vcpus)
cpuOpts.cpuSockets = cpuInfo.sockets
cpuOpts.cpuCores = cpuInfo.cores
cpuOpts.cpuThreads = cpuInfo.threads
cpuOpts.cpuNumaNodes = numaIDs
cpuOpts.cpuNumaMapping = numa
cpuOpts.cpuNumaHostNodes = hostNodes
}
cpuOpts.hugepages = ""
if util.IsTrue(d.expandedConfig["limits.memory.hugepages"]) {
hugetlb, err := localUtil.HugepagesPath()
if err != nil {
return nil, err
}
cpuOpts.hugepages = hugetlb
}
// Determine per-node memory limit.
memSizeMB := memSizeBytes / 1024 / 1024
nodeMemory := int64(memSizeMB / int64(len(hostNodes)))
cpuOpts.memory = nodeMemory
return &cpuOpts, nil
}
// addCPUMemoryConfig adds the qemu config required for setting the number of virtualised CPUs and memory.
// If sb is nil then no config is written.
func (d *qemu) addCPUMemoryConfig(conf *[]cfg.Section, cpuType string, cpuInfo *cpuTopology) error {
// Configure memory limit.
memSize := d.expandedConfig["limits.memory"]
if memSize == "" {
memSize = qemudefault.MemSize // Default if no memory limit specified.
}
memSizeBytes, err := ParseMemoryStr(memSize)
if err != nil {
return fmt.Errorf("limits.memory invalid: %w", err)
}
cpuOpts, err := d.getCPUOpts(cpuInfo, memSizeBytes)
if err != nil {
return err
}
cpuPinning := cpuInfo.vcpus != nil
// Set hotplug limits.
// kvm64 has a limit of 39 bits for aarch64 and 40 bits on x86_64, so just limit everyone to 39 bits (512GB).
// Other types we don't know so just don't allow hotplug.
var maxMemoryBytes int64
cpuPhysBits := uint64(39)
limitsMemoryHotplug := d.expandedConfig["limits.memory.hotplug"]
memoryHotplugEnabled := !util.IsFalse(limitsMemoryHotplug)
if (cpuType == "host" || cpuType == "kvm64") && memoryHotplugEnabled {
if !util.IsTrueOrEmpty(limitsMemoryHotplug) {
maxMemoryBytes, err = units.ParseByteSizeString(limitsMemoryHotplug)
if err != nil {
return err
}
if maxMemoryBytes < memSizeBytes {
return fmt.Errorf("'limits.memory.hotplug' value should be greater than or equal to 'limits.memory'")
}
}
if maxMemoryBytes == 0 {
// Attempt to get the CPU physical address space limits.
cpu, err := resources.GetCPU()
if err != nil {
return err
}
var lowestPhysBits uint64
for _, socket := range cpu.Sockets {
if socket.AddressSizes != nil && (socket.AddressSizes.PhysicalBits < lowestPhysBits || lowestPhysBits == 0) {
lowestPhysBits = socket.AddressSizes.PhysicalBits
}
}
// If a physical address size was detected, either align it with the VM (CPU passthrough) or use it as an upper bound.
if lowestPhysBits > 0 && (cpuType == "host" || lowestPhysBits < cpuPhysBits) {
cpuPhysBits = lowestPhysBits
}
// Reduce the maximum by one bit to allow QEMU some headroom.
cpuPhysBits--
// Calculate the max memory limit.
maxMemoryBytes = int64(math.Pow(2, float64(cpuPhysBits)))
// Cap to 1TB.
if maxMemoryBytes > 1024*1024*1024*1024 {
maxMemoryBytes = 1024 * 1024 * 1024 * 1024
}
// On standalone systems, further cap to the system's total memory.
if !d.state.ServerClustered {
totalMemory, err := linux.DeviceTotalMemory()
if err != nil {
return err
}
maxMemoryBytes = totalMemory
}
}
// Allow the user to go past any expected limit.
if maxMemoryBytes < memSizeBytes {
maxMemoryBytes = memSizeBytes
}
} else {
// Prevent memory hotplug.
maxMemoryBytes = memSizeBytes
}
if conf != nil {
*conf = append(*conf, qemuMemory(&qemuMemoryOpts{memSizeBytes / 1024 / 1024, maxMemoryBytes / 1024 / 1024})...)
*conf = append(*conf, qemuCPU(cpuOpts, cpuPinning)...)
}
return nil
}
// addFileDescriptor adds a file path to the list of files to open and pass file descriptor to qemu.
// Returns the file descriptor number that qemu will receive.
func (d *qemu) addFileDescriptor(fdFiles *[]*os.File, file *os.File) int {
// Append the tap device file path to the list of files to be opened and passed to qemu.
*fdFiles = append(*fdFiles, file)
return 2 + len(*fdFiles) // Use 2+fdFiles count, as first user file descriptor is 3.
}
// addRootDriveConfig adds the qemu config required for adding the root drive.
func (d *qemu) addRootDriveConfig(qemuDev map[string]any, mountInfo *storagePools.MountInfo, bootIndexes map[string]int, rootDriveConf deviceConfig.MountEntryItem) (monitorHook, error) {
if rootDriveConf.TargetPath != "/" {
return nil, errors.New("Non-root drive config supplied")
}
if !d.storagePool.Driver().Info().Remote && mountInfo.DiskPath == "" {
return nil, errors.New("No root disk path available from mount")
}
// Generate a new device config with the root device path expanded.
driveConf := deviceConfig.MountEntryItem{
DevName: rootDriveConf.DevName,
DevPath: mountInfo.DiskPath,
Opts: rootDriveConf.Opts,
TargetPath: rootDriveConf.TargetPath,
Limits: rootDriveConf.Limits,
Attached: true,
}
if d.storagePool.Driver().Info().Remote {
vol := d.storagePool.GetVolume(storageDrivers.VolumeTypeVM, storageDrivers.ContentTypeBlock, project.Instance(d.project.Name, d.name), nil)
if slices.Contains([]string{"ceph", "cephfs"}, d.storagePool.Driver().Info().Name) {
config := d.storagePool.ToAPI().Config
userName := config["ceph.user.name"]
if userName == "" {
userName = storageDrivers.CephDefaultUser
}
clusterName := config["ceph.cluster_name"]
if clusterName == "" {
clusterName = storageDrivers.CephDefaultUser
}
driveConf.DevPath = device.DiskGetRBDFormat(clusterName, userName, config["ceph.osd.pool_name"], vol.Name())
}
}
return d.addDriveConfig(qemuDev, bootIndexes, driveConf)
}
// driveDirConfig9p generates the qemu config required for adding a supplementary drive directory share using 9p.
func (d *qemu) driveDirConfig9p(qemuDev map[string]any, busName string, agentMounts *[]instancetype.VMAgentMount, driveConf deviceConfig.MountEntryItem) []cfg.Section {
mountTag := "incus_" + driveConf.DevName
agentMount := instancetype.VMAgentMount{
Source: mountTag,
Target: driveConf.TargetPath,
FSType: "9p",
// We need to specify to use the virtio transport to support more VM guest OSes.
// Also set the msize to 32MB to allow for reasonably fast 9p access.
Options: []string{"trans=virtio,msize=33554432"},
}
readonly := slices.Contains(driveConf.Opts, "ro")
// Indicate to agent to mount this readonly. Note: This is purely to indicate to VM guest that this is
// readonly, it should *not* be used as a security measure, as the VM guest could remount it R/W.
if readonly {
agentMount.Options = append(agentMount.Options, "ro")
}
// Record the mount for the agent.
*agentMounts = append(*agentMounts, agentMount)
// Add 9p share config.
driveDir9pOpts := qemuDriveDirOpts{
dev: qemuDevOpts{
busName: busName,
devBus: qemuDev["bus"].(string),
devAddr: qemuDev["addr"].(string),
multifunction: qemuDev["multifunction"].(bool),
},
devName: driveConf.DevName,
mountTag: mountTag,
readonly: readonly,
path: driveConf.DevPath,
protocol: "9p",
}
return qemuDriveDir(&driveDir9pOpts)
}
// addDriveDirConfigVirtiofs adds the qemu config required for adding a supplementary drive directory share using virtiofs.
func (d *qemu) addDriveDirConfigVirtiofs(qemuDev map[string]any, agentMounts *[]instancetype.VMAgentMount, driveConf deviceConfig.MountEntryItem) (monitorHook, error) {
escapedDeviceName := linux.PathNameEncode(driveConf.DevName)
deviceID := qemuDeviceIDPrefix + escapedDeviceName
mountTag := "incus_" + driveConf.DevName
if agentMounts != nil {
agentMount := instancetype.VMAgentMount{
Source: mountTag,
Target: driveConf.TargetPath,
FSType: "virtiofs",
}
// Indicate to agent to mount this readonly. Note: This is purely to indicate to VM guest that this is
// readonly, it should *not* be used as a security measure, as the VM guest could remount it R/W.
if slices.Contains(driveConf.Opts, "ro") {
agentMount.Options = append(agentMount.Options, "ro")
}
// Record the mount for the agent.
*agentMounts = append(*agentMounts, agentMount)
}
if qemuDev == nil {
qemuDev = map[string]any{}
}
qemuDev["driver"] = "vhost-user-fs-pci"
qemuDev["tag"] = mountTag
qemuDev["chardev"] = mountTag
qemuDev["id"] = deviceID
monHook := func(m *qmp.Monitor) error {
reverter := revert.New()
defer reverter.Fail()
// Detect virtiofsd path.
virtiofsdSockPath := filepath.Join(d.DevicesPath(), fmt.Sprintf("virtio-fs.%s.sock", driveConf.DevName))
if !util.PathExists(virtiofsdSockPath) {
return errors.New("Virtiofsd isn't running")
}
addr, err := net.ResolveUnixAddr("unix", virtiofsdSockPath)
if err != nil {
return err
}
virtiofsSock, err := net.DialUnix("unix", nil, addr)
if err != nil {
return fmt.Errorf("Error connecting to virtiofs socket %q: %w", virtiofsdSockPath, err)
}
defer func() { _ = virtiofsSock.Close() }() // Close file after device has been added.
virtiofsFile, err := virtiofsSock.File()
if err != nil {
return fmt.Errorf("Error opening virtiofs socket %q: %w", virtiofsdSockPath, err)
}
err = m.SendFile(virtiofsdSockPath, virtiofsFile)
if err != nil {
return fmt.Errorf("Failed to send virtiofs file descriptor: %w", err)
}
reverter.Add(func() { _ = m.CloseFile(virtiofsdSockPath) })
err = m.AddCharDevice(map[string]any{
"id": mountTag,
"backend": map[string]any{
"type": "socket",
"data": map[string]any{
"addr": map[string]any{
"type": "fd",
"data": map[string]any{
"str": virtiofsdSockPath,
},
},
"server": false,
},
},
})
if err != nil {
return fmt.Errorf("Failed to add the character device: %w", err)
}
reverter.Add(func() { _ = m.RemoveCharDevice(mountTag) })
_, ok := qemuDev["bus"]
if !ok {
// Try to get a PCI address for hotplugging.
pciDeviceName, err := d.getPCIHotplug()
if err != nil {
return err
}
d.logger.Debug("Using PCI bus device to hotplug virtiofs into", logger.Ctx{"device": driveConf.DevName, "port": pciDeviceName, "was": qemuDev["bus"]})
qemuDev["bus"] = pciDeviceName
qemuDev["addr"] = "00.0"
}
err = m.AddDevice(qemuDev)
if err != nil {
return fmt.Errorf("Failed to add the virtiofs device: %w", err)
}
reverter.Success()
return nil
}
return monHook, nil
}
// addDriveConfig adds the qemu config required for adding a supplementary drive.
func (d *qemu) addDriveConfig(qemuDev map[string]any, bootIndexes map[string]int, driveConf deviceConfig.MountEntryItem) (monitorHook, error) {
aioMode := "native" // Use native kernel async IO and O_DIRECT by default.
cacheMode := "none" // Bypass host cache, use O_DIRECT semantics by default.
media := "disk"
isRBDImage := strings.HasPrefix(driveConf.DevPath, device.RBDFormatPrefix)
// Check supported features.
// Use io_uring over native for added performance (if supported by QEMU and kernel is recent enough).
// We've seen issues starting VMs when running with io_ring AIO mode on kernels before 5.13.
info := DriverStatuses()[instancetype.VM].Info
minVer, _ := version.NewDottedVersion("5.13.0")
_, ioUring := info.Features["io_uring"]
if slices.Contains(driveConf.Opts, device.DiskIOUring) && ioUring && d.state.OS.KernelVersion.Compare(minVer) >= 0 {
aioMode = "io_uring"
}
var isBlockDev bool
// Detect device caches and I/O modes.
if isRBDImage {
// For RBD, we want writeback to allow for the system-configured "rbd cache" to take effect if present.
cacheMode = "writeback"
} else {
srcDevPath := driveConf.DevPath // This should not be used for passing to QEMU, only for probing.
// Detect if existing file descriptor format is being supplied.
if strings.HasPrefix(driveConf.DevPath, fmt.Sprintf("%s:", device.DiskFileDescriptorMountPrefix)) {
// Expect devPath in format "fd:<fdNum>:<devPath>".
devPathParts := strings.SplitN(driveConf.DevPath, ":", 3)
if len(devPathParts) != 3 || !strings.HasPrefix(driveConf.DevPath, fmt.Sprintf("%s:", device.DiskFileDescriptorMountPrefix)) {
return nil, fmt.Errorf("Unexpected devPath file descriptor format %q", driveConf.DevPath)
}
// Map the file descriptor to the file descriptor path it will be in the QEMU process.
fd, err := strconv.Atoi(devPathParts[1])
if err != nil {
return nil, fmt.Errorf("Invalid file descriptor %q: %w", devPathParts[1], err)
}
// Extract original dev path for additional probing below.
srcDevPath = devPathParts[2]
if srcDevPath == "" {
return nil, errors.New("Device source path is empty")
}
driveConf.DevPath = fmt.Sprintf("/proc/self/fd/%d", fd)
} else if driveConf.TargetPath != "/" {
// Only the root disk device is allowed to pass local devices to us without using an FD.
return nil, fmt.Errorf("Invalid device path format %q", driveConf.DevPath)
}
srcDevPathInfo, err := os.Stat(srcDevPath)
if err != nil {
return nil, fmt.Errorf("Invalid source path %q: %w", srcDevPath, err)
}
isBlockDev = linux.IsBlockdev(srcDevPathInfo.Mode())
// Handle I/O mode configuration.
if !isBlockDev {
// Disk dev path is a file, check what the backing filesystem is.
fsType, err := linux.DetectFilesystem(srcDevPath)
if err != nil {
return nil, fmt.Errorf("Failed detecting filesystem type of %q: %w", srcDevPath, err)
}
// If backing FS is ZFS or BTRFS, avoid using direct I/O and use host page cache only.
// We've seen ZFS lock up and BTRFS checksum issues when using direct I/O on image files.
if fsType == "zfs" || fsType == "btrfs" {
aioMode = "threads"
cacheMode = "writeback" // Use host cache, with neither O_DSYNC nor O_DIRECT semantics.
} else {
// Use host cache, with neither O_DSYNC nor O_DIRECT semantics if filesystem
// doesn't support Direct I/O.
f, err := os.OpenFile(srcDevPath, unix.O_DIRECT|unix.O_RDONLY, 0)
if err != nil {
cacheMode = "writeback"
} else {
_ = f.Close() // Don't leak FD.
}
}
if cacheMode == "writeback" && driveConf.FSType != "iso9660" {
// Only warn about using writeback cache if the drive image is writable.
d.logger.Warn("Using writeback cache I/O", logger.Ctx{"device": driveConf.DevName, "devPath": srcDevPath, "fsType": fsType})
}
} else if !slices.Contains(driveConf.Opts, device.DiskDirectIO) {
// If drive config indicates we need to use unsafe I/O then use it.
d.logger.Warn("Using unsafe cache I/O", logger.Ctx{"device": driveConf.DevName, "devPath": srcDevPath})
aioMode = "threads"
cacheMode = "unsafe" // Use host cache, but ignore all sync requests from guest.
}
}
// Special case ISO images as cdroms.
if driveConf.FSType == "iso9660" {
media = "cdrom"
}
// Check if the user has overridden the bus.
bus := "virtio-scsi"
for _, opt := range driveConf.Opts {
if !strings.HasPrefix(opt, "bus=") {
continue
}
bus = strings.TrimPrefix(opt, "bus=")
break
}
// Check if the user has overridden the cache mode.
for _, opt := range driveConf.Opts {
if !strings.HasPrefix(opt, "cache=") {
continue
}
cacheMode = strings.TrimPrefix(opt, "cache=")
break
}
// Check if the user has overridden the WWN.
var wwn string
for _, opt := range driveConf.Opts {
if !strings.HasPrefix(opt, "wwn=") {
continue
}
wwn = strings.TrimPrefix(opt, "wwn=")
break
}
// QMP uses two separate values for the cache.
directCache := true // Bypass host cache, use O_DIRECT semantics by default.
noFlushCache := false // Don't ignore any flush requests for the device.
if cacheMode == "unsafe" {
aioMode = "threads"
directCache = false
noFlushCache = true
} else if cacheMode == "writeback" {
aioMode = "threads"
directCache = false
}
escapedDeviceName := linux.PathNameEncode(driveConf.DevName)
blockDev := map[string]any{
"aio": aioMode,
"cache": map[string]any{
"direct": directCache,
"no-flush": noFlushCache,
},
"discard": "unmap", // Forward as an unmap request. This is the same as `discard=on` in the qemu config file.
"driver": "file",
"node-name": d.blockNodeName(escapedDeviceName),
"read-only": false,
}
var rbdSecret string
// If driver is "file", QEMU requires the file to be a regular file.
// However, if the file is a character or block device, driver needs to be set to "host_device".
if isBlockDev {
blockDev["driver"] = "host_device"
} else if isRBDImage {
blockDev["driver"] = "rbd"
poolName, volName, opts, err := device.DiskParseRBDFormat(driveConf.DevPath)
if err != nil {
return nil, fmt.Errorf("Failed parsing rbd string: %w", err)
}
// Driver and pool name arguments can be ignored as CephGetRBDImageName doesn't need them.
volumeType := storageDrivers.VolumeTypeCustom
volumeName := project.StorageVolume(d.project.Name, volName)
// Handle different name for instance volumes.
if driveConf.TargetPath == "/" {
volumeType = storageDrivers.VolumeTypeVM
volumeName = volName
}
// Identify the right content type.
rbdContentType := storageDrivers.ContentTypeBlock
if driveConf.FSType == "iso9660" {
rbdContentType = storageDrivers.ContentTypeISO
}
// Get the RBD image name.
vol := storageDrivers.NewVolume(nil, "", volumeType, rbdContentType, volumeName, nil, nil)
rbdImageName := storageDrivers.CephGetRBDImageName(vol, "", false)
// Scan & pass through options.
clusterName := storageDrivers.CephDefaultCluster
userName := storageDrivers.CephDefaultUser
blockDev["pool"] = poolName
blockDev["image"] = rbdImageName
for key, val := range opts {
// We use 'id' where qemu uses 'user'.
if key == "id" {
blockDev["user"] = val
userName = val
} else if key == "cluster" {
clusterName = val
} else {
blockDev[key] = val
}
}
// Parse the secret (QEMU runs unprivileged and can't read the keyring directly).
rbdSecret, err = storageDrivers.CephKeyring(clusterName, userName)
if err != nil {
return nil, err
}
// The aio option isn't available when using the rbd driver.
delete(blockDev, "aio")
}
readonly := slices.Contains(driveConf.Opts, "ro")
if readonly {
blockDev["read-only"] = true
}
if !isRBDImage {
blockDev["locking"] = "off"
}
if qemuDev == nil {
qemuDev = map[string]any{}
}
qemuDev["id"] = fmt.Sprintf("%s%s", qemuDeviceIDPrefix, escapedDeviceName)
qemuDev["drive"] = blockDev["node-name"].(string)
qemuDev["serial"] = fmt.Sprintf("%s%s", qemuBlockDevIDPrefix, escapedDeviceName)
if wwn != "" {
wwnID, err := strconv.ParseUint(strings.TrimPrefix(wwn, "0x"), 16, 64)
if err != nil {
return nil, err
}
qemuDev["wwn"] = wwnID
}
if bus == "virtio-scsi" {
qemuDev["device_id"] = d.blockNodeName(escapedDeviceName)
qemuDev["channel"] = 0
qemuDev["lun"] = 1
qemuDev["bus"] = "qemu_scsi.0"
if media == "disk" {
qemuDev["driver"] = "scsi-hd"
} else if media == "cdrom" {
qemuDev["driver"] = "scsi-cd"
}
} else if slices.Contains([]string{"nvme", "virtio-blk"}, bus) {
if qemuDev["bus"] == nil {
// Try to get a PCI address for hotplugging.
pciDeviceName, err := d.getPCIHotplug()
if err != nil {
return nil, err
}
d.logger.Debug("Using PCI bus device to hotplug drive into", logger.Ctx{"device": driveConf.DevName, "port": pciDeviceName})
qemuDev["bus"] = pciDeviceName
qemuDev["addr"] = "00.0"
}
qemuDev["driver"] = bus
} else if bus == "usb" {
qemuDev["driver"] = "usb-storage"
qemuDev["bus"] = "qemu_usb.0"
}
if bootIndexes != nil {
qemuDev["bootindex"] = bootIndexes[driveConf.DevName]
}
monHook := func(m *qmp.Monitor) error {
reverter := revert.New()
defer reverter.Fail()
nodeName := d.blockNodeName(escapedDeviceName)
if isRBDImage {
secretID := fmt.Sprintf("pool_%s_%s", blockDev["pool"], blockDev["user"])
err := m.AddSecret(secretID, rbdSecret)
if err != nil {
return err
}
blockDev["key-secret"] = secretID
} else {
permissions := unix.O_RDWR
if readonly {
permissions = unix.O_RDONLY
}
if directCache {
permissions |= unix.O_DIRECT
}
f, err := os.OpenFile(driveConf.DevPath, permissions, 0)
if err != nil {
return fmt.Errorf("Failed opening file descriptor for disk device %q: %w", driveConf.DevName, err)
}
defer func() { _ = f.Close() }()
info, err := m.SendFileWithFDSet(nodeName, f, readonly)
if err != nil {
return fmt.Errorf("Failed sending file descriptor of %q for disk device %q: %w", f.Name(), driveConf.DevName, err)
}
reverter.Add(func() {
_ = m.RemoveFDFromFDSet(nodeName)
})
blockDev["filename"] = fmt.Sprintf("/dev/fdset/%d", info.ID)
}
err := m.AddBlockDevice(blockDev, qemuDev, driveConf.Attached)
if err != nil {
return fmt.Errorf("Failed adding block device for disk device %q: %w", driveConf.DevName, err)
}
if driveConf.Limits != nil {
err = m.SetBlockThrottle(qemuDev["id"].(string), int(driveConf.Limits.ReadBytes), int(driveConf.Limits.WriteBytes), int(driveConf.Limits.ReadIOps), int(driveConf.Limits.WriteIOps))
if err != nil {
return fmt.Errorf("Failed applying limits for disk device %q: %w", driveConf.DevName, err)
}
}
reverter.Success()
return nil
}
return monHook, nil
}
// addNetDevConfig adds the qemu config required for adding a network device.
// The qemuDev map is expected to be preconfigured with the settings for an existing port to use for the device.
func (d *qemu) addNetDevConfig(busName string, qemuDev map[string]any, bootIndexes map[string]int, nicConfig []deviceConfig.RunConfigItem) (monitorHook, error) {
reverter := revert.New()
defer reverter.Fail()
var devName, nicName, devHwaddr, pciSlotName, pciIOMMUGroup, vDPADevName, vhostVDPAPath, maxVQP string
for _, nicItem := range nicConfig {
if nicItem.Key == "devName" {
devName = nicItem.Value
} else if nicItem.Key == "link" {
nicName = nicItem.Value
} else if nicItem.Key == "hwaddr" {
devHwaddr = nicItem.Value
} else if nicItem.Key == "pciSlotName" {
pciSlotName = nicItem.Value
} else if nicItem.Key == "pciIOMMUGroup" {
pciIOMMUGroup = nicItem.Value
} else if nicItem.Key == "vDPADevName" {
vDPADevName = nicItem.Value
} else if nicItem.Key == "vhostVDPAPath" {
vhostVDPAPath = nicItem.Value
} else if nicItem.Key == "maxVQP" {
maxVQP = nicItem.Value
}
}
escapedDeviceName := linux.PathNameEncode(devName)
qemuDev["id"] = fmt.Sprintf("%s%s", qemuDeviceIDPrefix, escapedDeviceName)
if len(bootIndexes) > 0 {
bootIndex, found := bootIndexes[devName]
if found {
qemuDev["bootindex"] = bootIndex
}
}
var monHook func(m *qmp.Monitor) error
// configureQueues modifies qemuDev with the queue configuration based on vCPUs.
// Returns the number of queues to use with NIC.
configureQueues := func(cpuCount int) int {
// Number of queues is the same as number of vCPUs. Run with a minimum of two queues.
queueCount := max(cpuCount, 2)
// Number of vectors is number of vCPUs * 2 (RX/TX) + 2 (config/control MSI-X).
vectors := 2*queueCount + 2
if busName != "usb" {
qemuDev["mq"] = true
if slices.Contains([]string{"pcie", "pci"}, busName) {
qemuDev["vectors"] = vectors
}
}
return queueCount
}
// tapMonHook is a helper function used as the monitor hook for macvtap and tap interfaces to open
// multi-queue file handles to both the interface device and the vhost-net device and pass them to QEMU.
tapMonHook := func(deviceFile func() (*os.File, error)) func(m *qmp.Monitor) error {
return func(m *qmp.Monitor) error {
reverter := revert.New()
defer reverter.Fail()
cpus, err := m.QueryCPUs()
if err != nil {
return errors.New("Failed getting CPU list for NIC queues")
}
queueCount := configureQueues(len(cpus))
// Enable vhost_net offloading if available.
info := DriverStatuses()[instancetype.VM].Info
_, vhostNetEnabled := info.Features["vhost_net"]
// Open the device once for each queue and pass to QEMU.
fds := make([]string, 0, queueCount)
vhostfds := make([]string, 0, queueCount)
for i := range queueCount {
devFile, err := deviceFile()
if err != nil {
return fmt.Errorf("Error opening netdev file for queue %d: %w", i, err)
}
defer func() { _ = devFile.Close() }() // Close file after device has been added.
devFDName := fmt.Sprintf("%s.%d", devFile.Name(), i)
err = m.SendFile(devFDName, devFile)
if err != nil {
return fmt.Errorf("Failed to send %q file descriptor for queue %d: %w", devFDName, i, err)
}
reverter.Add(func() { _ = m.CloseFile(devFDName) })
fds = append(fds, devFDName)
if vhostNetEnabled {
// Open a vhost-net file handle for each device file handle.
vhostFile, err := os.OpenFile("/dev/vhost-net", os.O_RDWR, 0)
if err != nil {
return fmt.Errorf("Error opening /dev/vhost-net for queue %d: %w", i, err)
}
defer func() { _ = vhostFile.Close() }() // Close file after device has been added.
vhostFDName := fmt.Sprintf("%s.%d", vhostFile.Name(), i)
err = m.SendFile(vhostFDName, vhostFile)
if err != nil {
return fmt.Errorf("Failed to send %q file descriptor for queue %d: %w", vhostFDName, i, err)
}
reverter.Add(func() { _ = m.CloseFile(vhostFDName) })
vhostfds = append(vhostfds, vhostFDName)
}
}
qemuNetDev := map[string]any{
"id": fmt.Sprintf("%s%s", qemuNetDevIDPrefix, escapedDeviceName),
"type": "tap",
"vhost": vhostNetEnabled,
}
if slices.Contains([]string{"pcie", "pci"}, busName) {
qemuDev["driver"] = "virtio-net-pci"
} else if busName == "ccw" {
qemuDev["driver"] = "virtio-net-ccw"
} else if busName == "usb" {
qemuDev["driver"] = "usb-net"
}
qemuNetDev["fds"] = strings.Join(fds, ":")
if len(vhostfds) > 0 {
qemuNetDev["vhostfds"] = strings.Join(vhostfds, ":")
}
qemuDev["netdev"] = qemuNetDev["id"].(string)
qemuDev["mac"] = devHwaddr
err = m.AddNIC(qemuNetDev, qemuDev)
if err != nil {
return fmt.Errorf("Failed setting up device %q: %w", devName, err)
}
reverter.Success()
return nil
}
}
// Detect MACVTAP interface types and figure out which tap device is being used.
// This is so we can open a file handle to the tap device and pass it to the qemu process.
if util.PathExists(fmt.Sprintf("/sys/class/net/%s/macvtap", nicName)) {
content, err := os.ReadFile(fmt.Sprintf("/sys/class/net/%s/ifindex", nicName))
if err != nil {
return nil, fmt.Errorf("Error getting tap device ifindex: %w", err)
}
ifindex, err := strconv.Atoi(strings.TrimSpace(string(content)))
if err != nil {
return nil, fmt.Errorf("Error parsing tap device ifindex: %w", err)
}
devFile := func() (*os.File, error) {
return os.OpenFile(fmt.Sprintf("/dev/tap%d", ifindex), os.O_RDWR, 0)
}
monHook = tapMonHook(devFile)
} else if util.PathExists(fmt.Sprintf("/sys/class/net/%s/tun_flags", nicName)) {
// Detect TAP interface and use IOCTL TUNSETIFF on /dev/net/tun to get the file handle to it.
// This is so we can open a file handle to the tap device and pass it to the qemu process.
devFile := func() (*os.File, error) {
reverter := revert.New()
defer reverter.Fail()
f, err := os.OpenFile("/dev/net/tun", os.O_RDWR, 0)
if err != nil {
return nil, err
}
reverter.Add(func() { _ = f.Close() })
ifr, err := unix.NewIfreq(nicName)
if err != nil {
return nil, fmt.Errorf("Error creating new ifreq for %q: %w", nicName, err)
}
// These settings need to be compatible with what the device created the interface with
// and what QEMU is expecting.
ifr.SetUint16(unix.IFF_TAP | unix.IFF_NO_PI | unix.IFF_ONE_QUEUE | unix.IFF_MULTI_QUEUE | unix.IFF_VNET_HDR)
// Sets the file handle to point to the requested NIC interface.
err = unix.IoctlIfreq(int(f.Fd()), unix.TUNSETIFF, ifr)
if err != nil {
return nil, fmt.Errorf("Error getting TAP file handle for %q: %w", nicName, err)
}
reverter.Success()
return f, nil
}
monHook = tapMonHook(devFile)
} else if util.PathExists(vhostVDPAPath) {
monHook = func(m *qmp.Monitor) error {
reverter := revert.New()
defer reverter.Fail()
vdpaDevFile, err := os.OpenFile(vhostVDPAPath, os.O_RDWR, 0)
if err != nil {
return fmt.Errorf("Error opening vDPA device file %q: %w", vdpaDevFile.Name(), err)
}
defer func() { _ = vdpaDevFile.Close() }() // Close file after device has been added.
vDPADevFDName := fmt.Sprintf("%s.0", vdpaDevFile.Name())
err = m.SendFile(vDPADevFDName, vdpaDevFile)
if err != nil {
return fmt.Errorf("Failed to send %q file descriptor: %w", vDPADevFDName, err)
}
reverter.Add(func() { _ = m.CloseFile(vDPADevFDName) })
queues, err := strconv.Atoi(maxVQP)
if err != nil {
return fmt.Errorf("Failed to convert maxVQP (%q) to int: %w", maxVQP, err)
}
qemuNetDev := map[string]any{
"id": fmt.Sprintf("vhost-%s", vDPADevName),
"type": "vhost-vdpa",
"vhostfd": vDPADevFDName,
"queues": queues,
}
if slices.Contains([]string{"pcie", "pci"}, busName) {
qemuDev["driver"] = "virtio-net-pci"
} else if busName == "ccw" {
qemuDev["driver"] = "virtio-net-ccw"
} else if busName == "usb" {
qemuDev["driver"] = "usb-net"
}
qemuDev["netdev"] = qemuNetDev["id"].(string)
qemuDev["page-per-vq"] = true
qemuDev["iommu_platform"] = true
qemuDev["disable-legacy"] = true
err = m.AddNIC(qemuNetDev, qemuDev)
if err != nil {
return fmt.Errorf("Failed setting up device %q: %w", devName, err)
}
reverter.Success()
return nil
}
} else if pciSlotName != "" {
// Detect physical passthrough device.
if slices.Contains([]string{"pcie", "pci"}, busName) {
qemuDev["driver"] = "vfio-pci"
} else if busName == "ccw" {
qemuDev["driver"] = "vfio-ccw"
}
qemuDev["host"] = pciSlotName
if d.state.OS.UnprivUser != "" {
if pciIOMMUGroup == "" {
return nil, errors.New("No PCI IOMMU group supplied")
}
vfioGroupFile := fmt.Sprintf("/dev/vfio/%s", pciIOMMUGroup)
err := os.Chown(vfioGroupFile, int(d.state.OS.UnprivUID), -1)
if err != nil {
return nil, fmt.Errorf("Failed to chown vfio group device %q: %w", vfioGroupFile, err)
}
reverter.Add(func() { _ = os.Chown(vfioGroupFile, 0, -1) })
}
monHook = func(m *qmp.Monitor) error {
err := m.AddNIC(nil, qemuDev)
if err != nil {
return fmt.Errorf("Failed setting up device %q: %w", devName, err)
}
return nil
}
}
if monHook == nil {
return nil, errors.New("Unrecognised device type")
}
reverter.Success()
return monHook, nil
}
// writeNICDevConfig writes the NIC config for the specified device into the NICConfigDir.
// This will be used by the agent to rename the NIC interfaces inside the VM guest.
func (d *qemu) writeNICDevConfig(mtuStr string, devName string, nicName string, devHwaddr string) error {
// Parse MAC address to ensure it is in a canonical form (avoiding casing/presentation differences).
hw, err := net.ParseMAC(devHwaddr)
if err != nil {
return fmt.Errorf("Failed parsing MAC %q: %w", devHwaddr, err)
}
nicConfig := deviceConfig.NICConfig{
DeviceName: devName,
NICName: nicName,
MACAddress: hw.String(),
}
if mtuStr != "" {
mtuInt, err := strconv.ParseUint(mtuStr, 10, 32)
if err != nil {
return fmt.Errorf("Failed parsing MTU: %w", err)
}
nicConfig.MTU = uint32(mtuInt)
}
nicConfigBytes, err := json.Marshal(nicConfig)
if err != nil {
return fmt.Errorf("Failed encoding NIC config: %w", err)
}
nicFile := filepath.Join(d.Path(), "config", deviceConfig.NICConfigDir, fmt.Sprintf("%s.json", linux.PathNameEncode(nicConfig.DeviceName)))
err = os.WriteFile(nicFile, nicConfigBytes, 0o700)
if err != nil {
return fmt.Errorf("Failed writing NIC config: %w", err)
}
return nil
}
// addPCIDevConfig adds the qemu config required for adding a raw PCI device.
func (d *qemu) addPCIDevConfig(conf *[]cfg.Section, bus *qemuBus, pciConfig []deviceConfig.RunConfigItem) error {
var devName, pciSlotName string
for _, pciItem := range pciConfig {
if pciItem.Key == "devName" {
devName = pciItem.Value
} else if pciItem.Key == "pciSlotName" {
pciSlotName = pciItem.Value
}
}
devBus, devAddr, multi := bus.allocate(fmt.Sprintf("incus_%s", devName))
pciPhysicalOpts := qemuPCIPhysicalOpts{
dev: qemuDevOpts{
busName: bus.name,
devBus: devBus,
devAddr: devAddr,
multifunction: multi,
},
devName: devName,
pciSlotName: pciSlotName,
}
*conf = append(*conf, qemuPCIPhysical(&pciPhysicalOpts)...)
return nil
}
// addGPUDevConfig adds the qemu config required for adding a GPU device.
func (d *qemu) addGPUDevConfig(conf *[]cfg.Section, bus *qemuBus, gpuConfig []deviceConfig.RunConfigItem) error {
var devName, pciSlotName, vgpu string
for _, gpuItem := range gpuConfig {
if gpuItem.Key == "devName" {
devName = gpuItem.Value
} else if gpuItem.Key == "pciSlotName" {
pciSlotName = gpuItem.Value
} else if gpuItem.Key == "vgpu" {
vgpu = gpuItem.Value
}
}
vgaMode := func() bool {
// No VGA mode on mdev.
if vgpu != "" {
return false
}
// No VGA mode on non-x86.
if d.architecture != osarch.ARCH_64BIT_INTEL_X86 {
return false
}
// Only enable if present on the card.
if !util.PathExists(filepath.Join("/sys/bus/pci/devices", pciSlotName, "boot_vga")) {
return false
}
// Skip SRIOV VFs as those are shared with the host card.
if util.PathExists(filepath.Join("/sys/bus/pci/devices", pciSlotName, "physfn")) {
return false
}
return true
}()
devBus, devAddr, multi := bus.allocate(fmt.Sprintf("incus_%s", devName))
gpuDevPhysicalOpts := qemuGPUDevPhysicalOpts{
dev: qemuDevOpts{
busName: bus.name,
devBus: devBus,
devAddr: devAddr,
multifunction: multi,
},
devName: devName,
pciSlotName: pciSlotName,
vga: vgaMode,
vgpu: vgpu,
}
// Add main GPU device in VGA mode to qemu config.
*conf = append(*conf, qemuGPUDevPhysical(&gpuDevPhysicalOpts)...)
var iommuGroupPath string
if vgpu != "" {
iommuGroupPath = filepath.Join("/sys/bus/mdev/devices", vgpu, "iommu_group", "devices")
} else {
// Add any other related IOMMU VFs as generic PCI devices.
iommuGroupPath = filepath.Join("/sys/bus/pci/devices", pciSlotName, "iommu_group", "devices")
}
if util.PathExists(iommuGroupPath) {
// Extract parent slot name by removing any virtual function ID.
parts := strings.SplitN(pciSlotName, ".", 2)
prefix := parts[0]
// Iterate the members of the IOMMU group and override any that match the parent slot name prefix.
err := filepath.Walk(iommuGroupPath, func(path string, _ os.FileInfo, err error) error {
if err != nil {
return err
}
iommuSlotName := filepath.Base(path) // Virtual function's address is dir name.
// Match any VFs that are related to the GPU device (but not the GPU device itself).
if strings.HasPrefix(iommuSlotName, prefix) && iommuSlotName != pciSlotName {
// Add VF device without VGA mode to qemu config.
devBus, devAddr, multi := bus.allocate(fmt.Sprintf("incus_%s", devName))
gpuDevPhysicalOpts := qemuGPUDevPhysicalOpts{
dev: qemuDevOpts{
busName: bus.name,
devBus: devBus,
devAddr: devAddr,
multifunction: multi,
},
// Generate associated device name by combining main device name and VF ID.
devName: fmt.Sprintf("%s_%s", devName, devAddr),
pciSlotName: iommuSlotName,
vga: false,
vgpu: "",
}
*conf = append(*conf, qemuGPUDevPhysical(&gpuDevPhysicalOpts)...)
}
return nil
})
if err != nil {
return err
}
}
return nil
}
func (d *qemu) addUSBDeviceConfig(usbDev deviceConfig.USBDeviceItem) (monitorHook, error) {
qemuDev := map[string]any{
"id": fmt.Sprintf("%s%s", qemuDeviceIDPrefix, usbDev.DeviceName),
"driver": "usb-host",
"bus": "qemu_usb.0",
}
monHook := func(m *qmp.Monitor) error {
reverter := revert.New()
defer reverter.Fail()
f, err := os.OpenFile(usbDev.HostDevicePath, unix.O_RDWR, 0)
if err != nil {
return fmt.Errorf("Failed to open host device: %w", err)
}
defer func() { _ = f.Close() }()
info, err := m.SendFileWithFDSet(qemuDev["id"].(string), f, false)
if err != nil {
return fmt.Errorf("Failed to send file descriptor: %w", err)
}
reverter.Add(func() {
_ = m.RemoveFDFromFDSet(qemuDev["id"].(string))
})
qemuDev["hostdevice"] = fmt.Sprintf("/dev/fdset/%d", info.ID)
err = m.AddDevice(qemuDev)
if err != nil {
return fmt.Errorf("Failed to add device: %w", err)
}
reverter.Success()
return nil
}
return monHook, nil
}
func (d *qemu) addTPMDeviceConfig(conf *[]cfg.Section, tpmConfig []deviceConfig.RunConfigItem, fdFiles *[]*os.File) error {
var devName, socketPath string
for _, tpmItem := range tpmConfig {
if tpmItem.Key == "path" {
socketPath = tpmItem.Value
} else if tpmItem.Key == "devName" {
devName = tpmItem.Value
}
}
fd, err := unix.Open(socketPath, unix.O_PATH|unix.O_CLOEXEC, 0)
if err != nil {
return err
}
tpmFD := d.addFileDescriptor(fdFiles, os.NewFile(uintptr(fd), socketPath))
tpmDriver := "tpm-tis-device"
if d.architecture == osarch.ARCH_64BIT_INTEL_X86 {
tpmDriver = "tpm-crb"
}
tpmOpts := qemuTPMOpts{
devName: devName,
path: fmt.Sprintf("/proc/self/fd/%d", tpmFD),
driver: tpmDriver,
}
*conf = append(*conf, qemuTPM(&tpmOpts)...)
return nil
}
func (d *qemu) addVmgenDeviceConfig(conf *[]cfg.Section, guid string) error {
vmgenIDOpts := qemuVmgenIDOpts{
guid: guid,
}
*conf = append(*conf, qemuVmgen(&vmgenIDOpts)...)
return nil
}
// pidFilePath returns the path where the qemu process should write its PID.
func (d *qemu) pidFilePath() string {
return filepath.Join(d.RunPath(), "qemu.pid")
}
// pid gets the PID of the running qemu process. Returns 0 if PID file or process not found, and -1 if err non-nil.
func (d *qemu) pid() (int, error) {
pidStr, err := os.ReadFile(d.pidFilePath())
if errors.Is(err, fs.ErrNotExist) {
return 0, nil // PID file has gone.
}
if err != nil {
return -1, err
}
pid, err := strconv.Atoi(strings.TrimSpace(string(pidStr)))
if err != nil {
return -1, err
}
cmdLineProcFilePath := fmt.Sprintf("/proc/%d/cmdline", pid)
cmdLine, err := os.ReadFile(cmdLineProcFilePath)
if err != nil {
return 0, nil // Process has gone.
}
qemuSearchString := []byte("qemu-system")
instUUID := []byte(d.localConfig["volatile.uuid"])
if !bytes.Contains(cmdLine, qemuSearchString) || !bytes.Contains(cmdLine, instUUID) {
return -1, errors.New("PID doesn't match the running process")
}
return pid, nil
}
// forceStop kills the QEMU prorcess if running.
func (d *qemu) forceStop() error {
pid, _ := d.pid()
if pid > 0 {
err := d.killQemuProcess(pid)
if err != nil {
return fmt.Errorf("Failed to stop VM process %d: %w", pid, err)
}
}
return nil
}
// Stop the VM.
func (d *qemu) Stop(stateful bool) error {
d.logger.Debug("Stop started", logger.Ctx{"stateful": stateful})
defer d.logger.Debug("Stop finished", logger.Ctx{"stateful": stateful})
// Must be run prior to creating the operation lock.
// Allow to proceed if statusCode is Error or Frozen as we may need to forcefully kill the QEMU process.
// Also Stop() is called from migrateSendLive in some cases, and instance status will be Frozen then.
statusCode := d.statusCode()
if !d.isRunningStatusCode(statusCode) && statusCode != api.Error && statusCode != api.Frozen {
return ErrInstanceIsStopped
}
// Check for stateful.
if stateful {
// Confirm the instance has stateful migration enabled.
if !d.CanLiveMigrate() {
return errors.New("Stateful stop requires migration.stateful to be set to true")
}
// Confirm the instance has sufficient reserved state space.
err := d.checkStateStorage()
if err != nil {
return err
}
}
// Attempt to save the console log from ring buffer before the instance is stopped. Must be run prior to creating the operation lock.
_, _ = d.ConsoleLog()
// Setup a new operation.
// Allow inheriting of ongoing restart or restore operation (we are called from restartCommon and Restore).
// Don't allow reuse when creating a new stop operation. This prevents other operations from interfering.
// Allow reuse of a reusable ongoing stop operation as Shutdown() may be called first, which allows reuse
// of its operations. This allow for Stop() to inherit from Shutdown() where instance is stuck.
op, err := operationlock.CreateWaitGet(d.Project().Name, d.Name(), d.op, operationlock.ActionStop, []operationlock.Action{operationlock.ActionRestart, operationlock.ActionRestore, operationlock.ActionMigrate}, false, true)
if err != nil {
if errors.Is(err, operationlock.ErrNonReusuableSucceeded) {
// An existing matching operation has now succeeded, return.
return nil
}
return err
}
// Connect to the monitor.
monitor, err := d.qmpConnect()
if err != nil {
d.logger.Warn("Failed connecting to monitor, forcing stop", logger.Ctx{"err": err})
// If we fail to connect, it's most likely because the VM is already off, but it could also be
// because the qemu process is not responding, check if process still exists and kill it if needed.
err = d.forceStop()
if err != nil {
op.Done(err)
return err
}
// Wait for QEMU process to exit and perform device cleanup.
err = d.onStop("stop")
if err != nil {
op.Done(err)
return err
}
op.Done(nil)
return nil
}
// Handle stateful stop.
if stateful {
// Dump the state.
err = d.saveState(monitor)
if err != nil {
op.Done(err)
return err
}
d.stateful = true
err = d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.UpdateInstanceStatefulFlag(ctx, d.id, true)
})
if err != nil {
op.Done(err)
return err
}
}
// Get the wait channel.
chDisconnect, err := monitor.Wait()
if err != nil {
d.logger.Warn("Failed getting monitor disconnection channel, forcing stop", logger.Ctx{"err": err})
err = d.forceStop()
if err != nil {
op.Done(err)
return err
}
} else {
// Request the VM stop immediately.
err = monitor.Quit()
if err != nil {
d.logger.Warn("Failed sending monitor quit command, forcing stop", logger.Ctx{"err": err})
err = d.forceStop()
if err != nil {
op.Done(err)
return err
}
}
// Wait for QEMU to exit (can take a while if pending I/O).
// As this is a forceful stop of the VM we don't wait as long as during a clean shutdown because
// the QEMU process may be not responding correctly.
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
defer cancel()
select {
case <-chDisconnect:
case <-ctx.Done():
d.logger.Warn("Timed out waiting for monitor to disconnect, forcing stop")
err = d.forceStop()
if err != nil {
op.Done(err)
return err
}
}
}
// Wait for operation lock to be Done. This is normally completed by onStop which picks up the same
// operation lock and then marks it as Done after the instance stops and the devices have been cleaned up.
// However if the operation has failed for another reason we will collect the error here.
err = op.Wait(context.Background())
status := d.statusCode()
if status != api.Stopped {
errPrefix := fmt.Errorf("Failed stopping instance, status is %q", status)
if err != nil {
return fmt.Errorf("%s: %w", errPrefix.Error(), err)
}
return errPrefix
}
// Now handle errors from stop sequence and return to caller if wasn't completed cleanly.
if err != nil {
return err
}
return nil
}
// Unfreeze restores the instance to running.
func (d *qemu) Unfreeze() error {
// Connect to the monitor.
monitor, err := d.qmpConnect()
if err != nil {
return err
}
// Send the cont command.
err = monitor.Start()
if err != nil {
return err
}
d.state.Events.SendLifecycle(d.project.Name, lifecycle.InstanceResumed.Event(d, nil))
return nil
}
// IsPrivileged does not apply to virtual machines. Always returns false.
func (d *qemu) IsPrivileged() bool {
return false
}
// snapshot creates a snapshot of the instance.
func (d *qemu) snapshot(name string, expiry time.Time, stateful bool) error {
var err error
var monitor *qmp.Monitor
// Deal with state.
if stateful {
// Confirm the instance has stateful migration enabled.
if !d.CanLiveMigrate() {
return errors.New("Stateful snapshot requires migration.stateful to be set to true")
}
// Confirm the instance has sufficient reserved state space.
err = d.checkStateStorage()
if err != nil {
return err
}
// Quick checks.
if !d.IsRunning() {
return errors.New("Unable to create a stateful snapshot. The instance isn't running")
}
// Connect to the monitor.
monitor, err = d.qmpConnect()
if err != nil {
return err
}
// Dump the state.
err = d.saveState(monitor)
if err != nil {
return err
}
}
// Create the snapshot.
err = d.snapshotCommon(d, name, expiry, stateful)
if err != nil {
return err
}
// Resume the VM once the disk state has been saved.
if stateful {
// Remove the state from the main volume.
err = os.Remove(d.StatePath())
if err != nil {
return err
}
err = monitor.Start()
if err != nil {
return err
}
}
return nil
}
// Snapshot takes a new snapshot.
func (d *qemu) Snapshot(name string, expiry time.Time, stateful bool) error {
return d.snapshot(name, expiry, stateful)
}
// Restore restores an instance snapshot.
func (d *qemu) Restore(source instance.Instance, stateful bool) error {
op, err := operationlock.Create(d.Project().Name, d.Name(), d.op, operationlock.ActionRestore, false, false)
if err != nil {
return fmt.Errorf("Failed to create instance restore operation: %w", err)
}
defer op.Done(nil)
var ctxMap logger.Ctx
// Stop the instance.
wasRunning := false
if d.IsRunning() {
wasRunning = true
ephemeral := d.IsEphemeral()
if ephemeral {
// Unset ephemeral flag.
args := db.InstanceArgs{
Architecture: d.Architecture(),
Config: d.LocalConfig(),
Description: d.Description(),
Devices: d.LocalDevices(),
Ephemeral: false,
Profiles: d.Profiles(),
Project: d.Project().Name,
Type: d.Type(),
Snapshot: d.IsSnapshot(),
}
err := d.Update(args, false)
if err != nil {
op.Done(err)
return err
}
// On function return, set the flag back on.
defer func() {
args.Ephemeral = ephemeral
_ = d.Update(args, false)
}()
}
// This will unmount the instance storage.
err := d.Stop(false)
if err != nil {
op.Done(err)
return err
}
// Refresh the operation as that one is now complete.
op, err = operationlock.Create(d.Project().Name, d.Name(), d.op, operationlock.ActionRestore, false, false)
if err != nil {
return fmt.Errorf("Failed to create instance restore operation: %w", err)
}
defer op.Done(nil)
}
ctxMap = logger.Ctx{
"created": d.creationDate,
"ephemeral": d.ephemeral,
"used": d.lastUsedDate,
"source": source.Name(),
}
d.logger.Info("Restoring instance", ctxMap)
// Load the storage driver.
pool, err := storagePools.LoadByInstance(d.state, d)
if err != nil {
op.Done(err)
return err
}
// Restore the rootfs.
err = pool.RestoreInstanceSnapshot(d, source, nil)
if err != nil {
op.Done(err)
return err
}
// Restore the configuration.
args := db.InstanceArgs{
Architecture: source.Architecture(),
Config: source.LocalConfig(),
Description: source.Description(),
Devices: source.LocalDevices(),
Ephemeral: source.IsEphemeral(),
Profiles: source.Profiles(),
Project: source.Project().Name,
Type: source.Type(),
Snapshot: source.IsSnapshot(),
}
// Don't pass as user-requested as there's no way to fix a bad config.
// This will call d.UpdateBackupFile() to ensure snapshot list is up to date.
err = d.Update(args, false)
if err != nil {
op.Done(err)
return err
}
d.stateful = stateful
// Restart the instance.
if wasRunning || stateful {
d.logger.Debug("Starting instance after snapshot restore")
err := d.Start(stateful)
if err != nil {
op.Done(err)
return err
}
}
d.state.Events.SendLifecycle(d.project.Name, lifecycle.InstanceRestored.Event(d, map[string]any{"snapshot": source.Name()}))
d.logger.Info("Restored instance", ctxMap)
return nil
}
// Rename the instance. Accepts an argument to enable applying deferred TemplateTriggerRename.
func (d *qemu) Rename(newName string, applyTemplateTrigger bool) error {
oldName := d.Name()
ctxMap := logger.Ctx{
"created": d.creationDate,
"ephemeral": d.ephemeral,
"used": d.lastUsedDate,
"newname": newName,
}
d.logger.Info("Renaming instance", ctxMap)
// Quick checks.
err := instance.ValidName(newName, d.IsSnapshot())
if err != nil {
return err
}
if d.IsRunning() {
return errors.New("Renaming of running instance not allowed")
}
// Clean things up.
d.cleanup()
pool, err := storagePools.LoadByInstance(d.state, d)
if err != nil {
return fmt.Errorf("Failed loading instance storage pool: %w", err)
}
if d.IsSnapshot() {
_, newSnapName, _ := api.GetParentAndSnapshotName(newName)
err = pool.RenameInstanceSnapshot(d, newSnapName, nil)
if err != nil {
return fmt.Errorf("Rename instance snapshot: %w", err)
}
} else {
err = pool.RenameInstance(d, newName, nil)
if err != nil {
return fmt.Errorf("Rename instance: %w", err)
}
if applyTemplateTrigger {
err = d.DeferTemplateApply(instance.TemplateTriggerRename)
if err != nil {
return err
}
}
}
if !d.IsSnapshot() {
var results []string
err := d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
var err error
// Rename all the instance snapshot database entries.
results, err = tx.GetInstanceSnapshotsNames(ctx, d.project.Name, oldName)
if err != nil {
d.logger.Error("Failed to get instance snapshots", ctxMap)
return fmt.Errorf("Failed to get instance snapshots: Failed getting instance snapshot names: %w", err)
}
for _, sname := range results {
// Rename the snapshot.
oldSnapName := strings.SplitN(sname, internalInstance.SnapshotDelimiter, 2)[1]
baseSnapName := filepath.Base(sname)
err := dbCluster.RenameInstanceSnapshot(ctx, tx.Tx(), d.project.Name, oldName, oldSnapName, baseSnapName)
if err != nil {
d.logger.Error("Failed renaming snapshot", ctxMap)
return err
}
}
return nil
})
if err != nil {
return err
}
}
// Rename the instance database entry.
err = d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
if d.IsSnapshot() {
oldParts := strings.SplitN(oldName, internalInstance.SnapshotDelimiter, 2)
newParts := strings.SplitN(newName, internalInstance.SnapshotDelimiter, 2)
return dbCluster.RenameInstanceSnapshot(ctx, tx.Tx(), d.project.Name, oldParts[0], oldParts[1], newParts[1])
}
return dbCluster.RenameInstance(ctx, tx.Tx(), d.project.Name, oldName, newName)
})
if err != nil {
d.logger.Error("Failed renaming instance", ctxMap)
return err
}
// Rename the logging path.
newFullName := project.Instance(d.Project().Name, d.Name())
_ = os.RemoveAll(internalUtil.LogPath(newFullName))
if util.PathExists(d.LogPath()) {
err := os.Rename(d.LogPath(), internalUtil.LogPath(newFullName))
if err != nil {
d.logger.Error("Failed renaming instance", ctxMap)
return err
}
}
// Rename the runtime path.
newFullName = project.Instance(d.Project().Name, d.Name())
_ = os.RemoveAll(internalUtil.RunPath(newFullName))
if util.PathExists(d.RunPath()) {
err := os.Rename(d.RunPath(), internalUtil.RunPath(newFullName))
if err != nil {
d.logger.Error("Failed renaming instance", ctxMap)
return err
}
}
reverter := revert.New()
defer reverter.Fail()
// Set the new name in the struct.
d.name = newName
reverter.Add(func() { d.name = oldName })
// Rename the backups.
backups, err := d.Backups()
if err != nil {
return err
}
for _, backup := range backups {
b := backup
oldName := b.Name()
backupName := strings.Split(oldName, "/")[1]
newName := fmt.Sprintf("%s/%s", newName, backupName)
err = b.Rename(newName)
if err != nil {
return err
}
reverter.Add(func() { _ = b.Rename(oldName) })
}
// Update lease files.
err = network.UpdateDNSMasqStatic(d.state, "")
if err != nil {
return err
}
// Reset cloud-init instance-id (causes a re-run on name changes).
if !d.IsSnapshot() {
err = d.resetInstanceID()
if err != nil {
return err
}
}
// Update the backup file.
err = d.UpdateBackupFile()
if err != nil {
return err
}
d.logger.Info("Renamed instance", ctxMap)
if d.isSnapshot {
d.state.Events.SendLifecycle(d.project.Name, lifecycle.InstanceSnapshotRenamed.Event(d, map[string]any{"old_name": oldName}))
} else {
err = d.state.Authorizer.RenameInstance(d.state.ShutdownCtx, d.project.Name, oldName, newName)
if err != nil {
logger.Error("Failed to rename instance in authorizer", logger.Ctx{"old_name": oldName, "new_name": newName, "project": d.project.Name, "error": err})
}
d.state.Events.SendLifecycle(d.project.Name, lifecycle.InstanceRenamed.Event(d, map[string]any{"old_name": oldName}))
}
reverter.Success()
return nil
}
// Indirection to detachDisk.
func qemuDetachDisk(s *state.State, id int) func(string) error {
return func(name string) error {
inst, err := instance.LoadByID(s, id)
if err != nil {
return err
}
qemuInst, ok := inst.(*qemu)
if !ok {
return fmt.Errorf("Couldn't assert QEMU object from interface")
}
return qemuInst.detachDisk(name)
}
}
// Detach a disk from the instance.
func (d *qemu) detachDisk(name string) error {
diskName := strings.TrimPrefix(name, qemuDeviceIDPrefix)
// Load and detach the disk.
config, ok := d.expandedDevices[diskName]
if !ok {
return fmt.Errorf("Couldn't find device %s", diskName)
}
dev, err := d.deviceLoad(d, diskName, config)
if err != nil {
return err
}
err = d.deviceStop(dev, true, "")
if err != nil {
return err
}
// Check if it's a special device (we don't store detached state on those).
if slices.Contains([]string{"agent:config", "cloud-init:config"}, config["source"]) {
return nil
}
// Find the disk device.
_, ok = d.localDevices[diskName]
if !ok {
// Device came from a profile, we can't save its state.
return nil
}
d.localDevices[diskName]["attached"] = "false"
return d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
devices, err := dbCluster.APIToDevices(d.localDevices.CloneNative())
if err != nil {
return err
}
return dbCluster.UpdateInstanceDevices(ctx, tx.Tx(), int64(d.id), devices)
})
}
// Update the instance config.
func (d *qemu) Update(args db.InstanceArgs, userRequested bool) error {
// Setup a new operation.
op, err := operationlock.CreateWaitGet(d.Project().Name, d.Name(), d.op, operationlock.ActionUpdate, []operationlock.Action{operationlock.ActionRestart, operationlock.ActionRestore}, false, false)
if err != nil {
return fmt.Errorf("Failed to create instance update operation: %w", err)
}
defer op.Done(nil)
// Setup the reverter.
reverter := revert.New()
defer reverter.Fail()
// Set sane defaults for unset keys.
if args.Project == "" {
args.Project = api.ProjectDefaultName
}
if args.Architecture == 0 {
args.Architecture = d.architecture
}
if args.Config == nil {
args.Config = map[string]string{}
}
if args.Devices == nil {
args.Devices = deviceConfig.Devices{}
}
if args.Profiles == nil {
args.Profiles = []api.Profile{}
}
if userRequested {
// Validate the new config.
err := instance.ValidConfig(d.state.OS, args.Config, false, d.dbType)
if err != nil {
return fmt.Errorf("Invalid config: %w", err)
}
// Validate the new devices without using expanded devices validation (expensive checks disabled).
err = instance.ValidDevices(d.state, d.project, d.Type(), args.Devices, nil)
if err != nil {
return fmt.Errorf("Invalid devices: %w", err)
}
}
var profiles []string
err = d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Validate the new profiles.
profiles, err = tx.GetProfileNames(ctx, args.Project)
return err
})
if err != nil {
return fmt.Errorf("Failed to get profiles: %w", err)
}
checkedProfiles := []string{}
for _, profile := range args.Profiles {
if !slices.Contains(profiles, profile.Name) {
return fmt.Errorf("Requested profile '%s' doesn't exist", profile.Name)
}
if slices.Contains(checkedProfiles, profile.Name) {
return errors.New("Duplicate profile found in request")
}
checkedProfiles = append(checkedProfiles, profile.Name)
}
// Validate the new architecture.
if args.Architecture != 0 {
_, err = osarch.ArchitectureName(args.Architecture)
if err != nil {
return fmt.Errorf("Invalid architecture ID: %s", err)
}
}
// Get a copy of the old configuration.
oldDescription := d.Description()
oldArchitecture := 0
err = util.DeepCopy(&d.architecture, &oldArchitecture)
if err != nil {
return err
}
oldEphemeral := false
err = util.DeepCopy(&d.ephemeral, &oldEphemeral)
if err != nil {
return err
}
oldExpandedDevices := deviceConfig.Devices{}
err = util.DeepCopy(&d.expandedDevices, &oldExpandedDevices)
if err != nil {
return err
}
oldExpandedConfig := map[string]string{}
err = util.DeepCopy(&d.expandedConfig, &oldExpandedConfig)
if err != nil {
return err
}
oldLocalDevices := deviceConfig.Devices{}
err = util.DeepCopy(&d.localDevices, &oldLocalDevices)
if err != nil {
return err
}
oldLocalConfig := map[string]string{}
err = util.DeepCopy(&d.localConfig, &oldLocalConfig)
if err != nil {
return err
}
oldProfiles := []api.Profile{}
err = util.DeepCopy(&d.profiles, &oldProfiles)
if err != nil {
return err
}
oldExpiryDate := d.expiryDate
// Revert local changes if update fails.
reverter.Add(func() {
d.description = oldDescription
d.architecture = oldArchitecture
d.ephemeral = oldEphemeral
d.expandedConfig = oldExpandedConfig
d.expandedDevices = oldExpandedDevices
d.localConfig = oldLocalConfig
d.localDevices = oldLocalDevices
d.profiles = oldProfiles
d.expiryDate = oldExpiryDate
})
// Apply the various changes to local vars.
d.description = args.Description
d.architecture = args.Architecture
d.ephemeral = args.Ephemeral
d.localConfig = args.Config
d.localDevices = args.Devices
d.profiles = args.Profiles
d.expiryDate = args.ExpiryDate
// Expand the config.
err = d.expandConfig()
if err != nil {
return err
}
// Diff the configurations.
changedConfig := []string{}
for key := range oldExpandedConfig {
if oldExpandedConfig[key] != d.expandedConfig[key] {
if !slices.Contains(changedConfig, key) {
changedConfig = append(changedConfig, key)
}
}
}
for key := range d.expandedConfig {
if oldExpandedConfig[key] != d.expandedConfig[key] {
if !slices.Contains(changedConfig, key) {
changedConfig = append(changedConfig, key)
}
}
}
// Diff the devices.
removeDevices, addDevices, updateDevices, allUpdatedKeys := oldExpandedDevices.Update(d.expandedDevices, func(oldDevice deviceConfig.Device, newDevice deviceConfig.Device) []string {
// This function needs to return a list of fields that are excluded from differences
// between oldDevice and newDevice. The result of this is that as long as the
// devices are otherwise identical except for the fields returned here, then the
// device is considered to be being "updated" rather than "added & removed".
oldDevType, err := device.LoadByType(d.state, d.Project().Name, oldDevice)
if err != nil {
return []string{} // Couldn't create Device, so this cannot be an update.
}
newDevType, err := device.LoadByType(d.state, d.Project().Name, newDevice)
if err != nil {
return []string{} // Couldn't create Device, so this cannot be an update.
}
return newDevType.UpdatableFields(oldDevType)
})
// Prevent adding or updating device initial configuration.
if util.StringPrefixInSlice("initial.", allUpdatedKeys) {
for devName, newDev := range addDevices {
for k, newVal := range newDev {
if !strings.HasPrefix(k, "initial.") {
continue
}
oldDev, ok := removeDevices[devName]
if !ok {
return errors.New("New device with initial configuration cannot be added once the instance is created")
}
oldVal, ok := oldDev[k]
if !ok {
return errors.New("Device initial configuration cannot be added once the instance is created")
}
// If newVal is an empty string it means the initial configuration
// has been removed.
if newVal != "" && newVal != oldVal {
return errors.New("Device initial configuration cannot be modified once the instance is created")
}
}
}
}
if userRequested {
// Do some validation of the config diff (allows mixed instance types for profiles).
err = instance.ValidConfig(d.state.OS, d.expandedConfig, true, instancetype.Any)
if err != nil {
return fmt.Errorf("Invalid expanded config: %w", err)
}
// Do full expanded validation of the devices diff.
err = instance.ValidDevices(d.state, d.project, d.Type(), d.localDevices, d.expandedDevices)
if err != nil {
return fmt.Errorf("Invalid expanded devices: %w", err)
}
// Validate root device
_, oldRootDev, oldErr := internalInstance.GetRootDiskDevice(oldExpandedDevices.CloneNative())
_, newRootDev, newErr := internalInstance.GetRootDiskDevice(d.expandedDevices.CloneNative())
if oldErr == nil && newErr == nil && oldRootDev["pool"] != newRootDev["pool"] {
return fmt.Errorf("Cannot update root disk device pool name to %q", newRootDev["pool"])
}
// Ensure the instance has a root disk.
if newErr != nil {
return fmt.Errorf("Invalid root disk device: %w", newErr)
}
}
// If apparmor changed, re-validate the apparmor profile (even if not running).
if slices.Contains(changedConfig, "raw.apparmor") {
qemuPath, _, err := d.qemuArchConfig(d.architecture)
if err != nil {
return err
}
err = apparmor.InstanceValidate(d.state.OS, d, []string{qemuPath})
if err != nil {
return fmt.Errorf("Parse AppArmor profile: %w", err)
}
}
isRunning := d.IsRunning()
// Use the device interface to apply update changes.
err = d.devicesUpdate(d, removeDevices, addDevices, updateDevices, oldExpandedDevices, isRunning, userRequested)
if err != nil {
return err
}
if isRunning {
// Only certain keys can be changed on a running VM.
liveUpdateKeys := []string{
"cluster.evacuate",
"limits.memory",
"security.agent.metrics",
"security.csm",
"security.protection.delete",
"security.guestapi",
"security.secureboot",
}
liveUpdateKeyPrefixes := []string{
"boot.",
"cloud-init.",
"environment.",
"image.",
"snapshots.",
"user.",
"volatile.",
}
isLiveUpdatable := func(key string) bool {
// Skip container config keys for VMs
_, ok := internalInstance.InstanceConfigKeysContainer[key]
if ok {
return true
}
if key == "limits.cpu" {
return d.architectureSupportsCPUHotplug()
}
if slices.Contains(liveUpdateKeys, key) {
return true
}
if util.StringHasPrefix(key, liveUpdateKeyPrefixes...) {
return true
}
return false
}
// Check only keys that support live update have changed.
for _, key := range changedConfig {
if !isLiveUpdatable(key) {
return fmt.Errorf("Key %q cannot be updated when VM is running", key)
}
}
// Apply live update for each key.
for _, key := range changedConfig {
value := d.expandedConfig[key]
if key == "limits.cpu" {
oldValue := oldExpandedConfig["limits.cpu"]
if oldValue != "" {
_, err := strconv.Atoi(oldValue)
if err != nil {
return fmt.Errorf("Cannot update key %q when using CPU pinning and the VM is running", key)
}
}
// If the key is being unset, set it to default value.
if value == "" {
value = "1"
}
limit, err := strconv.Atoi(value)
if err != nil {
return errors.New("Cannot change CPU pinning when VM is running")
}
// Hotplug the CPUs.
err = d.setCPUs(nil, limit)
if err != nil {
return fmt.Errorf("Failed updating cpu limit: %w", err)
}
} else if key == "limits.memory" {
err = d.updateMemoryLimit(value)
if err != nil {
if err != nil {
return fmt.Errorf("Failed updating memory limit: %w", err)
}
}
} else if key == "security.csm" {
// Defer rebuilding nvram until next start.
d.localConfig["volatile.apply_nvram"] = "true"
} else if key == "security.secureboot" {
// Defer rebuilding nvram until next start.
d.localConfig["volatile.apply_nvram"] = "true"
} else if key == "security.guestapi" {
err = d.advertiseVsockAddress()
if err != nil {
return err
}
}
}
}
// Clear the "volatile.cpu.nodes" if needed.
d.ClearLimitsCPUNodes(changedConfig)
if d.architectureSupportsUEFI(d.architecture) && (slices.Contains(changedConfig, "security.secureboot") || slices.Contains(changedConfig, "security.csm")) {
// setupNvram() requires instance's config volume to be mounted.
// The easiest way to detect that is to check if instance is running.
// TODO: extend storage API to be able to check if volume is already mounted?
if !isRunning {
// Mount the instance's config volume.
_, err := d.mount()
if err != nil {
return err
}
defer func() { _ = d.unmount() }()
}
// Re-generate the NVRAM.
err = d.setupNvram()
if err != nil {
return err
}
}
// Re-generate the instance-id if needed.
if !d.IsSnapshot() && d.needsNewInstanceID(changedConfig, oldExpandedDevices) {
err = d.resetInstanceID()
if err != nil {
return err
}
}
// Finally, apply the changes to the database.
err = d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Snapshots should update only their descriptions and expiry date.
if d.IsSnapshot() {
return tx.UpdateInstanceSnapshot(d.id, d.description, d.expiryDate)
}
object, err := dbCluster.GetInstance(ctx, tx.Tx(), d.project.Name, d.name)
if err != nil {
return err
}
object.Description = d.description
object.Architecture = d.architecture
object.Ephemeral = d.ephemeral
object.ExpiryDate = sql.NullTime{Time: d.expiryDate, Valid: true}
err = dbCluster.UpdateInstance(ctx, tx.Tx(), d.project.Name, d.name, *object)
if err != nil {
return err
}
err = dbCluster.UpdateInstanceConfig(ctx, tx.Tx(), int64(object.ID), d.localConfig)
if err != nil {
return err
}
devices, err := dbCluster.APIToDevices(d.localDevices.CloneNative())
if err != nil {
return err
}
err = dbCluster.UpdateInstanceDevices(ctx, tx.Tx(), int64(object.ID), devices)
if err != nil {
return err
}
profileNames := make([]string, 0, len(d.profiles))
for _, profile := range d.profiles {
profileNames = append(profileNames, profile.Name)
}
return dbCluster.UpdateInstanceProfiles(ctx, tx.Tx(), object.ID, object.Project, profileNames)
})
if err != nil {
return fmt.Errorf("Failed to update database: %w", err)
}
err = d.UpdateBackupFile()
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf("Failed to write backup file: %w", err)
}
// Changes have been applied and recorded, do not revert if an error occurs from here.
reverter.Success()
if isRunning {
// Send devIncus notifications only for user.* key changes
for _, key := range changedConfig {
if !strings.HasPrefix(key, "user.") {
continue
}
msg := map[string]any{
"key": key,
"old_value": oldExpandedConfig[key],
"value": d.expandedConfig[key],
}
err = d.devIncusEventSend("config", msg)
if err != nil {
return err
}
}
// Device changes
for k, m := range removeDevices {
msg := map[string]any{
"action": "removed",
"name": k,
"config": m,
}
err = d.devIncusEventSend("device", msg)
if err != nil {
return err
}
}
for k, m := range updateDevices {
msg := map[string]any{
"action": "updated",
"name": k,
"config": m,
}
err = d.devIncusEventSend("device", msg)
if err != nil {
return err
}
}
for k, m := range addDevices {
msg := map[string]any{
"action": "added",
"name": k,
"config": m,
}
err = d.devIncusEventSend("device", msg)
if err != nil {
return err
}
}
}
if userRequested {
if d.isSnapshot {
d.state.Events.SendLifecycle(d.project.Name, lifecycle.InstanceSnapshotUpdated.Event(d, nil))
} else {
d.state.Events.SendLifecycle(d.project.Name, lifecycle.InstanceUpdated.Event(d, nil))
}
}
return nil
}
// updateMemoryLimit live updates the VM's memory limit by reszing the balloon device.
func (d *qemu) updateMemoryLimit(newLimit string) error {
if newLimit == "" {
return nil
}
if util.IsTrue(d.expandedConfig["limits.memory.hugepages"]) {
return errors.New("Cannot live update memory limit when using huge pages")
}
// Check new size string is valid and convert to bytes.
newSizeBytes, err := ParseMemoryStr(newLimit)
if err != nil {
return fmt.Errorf("Invalid memory size: %w", err)
}
newSizeMB := newSizeBytes / 1024 / 1024
// Connect to the monitor.
monitor, err := d.qmpConnect()
if err != nil {
return err // The VM isn't running as no monitor socket available.
}
baseSizeBytes, err := monitor.GetMemorySizeBytes()
if err != nil {
return err
}
baseSizeMB := baseSizeBytes / 1024 / 1024
curSizeBytes, err := monitor.GetMemoryBalloonSizeBytes()
if err != nil {
return err
}
curSizeMB := curSizeBytes / 1024 / 1024
if curSizeMB == newSizeMB {
return nil
} else if baseSizeMB < newSizeMB {
if util.IsFalse(d.expandedConfig["limits.memory.hotplug"]) {
return fmt.Errorf("Memory hotplug feature is disabled")
}
return d.hotplugMemory(monitor, newSizeBytes-curSizeBytes)
}
// Set effective memory size.
err = monitor.SetMemoryBalloonSizeBytes(newSizeBytes)
if err != nil {
return err
}
// Changing the memory balloon can take time, so poll the effective size to check it has shrunk within 1%
// of the target size, which we then take as success (it may still continue to shrink closer to target).
for range 10 {
curSizeBytes, err = monitor.GetMemoryBalloonSizeBytes()
if err != nil {
return err
}
curSizeMB = curSizeBytes / 1024 / 1024
var diff int64
if curSizeMB < newSizeMB {
diff = newSizeMB - curSizeMB
} else {
diff = curSizeMB - newSizeMB
}
if diff <= (newSizeMB / 100) {
return nil // We reached to within 1% of our target size.
}
time.Sleep(500 * time.Millisecond)
}
return fmt.Errorf("Failed setting memory to %dMiB (currently %dMiB) as it was taking too long", newSizeMB, curSizeMB)
}
// hotplugMemory attaches a memory device to a running VM,
// respecting NUMA node placement and hugepages.
func (d *qemu) hotplugMemory(monitor *qmp.Monitor, sizeBytes int64) error {
// Get CPU information.
cpuInfo, err := d.cpuTopology(d.expandedConfig["limits.cpu"])
if err != nil {
return err
}
// Fetch memory configuration
cpuOpts, err := d.getCPUOpts(cpuInfo, sizeBytes)
if err != nil {
return err
}
cpuPinning := cpuInfo.vcpus != nil
// Get CPUs and memory configuration
conf := qemuCPU(cpuOpts, cpuPinning)
memoryObjects := map[int]cfg.Section{}
for _, section := range conf {
// Name is in the form 'object "mem0"', so the last quote needs to be removed.
// This allows proper parsing of the memory object index.
sectionName := section.Name[:len(section.Name)-1]
index, err := extractTrailingNumber(sectionName, "object \"mem")
if err != nil {
continue
}
memoryObjects[index] = section
}
// Find first available memory object index.
nextMemIndex, err := findNextMemoryIndex(monitor)
if err != nil {
return err
}
// Find first available pc-dimm device index.
nextDimmIndex, err := findNextDimmIndex(monitor)
if err != nil {
return err
}
for index, memory := range memoryObjects {
memIndex := nextMemIndex + index
dimmIndex := nextDimmIndex + index
memObj := memoryConfigSectionToMap(&memory)
memObj["id"] = fmt.Sprintf("mem%d", memIndex)
err = monitor.AddObject(memObj)
if err != nil {
return err
}
memDev := map[string]any{
"driver": "pc-dimm",
"id": fmt.Sprintf("dimm%d", dimmIndex),
"memdev": fmt.Sprintf("mem%d", memIndex),
"node": index,
}
err = monitor.AddDevice(memDev)
if err != nil {
return err
}
}
return nil
}
func (d *qemu) removeUnixDevices() error {
// Check that we indeed have devices to remove.
if !util.PathExists(d.DevicesPath()) {
return nil
}
// Load the directory listing.
dents, err := os.ReadDir(d.DevicesPath())
if err != nil {
return err
}
for _, f := range dents {
// Skip non-Unix devices.
if !strings.HasPrefix(f.Name(), "forkmknod.unix.") && !strings.HasPrefix(f.Name(), "unix.") && !strings.HasPrefix(f.Name(), "infiniband.unix.") {
continue
}
// Remove the entry
devicePath := filepath.Join(d.DevicesPath(), f.Name())
err := os.Remove(devicePath)
if err != nil {
d.logger.Error("Failed removing unix device", logger.Ctx{"err": err, "path": devicePath})
}
}
return nil
}
func (d *qemu) removeDiskDevices() error {
// Check that we indeed have devices to remove.
if !util.PathExists(d.DevicesPath()) {
return nil
}
// Load the directory listing.
dents, err := os.ReadDir(d.DevicesPath())
if err != nil {
return err
}
for _, f := range dents {
// Skip non-disk devices
if !strings.HasPrefix(f.Name(), "disk.") {
continue
}
// Always try to unmount the host side.
_ = unix.Unmount(filepath.Join(d.DevicesPath(), f.Name()), unix.MNT_DETACH)
// Remove the entry.
diskPath := filepath.Join(d.DevicesPath(), f.Name())
err := os.Remove(diskPath)
if err != nil {
d.logger.Error("Failed to remove disk device path", logger.Ctx{"err": err, "path": diskPath})
}
}
return nil
}
func (d *qemu) cleanup() {
// Unmount any leftovers
_ = d.removeUnixDevices()
_ = d.removeDiskDevices()
// Remove the security profiles
_ = apparmor.InstanceDelete(d.state.OS, d)
// Remove the devices path
_ = os.Remove(d.DevicesPath())
// Remove the shmounts path
_ = os.RemoveAll(d.ShmountsPath())
}
// cleanupDevices performs any needed device cleanup steps when instance is stopped.
// Must be called before root volume is unmounted.
func (d *qemu) cleanupDevices() {
// Clear up the config drive mount.
err := d.configDriveMountPathClear()
if err != nil {
d.logger.Warn("Failed cleaning up config drive mount", logger.Ctx{"err": err})
}
for _, entry := range d.expandedDevices.Reversed() {
dev, err := d.deviceLoad(d, entry.Name, entry.Config)
if err != nil {
if errors.Is(err, device.ErrUnsupportedDevType) {
continue // Skip unsupported device (allows for mixed instance type profiles).
}
// Just log an error, but still allow the device to be stopped if usable device returned.
d.logger.Error("Failed stop validation for device", logger.Ctx{"device": entry.Name, "err": err})
}
// If a usable device was returned from deviceLoad try to stop anyway, even if validation fails.
// This allows for the scenario where a new version has additional validation restrictions
// than older versions and we still need to allow previously valid devices to be stopped even if
// they are no longer considered valid.
if dev != nil {
err = d.deviceStop(dev, false, "")
if err != nil {
d.logger.Error("Failed to stop device", logger.Ctx{"device": dev.Name(), "err": err})
}
}
}
}
func (d *qemu) init() error {
// Compute the expanded config and device list.
err := d.expandConfig()
if err != nil {
return err
}
return nil
}
// Delete the instance.
func (d *qemu) Delete(force bool) error {
// Setup a new operation.
op, err := operationlock.CreateWaitGet(d.Project().Name, d.Name(), d.op, operationlock.ActionDelete, nil, false, false)
if err != nil {
return fmt.Errorf("Failed to create instance delete operation: %w", err)
}
defer op.Done(nil)
if d.IsRunning() {
return api.StatusErrorf(http.StatusBadRequest, "Instance is running")
}
err = d.delete(force)
if err != nil {
return err
}
// If dealing with a snapshot, refresh the backup file on the parent.
if d.IsSnapshot() {
parentName, _, _ := api.GetParentAndSnapshotName(d.name)
// Load the parent.
parent, err := instance.LoadByProjectAndName(d.state, d.project.Name, parentName)
if err != nil {
return fmt.Errorf("Invalid parent: %w", err)
}
// Update the backup file.
err = parent.UpdateBackupFile()
if err != nil {
return err
}
}
return nil
}
// Delete the instance without creating an operation lock.
func (d *qemu) delete(force bool) error {
ctxMap := logger.Ctx{
"created": d.creationDate,
"ephemeral": d.ephemeral,
"used": d.lastUsedDate,
}
if d.isSnapshot {
d.logger.Info("Deleting instance snapshot", ctxMap)
} else {
d.logger.Info("Deleting instance", ctxMap)
}
// Check if instance is delete protected.
if !force && util.IsTrue(d.expandedConfig["security.protection.delete"]) && !d.IsSnapshot() {
return errors.New("Instance is protected")
}
// Delete any persistent warnings for instance.
err := d.warningsDelete()
if err != nil {
return err
}
// Attempt to initialize storage interface for the instance.
pool, err := d.getStoragePool()
if err != nil && !response.IsNotFoundError(err) {
return err
} else if pool != nil {
if d.IsSnapshot() {
// Remove snapshot volume and database record.
err = pool.DeleteInstanceSnapshot(d, nil)
if err != nil {
return err
}
} else {
// Remove all snapshots.
err := d.deleteSnapshots(func(snapInst instance.Instance) error {
return snapInst.(*qemu).delete(true) // Internal delete function that doesn't lock.
})
if err != nil {
return fmt.Errorf("Failed deleting instance snapshots: %w", err)
}
// Remove the storage volume and database records.
err = pool.DeleteInstance(d, nil)
if err != nil {
return err
}
}
}
// Perform other cleanup steps if not snapshot.
if !d.IsSnapshot() {
// Remove all backups.
backups, err := d.Backups()
if err != nil {
return err
}
for _, backup := range backups {
err = backup.Delete()
if err != nil {
return err
}
}
// Run device removal function for each device.
d.devicesRemove(d)
// Clean things up.
d.cleanup()
}
err = d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Remove the database record of the instance or snapshot instance.
return tx.DeleteInstance(ctx, d.Project().Name, d.Name())
})
if err != nil {
d.logger.Error("Failed deleting instance entry", logger.Ctx{"project": d.Project().Name})
return err
}
if d.isSnapshot {
d.logger.Info("Deleted instance snapshot", ctxMap)
} else {
d.logger.Info("Deleted instance", ctxMap)
}
if d.isSnapshot {
d.state.Events.SendLifecycle(d.project.Name, lifecycle.InstanceSnapshotDeleted.Event(d, nil))
} else {
err = d.state.Authorizer.DeleteInstance(d.state.ShutdownCtx, d.project.Name, d.Name())
if err != nil {
logger.Error("Failed to remove instance from authorizer", logger.Ctx{"name": d.Name(), "project": d.project.Name, "error": err})
}
d.state.Events.SendLifecycle(d.project.Name, lifecycle.InstanceDeleted.Event(d, nil))
}
return nil
}
// Export publishes the instance.
func (d *qemu) Export(metaWriter io.Writer, rootfsWriter io.Writer, properties map[string]string, expiration time.Time, tracker *ioprogress.ProgressTracker) (*api.ImageMetadata, error) {
ctxMap := logger.Ctx{
"created": d.creationDate,
"ephemeral": d.ephemeral,
"used": d.lastUsedDate,
}
if d.IsRunning() {
return nil, errors.New("Cannot export a running instance as an image")
}
d.logger.Info("Exporting instance", ctxMap)
// Start the storage.
mountInfo, err := d.mount()
if err != nil {
d.logger.Error("Failed exporting instance", ctxMap)
return nil, err
}
defer func() { _ = d.unmount() }()
// Create the tarball.
metaTarWriter := instancewriter.NewInstanceTarWriter(metaWriter, nil)
// Path inside the tar image is the pathname starting after cDir.
cDir := d.Path()
offset := len(cDir) + 1
writeToMetaTar := func(path string, fi os.FileInfo, err error) error {
if err != nil {
return err
}
err = metaTarWriter.WriteFile(path[offset:], path, fi, false)
if err != nil {
d.logger.Debug("Error tarring up", logger.Ctx{"path": path, "err": err})
return err
}
return nil
}
// Get the instance's architecture.
var arch string
if d.IsSnapshot() {
parentName, _, _ := api.GetParentAndSnapshotName(d.name)
parent, err := instance.LoadByProjectAndName(d.state, d.project.Name, parentName)
if err != nil {
_ = metaTarWriter.Close()
d.logger.Error("Failed exporting instance", ctxMap)
return nil, err
}
arch, _ = osarch.ArchitectureName(parent.Architecture())
} else {
arch, _ = osarch.ArchitectureName(d.architecture)
}
if arch == "" {
arch, err = osarch.ArchitectureName(d.state.OS.Architectures[0])
if err != nil {
d.logger.Error("Failed exporting instance", ctxMap)
return nil, err
}
}
// Generate metadata.yaml.
meta := api.ImageMetadata{}
fnam := filepath.Join(cDir, "metadata.yaml")
if util.PathExists(fnam) {
// Parse the metadata.
content, err := os.ReadFile(fnam)
if err != nil {
_ = metaTarWriter.Close()
d.logger.Error("Failed exporting instance", ctxMap)
return nil, err
}
err = yaml.Unmarshal(content, &meta)
if err != nil {
_ = metaTarWriter.Close()
d.logger.Error("Failed exporting instance", ctxMap)
return nil, err
}
}
// Fill in the metadata.
meta.Architecture = arch
meta.CreationDate = time.Now().UTC().Unix()
if meta.Properties == nil {
meta.Properties = map[string]string{}
}
maps.Copy(meta.Properties, properties)
if !expiration.IsZero() {
meta.ExpiryDate = expiration.UTC().Unix()
}
// Write the new metadata.yaml.
tempDir, err := os.MkdirTemp("", "incus_metadata_")
if err != nil {
_ = metaTarWriter.Close()
d.logger.Error("Failed exporting instance", ctxMap)
return nil, err
}
defer func() { _ = os.RemoveAll(tempDir) }()
data, err := yaml.Marshal(&meta)
if err != nil {
_ = metaTarWriter.Close()
d.logger.Error("Failed exporting instance", ctxMap)
return nil, err
}
fnam = filepath.Join(tempDir, "metadata.yaml")
err = os.WriteFile(fnam, data, 0o644)
if err != nil {
_ = metaTarWriter.Close()
d.logger.Error("Failed exporting instance", ctxMap)
return nil, err
}
// Add metadata.yaml to the tarball.
fi, err := os.Lstat(fnam)
if err != nil {
_ = metaTarWriter.Close()
d.logger.Error("Failed exporting instance", ctxMap)
return nil, err
}
tmpOffset := len(filepath.Dir(fnam)) + 1
err = metaTarWriter.WriteFile(fnam[tmpOffset:], fnam, fi, false)
if err != nil {
_ = metaTarWriter.Close()
d.logger.Debug("Error writing to tarfile", logger.Ctx{"err": err})
d.logger.Error("Failed exporting instance", ctxMap)
return nil, err
}
// Convert from raw to qcow2 and add to tarball.
tmpPath, err := os.MkdirTemp(internalUtil.VarPath("images"), "incus_export_")
if err != nil {
return nil, err
}
defer func() { _ = os.RemoveAll(tmpPath) }()
if mountInfo.DiskPath == "" {
return nil, errors.New("No disk path available from mount")
}
fPath := fmt.Sprintf("%s/rootfs.img", tmpPath)
// Convert to qcow2 image.
cmd := []string{
"nice", "-n19", // Run with low priority to reduce CPU impact on other processes.
"qemu-img", "convert", "-p", "-f", "raw", "-O", "qcow2",
}
if rootfsWriter != nil {
// Compress the qcow2 image if publishing a split image.
cmd = append(cmd, "-c")
}
reverter := revert.New()
defer reverter.Fail()
// Check for Direct I/O support.
from, err := os.OpenFile(mountInfo.DiskPath, unix.O_DIRECT|unix.O_RDONLY, 0)
if err == nil {
cmd = append(cmd, "-T", "none")
_ = from.Close()
}
to, err := os.OpenFile(fPath, unix.O_DIRECT|unix.O_CREAT, 0o600)
if err == nil {
cmd = append(cmd, "-t", "none")
_ = to.Close()
}
reverter.Add(func() { _ = os.Remove(fPath) })
cmd = append(cmd, mountInfo.DiskPath, fPath)
_, err = apparmor.QemuImg(d.state.OS, cmd, mountInfo.DiskPath, fPath, tracker)
if err != nil {
return nil, fmt.Errorf("Failed converting instance to qcow2: %w", err)
}
// Read converted file info and write file to tarball in the case of unified image
// For split images, just write as a qcow2 file
if rootfsWriter == nil {
imgOffset := len(tmpPath) + 1
fi, err = os.Lstat(fPath)
if err != nil {
return nil, err
}
err = metaTarWriter.WriteFile(fPath[imgOffset:], fPath, fi, false)
if err != nil {
return nil, err
}
} else {
f, err := os.Open(fPath)
if err != nil {
return nil, err
}
r := io.Reader(f)
_, err = io.Copy(rootfsWriter, r)
if err != nil {
return nil, err
}
}
// Include all the templates.
fnam = d.TemplatesPath()
if util.PathExists(fnam) {
err = filepath.Walk(fnam, writeToMetaTar)
if err != nil {
d.logger.Error("Failed exporting instance", ctxMap)
return nil, err
}
}
err = metaTarWriter.Close()
if err != nil {
d.logger.Error("Failed exporting instance", ctxMap)
return nil, err
}
reverter.Success()
d.logger.Info("Exported instance", ctxMap)
return &meta, nil
}
// MigrateSend is not currently supported.
func (d *qemu) MigrateSend(args instance.MigrateSendArgs) error {
d.logger.Debug("Migration send starting")
defer d.logger.Debug("Migration send stopped")
// Check for stateful support.
if args.Live && !d.CanLiveMigrate() {
return errors.New("Live migration requires migration.stateful to be set to true")
}
// Setup a new operation.
op, err := operationlock.CreateWaitGet(d.Project().Name, d.Name(), d.op, operationlock.ActionMigrate, nil, false, true)
if err != nil {
return err
}
// Wait for essential migration connections before negotiation.
connectionsCtx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
filesystemConn, err := args.FilesystemConn(connectionsCtx)
if err != nil {
op.Done(err)
return err
}
pool, err := storagePools.LoadByInstance(d.state, d)
if err != nil {
err := fmt.Errorf("Failed loading instance: %w", err)
op.Done(err)
return err
}
clusterMove := args.ClusterMoveSourceName != ""
remoteClusterMove := clusterMove && pool.Driver().Info().Remote
storageMove := args.StoragePool != ""
// The refresh argument passed to MigrationTypes() is always set
// to false here. The migration source/sender doesn't need to care whether
// or not it's doing a refresh as the migration sink/receiver will know
// this, and adjust the migration types accordingly.
// The same applies for clusterMove and storageMove, which are set to the most optimized defaults.
poolMigrationTypes := pool.MigrationTypes(storagePools.InstanceContentType(d), false, args.Snapshots, true, false)
if len(poolMigrationTypes) == 0 {
err := errors.New("No source migration types available")
op.Done(err)
return err
}
// Convert the pool's migration type options to an offer header to target.
// Populate the Fs, ZfsFeatures and RsyncFeatures fields.
offerHeader := localMigration.TypesToHeader(poolMigrationTypes...)
// Offer to send index header.
indexHeaderVersion := localMigration.IndexHeaderVersion
offerHeader.IndexHeaderVersion = &indexHeaderVersion
// For VMs, send block device size hint in offer header so that target can create the volume the same size.
blockSize, err := storagePools.InstanceDiskBlockSize(pool, d, d.op)
if err != nil {
err := fmt.Errorf("Failed getting source disk size: %w", err)
op.Done(err)
return err
}
d.logger.Debug("Set migration offer volume size", logger.Ctx{"blockSize": blockSize})
offerHeader.VolumeSize = &blockSize
srcConfig, err := pool.GenerateInstanceBackupConfig(d, args.Snapshots, d.op)
if err != nil {
err := fmt.Errorf("Failed generating instance migration config: %w", err)
op.Done(err)
return err
}
contentType := storagePools.InstanceContentType(d)
// If we are copying snapshots, retrieve a list of snapshots from source volume.
if args.Snapshots {
offerHeader.SnapshotNames = make([]string, 0, len(srcConfig.Snapshots))
offerHeader.Snapshots = make([]*migration.Snapshot, 0, len(srcConfig.Snapshots))
for i := range srcConfig.Snapshots {
offerHeader.SnapshotNames = append(offerHeader.SnapshotNames, srcConfig.Snapshots[i].Name)
// Calculating snapshot size can be very slow, skip unless absolutely needed.
if !remoteClusterMove || storageMove {
snapSize, err := storagePools.CalculateVolumeSnapshotSize(d.Project().Name, pool, contentType, storageDrivers.VolumeTypeVM, d.Name(), srcConfig.Snapshots[i].Name)
if err != nil {
return err
}
srcConfig.Snapshots[i].Config["size"] = fmt.Sprintf("%d", snapSize)
}
offerHeader.Snapshots = append(offerHeader.Snapshots, instance.SnapshotToProtobuf(srcConfig.Snapshots[i]))
}
}
// Offer QEMU to QEMU live state transfer state transfer feature.
// If the request is for live migration, then offer that live QEMU to QEMU state transfer can proceed.
// Otherwise we'll fallback to doing stateful stop, migrate, and then stateful start, which will still
// fulfil the "live" part of the request, albeit with longer pause of the instance during the process.
if args.Live {
offerHeader.Criu = migration.CRIUType_VM_QEMU.Enum()
}
// Send offer to target.
d.logger.Debug("Sending migration offer to target")
err = args.ControlSend(offerHeader)
if err != nil {
err := fmt.Errorf("Failed sending migration offer header: %w", err)
op.Done(err)
return err
}
// Receive response from target.
d.logger.Debug("Waiting for migration offer response from target")
respHeader := &migration.MigrationHeader{}
err = args.ControlReceive(respHeader)
if err != nil {
err := fmt.Errorf("Failed receiving migration offer response: %w", err)
op.Done(err)
return err
}
d.logger.Debug("Got migration offer response from target")
// Negotiated migration types.
migrationTypes, err := localMigration.MatchTypes(respHeader, migration.MigrationFSType_RSYNC, poolMigrationTypes)
if err != nil {
err := fmt.Errorf("Failed to negotiate migration type: %w", err)
op.Done(err)
return err
}
volSourceArgs := &localMigration.VolumeSourceArgs{
IndexHeaderVersion: respHeader.GetIndexHeaderVersion(), // Enable index header frame if supported.
Name: d.Name(),
MigrationType: migrationTypes[0],
Snapshots: offerHeader.SnapshotNames,
TrackProgress: true,
Refresh: respHeader.GetRefresh(),
AllowInconsistent: args.AllowInconsistent,
VolumeOnly: !args.Snapshots,
Info: &localMigration.Info{Config: srcConfig},
ClusterMove: clusterMove,
StorageMove: storageMove,
}
// Only send the snapshots that the target requests when refreshing.
if respHeader.GetRefresh() {
volSourceArgs.Snapshots = respHeader.GetSnapshotNames()
allSnapshots := volSourceArgs.Info.Config.VolumeSnapshots
// Ensure that only the requested snapshots are included in the migration index header.
volSourceArgs.Info.Config.VolumeSnapshots = make([]*api.StorageVolumeSnapshot, 0, len(volSourceArgs.Snapshots))
for i := range allSnapshots {
if slices.Contains(volSourceArgs.Snapshots, allSnapshots[i].Name) {
volSourceArgs.Info.Config.VolumeSnapshots = append(volSourceArgs.Info.Config.VolumeSnapshots, allSnapshots[i])
}
}
}
// Detect whether the far side has chosen to use QEMU to QEMU live state transfer mode, and if so then
// wait for the connection to be established.
var stateConn io.ReadWriteCloser
if args.Live && respHeader.Criu != nil && *respHeader.Criu == migration.CRIUType_VM_QEMU {
stateConn, err = args.StateConn(connectionsCtx)
if err != nil {
op.Done(err)
return err
}
}
g, ctx := errgroup.WithContext(context.Background())
// Start control connection monitor.
g.Go(func() error {
d.logger.Debug("Migrate send control monitor started")
defer d.logger.Debug("Migrate send control monitor finished")
controlResult := make(chan error, 1) // Buffered to allow go routine to end if no readers.
// This will read the result message from the target side and detect disconnections.
go func() {
resp := migration.MigrationControl{}
err := args.ControlReceive(&resp)
if err != nil {
err = fmt.Errorf("Error reading migration control target: %w", err)
} else if !resp.GetSuccess() {
err = fmt.Errorf("Error from migration control target: %s", resp.GetMessage())
}
controlResult <- err
}()
// End as soon as we get control message/disconnection from the target side or a local error.
select {
case <-ctx.Done():
err = ctx.Err()
case err = <-controlResult:
}
return err
})
// Start error monitoring routine, this will detect when an error is returned from the other routines,
// and if that happens it will disconnect the migration connections which will trigger the other routines
// to finish.
go func() {
<-ctx.Done()
args.Disconnect()
}()
g.Go(func() error {
d.logger.Debug("Migrate send transfer started")
defer d.logger.Debug("Migrate send transfer finished")
var err error
// Start live state transfer using state connection if supported.
if stateConn != nil {
// When performing intra-cluster same-name move, take steps to prevent corruption
// of volatile device config keys during start & stop of instance on source/target.
if args.ClusterMoveSourceName == d.name {
// Disable VolatileSet from persisting changes to the database.
// This is so the volatile changes written by the running receiving member
// are not lost when the source instance is stopped.
d.volatileSetPersistDisable = true
// Store a reference to this instance (which has the old volatile settings)
// to allow the onStop hook to pick it up, which allows the devices being
// stopped to access their volatile settings stored when the instance
// originally started on this cluster member.
instanceRefSet(d)
defer instanceRefClear(d)
}
err = d.migrateSendLive(pool, args.ClusterMoveSourceName, args.StoragePool, blockSize, filesystemConn, stateConn, volSourceArgs)
if err != nil {
return err
}
} else {
// Perform stateful stop if live state transfer is not supported by target.
if args.Live {
err = d.Stop(true)
if err != nil {
return fmt.Errorf("Failed statefully stopping instance: %w", err)
}
}
err = pool.MigrateInstance(d, filesystemConn, volSourceArgs, d.op)
if err != nil {
return err
}
}
return nil
})
// Wait for routines to finish and collect first error.
{
err := g.Wait()
if err != nil {
op.Done(err)
return err
}
op.Done(nil)
d.state.Events.SendLifecycle(d.project.Name, lifecycle.InstanceMigrated.Event(d, nil))
return nil
}
}
// migrateSendLive performs live migration send process.
func (d *qemu) migrateSendLive(pool storagePools.Pool, clusterMoveSourceName string, storagePool string, rootDiskSize int64, filesystemConn io.ReadWriteCloser, stateConn io.ReadWriteCloser, volSourceArgs *localMigration.VolumeSourceArgs) error {
monitor, err := d.qmpConnect()
if err != nil {
return err
}
rootDiskName := "incus_root" // Name of source disk device to sync from
nbdTargetDiskName := "incus_root_nbd" // Name of NBD disk device added to local VM to sync to.
rootSnapshotDiskName := "incus_root_snapshot" // Name of snapshot disk device to use.
// If we are performing an intra-cluster member move on a Ceph storage pool without storage change
// then we can treat this as shared storage and avoid needing to sync the root disk.
sameSharedStorage := clusterMoveSourceName != "" && pool.Driver().Info().Remote && storagePool == ""
reverter := revert.New()
// Non-shared storage snapshot setup.
if !sameSharedStorage {
// Setup migration capabilities.
capabilities := map[string]bool{
// Automatically throttle down the guest to speed up convergence of RAM migration.
"auto-converge": true,
// Allow the migration to be paused after the source qemu releases the block devices but
// before the serialisation of the device state, to avoid a race condition between
// migration and blockdev-mirror. This requires that the migration be continued after it
// has reached the "pre-switchover" status.
"pause-before-switchover": true,
// During storage migration encode blocks of zeroes efficiently.
"zero-blocks": true,
}
err = monitor.MigrateSetCapabilities(capabilities)
if err != nil {
return fmt.Errorf("Failed setting migration capabilities: %w", err)
}
parameters := map[string]any{
"cpu-throttle-initial": 50,
"throttle-trigger-threshold": 20,
}
err = monitor.MigrateSetParameters(parameters)
if err != nil {
return fmt.Errorf("Failed setting migration parameters: %w", err)
}
// Create snapshot of the root disk.
// We use the VM's config volume for this so that the maximum size of the snapshot can be limited
// by setting the root disk's `size.state` property.
snapshotFile := filepath.Join(d.Path(), "migration_snapshot.qcow2")
// Ensure there are no existing migration snapshot files.
err = os.Remove(snapshotFile)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return err
}
// Create qcow2 disk image with the maximum size set to the instance's root disk size for use as
// a CoW target for the migration snapshot. This will be used during migration to store writes in
// the guest whilst the storage driver is transferring the root disk and snapshots to the target.
_, err = subprocess.RunCommand("qemu-img", "create", "-f", "qcow2", snapshotFile, fmt.Sprintf("%d", rootDiskSize))
if err != nil {
return fmt.Errorf("Failed opening file image for migration storage snapshot %q: %w", snapshotFile, err)
}
defer func() { _ = os.Remove(snapshotFile) }()
// Pass the snapshot file to the running QEMU process.
snapFile, err := os.OpenFile(snapshotFile, unix.O_RDWR, 0)
if err != nil {
return fmt.Errorf("Failed opening file descriptor for migration storage snapshot %q: %w", snapshotFile, err)
}
defer func() { _ = snapFile.Close() }()
// Remove the snapshot file as we don't want to sync this to the target.
err = os.Remove(snapshotFile)
if err != nil {
return err
}
info, err := monitor.SendFileWithFDSet(rootSnapshotDiskName, snapFile, false)
if err != nil {
return fmt.Errorf("Failed sending file descriptor of %q for migration storage snapshot: %w", snapFile.Name(), err)
}
defer func() { _ = monitor.RemoveFDFromFDSet(rootSnapshotDiskName) }()
_ = snapFile.Close() // Don't prevent clean unmount when instance is stopped.
// Add the snapshot file as a block device (not visible to the guest OS).
err = monitor.AddBlockDevice(map[string]any{
"driver": "qcow2",
"node-name": rootSnapshotDiskName,
"read-only": false,
"file": map[string]any{
"driver": "file",
"filename": fmt.Sprintf("/dev/fdset/%d", info.ID),
},
}, nil, true)
if err != nil {
return fmt.Errorf("Failed adding migration storage snapshot block device: %w", err)
}
defer func() {
_ = monitor.RemoveBlockDevice(rootSnapshotDiskName)
}()
// Take a snapshot of the root disk and redirect writes to the snapshot disk.
err = monitor.BlockDevSnapshot(rootDiskName, rootSnapshotDiskName)
if err != nil {
return fmt.Errorf("Failed taking temporary migration storage snapshot: %w", err)
}
reverter.Add(func() {
// Resume guest (this is needed as it will prevent merging the snapshot if paused).
err = monitor.Start()
if err != nil {
d.logger.Warn("Failed resuming instance", logger.Ctx{"err": err})
}
// Try and merge snapshot back to the source disk on failure so we don't lose writes.
err = monitor.BlockCommit(rootSnapshotDiskName)
if err != nil {
d.logger.Error("Failed merging migration storage snapshot", logger.Ctx{"err": err})
}
})
defer reverter.Fail() // Run the revert fail before the earlier defers.
d.logger.Debug("Setup temporary migration storage snapshot")
} else {
// Still set some options for shared storage.
capabilities := map[string]bool{
// Automatically throttle down the guest to speed up convergence of RAM migration.
"auto-converge": true,
}
err = monitor.MigrateSetCapabilities(capabilities)
if err != nil {
return fmt.Errorf("Failed setting migration capabilities: %w", err)
}
parameters := map[string]any{
"cpu-throttle-initial": 50,
"throttle-trigger-threshold": 20,
}
err = monitor.MigrateSetParameters(parameters)
if err != nil {
return fmt.Errorf("Failed setting migration parameters: %w", err)
}
}
// Perform storage transfer while instance is still running.
// For shared storage the storage driver will likely not do much here, but we still call it anyway for the
// sense checks it performs.
// We enable AllowInconsistent mode as this allows for transferring the VM storage whilst it is running
// and the snapshot we took earlier is designed to provide consistency anyway.
volSourceArgs.AllowInconsistent = true
err = pool.MigrateInstance(d, filesystemConn, volSourceArgs, d.op)
if err != nil {
return err
}
// Derive the effective storage project name from the instance config's project.
storageProjectName, err := project.StorageVolumeProject(d.state.DB.Cluster, d.project.Name, db.StoragePoolVolumeTypeCustom)
if err != nil {
return err
}
// Notify the shared disks that they're going to be accessed from another system.
for _, dev := range d.expandedDevices.Sorted() {
if dev.Config["type"] != "disk" || dev.Config["path"] == "/" || dev.Config["pool"] == "" {
continue
}
// Load the pool for the disk.
diskPool, err := storagePools.LoadByName(d.state, dev.Config["pool"])
if err != nil {
return fmt.Errorf("Failed loading storage pool: %w", err)
}
// Check that we're on shared storage.
if !diskPool.Driver().Info().Remote {
continue
}
// Setup the volume entry.
extraSourceArgs := &localMigration.VolumeSourceArgs{
ClusterMove: true,
}
vol := diskPool.GetVolume(storageDrivers.VolumeTypeCustom, storageDrivers.ContentTypeBlock, project.StorageVolume(storageProjectName, dev.Config["source"]), nil)
// Call MigrateVolume on the source.
err = diskPool.Driver().MigrateVolume(vol, nil, extraSourceArgs, nil)
if err != nil {
return fmt.Errorf("Failed to prepare device %q for migration: %w", dev.Name, err)
}
}
// Non-shared storage snapshot transfer.
if !sameSharedStorage {
listener, err := net.Listen("unix", "")
if err != nil {
return fmt.Errorf("Failed creating NBD unix listener: %w", err)
}
defer func() { _ = listener.Close() }()
go func() {
d.logger.Debug("NBD listener waiting for accept")
nbdConn, err := listener.Accept()
if err != nil {
d.logger.Error("Failed accepting connection to NBD client unix listener", logger.Ctx{"err": err})
return
}
defer func() { _ = nbdConn.Close() }()
d.logger.Debug("NBD connection on source started")
go func() { _, _ = io.Copy(filesystemConn, nbdConn) }()
_, _ = io.Copy(nbdConn, filesystemConn)
d.logger.Debug("NBD connection on source finished")
}()
// Connect to NBD migration target and add it the source instance as a disk device.
d.logger.Debug("Connecting to migration NBD storage target")
err = monitor.AddBlockDevice(map[string]any{
"node-name": nbdTargetDiskName,
"driver": "raw",
"file": map[string]any{
"driver": "nbd",
"export": qemuMigrationNBDExportName,
"server": map[string]any{
"type": "unix",
"abstract": true,
"path": strings.TrimPrefix(listener.Addr().String(), "@"),
},
},
}, nil, true)
if err != nil {
return fmt.Errorf("Failed adding NBD device: %w", err)
}
reverter.Add(func() {
time.Sleep(time.Second) // Wait for it to be released.
err := monitor.RemoveBlockDevice(nbdTargetDiskName)
if err != nil {
d.logger.Warn("Failed removing NBD storage target device", logger.Ctx{"err": err})
}
})
d.logger.Debug("Connected to migration NBD storage target")
// Begin transferring any writes that occurred during the storage migration by transferring the
// contents of the (top) migration snapshot to the target disk to bring them into sync.
// Once this has completed the guest OS will be paused.
d.logger.Debug("Migration storage snapshot transfer started")
err = monitor.BlockDevMirror(rootSnapshotDiskName, nbdTargetDiskName)
if err != nil {
return fmt.Errorf("Failed transferring migration storage snapshot: %w", err)
}
reverter.Add(func() {
err = monitor.BlockJobCancel(rootSnapshotDiskName)
if err != nil {
d.logger.Error("Failed cancelling block job", logger.Ctx{"err": err})
}
})
d.logger.Debug("Migration storage snapshot transfer finished")
}
d.logger.Debug("Stateful migration checkpoint send starting")
// Send checkpoint to QEMU process on target. This will pause the guest OS (if not already paused).
pipeRead, pipeWrite, err := os.Pipe()
if err != nil {
return err
}
defer func() {
_ = pipeRead.Close()
_ = pipeWrite.Close()
}()
go func() { _, _ = io.Copy(stateConn, pipeRead) }()
err = d.saveStateHandle(monitor, pipeWrite)
if err != nil {
return fmt.Errorf("Failed starting state transfer to target: %w", err)
}
// Start monitoring the migration progress.
chMonitor := make(chan bool, 1)
if d.op != nil {
go func() {
for {
// Wait for next update.
select {
case <-chMonitor:
return
case <-time.After(time.Second):
}
// Get current migration progress.
progress, err := monitor.QueryMigrate()
if err != nil {
// Stop monitoring on error.
return
}
// Post update.
percent := int64(float64(progress.RAM.Transferred) / float64(progress.RAM.Total) * float64(100))
speed := int64(progress.RAM.MBps * 1024 * 1024 / 8)
metadata := map[string]any{}
metadata["progress"] = map[string]string{
"stage": "live_migrate_instance",
"processed": strconv.FormatInt(progress.RAM.Transferred, 10),
"percent": strconv.FormatInt(percent, 10),
"speed": strconv.FormatInt(speed, 10),
}
metadata["live_migrate_instance_progress"] = fmt.Sprintf("Live migration: %s remaining (%s/s) (%d%% CPU throttle)", units.GetByteSizeString(progress.RAM.Remaining, 2), units.GetByteSizeString(speed, 2), progress.CPUThrottlePercentage)
_ = d.op.UpdateMetadata(metadata)
}
}()
}
// Non-shared storage snapshot transfer finalization.
if !sameSharedStorage {
// Wait until state transfer has reached pre-switchover state (the guest OS will remain paused).
err = monitor.MigrateWait("pre-switchover")
if err != nil {
return fmt.Errorf("Failed waiting for state transfer to reach pre-switchover stage: %w", err)
}
d.logger.Debug("Stateful migration checkpoint reached pre-switchover phase")
// Complete the migration snapshot sync process (the guest OS will remain paused).
d.logger.Debug("Migration storage snapshot transfer commit started")
err = monitor.BlockJobCancel(rootSnapshotDiskName)
if err != nil {
return fmt.Errorf("Failed cancelling block job: %w", err)
}
d.logger.Debug("Migration storage snapshot transfer commit finished")
// Finalise the migration state transfer (the guest OS will remain paused).
err = monitor.MigrateContinue("pre-switchover")
if err != nil {
return fmt.Errorf("Failed continuing state transfer: %w", err)
}
d.logger.Debug("Stateful migration checkpoint send continuing")
}
// Wait until the migration state transfer has completed (the guest OS will remain paused).
err = monitor.MigrateWait("completed")
if err != nil {
return fmt.Errorf("Failed waiting for state transfer to reach completed stage: %w", err)
}
close(chMonitor)
d.logger.Debug("Stateful migration checkpoint send finished")
if clusterMoveSourceName != "" {
// If doing an intra-cluster member move then we will be deleting the instance on the source,
// so lets just stop it after migration is completed.
err = d.Stop(false)
if err != nil {
return fmt.Errorf("Failed stopping instance: %w", err)
}
} else {
// Remove the NBD client disk.
err := monitor.RemoveBlockDevice(nbdTargetDiskName)
if err != nil {
d.logger.Warn("Failed removing NBD storage target device", logger.Ctx{"err": err})
}
d.logger.Debug("Removed NBD storage target device")
// Resume guest.
err = monitor.Start()
if err != nil {
return fmt.Errorf("Failed resuming instance: %w", err)
}
d.logger.Debug("Resumed instance")
// Merge snapshot back to the source disk so we don't lose the writes.
d.logger.Debug("Merge migration storage snapshot on source started")
err = monitor.BlockCommit(rootSnapshotDiskName)
if err != nil {
return fmt.Errorf("Failed merging migration storage snapshot: %w", err)
}
d.logger.Debug("Merge migration storage snapshot on source finished")
}
reverter.Success()
return nil
}
func (d *qemu) MigrateReceive(args instance.MigrateReceiveArgs) error {
d.logger.Debug("Migration receive starting")
defer d.logger.Debug("Migration receive stopped")
// Wait for essential migration connections before negotiation.
connectionsCtx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
filesystemConn, err := args.FilesystemConn(connectionsCtx)
if err != nil {
return err
}
// Receive offer from source.
d.logger.Debug("Waiting for migration offer from source")
offerHeader := &migration.MigrationHeader{}
err = args.ControlReceive(offerHeader)
if err != nil {
return fmt.Errorf("Failed receiving migration offer from source: %w", err)
}
// When doing a cluster same-name move we cannot load the storage pool using the instance's volume DB
// record because it may be associated to the wrong cluster member. Instead we ascertain the pool to load
// using the instance's root disk device.
if args.ClusterMoveSourceName == d.name {
if args.StoragePool != "" {
d.storagePool, err = storagePools.LoadByName(d.state, args.StoragePool)
if err != nil {
return fmt.Errorf("Failed loading storage pool: %w", err)
}
} else {
_, rootDiskDevice, err := d.getRootDiskDevice()
if err != nil {
return fmt.Errorf("Failed getting root disk: %w", err)
}
if rootDiskDevice["pool"] == "" {
return errors.New("The instance's root device is missing the pool property")
}
// Initialize the storage pool cache.
d.storagePool, err = storagePools.LoadByName(d.state, rootDiskDevice["pool"])
if err != nil {
return fmt.Errorf("Failed loading storage pool: %w", err)
}
}
}
pool, err := storagePools.LoadByInstance(d.state, d)
if err != nil {
return err
}
// The source will never set Refresh in the offer header.
// However, to determine the correct migration type Refresh needs to be set.
offerHeader.Refresh = &args.Refresh
clusterMove := args.ClusterMoveSourceName != ""
storageMove := args.StoragePool != ""
// Extract the source's migration type and then match it against our pool's supported types and features.
// If a match is found the combined features list will be sent back to requester.
contentType := storagePools.InstanceContentType(d)
respTypes, err := localMigration.MatchTypes(offerHeader, storagePools.FallbackMigrationType(contentType), pool.MigrationTypes(contentType, args.Refresh, args.Snapshots, clusterMove, storageMove))
if err != nil {
return err
}
// The migration header to be sent back to source with our target options.
// Convert response type to response header and copy snapshot info into it.
respHeader := localMigration.TypesToHeader(respTypes...)
// Respond with our maximum supported header version if the requested version is higher than ours.
// Otherwise just return the requested header version to the source.
indexHeaderVersion := min(offerHeader.GetIndexHeaderVersion(), localMigration.IndexHeaderVersion)
respHeader.IndexHeaderVersion = &indexHeaderVersion
respHeader.SnapshotNames = offerHeader.SnapshotNames
respHeader.Snapshots = offerHeader.Snapshots
respHeader.Refresh = &args.Refresh
if args.Refresh {
// Get the remote snapshots on the source.
sourceSnapshots := offerHeader.GetSnapshots()
sourceSnapshotComparable := make([]storagePools.ComparableSnapshot, 0, len(sourceSnapshots))
for _, sourceSnap := range sourceSnapshots {
sourceSnapshotComparable = append(sourceSnapshotComparable, storagePools.ComparableSnapshot{
Name: sourceSnap.GetName(),
CreationDate: time.Unix(sourceSnap.GetCreationDate(), 0),
})
}
// Get existing snapshots on the local target.
targetSnapshots, err := d.Snapshots()
if err != nil {
return err
}
targetSnapshotsComparable := make([]storagePools.ComparableSnapshot, 0, len(targetSnapshots))
for _, targetSnap := range targetSnapshots {
_, targetSnapName, _ := api.GetParentAndSnapshotName(targetSnap.Name())
targetSnapshotsComparable = append(targetSnapshotsComparable, storagePools.ComparableSnapshot{
Name: targetSnapName,
CreationDate: targetSnap.CreationDate(),
})
}
// Compare the two sets.
syncSourceSnapshotIndexes, deleteTargetSnapshotIndexes := storagePools.CompareSnapshots(sourceSnapshotComparable, targetSnapshotsComparable, args.RefreshExcludeOlder)
// Delete the extra local snapshots first.
for _, deleteTargetSnapshotIndex := range deleteTargetSnapshotIndexes {
err := targetSnapshots[deleteTargetSnapshotIndex].Delete(true)
if err != nil {
return err
}
}
// Only request to send the snapshots that need updating.
syncSnapshotNames := make([]string, 0, len(syncSourceSnapshotIndexes))
syncSnapshots := make([]*migration.Snapshot, 0, len(syncSourceSnapshotIndexes))
for _, syncSourceSnapshotIndex := range syncSourceSnapshotIndexes {
syncSnapshotNames = append(syncSnapshotNames, sourceSnapshots[syncSourceSnapshotIndex].GetName())
syncSnapshots = append(syncSnapshots, sourceSnapshots[syncSourceSnapshotIndex])
}
respHeader.Snapshots = syncSnapshots
respHeader.SnapshotNames = syncSnapshotNames
offerHeader.Snapshots = syncSnapshots
offerHeader.SnapshotNames = syncSnapshotNames
}
// Negotiate support for QEMU to QEMU live state transfer.
// If the request is for live migration, then respond that live QEMU to QEMU state transfer can proceed.
// Otherwise we'll fallback to doing stateful stop, migrate, and then stateful start, which will still
// fulfil the "live" part of the request, albeit with longer pause of the instance during the process.
poolInfo := pool.Driver().Info()
var useStateConn bool
if args.Live && offerHeader.Criu != nil && *offerHeader.Criu == migration.CRIUType_VM_QEMU {
respHeader.Criu = migration.CRIUType_VM_QEMU.Enum()
useStateConn = true
}
// Send response to source.
d.logger.Debug("Sending migration response to source")
err = args.ControlSend(respHeader)
if err != nil {
return fmt.Errorf("Failed sending migration response to source: %w", err)
}
d.logger.Debug("Sent migration response to source")
// Establish state transfer connection if needed.
var stateConn io.ReadWriteCloser
if args.Live && useStateConn {
stateConn, err = args.StateConn(connectionsCtx)
if err != nil {
return err
}
}
reverter := revert.New()
defer reverter.Fail()
g, ctx := errgroup.WithContext(context.Background())
// Start control connection monitor.
g.Go(func() error {
d.logger.Debug("Migrate receive control monitor started")
defer d.logger.Debug("Migrate receive control monitor finished")
controlResult := make(chan error, 1) // Buffered to allow go routine to end if no readers.
// This will read the result message from the source side and detect disconnections.
go func() {
resp := migration.MigrationControl{}
err := args.ControlReceive(&resp)
if err != nil {
err = fmt.Errorf("Error reading migration control source: %w", err)
} else if !resp.GetSuccess() {
err = fmt.Errorf("Error from migration control source: %s", resp.GetMessage())
}
controlResult <- err
}()
// End as soon as we get control message/disconnection from the source side or a local error.
select {
case <-ctx.Done():
err = ctx.Err()
case err = <-controlResult:
}
return err
})
// Start error monitoring routine, this will detect when an error is returned from the other routines,
// and if that happens it will disconnect the migration connections which will trigger the other routines
// to finish.
go func() {
<-ctx.Done()
args.Disconnect()
}()
// Start filesystem transfer routine and initialize a channel that is closed when the routine finishes.
fsTransferDone := make(chan struct{})
g.Go(func() error {
defer close(fsTransferDone)
d.logger.Debug("Migrate receive transfer started")
defer d.logger.Debug("Migrate receive transfer finished")
var err error
snapshots := make([]*migration.Snapshot, 0)
// Legacy: we only sent the snapshot names, so we just copy the instances's config over,
// same as we used to do.
if len(offerHeader.SnapshotNames) != len(offerHeader.Snapshots) {
// Convert the instance to an api.InstanceSnapshot.
profileNames := make([]string, 0, len(d.Profiles()))
for _, p := range d.Profiles() {
profileNames = append(profileNames, p.Name)
}
architectureName, _ := osarch.ArchitectureName(d.Architecture())
apiInstSnap := &api.InstanceSnapshot{
InstanceSnapshotPut: api.InstanceSnapshotPut{
ExpiresAt: time.Time{},
},
Architecture: architectureName,
CreatedAt: d.CreationDate(),
LastUsedAt: d.LastUsedDate(),
Config: d.LocalConfig(),
Devices: d.LocalDevices().CloneNative(),
Ephemeral: d.IsEphemeral(),
Stateful: d.IsStateful(),
Profiles: profileNames,
}
for _, name := range offerHeader.SnapshotNames {
base := instance.SnapshotToProtobuf(apiInstSnap)
base.Name = &name
snapshots = append(snapshots, base)
}
} else {
snapshots = offerHeader.Snapshots
}
volTargetArgs := localMigration.VolumeTargetArgs{
IndexHeaderVersion: respHeader.GetIndexHeaderVersion(),
Name: d.Name(),
MigrationType: respTypes[0],
Refresh: args.Refresh, // Indicate to receiver volume should exist.
TrackProgress: true, // Use a progress tracker on receiver to get in-cluster progress information.
Live: false, // Indicates we won't get a final rootfs sync.
VolumeSize: offerHeader.GetVolumeSize(), // Block size setting override.
VolumeOnly: !args.Snapshots,
ClusterMoveSourceName: args.ClusterMoveSourceName,
StoragePool: args.StoragePool,
}
// At this point we have already figured out the parent instances's root
// disk device so we can simply retrieve it from the expanded devices.
parentStoragePool := ""
parentExpandedDevices := d.ExpandedDevices()
parentLocalRootDiskDeviceKey, parentLocalRootDiskDevice, _ := internalInstance.GetRootDiskDevice(parentExpandedDevices.CloneNative())
if parentLocalRootDiskDeviceKey != "" {
parentStoragePool = parentLocalRootDiskDevice["pool"]
}
if parentStoragePool == "" {
return errors.New("Instance's root device is missing the pool property")
}
// A zero length Snapshots slice indicates volume only migration in
// VolumeTargetArgs. So if VolumeOnly was requested, do not populate them.
if args.Snapshots {
volTargetArgs.Snapshots = make([]*migration.Snapshot, 0, len(snapshots))
for _, snap := range snapshots {
migrationSnapshot := &migration.Snapshot{Name: snap.Name}
migration.SetSnapshotConfigValue(migrationSnapshot, "size", migration.GetSnapshotConfigValue(snap, "size"))
volTargetArgs.Snapshots = append(volTargetArgs.Snapshots, migrationSnapshot)
// Only create snapshot instance DB records if not doing a cluster same-name move.
// As otherwise the DB records will already exist.
if args.ClusterMoveSourceName != d.name {
snapArgs, err := instance.SnapshotProtobufToInstanceArgs(d.state, d, snap)
if err != nil {
return err
}
// The offerHeader, depending on the case, stores information about either an InstanceSnapshot
// or a StorageVolumeSnapshot. In the Config, we pass information about the volume size,
// but an InstanceSnapshot config cannot have a 'size' key. This key should be removed
// before passing the data to the CreateInternal method.
delete(snapArgs.Config, "size")
// Ensure that snapshot and parent instance have the same storage pool in
// their local root disk device. If the root disk device for the snapshot
// comes from a profile on the new instance as well we don't need to do
// anything.
if snapArgs.Devices != nil {
snapLocalRootDiskDeviceKey, _, _ := internalInstance.GetRootDiskDevice(snapArgs.Devices.CloneNative())
if snapLocalRootDiskDeviceKey != "" {
snapArgs.Devices[snapLocalRootDiskDeviceKey]["pool"] = parentStoragePool
}
}
// Create the snapshot instance.
_, snapInstOp, cleanup, err := instance.CreateInternal(d.state, *snapArgs, d.op, true, false)
if err != nil {
return fmt.Errorf("Failed creating instance snapshot record %q: %w", snapArgs.Name, err)
}
reverter.Add(cleanup)
defer snapInstOp.Done(err)
}
}
}
err = pool.CreateInstanceFromMigration(d, filesystemConn, volTargetArgs, d.op)
if err != nil {
return fmt.Errorf("Failed creating instance on target: %w", err)
}
// Derive the effective storage project name from the instance config's project.
storageProjectName, err := project.StorageVolumeProject(d.state.DB.Cluster, d.project.Name, db.StoragePoolVolumeTypeCustom)
if err != nil {
return err
}
// Notify the shared disks that they're going to be accessed from another system.
for _, dev := range d.expandedDevices.Sorted() {
if dev.Config["type"] != "disk" || dev.Config["path"] == "/" || dev.Config["pool"] == "" {
continue
}
// Load the pool for the disk.
diskPool, err := storagePools.LoadByName(d.state, dev.Config["pool"])
if err != nil {
return fmt.Errorf("Failed loading storage pool: %w", err)
}
// Check that we're on shared storage.
if !diskPool.Driver().Info().Remote {
continue
}
// Setup the volume entry.
extraTargetArgs := localMigration.VolumeTargetArgs{
ClusterMoveSourceName: args.ClusterMoveSourceName,
StoragePool: args.StoragePool,
}
vol := diskPool.GetVolume(storageDrivers.VolumeTypeCustom, storageDrivers.ContentTypeBlock, project.StorageVolume(storageProjectName, dev.Config["source"]), nil)
// Call MigrateVolume on the source.
err = diskPool.Driver().CreateVolumeFromMigration(vol, nil, extraTargetArgs, nil, nil)
if err != nil {
return fmt.Errorf("Failed to prepare device %q for migration: %w", dev.Name, err)
}
}
// Only delete all instance volumes on error if the pool volume creation has succeeded to
// avoid deleting an existing conflicting volume.
isRemoteClusterMove := clusterMove && poolInfo.Remote
if !volTargetArgs.Refresh && !isRemoteClusterMove {
reverter.Add(func() {
snapshots, _ := d.Snapshots()
snapshotCount := len(snapshots)
for k := range snapshots {
// Delete the snapshots in reverse order.
k = snapshotCount - 1 - k
_ = pool.DeleteInstanceSnapshot(snapshots[k], nil)
}
_ = pool.DeleteInstance(d, nil)
})
}
if args.ClusterMoveSourceName != d.name {
err = d.DeferTemplateApply(instance.TemplateTriggerCopy)
if err != nil {
return err
}
}
if args.Live {
// Start live state transfer using state connection if supported.
if stateConn != nil {
d.migrationReceiveStateful = map[string]io.ReadWriteCloser{
api.SecretNameState: stateConn,
}
// Populate the filesystem connection handle if doing non-shared storage migration.
sameSharedStorage := args.ClusterMoveSourceName != "" && poolInfo.Remote && args.StoragePool == ""
if !sameSharedStorage {
d.migrationReceiveStateful[api.SecretNameFilesystem] = filesystemConn
}
}
// Although the instance technically isn't considered stateful, we set this to allow
// starting from the migrated state file or migration state connection.
d.stateful = true
err = d.start(true, args.InstanceOperation)
if err != nil {
return err
}
}
return nil
})
{
// Wait until the filesystem transfer routine has finished.
<-fsTransferDone
// If context is cancelled by this stage, then an error has occurred.
// Wait for all routines to finish and collect the first error that occurred.
if ctx.Err() != nil {
err := g.Wait()
// Send failure response to source.
msg := migration.MigrationControl{
Success: proto.Bool(err == nil),
}
if err != nil {
msg.Message = proto.String(err.Error())
}
d.logger.Debug("Sending migration failure response to source", logger.Ctx{"err": err})
sendErr := args.ControlSend(&msg)
if sendErr != nil {
d.logger.Warn("Failed sending migration failure to source", logger.Ctx{"err": sendErr})
}
return err
}
// Send success response to source to control as nothing has gone wrong so far.
msg := migration.MigrationControl{
Success: proto.Bool(true),
}
d.logger.Debug("Sending migration success response to source", logger.Ctx{"success": msg.GetSuccess()})
err := args.ControlSend(&msg)
if err != nil {
d.logger.Warn("Failed sending migration success to source", logger.Ctx{"err": err})
return fmt.Errorf("Failed sending migration success to source: %w", err)
}
// Wait for all routines to finish (in this case it will be the control monitor) but do
// not collect the error, as it will just be a disconnect error from the source.
_ = g.Wait()
reverter.Success()
return nil
}
}
// CGroupSet is not implemented for VMs.
func (d *qemu) CGroup() (*cgroup.CGroup, error) {
return nil, instance.ErrNotImplemented
}
// FileSFTPConn returns a connection to the agent SFTP endpoint.
func (d *qemu) FileSFTPConn() (net.Conn, error) {
// VMs, unlike containers, cannot perform file operations if not running and using the agent.
if !d.IsRunning() {
return nil, errors.New("Instance is not running")
}
// Connect to the agent.
client, err := d.getAgentClient()
if err != nil {
return nil, err
}
// Get the HTTP transport.
httpTransport := client.Transport.(*http.Transport)
// Send the upgrade request.
u, err := url.Parse("https://custom.socket/1.0/sftp")
if err != nil {
return nil, err
}
req := &http.Request{
Method: http.MethodGet,
URL: u,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Header: make(http.Header),
Host: u.Host,
}
req.Header["Upgrade"] = []string{"sftp"}
req.Header["Connection"] = []string{"Upgrade"}
conn, err := httpTransport.DialContext(context.Background(), "tcp", "8443")
if err != nil {
return nil, err
}
tlsConn := tls.Client(conn, httpTransport.TLSClientConfig)
err = tlsConn.Handshake()
if err != nil {
return nil, err
}
err = req.Write(tlsConn)
if err != nil {
return nil, err
}
resp, err := http.ReadResponse(bufio.NewReader(tlsConn), req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusSwitchingProtocols {
return nil, fmt.Errorf("Dialing failed: expected status code 101 got %d", resp.StatusCode)
}
if resp.Header.Get("Upgrade") != "sftp" {
return nil, errors.New("Missing or unexpected Upgrade header in response")
}
return tlsConn, nil
}
// FileSFTP returns an SFTP connection to the agent endpoint.
func (d *qemu) FileSFTP() (*sftp.Client, error) {
// Connect to the forkfile daemon.
conn, err := d.FileSFTPConn()
if err != nil {
return nil, err
}
// Get a SFTP client.
client, err := sftp.NewClientPipe(conn, conn)
if err != nil {
_ = conn.Close()
return nil, err
}
go func() {
// Wait for the client to be done before closing the connection.
_ = client.Wait()
_ = conn.Close()
}()
return client, nil
}
// Console gets access to the instance's console.
func (d *qemu) Console(protocol string) (*os.File, chan error, error) {
var path string
switch protocol {
case instance.ConsoleTypeConsole:
path = d.consolePath()
case instance.ConsoleTypeVGA:
path = d.spicePath()
default:
return nil, nil, fmt.Errorf("Unknown protocol %q", protocol)
}
// When activating the text-based console, swap the backend to be a socket for an interactive connection.
if protocol == instance.ConsoleTypeConsole {
// Look for existing connections and reset.
conn, err := net.Dial("unix", path)
if err == nil {
_ = d.consoleSwapSocketWithRB()
_ = conn.Close()
// Allow for cleanup to complete on the existing connection.
time.Sleep(time.Second)
}
err = d.consoleSwapRBWithSocket()
if err != nil {
_ = d.consoleSwapSocketWithRB()
return nil, nil, fmt.Errorf("Failed to swap console ring buffer with socket: %w", err)
}
}
// Disconnection notification.
chDisconnect := make(chan error, 1)
// Open the console socket.
conn, err := net.Dial("unix", path)
if err != nil {
if protocol == instance.ConsoleTypeConsole {
_ = d.consoleSwapSocketWithRB()
}
return nil, nil, fmt.Errorf("Connect to console socket %q: %w", path, err)
}
file, err := (conn.(*net.UnixConn)).File()
if err != nil {
if protocol == instance.ConsoleTypeConsole {
_ = d.consoleSwapSocketWithRB()
}
return nil, nil, fmt.Errorf("Get socket file: %w", err)
}
_ = conn.Close()
// Handle disconnections.
go func() {
<-chDisconnect
_ = d.consoleSwapSocketWithRB()
}()
d.state.Events.SendLifecycle(d.project.Name, lifecycle.InstanceConsole.Event(d, logger.Ctx{"type": protocol}))
return file, chDisconnect, nil
}
// Exec a command inside the instance.
func (d *qemu) Exec(req api.InstanceExecPost, stdin *os.File, stdout *os.File, stderr *os.File) (instance.Cmd, error) {
reverter := revert.New()
defer reverter.Fail()
client, err := d.getAgentClient()
if err != nil {
return nil, err
}
agent, err := incus.ConnectIncusHTTP(nil, client)
if err != nil {
d.logger.Error("Failed to connect to the agent", logger.Ctx{"err": err})
return nil, errors.New("Failed to connect to the agent")
}
reverter.Add(agent.Disconnect)
dataDone := make(chan bool)
controlSendCh := make(chan api.InstanceExecControl)
controlResCh := make(chan error)
// This is the signal control handler, it receives signals from lxc CLI and forwards them to the VM agent.
controlHandler := func(control *websocket.Conn) {
closeMsg := websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")
defer func() { _ = control.WriteMessage(websocket.CloseMessage, closeMsg) }()
for {
select {
case cmd := <-controlSendCh:
controlResCh <- control.WriteJSON(cmd)
case <-dataDone:
return
}
}
}
args := incus.InstanceExecArgs{
Stdin: stdin,
Stdout: stdout,
Stderr: stderr,
DataDone: dataDone,
Control: controlHandler,
}
// Always needed for VM exec, as even for non-websocket requests from the client we need to connect the
// websockets for control and for capturing output to a file on the server.
req.WaitForWS = true
// Similarly, output recording is performed on the host rather than in the guest, so clear that bit from the request.
req.RecordOutput = false
op, err := agent.ExecInstance("", req, &args)
if err != nil {
return nil, err
}
instCmd := &qemuCmd{
cmd: op,
attachedChildPid: 0, // Process is not running on the host.
dataDone: args.DataDone,
cleanupFunc: reverter.Clone().Fail, // Pass revert function clone as clean up function.
controlSendCh: controlSendCh,
controlResCh: controlResCh,
}
d.state.Events.SendLifecycle(d.project.Name, lifecycle.InstanceExec.Event(d, logger.Ctx{"command": req.Command}))
reverter.Success()
return instCmd, nil
}
// RenderWithUsage renders the API response including disk usage.
func (d *qemu) RenderWithUsage() (any, any, error) {
resp, etag, err := d.Render()
if err != nil {
return nil, nil, err
}
// Currently only snapshot data needs usage added.
snapResp, ok := resp.(*api.InstanceSnapshot)
if !ok {
return resp, etag, nil
}
pool, err := d.getStoragePool()
if err != nil {
return nil, nil, err
}
// It is important that the snapshot not be mounted here as mounting a snapshot can trigger a very
// expensive filesystem UUID regeneration, so we rely on the driver implementation to get the info
// we are requesting as cheaply as possible.
volumeState, err := pool.GetInstanceUsage(d)
if err != nil {
return resp, etag, nil
}
snapResp.Size = volumeState.Used
return snapResp, etag, nil
}
// Render returns info about the instance.
func (d *qemu) Render() (any, any, error) {
profileNames := make([]string, 0, len(d.profiles))
for _, profile := range d.profiles {
profileNames = append(profileNames, profile.Name)
}
if d.IsSnapshot() {
// Prepare the response.
snapState := api.InstanceSnapshot{
CreatedAt: d.creationDate,
ExpandedConfig: d.expandedConfig,
ExpandedDevices: d.expandedDevices.CloneNative(),
LastUsedAt: d.lastUsedDate,
Name: strings.SplitN(d.name, "/", 2)[1],
Stateful: d.stateful,
Size: -1, // Default to uninitialized/error state (0 means no CoW usage).
}
snapState.Architecture = d.architectureName
snapState.Config = d.localConfig
snapState.Devices = d.localDevices.CloneNative()
snapState.Ephemeral = d.ephemeral
snapState.Profiles = profileNames
snapState.ExpiresAt = d.expiryDate
return &snapState, d.ETag(), nil
}
// Prepare the response.
statusCode := d.statusCode()
instState := api.Instance{
ExpandedConfig: d.expandedConfig,
ExpandedDevices: d.expandedDevices.CloneNative(),
Name: d.name,
Status: statusCode.String(),
StatusCode: statusCode,
Location: d.node,
Type: d.Type().String(),
}
instState.Description = d.description
instState.Architecture = d.architectureName
instState.Config = d.localConfig
instState.CreatedAt = d.creationDate
instState.Devices = d.localDevices.CloneNative()
instState.Ephemeral = d.ephemeral
instState.LastUsedAt = d.lastUsedDate
instState.Profiles = profileNames
instState.Stateful = d.stateful
instState.Project = d.project.Name
return &instState, d.ETag(), nil
}
// RenderFull returns all info about the instance.
func (d *qemu) RenderFull(hostInterfaces []net.Interface) (*api.InstanceFull, any, error) {
if d.IsSnapshot() {
return nil, nil, errors.New("RenderFull doesn't work with snapshots")
}
// Pre-fetch the data.
pool, err := d.getStoragePool()
if err != nil {
return nil, nil, err
}
err = pool.CacheInstanceSnapshots(d)
if err != nil {
return nil, nil, err
}
// Get the Instance struct.
base, etag, err := d.Render()
if err != nil {
return nil, nil, err
}
// Convert to InstanceFull.
vmState := api.InstanceFull{Instance: *base.(*api.Instance)}
// Add the InstanceState.
vmState.State, err = d.renderState(vmState.StatusCode)
if err != nil {
return nil, nil, err
}
// Add the InstanceSnapshots.
snaps, err := d.Snapshots()
if err != nil {
return nil, nil, err
}
for _, snap := range snaps {
render, _, err := snap.Render()
if err != nil {
return nil, nil, err
}
if vmState.Snapshots == nil {
vmState.Snapshots = []api.InstanceSnapshot{}
}
vmState.Snapshots = append(vmState.Snapshots, *render.(*api.InstanceSnapshot))
}
// Add the InstanceBackups.
backups, err := d.Backups()
if err != nil {
return nil, nil, err
}
for _, backup := range backups {
render := backup.Render()
if vmState.Backups == nil {
vmState.Backups = []api.InstanceBackup{}
}
vmState.Backups = append(vmState.Backups, *render)
}
return &vmState, etag, nil
}
// renderState returns just state info about the instance.
func (d *qemu) renderState(statusCode api.StatusCode) (*api.InstanceState, error) {
var err error
status := &api.InstanceState{}
pid, _ := d.pid()
if d.isRunningStatusCode(statusCode) {
if d.agentMetricsEnabled() {
// Try and get state info from agent.
status, err = d.agentGetState()
if err != nil {
if !errors.Is(err, errQemuAgentOffline) {
d.logger.Warn("Could not get VM state from agent", logger.Ctx{"err": err})
}
// Fallback data if agent is not reachable.
status = &api.InstanceState{}
status.Processes = -1
}
if len(status.Network) == 0 {
status.Network, err = d.getNetworkState()
if err != nil {
return nil, err
}
}
} else {
status.Processes = -1
status.Network, err = d.getNetworkState()
if err != nil {
return nil, err
}
}
// Populate the CPU time allocation
limitsCPU, ok := d.expandedConfig["limits.cpu"]
if ok {
cpuCount, err := strconv.ParseInt(limitsCPU, 10, 64)
if err != nil {
status.CPU.AllocatedTime = cpuCount * 1_000_000_000
}
} else {
status.CPU.AllocatedTime = qemudefault.CPUCores * 1_000_000_000
}
// Populate host_name for network devices.
for k, m := range d.ExpandedDevices() {
// We only care about nics.
if m["type"] != "nic" {
continue
}
// Get hwaddr from static or volatile config.
hwaddr := m["hwaddr"]
if hwaddr == "" {
hwaddr = d.localConfig[fmt.Sprintf("volatile.%s.hwaddr", k)]
}
// We have to match on hwaddr as device name can be different from the configured device
// name when reported from the agent inside the VM (due to the guest OS choosing name).
for netName, netStatus := range status.Network {
if netStatus.Hwaddr == hwaddr {
if netStatus.HostName == "" {
netStatus.HostName = d.localConfig[fmt.Sprintf("volatile.%s.host_name", k)]
status.Network[netName] = netStatus
}
}
}
}
status.Pid = int64(pid)
status.StartedAt, err = d.processStartedAt(d.InitPID())
if err != nil {
return status, err
}
}
status.Status = statusCode.String()
status.StatusCode = statusCode
status.Disk, err = d.diskState()
if err != nil && !errors.Is(err, storageDrivers.ErrNotSupported) {
d.logger.Warn("Error getting disk usage", logger.Ctx{"err": err})
}
return status, nil
}
// RenderState returns just state info about the instance.
func (d *qemu) RenderState(hostInterfaces []net.Interface) (*api.InstanceState, error) {
return d.renderState(d.statusCode())
}
// diskState gets disk usage info.
func (d *qemu) diskState() (map[string]api.InstanceStateDisk, error) {
pool, err := d.getStoragePool()
if err != nil {
return nil, err
}
// Get the root disk device config.
rootDiskName, _, err := d.getRootDiskDevice()
if err != nil {
return nil, err
}
usage, err := pool.GetInstanceUsage(d)
if err != nil {
return nil, err
}
disk := map[string]api.InstanceStateDisk{}
disk[rootDiskName] = api.InstanceStateDisk{
Usage: usage.Used,
Total: usage.Total,
}
return disk, nil
}
// agentGetState connects to the agent inside of the VM and does
// an API call to get the current state.
func (d *qemu) agentGetState() (*api.InstanceState, error) {
client, err := d.getAgentClient()
if err != nil {
return nil, err
}
agent, err := incus.ConnectIncusHTTP(nil, client)
if err != nil {
return nil, fmt.Errorf("Failed connecting to agent: %w", err)
}
defer agent.Disconnect()
status, _, err := agent.GetInstanceState("")
if err != nil {
return nil, err
}
return status, nil
}
// IsRunning returns whether or not the instance is running.
func (d *qemu) IsRunning() bool {
return d.isRunningStatusCode(d.statusCode())
}
// IsFrozen returns whether the instance frozen or not.
func (d *qemu) IsFrozen() bool {
return d.statusCode() == api.Frozen
}
// CanMigrate returns whether the instance can be migrated.
func (d *qemu) CanMigrate() string {
return d.canMigrate(d)
}
// LockExclusive attempts to get exclusive access to the instance's root volume.
func (d *qemu) LockExclusive() (*operationlock.InstanceOperation, error) {
if d.IsRunning() {
return nil, errors.New("Instance is running")
}
// Prevent concurrent operations the instance.
op, err := operationlock.Create(d.Project().Name, d.Name(), d.op, operationlock.ActionCreate, false, false)
if err != nil {
return nil, err
}
return op, err
}
// DeviceEventHandler handles events occurring on the instance's devices.
func (d *qemu) DeviceEventHandler(runConf *deviceConfig.RunConfig) error {
if !d.IsRunning() || runConf == nil {
return nil
}
// Handle uevents.
for _, uevent := range runConf.Uevents {
for _, event := range uevent {
fields := strings.SplitN(event, "=", 2)
if fields[0] != "ACTION" {
continue
}
switch fields[1] {
case "add":
for _, usbDev := range runConf.USBDevice {
// This ensures that the device is actually removed from QEMU before adding it again.
// In most cases the device will already be removed, but it is possible that the
// device still exists in QEMU before trying to add it again.
// If a USB device is physically detached from a running VM while the server
// itself is stopped, QEMU in theory will not delete the device.
err := d.deviceDetachUSB(usbDev)
if err != nil {
return err
}
err = d.deviceAttachUSB(usbDev)
if err != nil {
return err
}
}
case "remove":
for _, usbDev := range runConf.USBDevice {
err := d.deviceDetachUSB(usbDev)
if err != nil {
return err
}
}
}
}
}
// Handle disk reconfiguration.
for _, mount := range runConf.Mounts {
if mount.Limits == nil && mount.Size == 0 {
// This special case allows handling live attach/detach logic.
config, ok := d.expandedDevices[mount.DevName]
if !ok {
return fmt.Errorf("Couldn't find device %q", mount.DevName)
}
dev, err := d.deviceLoad(d, mount.DevName, config)
if err != nil {
return err
}
if mount.Attached {
_, err = d.deviceStart(dev, true)
if err != nil {
return err
}
} else {
err = d.deviceStop(dev, true, "")
if err != nil {
return err
}
}
continue
}
// Get the QMP monitor.
m, err := d.qmpConnect()
if err != nil {
return err
}
// Figure out the QEMU device ID.
devID := fmt.Sprintf("%s%s", qemuDeviceIDPrefix, linux.PathNameEncode(mount.DevName))
if mount.Limits != nil {
// Apply the limits.
err = m.SetBlockThrottle(devID, int(mount.Limits.ReadBytes), int(mount.Limits.WriteBytes), int(mount.Limits.ReadIOps), int(mount.Limits.WriteIOps))
if err != nil {
return fmt.Errorf("Failed applying limits for disk device %q: %w", mount.DevName, err)
}
}
if mount.Size > 0 {
// Update the size.
err = m.UpdateBlockSize(strings.SplitN(devID, "-", 2)[1])
if err != nil {
return fmt.Errorf("Failed updating disk size %q: %w", mount.DevName, err)
}
}
}
return nil
}
// reservedVsockID returns true if the given vsockID equals 0, 1 or 2.
// Those are reserved and we cannot use them.
func (d *qemu) reservedVsockID(vsockID uint32) bool {
return vsockID <= 2
}
// getVsockID returns the vsock Context ID for the VM.
func (d *qemu) getVsockID() (uint32, error) {
existingVsockID, ok := d.localConfig["volatile.vsock_id"]
if !ok {
return 0, errors.New("Context ID not set in volatile.vsock_id")
}
vsockID, err := strconv.ParseUint(existingVsockID, 10, 32)
if err != nil {
return 0, fmt.Errorf("Failed to parse volatile.vsock_id: %q: %w", existingVsockID, err)
}
if d.reservedVsockID(uint32(vsockID)) {
return 0, fmt.Errorf("Failed to use reserved vsock Context ID: %q", vsockID)
}
return uint32(vsockID), nil
}
// acquireVsockID tries to occupy the given vsock Context ID.
// If the ID is free it returns the corresponding file handle.
func (d *qemu) acquireVsockID(vsockID uint32) (*os.File, error) {
reverter := revert.New()
defer reverter.Fail()
vsockF, err := os.OpenFile("/dev/vhost-vsock", os.O_RDWR, 0)
if err != nil {
return nil, fmt.Errorf("Failed to open vhost socket: %w", err)
}
reverter.Add(func() { _ = vsockF.Close() })
// The vsock Context ID cannot be supplied as type uint32.
vsockIDInt := uint64(vsockID)
// Call the ioctl to set the context ID.
_, _, errno := unix.Syscall(unix.SYS_IOCTL, vsockF.Fd(), linux.IoctlVhostVsockSetGuestCid, uintptr(unsafe.Pointer(&vsockIDInt)))
if errno != 0 {
if !errors.Is(errno, unix.EADDRINUSE) {
return nil, fmt.Errorf("Failed ioctl syscall to vhost socket: %q", errno.Error())
}
// vsock Context ID is already in use.
return nil, nil
}
reverter.Success()
return vsockF, nil
}
// acquireExistingVsockID tries to acquire an already existing vsock Context ID from volatile.
// It returns both the acquired ID and opened vsock file handle for QEMU.
func (d *qemu) acquireExistingVsockID() (uint32, *os.File, error) {
vsockID, err := d.getVsockID()
if err != nil {
return 0, nil, err
}
// Check if the vsockID from last VM start is still not acquired in case the VM was stopped.
f, err := d.acquireVsockID(vsockID)
if err != nil {
return 0, nil, err
}
return vsockID, f, nil
}
// nextVsockID tries to acquire the next free vsock Context ID for the VM.
// It returns both the acquired ID and opened vsock file handle for QEMU.
func (d *qemu) nextVsockID() (uint32, *os.File, error) {
// Check if vsock ID from last VM start is present in volatile, then use that.
// This allows a running VM to be recovered after DB record deletion and that an agent connection still works
// after the VM's instance ID has changed.
// Continue in case of error since the caller requires a valid vsockID in any case.
vsockID, vsockF, _ := d.acquireExistingVsockID()
if vsockID != 0 && vsockF != nil {
return vsockID, vsockF, nil
}
// Ignore the error from before and start to acquire a new Context ID.
instanceUUID, err := uuid.Parse(d.localConfig["volatile.uuid"])
if err != nil {
return 0, nil, fmt.Errorf("Failed to parse instance UUID from volatile.uuid: %w", err)
}
r, err := localUtil.GetStableRandomGenerator(instanceUUID.String())
if err != nil {
return 0, nil, fmt.Errorf("Failed generating stable random seed from instance UUID %q: %w", instanceUUID, err)
}
timeout := time.Now().Add(5 * time.Second)
// Try to find a new Context ID.
for {
if time.Now().After(timeout) {
return 0, nil, errors.New("Timeout exceeded whilst trying to acquire the next vsock Context ID")
}
candidateVsockID := r.Uint32()
if d.reservedVsockID(candidateVsockID) {
continue
}
vsockF, err := d.acquireVsockID(candidateVsockID)
if err != nil {
return 0, nil, err
}
if vsockF != nil {
return candidateVsockID, vsockF, nil
}
}
}
// InitPID returns the instance's current process ID.
func (d *qemu) InitPID() int {
pid, _ := d.pid()
return pid
}
func (d *qemu) statusCode() api.StatusCode {
// Shortcut to avoid spamming QMP during ongoing operations.
op := operationlock.Get(d.Project().Name, d.Name())
if op != nil {
if op.Action() == operationlock.ActionStart {
return api.Stopped
}
if op.Action() == operationlock.ActionStop {
if util.IsTrue(d.LocalConfig()["volatile.last_state.ready"]) {
return api.Ready
}
return api.Running
}
}
// Connect to the monitor.
monitor, err := d.qmpConnect()
if err != nil {
// If cannot connect to monitor, but qemu process in pid file still exists, then likely qemu
// is unresponsive and this instance is in an error state.
pid, _ := d.pid()
if pid > 0 {
return api.Error
}
// If we fail to connect, chances are the VM isn't running.
return api.Stopped
}
status, err := monitor.Status()
if err != nil {
if errors.Is(err, qmp.ErrMonitorDisconnect) {
// If cannot connect to monitor, but qemu process in pid file still exists, then likely
// qemu is unresponsive and this instance is in an error state.
pid, _ := d.pid()
if pid > 0 {
return api.Error
}
return api.Stopped
}
return api.Error
}
switch status {
case "prelaunch", "running":
if status == "running" && util.IsTrue(d.LocalConfig()["volatile.last_state.ready"]) {
return api.Ready
}
return api.Running
case "inmigrate", "postmigrate", "finish-migrate", "save-vm", "suspended", "paused":
return api.Frozen
default:
return api.Error
}
}
// State returns the instance's state code.
func (d *qemu) State() string {
return strings.ToUpper(d.statusCode().String())
}
// EarlyLogFilePath returns the instance's early log path.
func (d *qemu) EarlyLogFilePath() string {
return filepath.Join(d.LogPath(), "qemu.early.log")
}
// LogFilePath returns the instance's log path.
func (d *qemu) LogFilePath() string {
return filepath.Join(d.LogPath(), "qemu.log")
}
// QMPLogFilePath returns the instance's QMP log path.
func (d *qemu) QMPLogFilePath() string {
return filepath.Join(d.LogPath(), "qemu.qmp.log")
}
// FillNetworkDevice takes a nic or infiniband device type and enriches it with automatically
// generated name and hwaddr properties if these are missing from the device.
func (d *qemu) FillNetworkDevice(name string, m deviceConfig.Device) (deviceConfig.Device, error) {
var err error
newDevice := m.Clone()
nicType, err := nictype.NICType(d.state, d.Project().Name, m)
if err != nil {
return nil, err
}
isPhysicalWithBridge := device.IsPhysicalNICWithBridge(d.state, d.Project().Name, m)
// Fill in the MAC address.
if (!slices.Contains([]string{"physical", "ipvlan"}, nicType) || isPhysicalWithBridge) && m["hwaddr"] == "" {
configKey := fmt.Sprintf("volatile.%s.hwaddr", name)
volatileHwaddr := d.localConfig[configKey]
if volatileHwaddr == "" {
// Generate a new MAC address.
volatileHwaddr, err = instance.DeviceNextInterfaceHWAddr()
if err != nil || volatileHwaddr == "" {
return nil, fmt.Errorf("Failed generating %q: %w", configKey, err)
}
// Update the database and update volatileHwaddr with stored value.
volatileHwaddr, err = d.insertConfigkey(configKey, volatileHwaddr)
if err != nil {
return nil, fmt.Errorf("Failed storing generated config key %q: %w", configKey, err)
}
// Set stored value into current instance config.
d.localConfig[configKey] = volatileHwaddr
d.expandedConfig[configKey] = volatileHwaddr
}
if volatileHwaddr == "" {
return nil, fmt.Errorf("Failed getting %q", configKey)
}
newDevice["hwaddr"] = volatileHwaddr
}
return newDevice, nil
}
// UpdateBackupFile writes the instance's backup.yaml file to storage.
func (d *qemu) UpdateBackupFile() error {
// Prevent concurrent updates to the backup file.
unlock, err := d.updateBackupFileLock(context.Background())
if err != nil {
return err
}
defer unlock()
// Write the current instance state to backup file.
pool, err := d.getStoragePool()
if err != nil {
return err
}
return pool.UpdateInstanceBackupFile(d, true, nil)
}
type cpuTopology struct {
sockets int
cores int
threads int
vcpus map[uint64]uint64
nodes map[uint64][]uint64
}
// cpuTopology takes the CPU limit and computes the QEMU CPU topology.
func (d *qemu) cpuTopology(limit string) (*cpuTopology, error) {
topology := &cpuTopology{}
// Set default to 1 vCPU.
if limit == "" {
limit = "1"
}
// Check if pinned or floating.
nrLimit, err := strconv.Atoi(limit)
if err == nil {
// We're not dealing with a pinned setup.
topology.sockets = 1
topology.cores = nrLimit
topology.threads = 1
return topology, nil
}
// Get CPU topology.
cpus, err := resources.GetCPU()
if err != nil {
return nil, err
}
// Expand the pins.
pins, err := resources.ParseCpuset(limit)
if err != nil {
return nil, err
}
// Match tracking.
vcpus := map[uint64]uint64{}
sockets := map[uint64][]uint64{}
cores := map[uint64][]uint64{}
numaNodes := map[uint64][]uint64{}
// Go through the physical CPUs looking for matches.
i := uint64(0)
for _, cpu := range cpus.Sockets {
for _, core := range cpu.Cores {
for _, thread := range core.Threads {
for _, pin := range pins {
if thread.ID == int64(pin) {
// Found a matching CPU.
vcpus[i] = uint64(pin)
// Track cores per socket.
_, ok := sockets[cpu.Socket]
if !ok {
sockets[cpu.Socket] = []uint64{}
}
if !slices.Contains(sockets[cpu.Socket], core.Core) {
sockets[cpu.Socket] = append(sockets[cpu.Socket], core.Core)
}
// Track threads per core.
_, ok = cores[core.Core]
if !ok {
cores[core.Core] = []uint64{}
}
if !slices.Contains(cores[core.Core], thread.Thread) {
cores[core.Core] = append(cores[core.Core], thread.Thread)
}
// Record NUMA node for thread.
_, ok = cores[core.Core]
if !ok {
numaNodes[thread.NUMANode] = []uint64{}
}
numaNodes[thread.NUMANode] = append(numaNodes[thread.NUMANode], i)
i++
}
}
}
}
}
// Confirm we're getting the expected number of CPUs.
if len(pins) != len(vcpus) {
return nil, fmt.Errorf("Unavailable CPUs requested: %s", limit)
}
// Validate the topology.
valid := true
nrSockets := 0
nrCores := 0
nrThreads := 0
// Confirm that there is no balancing inconsistencies.
countCores := -1
for _, cores := range sockets {
if countCores != -1 && len(cores) != countCores {
valid = false
break
}
countCores = len(cores)
}
countThreads := -1
for _, threads := range cores {
if countThreads != -1 && len(threads) != countThreads {
valid = false
break
}
countThreads = len(threads)
}
// Check against double listing of CPU.
if len(sockets)*countCores*countThreads != len(vcpus) {
valid = false
}
// Build up the topology.
if valid {
// Valid topology.
nrSockets = len(sockets)
nrCores = countCores
nrThreads = countThreads
} else {
d.logger.Warn("Instance uses a CPU pinning profile which doesn't match hardware layout")
// Fallback on pretending everything are cores.
nrSockets = 1
nrCores = len(vcpus)
nrThreads = 1
}
// Prepare struct.
topology.sockets = nrSockets
topology.cores = nrCores
topology.threads = nrThreads
topology.vcpus = vcpus
topology.nodes = numaNodes
return topology, nil
}
func (d *qemu) devIncusEventSend(eventType string, eventMessage map[string]any) error {
event := jmap.Map{}
event["type"] = eventType
event["timestamp"] = time.Now()
event["metadata"] = eventMessage
client, err := d.getAgentClient()
if err != nil {
// Don't fail if the VM simply doesn't have an agent.
if errors.Is(err, errQemuAgentOffline) {
return nil
}
return err
}
agentArgs := &incus.ConnectionArgs{
SkipGetEvents: true,
SkipGetServer: true,
}
agent, err := incus.ConnectIncusHTTP(agentArgs, client)
if err != nil {
d.logger.Error("Failed to connect to the agent", logger.Ctx{"err": err})
return errors.New("Failed to connect to the agent")
}
defer agent.Disconnect()
_, _, err = agent.RawQuery("POST", "/1.0/events", &event, "")
if err != nil {
return err
}
return nil
}
// Info returns "qemu" and the currently loaded qemu version.
func (d *qemu) Info() instance.Info {
data := instance.Info{
Name: "qemu",
Features: make(map[string]any),
Type: instancetype.VM,
Error: errors.New("Unknown error"),
}
if !util.PathExists("/dev/kvm") {
data.Error = errors.New("KVM support is missing (no /dev/kvm)")
return data
}
err := linux.LoadModule("vhost_vsock")
if err != nil {
data.Error = errors.New("vhost_vsock kernel module not loaded")
return data
}
if !util.PathExists("/dev/vsock") {
data.Error = errors.New("Vsock support is missing (no /dev/vsock)")
return data
}
hostArch, err := osarch.ArchitectureGetLocalID()
if err != nil {
logger.Errorf("Failed getting CPU architecture during QEMU initialization: %v", err)
data.Error = errors.New("Failed getting CPU architecture")
return data
}
qemuPath, _, err := d.qemuArchConfig(hostArch)
if err != nil {
data.Error = fmt.Errorf("QEMU command not available: %v", err)
return data
}
out, err := exec.Command(qemuPath, "--version").Output()
if err != nil {
logger.Errorf("Failed getting version during QEMU initialization: %v", err)
data.Error = errors.New("Failed getting QEMU version")
return data
}
qemuOutput := strings.Fields(string(out))
if len(qemuOutput) >= 4 {
qemuVersion := strings.Fields(string(out))[3]
data.Version = qemuVersion
} else {
data.Version = "unknown" // Not necessarily an error that should prevent us using driver.
}
data.Features, err = d.checkFeatures(hostArch, qemuPath)
if err != nil {
logger.Errorf("Unable to run feature checks during QEMU initialization: %v", err)
data.Error = errors.New("QEMU failed to run feature checks")
return data
}
data.Error = nil
return data
}
func (d *qemu) checkFeatures(hostArch int, qemuPath string) (map[string]any, error) {
monitorPath, err := os.CreateTemp("", "")
if err != nil {
return nil, err
}
defer func() { _ = os.Remove(monitorPath.Name()) }()
qemuArgs := []string{
qemuPath,
"-S", // Do not start virtualisation.
"-nographic",
"-nodefaults",
"-no-user-config",
"-chardev", fmt.Sprintf("socket,id=monitor,path=%s,server=on,wait=off", qemuEscapeCmdline(monitorPath.Name())),
"-mon", "chardev=monitor,mode=control",
"-machine", qemuMachineType(hostArch),
}
if hostArch == osarch.ARCH_64BIT_INTEL_X86 {
// On Intel, use KVM acceleration as it's needed for SEV detection.
// This also happens to be less resource intensive but can't
// trivially be performed on all architectures without extra care about the
// machine type.
qemuArgs = append(qemuArgs, "-accel", "kvm")
}
if d.architectureSupportsUEFI(hostArch) {
// Try to locate a UEFI firmware.
var efiPath string
firmwares, err := edk2.GetArchitectureFirmwarePairsForUsage(hostArch, edk2.GENERIC)
if err != nil {
return nil, err
}
for _, firmwarePair := range firmwares {
if util.PathExists(firmwarePair.Code) {
efiPath = firmwarePair.Code
break
}
}
if efiPath == "" {
return nil, errors.New("Unable to locate a UEFI firmware")
}
qemuArgs = append(qemuArgs, "-drive", fmt.Sprintf("if=pflash,format=raw,readonly=on,file=%s", qemuEscapeCmdline(efiPath)))
}
var stderr bytes.Buffer
checkFeature := exec.Cmd{
Path: qemuPath,
Args: qemuArgs,
Stderr: &stderr,
}
err = checkFeature.Start()
if err != nil {
// QEMU not operational. VM support missing.
return nil, fmt.Errorf("Failed starting QEMU: %w", err)
}
defer func() { _ = checkFeature.Process.Kill() }()
// Start go routine that waits for QEMU to exit and captures the exit error (if any).
errWaitCh := make(chan error, 1)
go func() {
errWaitCh <- checkFeature.Wait()
}()
// Start go routine that tries to connect to QEMU's QMP socket in a loop (giving QEMU a chance to open it).
ctx, cancelMonitorConnect := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelMonitorConnect()
errMonitorCh := make(chan error, 1)
var monitor *qmp.Monitor
go func() {
var err error
// Try and connect to QMP socket until cancelled.
for {
monitor, err = qmp.Connect(monitorPath.Name(), qemuSerialChardevName, nil, "", d.detachDisk)
// QMP successfully connected or we have been cancelled.
if err == nil || ctx.Err() != nil {
break
}
time.Sleep(50 * time.Millisecond)
}
// Return last QMP connection error.
errMonitorCh <- err
}()
// Wait for premature QEMU exit or QMP to connect or timeout.
select {
case errMonitor := <-errMonitorCh:
// A non-nil error here means that QMP failed to connect before timing out.
// The last connection error is returned.
// A nil error means QMP successfully connected and we can continue.
if errMonitor != nil {
return nil, fmt.Errorf("QEMU monitor connect error: %w", errMonitor)
}
case errWait := <-errWaitCh:
// Any sort of premature exit, even a non-error one is problematic here, and should not occur.
return nil, fmt.Errorf("QEMU premature exit: %w (%v)", errWait, strings.TrimSpace(stderr.String()))
}
defer monitor.Disconnect()
features := make(map[string]any)
blockDevPath, err := os.CreateTemp("", "")
if err != nil {
return nil, err
}
defer func() { _ = os.Remove(blockDevPath.Name()) }()
// Check io_uring feature.
blockDev := map[string]any{
"node-name": d.blockNodeName("feature-check"),
"driver": "file",
"filename": blockDevPath.Name(),
"aio": "io_uring",
}
err = monitor.AddBlockDevice(blockDev, nil, true)
if err != nil {
logger.Debug("Failed adding block device during VM feature check", logger.Ctx{"err": err})
} else {
features["io_uring"] = struct{}{}
}
// Check CPU hotplug feature.
_, err = monitor.QueryHotpluggableCPUs()
if err != nil {
logger.Debug("Failed querying hotpluggable CPUs during VM feature check", logger.Ctx{"err": err})
} else {
features["cpu_hotplug"] = struct{}{}
}
// Check AMD SEV features (only for x86 architecture)
if hostArch == osarch.ARCH_64BIT_INTEL_X86 {
cmdline, err := os.ReadFile("/proc/cmdline")
if err != nil {
return nil, err
}
parts := strings.Split(string(cmdline), " ")
// Check if SME is enabled in the kernel command line. // codespell:ignore sme
if slices.Contains(parts, "mem_encrypt=on") {
features["sme"] = struct{}{} // codespell:ignore sme
}
// Check if SEV/SEV-ES are enabled
sev, err := os.ReadFile("/sys/module/kvm_amd/parameters/sev")
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return nil, err
} else if strings.TrimSpace(string(sev)) == "Y" {
// Host supports SEV, check if QEMU supports it as well.
capabilities, err := monitor.SEVCapabilities()
if err != nil {
logger.Debug("Failed querying SEV capability during VM feature check", logger.Ctx{"err": err})
} else {
features["sev"] = capabilities
// If SEV is enabled on host and supported by QEMU,
// check if the SEV-ES extension is enabled.
sevES, err := os.ReadFile("/sys/module/kvm_amd/parameters/sev_es")
if err != nil {
logger.Debug("Failed querying SEV-ES capability during VM feature check", logger.Ctx{"err": err})
} else if strings.TrimSpace(string(sevES)) == "Y" {
features["sev-es"] = struct{}{}
}
}
}
}
// Check if vhost-net accelerator (for NIC CPU offloading) is available.
if util.PathExists("/dev/vhost-net") {
features["vhost_net"] = struct{}{}
}
// Check if running nested.
cpus, err := resources.GetCPU()
if err != nil {
return nil, err
}
nested := false
for _, socket := range cpus.Sockets {
for _, core := range socket.Cores {
if slices.Contains(core.Flags, "hypervisor") {
nested = true
}
}
}
if nested {
features["nested"] = struct{}{}
}
// Get the host CPU model (x86_64 only for now).
if hostArch == osarch.ARCH_64BIT_INTEL_X86 {
model, err := monitor.QueryCPUModel("kvm64")
if err != nil {
return nil, err
}
cpuFlags := map[string]bool{}
for k, v := range model.Flags {
value, ok := v.(bool)
if !ok {
continue
}
cpuFlags[k] = value
}
features["flags"] = cpuFlags
}
return features, nil
}
// version returns the QEMU version.
func (d *qemu) version() (*version.DottedVersion, error) {
info := DriverStatuses()[instancetype.VM].Info
qemuVer, err := version.NewDottedVersion(info.Version)
if err != nil {
return nil, fmt.Errorf("Failed parsing QEMU version: %w", err)
}
return qemuVer, nil
}
func (d *qemu) Metrics(hostInterfaces []net.Interface) (*metrics.MetricSet, error) {
if !d.IsRunning() {
return nil, ErrInstanceIsStopped
}
if d.agentMetricsEnabled() {
metrics, err := d.getAgentMetrics()
if err != nil {
if !errors.Is(err, errQemuAgentOffline) {
d.logger.Warn("Could not get VM metrics from agent", logger.Ctx{"err": err})
}
// Fallback data if agent is not reachable.
return d.getQemuMetrics()
}
return metrics, nil
}
return d.getQemuMetrics()
}
func (d *qemu) getAgentMetrics() (*metrics.MetricSet, error) {
client, err := d.getAgentClient()
if err != nil {
return nil, err
}
agentArgs := &incus.ConnectionArgs{
SkipGetEvents: true,
SkipGetServer: true,
}
agent, err := incus.ConnectIncusHTTP(agentArgs, client)
if err != nil {
d.logger.Error("Failed to connect to the agent", logger.Ctx{"project": d.Project().Name, "instance": d.Name(), "err": err})
return nil, errors.New("Failed to connect to the agent")
}
defer agent.Disconnect()
resp, _, err := agent.RawQuery("GET", "/1.0/metrics", nil, "")
if err != nil {
return nil, err
}
var m metrics.Metrics
err = json.Unmarshal(resp.Metadata, &m)
if err != nil {
return nil, err
}
metricSet, err := metrics.MetricSetFromAPI(&m, map[string]string{"project": d.project.Name, "name": d.name, "type": instancetype.VM.String()})
if err != nil {
return nil, err
}
return metricSet, nil
}
func (d *qemu) getNetworkState() (map[string]api.InstanceStateNetwork, error) {
networks := map[string]api.InstanceStateNetwork{}
for k, m := range d.ExpandedDevices() {
if m["type"] != "nic" {
continue
}
dev, err := d.deviceLoad(d, k, m)
if err != nil {
if errors.Is(err, device.ErrUnsupportedDevType) {
continue // Skip unsupported device (allows for mixed instance type profiles).
}
d.logger.Warn("Failed state validation for device", logger.Ctx{"device": k, "err": err})
continue
}
// Only some NIC types support fallback state mechanisms when there is no agent.
nic, ok := dev.(device.NICState)
if !ok {
continue
}
network, err := nic.State()
if err != nil {
return nil, fmt.Errorf("Failed getting NIC state for %q: %w", k, err)
}
if network != nil {
networks[k] = *network
}
}
return networks, nil
}
func (d *qemu) agentMetricsEnabled() bool {
return util.IsTrueOrEmpty(d.expandedConfig["security.agent.metrics"])
}
func (d *qemu) deviceAttachUSB(usbConf deviceConfig.USBDeviceItem) error {
// Check if the agent is running.
monitor, err := d.qmpConnect()
if err != nil {
return err
}
monHook, err := d.addUSBDeviceConfig(usbConf)
if err != nil {
return err
}
err = monHook(monitor)
if err != nil {
return err
}
return nil
}
func (d *qemu) deviceDetachUSB(usbDev deviceConfig.USBDeviceItem) error {
// Check if the agent is running.
monitor, err := d.qmpConnect()
if err != nil {
return err
}
deviceID := fmt.Sprintf("%s%s", qemuDeviceIDPrefix, usbDev.DeviceName)
err = monitor.RemoveDevice(deviceID)
if err != nil && !api.StatusErrorCheck(err, http.StatusNotFound) {
return fmt.Errorf("Failed removing device: %w", err)
}
err = monitor.RemoveFDFromFDSet(deviceID)
if err != nil {
return fmt.Errorf("Failed removing FD set: %w", err)
}
return nil
}
// Block node names may only be up to 31 characters long, so use a hash if longer.
func (d *qemu) blockNodeName(name string) string {
if len(name) > 25 {
// If the name is too long, hash it as SHA-256 (32 bytes).
// Then encode the SHA-256 binary hash as Base64 Raw URL format and trim down to 25 chars.
// Raw URL avoids the use of "+" character and the padding "=" character which QEMU doesn't allow.
hash256 := sha256.New()
hash256.Write([]byte(name))
binaryHash := hash256.Sum(nil)
name = base64.RawURLEncoding.EncodeToString(binaryHash)
name = name[0:25]
}
// Apply the prefix.
return fmt.Sprintf("%s%s", qemuBlockDevIDPrefix, name)
}
func (d *qemu) setCPUs(monitor *qmp.Monitor, count int) error {
if count == 0 {
return nil
}
// Check if the agent is running.
if monitor == nil {
var err error
monitor, err = d.qmpConnect()
if err != nil {
return err
}
}
cpus, err := monitor.QueryHotpluggableCPUs()
if err != nil {
return fmt.Errorf("Failed to query hotpluggable CPUs: %w", err)
}
var availableCPUs []qmp.HotpluggableCPU
var hotpluggedCPUs []qmp.HotpluggableCPU
// Count the available and hotplugged CPUs.
for _, cpu := range cpus {
// If qom-path is unset, the CPU is available.
if cpu.QOMPath == "" {
availableCPUs = append(availableCPUs, cpu)
} else if strings.HasPrefix(cpu.QOMPath, "/machine/peripheral") {
hotpluggedCPUs = append(hotpluggedCPUs, cpu)
}
}
// The reserved CPUs includes both the hotplugged CPUs as well as the fixed one.
totalReservedCPUs := len(hotpluggedCPUs) + 1
// Nothing to do as the count matches the already reserved CPUs.
if count == totalReservedCPUs {
return nil
}
reverter := revert.New()
defer reverter.Fail()
// More CPUs requested.
if count > totalReservedCPUs {
// Cannot allocate more CPUs than the system provides.
if count > len(cpus) {
return errors.New("Cannot allocate more CPUs than available")
}
// This shouldn't trigger, but if it does, don't panic.
if count-totalReservedCPUs > len(availableCPUs) {
return errors.New("Unable to allocate more CPUs, not enough hotpluggable CPUs available")
}
// Only allocate the difference in CPUs.
for i := range count - totalReservedCPUs {
cpu := availableCPUs[i]
devID := fmt.Sprintf("cpu%d%d%d", cpu.Props.SocketID, cpu.Props.CoreID, cpu.Props.ThreadID)
qemuDev := map[string]any{
"id": devID,
"driver": cpu.Type,
"core-id": cpu.Props.CoreID,
}
// No such thing as sockets and threads on s390x.
if d.architecture != osarch.ARCH_64BIT_S390_BIG_ENDIAN {
qemuDev["socket-id"] = cpu.Props.SocketID
qemuDev["thread-id"] = cpu.Props.ThreadID
}
err := monitor.AddDevice(qemuDev)
if err != nil {
return fmt.Errorf("Failed to add device: %w", err)
}
reverter.Add(func() {
err := monitor.RemoveDevice(devID)
d.logger.Warn("Failed to remove CPU device", logger.Ctx{"err": err})
})
}
} else {
if totalReservedCPUs-count > len(hotpluggedCPUs) {
// This shouldn't trigger, but if it does, don't panic.
return errors.New("Unable to remove CPUs, not enough hotpluggable CPUs available")
}
// Less CPUs requested.
for i := range totalReservedCPUs - count {
cpu := hotpluggedCPUs[i]
fields := strings.Split(cpu.QOMPath, "/")
devID := fields[len(fields)-1]
err := monitor.RemoveDevice(devID)
if err != nil {
return fmt.Errorf("Failed to remove CPU: %w", err)
}
reverter.Add(func() {
err := monitor.AddDevice(map[string]any{
"id": devID,
"driver": cpu.Type,
"socket-id": cpu.Props.SocketID,
"core-id": cpu.Props.CoreID,
"thread-id": cpu.Props.ThreadID,
})
d.logger.Warn("Failed to add CPU device", logger.Ctx{"err": err})
})
}
// QEMU doesn't immediately remove the thread from the vCPU list.
// Wait a second to allow the thread to fully exit and disappear from the vCPU list.
time.Sleep(time.Second)
}
reverter.Success()
// Run post-hotplug tasks.
err = d.postCPUHotplug(monitor)
if err != nil {
return err
}
return nil
}
func (d *qemu) architectureSupportsCPUHotplug() bool {
// Check supported features.
info := DriverStatuses()[instancetype.VM].Info
_, found := info.Features["cpu_hotplug"]
return found
}
func (d *qemu) postCPUHotplug(monitor *qmp.Monitor) error {
// Get the vCPU PID list.
pids, err := monitor.GetCPUs()
if err != nil {
return err
}
// Handle NUMA node restrictions.
numaNodes := d.expandedConfig["limits.cpu.nodes"]
if numaNodes != "" {
if numaNodes == "balanced" {
numaNodes = d.expandedConfig["volatile.cpu.nodes"]
}
// Parse the NUMA restriction.
numaNodeSet, err := resources.ParseNumaNodeSet(numaNodes)
if err != nil {
return err
}
// Get the CPU topology.
cpusTopology, err := resources.GetCPU()
if err != nil {
return err
}
// Get the isolated CPU ids.
isolatedCpusInt := resources.GetCPUIsolated()
// Build a map of NUMA node to CPU threads.
numaNodeToCPU := make(map[int64][]int64)
for _, cpu := range cpusTopology.Sockets {
for _, core := range cpu.Cores {
for _, thread := range core.Threads {
// Skip any isolated CPU thread.
if slices.Contains(isolatedCpusInt, thread.ID) {
continue
}
numaNodeToCPU[int64(thread.NUMANode)] = append(numaNodeToCPU[int64(thread.NUMANode)], thread.ID)
}
}
}
// Figure out the list of CPU threads for the NUMA node(s).
set := unix.CPUSet{}
for _, numaNode := range numaNodeSet {
for _, id := range numaNodeToCPU[numaNode] {
set.Set(int(id))
}
}
// Apply the restriction.
for _, pid := range pids {
// Apply the pin.
err := unix.SchedSetaffinity(pid, &set)
if err != nil {
return err
}
}
}
// Create a core scheduling group.
err = d.setCoreSched(pids)
if err != nil {
return fmt.Errorf("Failed to allocate new core scheduling domain for vCPU threads: %w", err)
}
return nil
}
// ConsoleLog returns all output sent to the instance's console's ring buffer since startup.
func (d *qemu) ConsoleLog() (string, error) {
// Setup a new operation.
op, err := operationlock.CreateWaitGet(d.Project().Name, d.Name(), d.op, operationlock.ActionConsoleRetrieve, []operationlock.Action{operationlock.ActionRestart, operationlock.ActionRestore, operationlock.ActionMigrate}, false, true)
if err != nil {
return "", err
}
// Only mark the operation as done if only processing the console retrieval.
if op.Action() == operationlock.ActionConsoleRetrieve {
defer op.Done(nil)
}
// Check if the agent is running.
monitor, err := d.qmpConnect()
if err != nil {
return "", err
}
logString, err := monitor.RingbufRead("console")
if err != nil {
// If a VM was started by an older version of Incus which was then upgraded, its
// console device won't be a ring buffer. We don't want to cause an error in this
// case, so just return an empty string.
if errors.Is(err, qmp.ErrNotARingbuf) {
return "", nil
}
return "", err
}
// If we got data back, append it to the log file for this instance.
if logString != "" {
logFile, err := os.OpenFile(d.ConsoleBufferLogPath(), os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o600)
if err != nil {
return "", err
}
defer logFile.Close()
_, err = logFile.WriteString(logString)
if err != nil {
return "", err
}
}
// Read and return the complete log for this instance.
fullLog, err := os.ReadFile(d.ConsoleBufferLogPath())
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
// If there's no log file yet, such as right at VM creation, return an empty string.
return "", nil
}
return "", err
}
return string(fullLog), nil
}
// consoleSwapRBWithSocket swaps the qemu backend for the instance's console to a unix socket.
func (d *qemu) consoleSwapRBWithSocket() error {
// This will wipe out anything in the existing ring buffer; save any buffered data to log file first.
_, err := d.ConsoleLog()
if err != nil {
return err
}
// Check if the agent is running.
monitor, err := d.qmpConnect()
if err != nil {
return err
}
// Create the unix socket here, which will be passed via file descriptor to qemu.
d.consoleSocket, err = net.ListenUnix("unix", &net.UnixAddr{Name: d.consolePath(), Net: "unix"})
if err != nil {
return err
}
d.consoleSocketFile, err = d.consoleSocket.File()
if err != nil {
_ = d.consoleSocket.Close()
_ = os.Remove(d.consolePath())
return err
}
return monitor.ChardevChange("console", qmp.ChardevChangeInfo{Type: "socket", FDName: "consoleSocket", File: d.consoleSocketFile})
}
// consoleSwapSocketWithRB swaps the qemu backend for the instance's console to a ring buffer.
func (d *qemu) consoleSwapSocketWithRB() error {
// Check if the agent is running.
monitor, err := d.qmpConnect()
if err != nil {
return err
}
defer func() {
// Clean up the old socket.
_ = d.consoleSocketFile.Close()
_ = d.consoleSocket.Close()
_ = os.Remove(d.consolePath())
}()
return monitor.ChardevChange("console", qmp.ChardevChangeInfo{Type: "ringbuf"})
}
// ConsoleScreenshot returns a screenshot of the current VGA console in PNG format.
func (d *qemu) ConsoleScreenshot(screenshotFile *os.File) error {
if !d.IsRunning() {
return errors.New("Instance is not running")
}
// Check if the agent is running.
monitor, err := d.qmpConnect()
if err != nil {
return err
}
err = screenshotFile.Chown(int(d.state.OS.UnprivUID), -1)
if err != nil {
return fmt.Errorf("Failed to chown screenshot path: %w", err)
}
// Take the screenshot.
err = monitor.Screendump(screenshotFile.Name())
if err != nil {
return fmt.Errorf("Failed taking screenshot: %w", err)
}
return nil
}
// ReloadDevice triggers an empty Update call to the underlying device.
func (d *qemu) ReloadDevice(devName string) error {
dev, err := d.deviceLoad(d, devName, d.expandedDevices[devName])
if err != nil {
return err
}
return dev.Update(d.expandedDevices, true)
}
// DumpGuestMemory dumps the guest memory to a file in the specified format.
func (d *qemu) DumpGuestMemory(w *os.File, format string) error {
if !d.IsRunning() {
return errors.New("Instance is not running")
}
// Check if the agent is running.
monitor, err := d.qmpConnect()
if err != nil {
return err
}
defer monitor.Disconnect()
// Dump the guest memory.
err = monitor.SendFile("memory-dump", w)
if err != nil {
return err
}
err = monitor.DumpGuestMemory("memory-dump", format)
if err != nil {
return err
}
// Close the writer.
err = w.Close()
if err != nil {
return err
}
return nil
}
// CanLiveMigrate returns whether the VM is live-migratable.
func (d *qemu) CanLiveMigrate() bool {
return util.IsTrue(d.expandedConfig["migration.stateful"])
}
|