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
|
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ash/crostini/crostini_manager.h"
#include <algorithm>
#include <map>
#include <string>
#include <string_view>
#include <vector>
#include "ash/constants/ash_features.h"
#include "base/barrier_callback.h"
#include "base/barrier_closure.h"
#include "base/check_op.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/files/file_util.h"
#include "base/files/scoped_file.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "base/metrics/histogram_functions.h"
#include "base/notimplemented.h"
#include "base/notreached.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/stringprintf.h"
#include "base/system/sys_info.h"
#include "base/task/bind_post_task.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "base/time/clock.h"
#include "base/time/default_clock.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "chrome/browser/ash/borealis/borealis_features.h"
#include "chrome/browser/ash/borealis/borealis_service.h"
#include "chrome/browser/ash/bruschetta/bruschetta_util.h"
#include "chrome/browser/ash/crostini/ansible/ansible_management_service.h"
#include "chrome/browser/ash/crostini/ansible/ansible_management_service_factory.h"
#include "chrome/browser/ash/crostini/baguette_installer.h"
#include "chrome/browser/ash/crostini/crostini_features.h"
#include "chrome/browser/ash/crostini/crostini_manager_factory.h"
#include "chrome/browser/ash/crostini/crostini_metrics_service.h"
#include "chrome/browser/ash/crostini/crostini_mount_provider.h"
#include "chrome/browser/ash/crostini/crostini_port_forwarder.h"
#include "chrome/browser/ash/crostini/crostini_port_forwarder_factory.h"
#include "chrome/browser/ash/crostini/crostini_pref_names.h"
#include "chrome/browser/ash/crostini/crostini_reporting_util.h"
#include "chrome/browser/ash/crostini/crostini_simple_types.h"
#include "chrome/browser/ash/crostini/crostini_sshfs.h"
#include "chrome/browser/ash/crostini/crostini_terminal_provider.h"
#include "chrome/browser/ash/crostini/crostini_types.mojom-shared.h"
#include "chrome/browser/ash/crostini/crostini_upgrade_available_notification.h"
#include "chrome/browser/ash/crostini/crostini_util.h"
#include "chrome/browser/ash/crostini/throttle/crostini_throttle_factory.h"
#include "chrome/browser/ash/drive/drive_integration_service.h"
#include "chrome/browser/ash/drive/drive_integration_service_factory.h"
#include "chrome/browser/ash/file_manager/path_util.h"
#include "chrome/browser/ash/guest_os/guest_id.h"
#include "chrome/browser/ash/guest_os/guest_os_pref_names.h"
#include "chrome/browser/ash/guest_os/guest_os_remover.h"
#include "chrome/browser/ash/guest_os/guest_os_session_tracker.h"
#include "chrome/browser/ash/guest_os/guest_os_session_tracker_factory.h"
#include "chrome/browser/ash/guest_os/guest_os_share_path.h"
#include "chrome/browser/ash/guest_os/guest_os_share_path_factory.h"
#include "chrome/browser/ash/guest_os/guest_os_stability_monitor.h"
#include "chrome/browser/ash/guest_os/public/guest_os_service.h"
#include "chrome/browser/ash/guest_os/public/guest_os_service_factory.h"
#include "chrome/browser/ash/guest_os/public/types.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_process_platform_part.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/views/crostini/crostini_expired_container_warning_view.h"
#include "chrome/browser/ui/views/crostini/crostini_update_filesystem_view.h"
#include "chrome/browser/ui/webui/ash/system_web_dialog/system_web_dialog_delegate.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/webui_url_constants.h"
#include "chromeos/ash/components/dbus/anomaly_detector/anomaly_detector_client.h"
#include "chromeos/ash/components/dbus/session_manager/session_manager_client.h"
#include "chromeos/ash/components/dbus/vm_concierge/concierge_service.pb.h"
#include "chromeos/ash/components/network/device_state.h"
#include "chromeos/ash/components/network/network_state.h"
#include "chromeos/ash/components/network/network_state_handler.h"
#include "chromeos/ash/components/scheduler_config/scheduler_configuration_manager.h"
#include "components/component_updater/component_updater_service.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
namespace crostini {
namespace {
const auto kStartVmTimeout = base::Seconds(300);
ash::CiceroneClient* GetCiceroneClient() {
return ash::CiceroneClient::Get();
}
ash::ConciergeClient* GetConciergeClient() {
return ash::ConciergeClient::Get();
}
// Find any callbacks for the specified |vm_name|, invoke them with
// |arguments|... and erase them from the map.
template <typename... Parameters, typename... Arguments>
void InvokeAndErasePendingCallbacks(
std::map<guest_os::GuestId, base::OnceCallback<void(Parameters...)>>*
vm_keyed_map,
const std::string& vm_name,
Arguments... arguments) {
for (auto it = vm_keyed_map->begin(); it != vm_keyed_map->end();) {
if (it->first.vm_name == vm_name) {
std::move(it->second).Run(arguments...);
vm_keyed_map->erase(it++);
} else {
++it;
}
}
}
// Find any callbacks for the specified |vm_name|, invoke them with
// |result| and erase them from the map.
void InvokeAndErasePendingCallbacks(
std::multimap<std::string, CrostiniManager::CrostiniResultCallback>*
vm_callbacks,
const std::string& vm_name,
CrostiniResult result) {
auto range = vm_callbacks->equal_range(vm_name);
for (auto it = range.first; it != range.second; ++it) {
std::move(it->second).Run(result);
}
vm_callbacks->erase(range.first, range.second);
}
void EraseCommandUuid(std::map<std::string, guest_os::GuestId>* uuid_map,
const std::string& vm_name) {
for (auto it = uuid_map->begin(); it != uuid_map->end();) {
if (it->second.vm_name == vm_name) {
uuid_map->erase(it++);
} else {
++it;
}
}
}
// Find any container callbacks for the specified |container_id|, invoke them
// with |result| and erase them from the map.
void InvokeAndErasePendingContainerCallbacks(
std::multimap<guest_os::GuestId, CrostiniManager::CrostiniResultCallback>*
container_callbacks,
const guest_os::GuestId& container_id,
CrostiniResult result) {
auto range = container_callbacks->equal_range(container_id);
for (auto it = range.first; it != range.second; ++it) {
VLOG(1) << "Invoking pending container callback for "
<< it->first.container_name;
// We end up here when triggered by an observer method, which is
// synchronous. Post the callback instead of continuing to run it in the
// same task so other observers of e.g. ContainerStarted have a chance to
// run and update first, so callers get a consistent view across GuestOS
// services. See e.g. b/249219794 for an example of what can break without
// this.
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(std::move(it->second), result));
}
container_callbacks->erase(range.first, range.second);
}
void EmitCorruptionStateMetric(CorruptionStates state) {
base::UmaHistogramEnumeration("Crostini.FilesystemCorruption", state);
}
void EmitTimeInStageHistogram(base::TimeDelta duration,
mojom::InstallerState state) {
std::string_view name;
switch (state) {
case mojom::InstallerState::kStart:
name = "Crostini.RestarterTimeInState2.Start";
break;
case mojom::InstallerState::kInstallImageLoader:
name = "Crostini.RestarterTimeInState2.InstallImageLoader";
break;
case mojom::InstallerState::kCreateDiskImage:
name = "Crostini.RestarterTimeInState2.CreateDiskImage";
break;
case mojom::InstallerState::kStartTerminaVm:
name = "Crostini.RestarterTimeInState2.StartTerminaVm";
break;
case mojom::InstallerState::kStartLxd:
name = "Crostini.RestarterTimeInState2.StartLxd";
break;
case mojom::InstallerState::kCreateContainer:
name = "Crostini.RestarterTimeInState2.CreateContainer";
break;
case mojom::InstallerState::kSetupContainer:
name = "Crostini.RestarterTimeInState2.SetupContainer";
break;
case mojom::InstallerState::kStartContainer:
case mojom::InstallerState::kFetchSshKeys_DEPRECATED:
case mojom::InstallerState::kMountContainer_DEPRECATED:
// kFetchSshKeys and kMountContainer are no longer used, but their values
// cannot be renumbered. Map the deprecated values to kStartContainer to
// allow the stage tracking logic to correctly find the histogram name of
// the stage preceding kConfigureContainer.
name = "Crostini.RestarterTimeInState2.StartContainer";
break;
case mojom::InstallerState::kConfigureContainer:
name = "Crostini.RestarterTimeInState2.ConfigureContainer";
break;
}
DCHECK(!name.empty());
base::UmaHistogramCustomTimes(name, duration, base::Milliseconds(10),
base::Hours(6), 50);
}
} // namespace
const char kCrostiniStabilityHistogram[] = "Crostini.Stability";
CrostiniManager::RestartId CrostiniManager::next_restart_id_ = 0;
CrostiniManager::RestartOptions::RestartOptions() = default;
CrostiniManager::RestartOptions::RestartOptions(RestartOptions&&) = default;
CrostiniManager::RestartOptions::~RestartOptions() = default;
CrostiniManager::RestartOptions& CrostiniManager::RestartOptions::operator=(
RestartOptions&&) = default;
class CrostiniManager::CrostiniRestarter
: public ash::VmShutdownObserver,
public ash::SchedulerConfigurationManagerBase::Observer {
public:
struct RestartRequest {
RestartId restart_id;
RestartOptions options;
CrostiniResultCallback callback;
raw_ptr<RestartObserver> observer; // optional
};
CrostiniRestarter(Profile* profile,
CrostiniManager* crostini_manager,
guest_os::GuestId container_id,
RestartRequest request);
~CrostiniRestarter() override;
void AddRequest(RestartRequest request);
// Start the restart flow. This should called immediately following
// construction and only once. This cannot be called directly from the
// constructor as in some cases it immediately (synchronously) fails and
// causes |this| to be deleted.
void Restart();
// ash::VmShutdownObserver
void OnVmShutdown(const std::string& vm_name) override;
void Timeout(mojom::InstallerState state);
// Cancel an individual request and fire its callback immediately. If there
// are no other outstanding requests, stop the restarter once possible.
void CancelRequest(RestartId restart_id);
// Abort the entire restart. Pending requests are immediately completed, and
// |callback| is called once the current operation has finished. Requests
// should not be added to an aborted restarter.
void Abort(base::OnceClosure callback);
// These are called directly from CrostiniManager.
void OnContainerDownloading(int download_percent);
void OnLxdContainerStarting(
vm_tools::cicerone::LxdContainerStartingSignal_Status status);
const guest_os::GuestId& container_id() { return container_id_; }
// This is public so CallRestarterStartLxdContainerFinishedForTesting can call
// it.
void StartLxdContainerFinished(CrostiniResult result);
private:
void StartStage(mojom::InstallerState stage);
void EmitMetricIfInIncorrectState(mojom::InstallerState expected);
using RequestFilter = base::RepeatingCallback<bool(const RestartRequest&)>;
// Removes matched requests and returns a closure which will run the
// corresponding completion callbacks.
base::OnceClosure ExtractRequests(RequestFilter filter,
CrostiniResult result);
void FinishRequests(RequestFilter filter, CrostiniResult result) {
return ExtractRequests(filter, result).Run();
}
// The restarter flow ends early if Abort() is called or all requests have
// been cancelled or otherwise fulfilled (e.g. when start_vm_only is set).
// If this method returns true, then FinishRestart() is called and |this|
// gets deleted so it is unsafe to refer to any member variables.
bool ReturnEarlyIfNeeded();
// In a successful complete restart, every function in the below list in
// called in order, from Restart() to FinishRestart(). If the restarter
// finishes early (i.e. restarter aborted, all requests cancelled or
// completed, operation fails or times out), it proceeds directly to
// FinishRestart().
// Public function - Restart();
void ContinueRestart();
void LoadComponentFinished(std::optional<base::ScopedFD> disk_image,
CrostiniResult result);
void OnBaguetteLoaded(CrostiniResult result);
void CreateDiskImageFinished(int64_t disk_size_bytes,
CrostiniResult result,
const base::FilePath& result_path);
// ash::SchedulerConfigurationManagerBase::Observer:
void OnConfigurationSet(bool success, size_t num_cores_disabled) override;
void OnConfigureContainerFinished(bool success);
void StartTerminaVmFinished(bool success);
void SharePathsFinished(bool success, const std::string& failure_reason);
void StartLxdFinished(CrostiniResult result);
void SetUpBaguetteUserFinished(CrostiniResult result);
void CreateLxdContainerFinished(CrostiniResult result);
void SetUpLxdContainerUserFinished(bool success);
// Public function - StartLxdContainerFinished(CrostiniResult result);
// FinishRestart() causes |this| to be deleted, so callers should return
// immediately after calling this.
void FinishRestart(CrostiniResult result);
// If the current operation can be cancelled, cancel it. This is run at most
// once, when all requests are cancelled or the restart is aborted.
void MaybeCancelCurrentOperation();
void LogRestarterResult(const RestartRequest& request, CrostiniResult result);
void OnConciergeAvailable(std::optional<base::ScopedFD> disk_iamge,
bool service_available);
base::OneShotTimer stage_timeout_timer_;
base::TimeTicks stage_start_;
// TODO(crbug/1153210): Better numbers for timeouts once we have data.
const std::map<mojom::InstallerState, base::TimeDelta> stage_timeouts_ = {
{mojom::InstallerState::kStart, base::Minutes(2)},
{mojom::InstallerState::kInstallImageLoader,
base::Hours(6)}, // May need to download DLC or component
{mojom::InstallerState::kCreateDiskImage, base::Minutes(5)},
{mojom::InstallerState::kStartTerminaVm, kStartVmTimeout},
{mojom::InstallerState::kStartLxd, base::Minutes(5)},
// While CreateContainer may need to download a file, we get progress
// messages that reset the countdown.
{mojom::InstallerState::kCreateContainer, base::Minutes(5)},
{mojom::InstallerState::kSetupContainer, base::Minutes(5)},
// StartContainer sends heartbeat messages on a 30-second interval, but
// there's a bit of work that's not covered by heartbeat messages so to be
// safe set a 8 minute timeout.
{mojom::InstallerState::kStartContainer, base::Minutes(8)},
// Configuration may be slow, making timeout 2 hours at first because some
// playbooks are gigantic (e.g. Chromium playbook).
{mojom::InstallerState::kConfigureContainer, base::Hours(2)},
};
// Use shorter timeouts for some states if Crostini is already installed.
const std::map<mojom::InstallerState, base::TimeDelta>
stage_timeouts_already_installed_ = {
{mojom::InstallerState::kInstallImageLoader, base::Minutes(5)},
// The configure step should only be reached during multi-container
// installation.
{mojom::InstallerState::kConfigureContainer, base::Seconds(5)},
};
raw_ptr<Profile> profile_;
// This isn't accessed after the CrostiniManager is destroyed and we need a
// reference to it during the CrostiniRestarter destructor.
raw_ptr<CrostiniManager> crostini_manager_;
const guest_os::GuestId container_id_;
bool is_initial_install_ = false;
std::vector<base::OnceClosure> abort_callbacks_;
// Options which only affect new containers will be taken from the first
// request.
std::vector<RestartRequest> requests_;
// Pulled out of requests_ for convenience.
base::ObserverList<CrostiniManager::RestartObserver>::Unchecked
observer_list_;
// TODO(timloh): This should just be an extra state at the start of the flow.
bool is_running_ = false;
// Data passed between different steps of the restart flow.
base::FilePath disk_path_;
size_t num_cores_disabled_ = 0;
mojom::InstallerState stage_ = mojom::InstallerState::kStart;
base::ScopedObservation<ash::SchedulerConfigurationManagerBase,
ash::SchedulerConfigurationManagerBase::Observer>
scheduler_configuration_manager_observation_{this};
base::ScopedObservation<CrostiniManager, ash::VmShutdownObserver>
vm_shutdown_observation_{this};
base::WeakPtrFactory<CrostiniRestarter> weak_ptr_factory_{this};
};
CrostiniManager::CrostiniRestarter::CrostiniRestarter(
Profile* profile,
CrostiniManager* crostini_manager,
guest_os::GuestId container_id,
RestartRequest request)
: profile_(profile),
crostini_manager_(crostini_manager),
container_id_(std::move(container_id)) {
AddRequest(std::move(request));
}
CrostiniManager::CrostiniRestarter::~CrostiniRestarter() {
if (!requests_.empty()) {
// This is triggered by logging out when restarts are in progress.
LOG(WARNING) << "Destroying with outstanding requests.";
for (const auto& request : requests_) {
LogRestarterResult(request, CrostiniResult::NEVER_FINISHED);
}
}
}
void CrostiniManager::CrostiniRestarter::Restart() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!CrostiniFeatures::Get()->IsAllowedNow(profile_)) {
LOG(ERROR) << "Crostini UI not allowed for profile "
<< profile_->GetProfileUserName();
FinishRestart(CrostiniResult::NOT_ALLOWED);
return;
}
vm_shutdown_observation_.Observe(crostini_manager_.get());
// TODO(b/205650706): It is possible to invoke a CrostiniRestarter to install
// Crostini without using the actual installer. We should handle these better.
RestartSource restart_source = requests_[0].options.restart_source;
is_initial_install_ =
restart_source == RestartSource::kInstaller ||
restart_source == RestartSource::kMultiContainerCreation;
StartStage(mojom::InstallerState::kStart);
if (ReturnEarlyIfNeeded()) {
return;
}
auto vm_info = crostini_manager_->GetVmInfo(container_id_.vm_name);
// If vm is stopping, we wait until OnVmShutdown() to kick it off.
if (vm_info && vm_info->state == VmState::STOPPING) {
LOG(WARNING) << "Delay restart due to vm stopping";
} else {
ContinueRestart();
}
}
void CrostiniManager::CrostiniRestarter::AddRequest(RestartRequest request) {
// CrostiniManager doesn't add requests to aborted restarts.
DCHECK(abort_callbacks_.empty());
if (request.observer) {
observer_list_.AddObserver(request.observer.get());
}
requests_.push_back(std::move(request));
}
void CrostiniManager::CrostiniRestarter::OnVmShutdown(
const std::string& vm_name) {
if (ReturnEarlyIfNeeded()) {
return;
}
if (vm_name == container_id_.vm_name) {
if (is_running_) {
LOG(WARNING) << "Unexpected VM shutdown during restart for " << vm_name;
FinishRestart(CrostiniResult::RESTART_FAILED_VM_STOPPED);
} else {
// We can only get here if Restart() was called to register the shutdown
// observer, and since is_running_ is false, we are waiting for this
// shutdown to actually kick off the process.
VLOG(1) << "resume restart on vm shutdown";
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(&CrostiniRestarter::ContinueRestart,
weak_ptr_factory_.GetWeakPtr()));
}
}
}
void CrostiniManager::CrostiniRestarter::Timeout(mojom::InstallerState state) {
CrostiniResult result = CrostiniResult::UNKNOWN_STATE_TIMED_OUT;
LOG(ERROR) << "Timed out in state " << state;
switch (state) {
case mojom::InstallerState::kInstallImageLoader:
result = CrostiniResult::INSTALL_IMAGE_LOADER_TIMED_OUT;
break;
case mojom::InstallerState::kCreateDiskImage:
result = CrostiniResult::CREATE_DISK_IMAGE_TIMED_OUT;
break;
case mojom::InstallerState::kStartTerminaVm:
result = CrostiniResult::START_TERMINA_VM_TIMED_OUT;
break;
case mojom::InstallerState::kStartLxd:
result = CrostiniResult::START_LXD_TIMED_OUT;
break;
case mojom::InstallerState::kCreateContainer:
result = CrostiniResult::CREATE_CONTAINER_TIMED_OUT;
break;
case mojom::InstallerState::kSetupContainer:
result = CrostiniResult::SETUP_CONTAINER_TIMED_OUT;
break;
case mojom::InstallerState::kStartContainer:
result = CrostiniResult::START_CONTAINER_TIMED_OUT;
break;
case mojom::InstallerState::kConfigureContainer:
result = CrostiniResult::CONFIGURE_CONTAINER_TIMED_OUT;
break;
case mojom::InstallerState::kStart:
result = CrostiniResult::START_TIMED_OUT;
break;
case mojom::InstallerState::kFetchSshKeys_DEPRECATED:
case mojom::InstallerState::kMountContainer_DEPRECATED:
NOTREACHED();
}
// Note: FinishRestart deletes |this|.
FinishRestart(result);
}
void CrostiniManager::CrostiniRestarter::CancelRequest(RestartId restart_id) {
size_t num_requests = requests_.size();
FinishRequests(
base::BindRepeating(
[](RestartId restart_id, const RestartRequest& request) -> bool {
return request.restart_id == restart_id;
},
restart_id),
CrostiniResult::RESTART_REQUEST_CANCELLED);
DCHECK_LE(requests_.size(), num_requests);
if (requests_.empty()) {
MaybeCancelCurrentOperation();
}
}
void CrostiniManager::CrostiniRestarter::Abort(base::OnceClosure callback) {
abort_callbacks_.push_back(std::move(callback));
if (requests_.empty()) {
// New requests are not added to aborted restarters, so we've already been
// aborted and/or all requests were explicitly cancelled.
return;
}
// Run the result callbacks immediately, but wait for the current step to
// finish before invoking the abort callback.
FinishRequests(
base::BindRepeating([](const RestartRequest& request) { return true; }),
CrostiniResult::RESTART_ABORTED);
MaybeCancelCurrentOperation();
}
void CrostiniManager::CrostiniRestarter::OnContainerDownloading(
int download_percent) {
if (!is_running_) {
return;
}
if (stage_timeout_timer_.IsRunning()) {
// We got a progress message, reset the timeout duration back to full.
stage_timeout_timer_.Reset();
}
for (auto& observer : observer_list_) {
observer.OnContainerDownloading(download_percent);
}
}
void CrostiniManager::CrostiniRestarter::OnLxdContainerStarting(
vm_tools::cicerone::LxdContainerStartingSignal_Status status) {
if (!is_running_ || !stage_timeout_timer_.IsRunning() ||
status != vm_tools::cicerone::LxdContainerStartingSignal::STARTING ||
stage_ != mojom::InstallerState::kStartContainer) {
VLOG(1) << "Got start container message but status is " << status
<< " and stage is " << stage_ << " so not extending timeout";
return;
}
// We got a progress message, reset the timeout duration back to full.
VLOG(1) << "Got start container heartbeat so extending timeout";
stage_timeout_timer_.Reset();
}
void CrostiniManager::CrostiniRestarter::StartLxdContainerFinished(
CrostiniResult result) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
CloseCrostiniUpdateFilesystemView();
if (ReturnEarlyIfNeeded()) {
return;
}
EmitMetricIfInIncorrectState(mojom::InstallerState::kStartContainer);
if (result != CrostiniResult::SUCCESS) {
FinishRestart(result);
return;
}
// If arc sideloading is enabled, configure the container for that.
crostini_manager_->ConfigureForArcSideload();
if (requests_[0].options.ansible_playbook.has_value()) {
// Check to see if there's any additional configuration via Ansible
// required.
StartStage(mojom::InstallerState::kConfigureContainer);
AnsibleManagementServiceFactory::GetForProfile(profile_)
->ConfigureContainer(
container_id_, requests_[0].options.ansible_playbook.value(),
base::BindOnce(&CrostiniRestarter::OnConfigureContainerFinished,
weak_ptr_factory_.GetWeakPtr()));
return;
}
// If default termina/penguin, then sshfs mount and reshare folders, else we
// are finished. Because the session tracker update and this method are racing
// on the same thread we do the update async once the session tracker is
// ready.
// TODO(crbug.com/377377749): might still need to do this for baguette?
if (container_id_ == DefaultContainerId()) {
crostini_manager_->primary_counter_mount_subscription_ =
guest_os::GuestOsSessionTrackerFactory::GetForProfile(profile_)
->RunOnceContainerStarted(
container_id_,
base::BindOnce(&CrostiniManager::MountCrostiniFilesBackground,
crostini_manager_->GetWeakPtr()));
}
FinishRestart(result);
}
void CrostiniManager::CrostiniRestarter::StartStage(
mojom::InstallerState stage) {
int finished_stage = static_cast<int>(stage) - 1;
if (finished_stage >= 0) {
EmitTimeInStageHistogram(
base::TimeTicks::Now() - stage_start_,
static_cast<mojom::InstallerState>(finished_stage));
}
this->stage_ = stage;
stage_start_ = base::TimeTicks::Now();
DCHECK(stage_timeouts_.find(stage) != stage_timeouts_.end());
auto delay = stage_timeouts_.at(stage);
if (requests_[0].options.restart_source != RestartSource::kInstaller) {
auto already_installed_it = stage_timeouts_already_installed_.find(stage);
if (already_installed_it != stage_timeouts_already_installed_.end()) {
delay = already_installed_it->second;
}
}
stage_timeout_timer_.Start(
FROM_HERE, delay,
base::BindOnce(&CrostiniRestarter::Timeout,
weak_ptr_factory_.GetWeakPtr(), stage));
for (auto& observer : observer_list_) {
observer.OnStageStarted(stage);
}
}
void CrostiniManager::CrostiniRestarter::EmitMetricIfInIncorrectState(
mojom::InstallerState expected) {
if (expected != stage_) {
base::UmaHistogramEnumeration("Crostini.InvalidStateTransition", expected);
}
}
base::OnceClosure CrostiniManager::CrostiniRestarter::ExtractRequests(
RequestFilter filter,
CrostiniResult result) {
std::vector<CrostiniResultCallback> callbacks;
for (auto it = requests_.begin(); it != requests_.end();) {
if (!filter.Run(*it)) {
it++;
continue;
}
LogRestarterResult(*it, result);
crostini_manager_->RemoveRestartId(it->restart_id);
if (it->observer) {
observer_list_.RemoveObserver(it->observer.get());
}
callbacks.push_back(std::move(it->callback));
it = requests_.erase(it);
}
return base::BindOnce(
[](std::vector<CrostiniResultCallback> callbacks, CrostiniResult result) {
for (auto& callback : callbacks) {
std::move(callback).Run(result);
}
},
std::move(callbacks), result);
}
bool CrostiniManager::CrostiniRestarter::ReturnEarlyIfNeeded() {
if (!requests_.empty()) {
return false;
}
// The result is ignored since there are no requests left.
FinishRestart(CrostiniResult::UNKNOWN_ERROR);
return true;
}
void CrostiniManager::CrostiniRestarter::ContinueRestart() {
is_running_ = true;
// Skip to the end immediately if testing.
if (crostini_manager_->skip_restart_for_testing()) {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(&CrostiniRestarter::StartLxdContainerFinished,
weak_ptr_factory_.GetWeakPtr(),
CrostiniResult::SUCCESS));
return;
}
StartStage(mojom::InstallerState::kInstallImageLoader);
if (base::FeatureList::IsEnabled(ash::features::kCrostiniContainerless)) {
// TODO(crbug.com/377377749): do we need to check for existence of any
// previous installs here, or has that already happened?
crostini_manager_->InstallBaguette(
base::BindOnce(&CrostiniRestarter::LoadComponentFinished,
weak_ptr_factory_.GetWeakPtr()));
} else {
crostini_manager_->InstallTermina(
base::BindOnce(&CrostiniRestarter::LoadComponentFinished,
weak_ptr_factory_.GetWeakPtr(), std::nullopt));
}
}
void CrostiniManager::CrostiniRestarter::LoadComponentFinished(
std::optional<base::ScopedFD> disk_image,
CrostiniResult result) {
if (ReturnEarlyIfNeeded()) {
return;
}
EmitMetricIfInIncorrectState(mojom::InstallerState::kInstallImageLoader);
if (result != CrostiniResult::SUCCESS) {
FinishRestart(result);
return;
}
// Set the pref here, after we first successfully install something
profile_->GetPrefs()->SetBoolean(crostini::prefs::kCrostiniEnabled, true);
// Ensure concierge is ready to serve requests
GetConciergeClient()->WaitForServiceToBeAvailable(
base::BindOnce(&CrostiniManager::CrostiniRestarter::OnConciergeAvailable,
weak_ptr_factory_.GetWeakPtr(), std::move(disk_image)));
}
void CrostiniManager::CrostiniRestarter::OnConciergeAvailable(
std::optional<base::ScopedFD> disk_image,
bool service_is_available) {
if (!service_is_available) {
LOG(ERROR) << "vm_concierge service is not available";
FinishRestart(CrostiniResult::CONCIERGE_START_FAILED);
return;
}
// Allow concierge to choose an appropriate disk image size.
int64_t disk_size_bytes = requests_[0].options.disk_size_bytes.value_or(0);
// If we have an already existing disk, CreateDiskImage will just return its
// path so we can pass it to StartTerminaVm.
StartStage(mojom::InstallerState::kCreateDiskImage);
crostini_manager_->CreateDiskImage(
container_id_.vm_name, std::move(disk_image),
vm_tools::concierge::StorageLocation::STORAGE_CRYPTOHOME_ROOT,
disk_size_bytes,
base::BindOnce(&CrostiniRestarter::CreateDiskImageFinished,
weak_ptr_factory_.GetWeakPtr(), disk_size_bytes));
}
void CrostiniManager::CrostiniRestarter::CreateDiskImageFinished(
int64_t disk_size_bytes,
CrostiniResult result,
const base::FilePath& result_path) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (result == CrostiniResult::CREATE_DISK_IMAGE_ALREADY_EXISTS &&
is_initial_install_) {
LOG(WARNING) << "Disk already existed for initial Crostini install. "
"Perhaps the VM was created via vmc?";
} else if (result == CrostiniResult::SUCCESS && !is_initial_install_) {
LOG(ERROR) << "Disk was created for a restart not tagged as an initial "
"Crostini installation.";
}
bool success = result == CrostiniResult::SUCCESS ||
result == CrostiniResult::CREATE_DISK_IMAGE_ALREADY_EXISTS;
for (auto& observer : observer_list_) {
observer.OnDiskImageCreated(success, result, disk_size_bytes);
}
if (ReturnEarlyIfNeeded()) {
return;
}
EmitMetricIfInIncorrectState(mojom::InstallerState::kCreateDiskImage);
if (!success) {
FinishRestart(result);
return;
}
crostini_manager_->EmitVmDiskTypeMetric(container_id_.vm_name);
disk_path_ = result_path;
auto* scheduler_configuration_manager =
g_browser_process->platform_part()->scheduler_configuration_manager();
std::optional<std::pair<bool, size_t>> scheduler_configuration =
scheduler_configuration_manager->GetLastReply();
if (!scheduler_configuration) {
// Wait for the configuration to become available.
LOG(WARNING) << "Scheduler configuration is not yet ready";
scheduler_configuration_manager_observation_.Observe(
scheduler_configuration_manager);
return;
}
OnConfigurationSet(scheduler_configuration->first,
scheduler_configuration->second);
}
// ash::SchedulerConfigurationManagerBase::Observer:
void CrostiniManager::CrostiniRestarter::OnConfigurationSet(
bool success,
size_t num_cores_disabled) {
if (ReturnEarlyIfNeeded()) {
return;
}
// Note: On non-x86_64 devices, the configuration request to debugd always
// fails. It is WAI, and to support that case, don't log anything even when
// |success| is false. |num_cores_disabled| is always set regardless of
// whether the call is successful.
scheduler_configuration_manager_observation_.Reset();
num_cores_disabled_ = num_cores_disabled;
StartStage(mojom::InstallerState::kStartTerminaVm);
crostini_manager_->StartTerminaVm(
container_id_.vm_name, disk_path_, num_cores_disabled_,
base::BindOnce(&CrostiniRestarter::StartTerminaVmFinished,
weak_ptr_factory_.GetWeakPtr()));
}
void CrostiniManager::CrostiniRestarter::OnConfigureContainerFinished(
bool success) {
if (ReturnEarlyIfNeeded()) {
return;
}
if (!success) {
// Failed to configure, time to abort.
FinishRestart(CrostiniResult::CONTAINER_CONFIGURATION_FAILED);
return;
}
FinishRestart(CrostiniResult::SUCCESS);
}
void CrostiniManager::CrostiniRestarter::StartTerminaVmFinished(bool success) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
VLOG(2) << "StartTerminaVmFinished for " << container_id_;
if (ReturnEarlyIfNeeded()) {
return;
}
EmitMetricIfInIncorrectState(mojom::InstallerState::kStartTerminaVm);
auto vm_info = crostini_manager_->GetVmInfo(container_id_.vm_name);
if (!success || !vm_info.has_value()) {
FinishRestart(CrostiniResult::VM_START_FAILED);
return;
}
// Cache kernel version for enterprise reporting, if it is enabled
// by policy, and we are in the default Termina case.
if (profile_->GetPrefs()->GetBoolean(
crostini::prefs::kReportCrostiniUsageEnabled) &&
container_id_.vm_name == kCrostiniDefaultVmName) {
crostini_manager_->UpdateTerminaVmKernelVersion();
}
// TODO(timloh): Requests with start_vm_only added too late will miss this and
// thus fail if any later step fails. Perhaps they should be completed
// immediately.
FinishRequests(base::BindRepeating([](const RestartRequest& request) {
return request.options.start_vm_only;
}),
CrostiniResult::SUCCESS);
if (ReturnEarlyIfNeeded()) {
return;
}
// Share any non-persisted paths for the VM.
// TODO(timloh): This should probably share paths from all requests. Requests
// added too late will also miss this.
guest_os::GuestOsSharePathFactory::GetForProfile(profile_)->SharePaths(
container_id_.vm_name, vm_info->info.seneschal_server_handle(),
requests_[0].options.share_paths,
base::BindOnce(&CrostiniRestarter::SharePathsFinished,
weak_ptr_factory_.GetWeakPtr()));
}
void CrostiniManager::CrostiniRestarter::SharePathsFinished(
bool success,
const std::string& failure_reason) {
VLOG(2) << "SharePathsFinished for " << container_id_;
if (!success) {
LOG(WARNING) << "Failed to share paths: " << failure_reason;
}
if (base::FeatureList::IsEnabled(ash::features::kCrostiniContainerless)) {
StartStage(mojom::InstallerState::kConfigureContainer);
crostini_manager_->SetUpBaguetteUser(
container_id_.vm_name, requests_[0].options.container_username,
base::BindOnce(&CrostiniRestarter::SetUpBaguetteUserFinished,
weak_ptr_factory_.GetWeakPtr()));
} else {
StartStage(mojom::InstallerState::kStartLxd);
crostini_manager_->StartLxd(
container_id_.vm_name,
base::BindOnce(&CrostiniRestarter::StartLxdFinished,
weak_ptr_factory_.GetWeakPtr()));
}
}
void CrostiniManager::CrostiniRestarter::StartLxdFinished(
CrostiniResult result) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (ReturnEarlyIfNeeded()) {
return;
}
EmitMetricIfInIncorrectState(mojom::InstallerState::kStartLxd);
if (result != CrostiniResult::SUCCESS) {
FinishRestart(result);
return;
}
FinishRequests(base::BindRepeating([](const RestartRequest& request) {
return request.options.stop_after_lxd_available;
}),
CrostiniResult::SUCCESS);
if (ReturnEarlyIfNeeded()) {
return;
}
StartStage(mojom::InstallerState::kCreateContainer);
crostini_manager_->CreateLxdContainer(
container_id_, requests_[0].options.image_server_url,
requests_[0].options.image_alias,
base::BindOnce(&CrostiniRestarter::CreateLxdContainerFinished,
weak_ptr_factory_.GetWeakPtr()));
}
void CrostiniManager::CrostiniRestarter::SetUpBaguetteUserFinished(
CrostiniResult result) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (ReturnEarlyIfNeeded()) {
return;
}
FinishRestart(result);
}
void CrostiniManager::CrostiniRestarter::CreateLxdContainerFinished(
CrostiniResult result) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (ReturnEarlyIfNeeded()) {
return;
}
EmitMetricIfInIncorrectState(mojom::InstallerState::kCreateContainer);
if (result != CrostiniResult::SUCCESS) {
FinishRestart(result);
return;
}
StartStage(mojom::InstallerState::kSetupContainer);
crostini_manager_->SetUpLxdContainerUser(
container_id_,
requests_[0].options.container_username.value_or(
DefaultContainerUserNameForProfile(profile_)),
base::BindOnce(&CrostiniRestarter::SetUpLxdContainerUserFinished,
weak_ptr_factory_.GetWeakPtr()));
}
void CrostiniManager::CrostiniRestarter::SetUpLxdContainerUserFinished(
bool success) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (ReturnEarlyIfNeeded()) {
return;
}
EmitMetricIfInIncorrectState(mojom::InstallerState::kSetupContainer);
if (!success) {
FinishRestart(CrostiniResult::CONTAINER_SETUP_FAILED);
return;
}
StartStage(mojom::InstallerState::kStartContainer);
crostini_manager_->StartLxdContainer(
container_id_,
base::BindOnce(&CrostiniRestarter::StartLxdContainerFinished,
weak_ptr_factory_.GetWeakPtr()));
}
void CrostiniManager::CrostiniRestarter::FinishRestart(CrostiniResult result) {
VLOG(2) << "Finishing restart with result: " << CrostiniResultString(result)
<< " for " << container_id_;
EmitTimeInStageHistogram(base::TimeTicks::Now() - stage_start_, stage_);
base::OnceClosure closure;
if (abort_callbacks_.empty()) {
if (!requests_.empty() && result != CrostiniResult::SUCCESS) {
LOG(ERROR) << "Failed to restart Crostini with error code: "
<< static_cast<int>(result)
<< ", container: " << container_id();
}
closure = ExtractRequests(
base::BindRepeating([](const RestartRequest& request) { return true; }),
result);
} else {
// Requests have already been completed, and new requests are not allowed.
for (auto& abort_callback : abort_callbacks_) {
std::move(abort_callback).Run();
}
abort_callbacks_.clear();
closure = base::DoNothing();
}
DCHECK(requests_.empty());
DCHECK(observer_list_.empty());
// CrostiniManager::RestartCompleted deletes |this|
crostini_manager_->RestartCompleted(this, std::move(closure));
}
void CrostiniManager::CrostiniRestarter::MaybeCancelCurrentOperation() {
if (stage_ == mojom::InstallerState::kInstallImageLoader) {
// Currently this is the only step that can be "cancelled". The relevant
// completion callback, LoadComponentFinished(), is still called.
crostini_manager_->CancelInstallTermina();
}
}
void CrostiniManager::CrostiniRestarter::LogRestarterResult(
const RestartRequest& request,
CrostiniResult result) {
// Log different histograms depending on the restart source. For an initial
// install, only log for the first request. The Crostini installer also has
// separate histograms in Crostini.SetupResult.
switch (request.options.restart_source) {
case RestartSource::kOther:
if (is_initial_install_) {
return;
}
base::UmaHistogramEnumeration("Crostini.RestarterResult", result);
return;
case RestartSource::kInstaller:
if (!is_initial_install_) {
LOG(WARNING)
<< "Restart request from Crostini installer was not first request.";
}
base::UmaHistogramEnumeration("Crostini.RestarterResult.Installer",
result);
return;
case RestartSource::kMultiContainerCreation:
if (!is_initial_install_) {
LOG(WARNING) << "Restart request for multi-container creation was not "
"first request.";
}
base::UmaHistogramEnumeration(
"Crostini.RestarterResult.MultiContainerCreation", result);
return;
default:
NOTREACHED();
}
}
// Unit tests need these to be initialized to sensible values. In Browser tests
// and real life, they are updated via MaybeUpdateCrostini.
bool CrostiniManager::is_dev_kvm_present_ = true;
bool CrostiniManager::is_vm_launch_allowed_ = true;
void CrostiniManager::UpdateVmState(std::string vm_name, VmState vm_state) {
auto vm_info = running_vms_.find(vm_name);
if (vm_info != running_vms_.end()) {
vm_info->second.state = vm_state;
return;
}
// This can happen normally when StopVm is called right after start up.
LOG(WARNING) << "Attempted to set state for unknown vm: " << vm_name;
}
bool CrostiniManager::IsVmRunning(std::string vm_name) {
auto vm_info = running_vms_.find(std::move(vm_name));
if (vm_info != running_vms_.end()) {
return vm_info->second.state == VmState::STARTED;
}
return false;
}
std::optional<VmInfo> CrostiniManager::GetVmInfo(std::string vm_name) {
auto it = running_vms_.find(std::move(vm_name));
if (it != running_vms_.end()) {
return it->second;
}
return std::nullopt;
}
void CrostiniManager::AddRunningVmForTesting(std::string vm_name,
uint32_t cid) {
guest_os::GuestId id(guest_os::VmType::TERMINA, vm_name, "");
guest_os::GuestOsSessionTrackerFactory::GetForProfile(profile_)
->AddGuestForTesting( // IN-TEST
id, guest_os::GuestInfo{id, cid, {}, {}, {}, {}});
running_vms_[std::move(vm_name)] = VmInfo{VmState::STARTED};
}
void CrostiniManager::AddStoppingVmForTesting(std::string vm_name) {
running_vms_[std::move(vm_name)] = VmInfo{VmState::STOPPING};
}
namespace {
ContainerOsVersion VersionFromOsRelease(
const vm_tools::cicerone::OsRelease& os_release) {
if (os_release.id() == "debian") {
if (os_release.version_id() == "9") {
return ContainerOsVersion::kDebianStretch;
} else if (os_release.version_id() == "10") {
return ContainerOsVersion::kDebianBuster;
} else if (os_release.version_id() == "11") {
return ContainerOsVersion::kDebianBullseye;
} else if (os_release.version_id() == "12") {
return ContainerOsVersion::kDebianBookworm;
} else {
return ContainerOsVersion::kDebianOther;
}
}
return ContainerOsVersion::kOtherOs;
}
bool IsUpgradableContainerVersion(ContainerOsVersion version) {
return version == ContainerOsVersion::kDebianStretch ||
version == ContainerOsVersion::kDebianBuster ||
version == ContainerOsVersion::kDebianBullseye;
}
} // namespace
void CrostiniManager::SetContainerOsRelease(
const guest_os::GuestId& container_id,
const vm_tools::cicerone::OsRelease& os_release) {
ContainerOsVersion version = VersionFromOsRelease(os_release);
// Store the os release version in prefs. We can use this value to decide if
// an upgrade can be offered.
UpdateContainerPref(profile_, container_id,
guest_os::prefs::kContainerOsVersionKey,
base::Value(static_cast<int>(version)));
UpdateContainerPref(profile_, container_id,
guest_os::prefs::kContainerOsPrettyNameKey,
base::Value(os_release.pretty_name()));
std::optional<ContainerOsVersion> old_version;
auto it = container_os_releases_.find(container_id);
if (it != container_os_releases_.end()) {
old_version = VersionFromOsRelease(it->second);
}
VLOG(1) << container_id;
VLOG(1) << "os_release.pretty_name " << os_release.pretty_name();
VLOG(1) << "os_release.name " << os_release.name();
VLOG(1) << "os_release.version " << os_release.version();
VLOG(1) << "os_release.version_id " << os_release.version_id();
VLOG(1) << "os_release.id " << os_release.id();
container_os_releases_[container_id] = os_release;
if (!old_version || *old_version != version) {
for (auto& observer : crostini_container_properties_observers_) {
observer.OnContainerOsReleaseChanged(
container_id, IsUpgradableContainerVersion(version));
}
}
base::UmaHistogramEnumeration("Crostini.ContainerOsVersion", version);
}
void CrostiniManager::ConfigureForArcSideload() {
ash::SessionManagerClient* session_manager_client =
ash::SessionManagerClient::Get();
if (!base::FeatureList::IsEnabled(features::kCrostiniArcSideload) ||
!session_manager_client) {
return;
}
session_manager_client->QueryAdbSideload(base::BindOnce(
// We use a lambda to keep the arc sideloading implementation local, and
// avoid header pollution. This means we have to manually check the weak
// pointer is alive.
[](base::WeakPtr<CrostiniManager> manager,
ash::SessionManagerClient::AdbSideloadResponseCode response_code,
bool is_allowed) {
if (!manager || !is_allowed ||
response_code !=
ash::SessionManagerClient::AdbSideloadResponseCode::SUCCESS) {
return;
}
vm_tools::cicerone::ConfigureForArcSideloadRequest request;
request.set_owner_id(manager->owner_id_);
request.set_vm_name(kCrostiniDefaultVmName);
request.set_container_name(kCrostiniDefaultContainerName);
GetCiceroneClient()->ConfigureForArcSideload(
request,
base::BindOnce(
[](std::optional<
vm_tools::cicerone::ConfigureForArcSideloadResponse>
response) {
if (!response) {
LOG(ERROR) << "Failed to configure for arc sideloading: no "
"response from vm";
return;
}
if (response->status() ==
vm_tools::cicerone::ConfigureForArcSideloadResponse::
SUCCEEDED) {
return;
}
LOG(ERROR) << "Failed to configure for arc sideloading: "
<< response->failure_reason();
}));
},
weak_ptr_factory_.GetWeakPtr()));
}
const vm_tools::cicerone::OsRelease* CrostiniManager::GetContainerOsRelease(
const guest_os::GuestId& container_id) const {
auto it = container_os_releases_.find(container_id);
if (it != container_os_releases_.end()) {
return &it->second;
}
return nullptr;
}
bool CrostiniManager::IsContainerUpgradeable(
const guest_os::GuestId& container_id) const {
ContainerOsVersion version = ContainerOsVersion::kUnknown;
const auto* os_release = GetContainerOsRelease(container_id);
if (os_release) {
version = VersionFromOsRelease(*os_release);
} else {
// Check prefs instead.
const base::Value* value = GetContainerPrefValue(
profile_, container_id, guest_os::prefs::kContainerOsVersionKey);
if (value) {
version = static_cast<ContainerOsVersion>(value->GetInt());
}
}
return IsUpgradableContainerVersion(version);
}
bool CrostiniManager::ShouldPromptContainerUpgrade(
const guest_os::GuestId& container_id) const {
if (!CrostiniFeatures::Get()->IsContainerUpgradeUIAllowed(profile_)) {
return false;
}
if (container_upgrade_prompt_shown_.count(container_id) != 0) {
// Already shown the upgrade dialog.
return false;
}
if (container_id != DefaultContainerId()) {
return false;
}
bool upgradable = IsContainerUpgradeable(container_id);
return upgradable;
}
void CrostiniManager::UpgradePromptShown(
const guest_os::GuestId& container_id) {
container_upgrade_prompt_shown_.insert(container_id);
}
bool CrostiniManager::IsUncleanStartup() const {
return is_unclean_startup_;
}
void CrostiniManager::SetUncleanStartupForTesting(bool is_unclean_startup) {
is_unclean_startup_ = is_unclean_startup;
}
void CrostiniManager::AddRunningContainerForTesting(std::string vm_name,
ContainerInfo info,
bool notify) {
auto* tracker =
guest_os::GuestOsSessionTrackerFactory::GetForProfile(profile_);
std::optional<guest_os::GuestInfo> vm_info = tracker->GetInfo(
guest_os::GuestId{guest_os::VmType::TERMINA, vm_name, ""});
CHECK(vm_info);
guest_os::GuestId id{guest_os::VmType::TERMINA, vm_name, info.name};
guest_os::GuestInfo guest_info{
id, vm_info->cid, info.username,
info.homedir, info.ipv4_address, info.sftp_vsock_port};
tracker->AddGuestForTesting(id, guest_info, notify); // IN-TEST
}
void CrostiniManager::UpdateLaunchMetricsForEnterpriseReporting() {
PrefService* const profile_prefs = profile_->GetPrefs();
const component_updater::ComponentUpdateService* const update_service =
g_browser_process->component_updater();
const base::Clock* const clock = base::DefaultClock::GetInstance();
WriteMetricsForReportingToPrefsIfEnabled(profile_prefs, update_service,
clock);
}
CrostiniManager* CrostiniManager::GetForProfile(Profile* profile) {
return CrostiniManagerFactory::GetForProfile(profile);
}
CrostiniManager::CrostiniManager(Profile* profile)
: profile_(profile),
owner_id_(CryptohomeIdForProfile(profile)),
baguette_installer_(profile_, *profile_->GetPrefs()) {
DCHECK(!profile_->IsOffTheRecord());
GetCiceroneClient()->AddObserver(this);
GetConciergeClient()->AddVmObserver(this);
GetConciergeClient()->AddDiskImageObserver(this);
if (ash::AnomalyDetectorClient::Get()) { // May be null in tests.
ash::AnomalyDetectorClient::Get()->AddObserver(this);
}
if (ash::NetworkHandler::IsInitialized()) {
network_state_handler_observer_.Observe(
ash::NetworkHandler::Get()->network_state_handler());
}
if (chromeos::PowerManagerClient::Get()) {
chromeos::PowerManagerClient::Get()->AddObserver(this);
}
CrostiniThrottleFactory::GetForBrowserContext(profile_);
guest_os_stability_monitor_ =
std::make_unique<guest_os::GuestOsStabilityMonitor>(
kCrostiniStabilityHistogram);
low_disk_notifier_ = std::make_unique<CrostiniLowDiskNotification>();
crostini_sshfs_ = std::make_unique<CrostiniSshfs>(profile_);
// It's possible for us to have containers in prefs while Crostini isn't
// enabled, for example, maybe policy changed and now Crostini isn't allowed
// any more. We still need to call RegisterContainer to update the terminal
// prefs. Note: This means changes only take effect after a restart,
// which is fine, since e.g. force-quitting a running VM because policy
// changed isn't something we're going to do.
for (const auto& vm_type : {kCrostiniDefaultVmType, kBaguetteDefaultVmType}) {
for (const auto& container : guest_os::GetContainers(profile_, vm_type)) {
if (crostini::CrostiniFeatures::Get()->IsEnabled(profile_)) {
RegisterContainer(container);
} else {
RegisterContainerTerminal(container);
}
}
}
// TODO(crbug.com/377377749): only instantiate baguette_installer_ if we care
// about baguette?
}
CrostiniManager::~CrostiniManager() {
RemoveDBusObservers();
}
base::WeakPtr<CrostiniManager> CrostiniManager::GetWeakPtr() {
return weak_ptr_factory_.GetWeakPtr();
}
void CrostiniManager::RemoveDBusObservers() {
if (dbus_observers_removed_) {
return;
}
dbus_observers_removed_ = true;
GetCiceroneClient()->RemoveObserver(this);
if (ash::AnomalyDetectorClient::Get()) { // May be null in tests.
ash::AnomalyDetectorClient::Get()->RemoveObserver(this);
}
if (chromeos::PowerManagerClient::Get()) {
chromeos::PowerManagerClient::Get()->RemoveObserver(this);
}
// GuestOsStabilityMonitor and LowDiskNotifier need to be destructed here so
// they can unregister from DBus clients that may no longer exist later.
guest_os_stability_monitor_.reset();
low_disk_notifier_.reset();
}
// static
bool CrostiniManager::IsDevKvmPresent() {
return is_dev_kvm_present_;
}
// static
bool CrostiniManager::IsVmLaunchAllowed() {
return is_vm_launch_allowed_;
}
void CrostiniManager::MaybeUpdateCrostini() {
// This is a new user session, perhaps using an old CrostiniManager.
container_upgrade_prompt_shown_.clear();
base::ThreadPool::PostTaskAndReply(
FROM_HERE, {base::MayBlock()},
base::BindOnce(&CrostiniManager::CheckPaths),
base::BindOnce(&CrostiniManager::CheckConciergeAvailable,
weak_ptr_factory_.GetWeakPtr()));
// Probe Concierge - if it's still running after an unclean shutdown, a
// success response will be received.
vm_tools::concierge::GetVmInfoRequest concierge_request;
concierge_request.set_owner_id(owner_id_);
concierge_request.set_name(kCrostiniDefaultVmName);
GetConciergeClient()->GetVmInfo(
std::move(concierge_request),
base::BindOnce(
[](base::WeakPtr<CrostiniManager> weak_this,
std::optional<vm_tools::concierge::GetVmInfoResponse> reply) {
if (weak_this) {
weak_this->is_unclean_startup_ =
reply.has_value() && reply->success();
if (weak_this->is_unclean_startup_) {
weak_this->RemoveUncleanSshfsMounts();
}
}
},
weak_ptr_factory_.GetWeakPtr()));
}
// static
void CrostiniManager::CheckPaths() {
is_dev_kvm_present_ = base::PathExists(base::FilePath("/dev/kvm"));
}
void CrostiniManager::CheckConciergeAvailable() {
GetConciergeClient()->WaitForServiceToBeAvailable(base::BindOnce(
&CrostiniManager::CheckVmLaunchAllowed, weak_ptr_factory_.GetWeakPtr()));
}
void CrostiniManager::CheckVmLaunchAllowed(bool service_is_available) {
if (service_is_available) {
vm_tools::concierge::GetVmLaunchAllowedRequest request;
GetConciergeClient()->GetVmLaunchAllowed(
std::move(request),
base::BindOnce(&CrostiniManager::OnCheckVmLaunchAllowed,
weak_ptr_factory_.GetWeakPtr()));
return;
}
LOG(ERROR)
<< "Couldn't contact concierge to check if untrusted VMs are allowed";
MaybeUpdateCrostiniAfterChecks();
}
void CrostiniManager::OnCheckVmLaunchAllowed(
std::optional<vm_tools::concierge::GetVmLaunchAllowedResponse> response) {
// is_vm_launch_allowed_ should be set before CrostiniFeatures is used,
// otherwise a (possibly incorrect) default value is read.
if (!response) {
// Didn't get a reply - assume that VM launch is allowed.
if (base::SysInfo::IsRunningOnChromeOS()) {
LOG(ERROR) << "Failed to determine if VM launch is allowed";
}
} else {
is_vm_launch_allowed_ = response->allowed();
LOG_IF(WARNING, !is_vm_launch_allowed_)
<< "VM launch not allowed: " << response->reason();
}
MaybeUpdateCrostiniAfterChecks();
}
void CrostiniManager::MaybeUpdateCrostiniAfterChecks() {
if (!CrostiniFeatures::Get()->IsEnabled(profile_)) {
return;
}
if (!CrostiniFeatures::Get()->IsAllowedNow(profile_)) {
return;
}
if (ShouldPromptContainerUpgrade(DefaultContainerId())) {
upgrade_available_notification_ =
CrostiniUpgradeAvailableNotification::Show(profile_, base::DoNothing());
}
}
void CrostiniManager::InstallBaguette(BaguetteImageCallback callback) {
if (install_baguette_never_completes_for_testing_) {
LOG(ERROR)
<< "Dropping InstallBaguette request. This is only used in tests.";
return;
}
baguette_installer_.Install(base::BindOnce(
[](BaguetteImageCallback callback,
BaguetteInstaller::InstallResult result,
std::optional<base::ScopedFD> fd) {
CrostiniResult res;
if (result == BaguetteInstaller::InstallResult::Success) {
res = CrostiniResult::SUCCESS;
} else if (result == BaguetteInstaller::InstallResult::Offline) {
LOG(ERROR) << "Installing Baguette failed: offline";
res = CrostiniResult::OFFLINE_WHEN_UPGRADE_REQUIRED;
} else if (result == BaguetteInstaller::InstallResult::Failure) {
LOG(ERROR) << "Installing Baguette failed";
res = CrostiniResult::LOAD_COMPONENT_FAILED;
} else if (result == BaguetteInstaller::InstallResult::NeedUpdate) {
LOG(ERROR) << "Installing Baguette failed: need update";
res = CrostiniResult::NEED_UPDATE;
} else if (result == BaguetteInstaller::InstallResult::Cancelled) {
LOG(ERROR) << "Installing Baguette failed: cancelled";
res = CrostiniResult::INSTALL_BAGUETTE_CANCELLED;
} else if (result == BaguetteInstaller::InstallResult::ChecksumError) {
LOG(ERROR) << "Installing Baguette failed: checksum did not match.";
res = CrostiniResult::DOWNLOAD_BAGUETTE_FAILED;
} else if (result == BaguetteInstaller::InstallResult::DownloadError) {
LOG(ERROR) << "Installing Baguette failed: download failed.";
res = CrostiniResult::DOWNLOAD_BAGUETTE_FAILED;
} else {
LOG(ERROR)
<< "Installing Baguette failed: encountered an unknown error.";
res = CrostiniResult::UNKNOWN_ERROR;
}
std::move(callback).Run(std::move(fd), res);
},
std::move(callback)));
}
void CrostiniManager::InstallTermina(CrostiniResultCallback callback) {
if (install_termina_never_completes_for_testing_) {
LOG(ERROR)
<< "Dropping InstallTermina request. This is only used in tests.";
return;
}
termina_installer_.Install(base::BindOnce(
[](CrostiniResultCallback callback,
TerminaInstaller::InstallResult result) {
CrostiniResult res;
if (result == TerminaInstaller::InstallResult::Success) {
res = CrostiniResult::SUCCESS;
} else if (result == TerminaInstaller::InstallResult::Offline) {
LOG(ERROR) << "Installing Termina failed: offline";
res = CrostiniResult::OFFLINE_WHEN_UPGRADE_REQUIRED;
} else if (result == TerminaInstaller::InstallResult::Failure) {
LOG(ERROR) << "Installing Termina failed";
res = CrostiniResult::LOAD_COMPONENT_FAILED;
} else if (result == TerminaInstaller::InstallResult::NeedUpdate) {
LOG(ERROR) << "Installing Termina failed: need update";
res = CrostiniResult::NEED_UPDATE;
} else if (result == TerminaInstaller::InstallResult::Cancelled) {
LOG(ERROR) << "Installing Termina failed: cancelled";
res = CrostiniResult::INSTALL_TERMINA_CANCELLED;
} else {
NOTREACHED()
<< "Got unexpected value of TerminaInstaller::InstallResult";
}
std::move(callback).Run(res);
},
std::move(callback)));
}
void CrostiniManager::CancelInstallTermina() {
termina_installer_.CancelInstall();
}
void CrostiniManager::UninstallTermina(BoolCallback callback) {
if (base::FeatureList::IsEnabled(ash::features::kCrostiniContainerless)) {
baguette_installer_.Uninstall(std::move(callback));
} else {
termina_installer_.Uninstall(std::move(callback));
}
}
void CrostiniManager::CreateDiskImage(
const std::string& vm_name,
std::optional<base::ScopedFD> disk_image,
vm_tools::concierge::StorageLocation storage_location,
int64_t disk_size_bytes,
CreateDiskImageCallback callback) {
if (vm_name.empty()) {
LOG(ERROR) << "VM name must not be empty";
std::move(callback).Run(CrostiniResult::CLIENT_ERROR, base::FilePath());
return;
}
vm_tools::concierge::CreateDiskImageRequest request;
request.set_cryptohome_id(CryptohomeIdForProfile(profile_));
request.set_vm_name(std::move(vm_name));
// The type of disk image to be created.
request.set_image_type(vm_tools::concierge::DISK_IMAGE_AUTO);
if (storage_location != vm_tools::concierge::STORAGE_CRYPTOHOME_ROOT) {
LOG(ERROR) << "'" << storage_location
<< "' is not a valid storage location";
std::move(callback).Run(CrostiniResult::CLIENT_ERROR, base::FilePath());
return;
}
request.set_storage_location(storage_location);
// The logical size of the new disk image, in bytes.
request.set_disk_size(std::move(disk_size_bytes));
if (base::FeatureList::IsEnabled(ash::features::kCrostiniContainerless)) {
if (!disk_image.has_value()) {
// CreateDiskImage will still run, as a no-op that provides the location
// of the disk image.
LOG(WARNING)
<< "No disk image was provided for baguette installation, this "
"should indicate an existing baguette disk image";
} else {
request.set_copy_baguette_image(true);
GetConciergeClient()->CreateDiskImageWithFd(
std::move(disk_image.value()), std::move(request),
base::BindOnce(&CrostiniManager::OnCreateDiskImage,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
return;
}
}
GetConciergeClient()->CreateDiskImage(
std::move(request),
base::BindOnce(&CrostiniManager::OnCreateDiskImage,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void CrostiniManager::StartTerminaVm(std::string name,
const base::FilePath& disk_path,
size_t num_cores_disabled,
BoolCallback callback) {
if (name.empty()) {
LOG(ERROR) << "name is required";
std::move(callback).Run(/*success=*/false);
return;
}
std::string disk_path_string = disk_path.AsUTF8Unsafe();
if (disk_path_string.empty()) {
LOG(ERROR) << "Disk path cannot be empty";
std::move(callback).Run(/*success=*/false);
return;
}
auto* anomaly_detector_client = ash::AnomalyDetectorClient::Get();
if (anomaly_detector_client &&
!anomaly_detector_client->IsGuestFileCorruptionSignalConnected()) {
LOG(ERROR) << "GuestFileCorruptionSignal not connected, will not be "
"able to detect file system corruption.";
std::move(callback).Run(/*success=*/false);
return;
}
for (auto& observer : vm_starting_observers_) {
observer.OnVmStarting();
}
vm_tools::concierge::StartVmRequest request;
if (base::FeatureList::IsEnabled(ash::features::kCrostiniContainerless)) {
request.mutable_vm()->set_tools_dlc_id(kToolsDlcName);
request.set_vm_type(
::vm_tools::concierge::VmInfo_VmType::VmInfo_VmType_BAGUETTE);
} else {
std::optional<std::string> dlc_id = termina_installer_.GetDlcId();
if (dlc_id.has_value()) {
request.mutable_vm()->set_dlc_id(*dlc_id);
}
}
request.set_name(std::move(name));
if (!base::FeatureList::IsEnabled(ash::features::kCrostiniContainerless)) {
request.set_start_termina(true);
}
request.set_owner_id(owner_id_);
request.set_timeout(static_cast<uint32_t>(kStartVmTimeout.InSeconds()));
if (base::FeatureList::IsEnabled(ash::features::kCrostiniGpuSupport)) {
request.set_enable_gpu(true);
}
if (profile_->GetPrefs()->GetBoolean(prefs::kCrostiniMicAllowed) &&
profile_->GetPrefs()->GetBoolean(::prefs::kAudioCaptureAllowed)) {
request.set_enable_audio_capture(true);
}
const int32_t cpus = base::SysInfo::NumberOfProcessors() - num_cores_disabled;
DCHECK_LT(0, cpus);
request.set_cpus(cpus);
vm_tools::concierge::DiskImage* disk_image = request.add_disks();
disk_image->set_path(std::move(disk_path_string));
if (base::FeatureList::IsEnabled(ash::features::kCrostiniContainerless)) {
disk_image->set_image_type(vm_tools::concierge::DISK_IMAGE_RAW);
} else {
disk_image->set_image_type(vm_tools::concierge::DISK_IMAGE_AUTO);
}
disk_image->set_writable(true);
disk_image->set_do_mount(false);
GetConciergeClient()->StartVm(
request, base::BindOnce(&CrostiniManager::OnStartTerminaVm,
weak_ptr_factory_.GetWeakPtr(), request.name(),
std::move(callback)));
}
void CrostiniManager::StopVm(std::string name,
CrostiniResultCallback callback) {
if (name.empty()) {
LOG(ERROR) << "name is required";
std::move(callback).Run(CrostiniResult::CLIENT_ERROR);
return;
}
UpdateVmState(name, VmState::STOPPING);
vm_tools::concierge::StopVmRequest request;
request.set_owner_id(owner_id_);
request.set_name(name);
GetConciergeClient()->StopVm(
std::move(request),
base::BindOnce(&CrostiniManager::OnStopVm, weak_ptr_factory_.GetWeakPtr(),
std::move(name), std::move(callback)));
}
void CrostiniManager::StopRunningVms(CrostiniResultCallback callback) {
std::vector<std::string> names;
LOG(WARNING) << "StopRunningVms";
for (const auto& it : running_vms_) {
if (it.second.state != VmState::STOPPING) {
names.push_back(it.first);
}
}
auto barrier = base::BarrierCallback<CrostiniResult>(
names.size(), base::BindOnce(
[](CrostiniResultCallback callback,
std::vector<CrostiniResult> results) {
auto result = CrostiniResult::SUCCESS;
for (auto res : results) {
if (res != CrostiniResult::SUCCESS) {
LOG(ERROR) << "StopVm failure code "
<< static_cast<int>(res);
result = res;
break;
}
}
std::move(callback).Run(result);
},
std::move(callback)));
for (const auto& name : names) {
VLOG(1) << "Stopping vm " << name;
StopVm(name, barrier);
}
}
void CrostiniManager::UpdateTerminaVmKernelVersion() {
vm_tools::concierge::GetVmEnterpriseReportingInfoRequest request;
request.set_vm_name(kCrostiniDefaultVmName);
request.set_owner_id(owner_id_);
GetConciergeClient()->GetVmEnterpriseReportingInfo(
std::move(request),
base::BindOnce(&CrostiniManager::OnGetTerminaVmKernelVersion,
weak_ptr_factory_.GetWeakPtr()));
}
void CrostiniManager::StartLxd(std::string vm_name,
CrostiniResultCallback callback) {
if (vm_name.empty()) {
LOG(ERROR) << "vm_name is required";
std::move(callback).Run(CrostiniResult::CLIENT_ERROR);
return;
}
if (!GetCiceroneClient()->IsStartLxdProgressSignalConnected()) {
LOG(ERROR) << "Async call to StartLxd can't complete when signals "
"are not connected.";
std::move(callback).Run(CrostiniResult::CLIENT_ERROR);
return;
}
vm_tools::cicerone::StartLxdRequest request;
request.set_vm_name(std::move(vm_name));
request.set_owner_id(owner_id_);
request.set_reset_lxd_db(
base::FeatureList::IsEnabled(ash::features::kCrostiniResetLxdDb));
GetCiceroneClient()->StartLxd(
std::move(request),
base::BindOnce(&CrostiniManager::OnStartLxd,
weak_ptr_factory_.GetWeakPtr(), request.vm_name(),
std::move(callback)));
}
void CrostiniManager::SetUpBaguetteUser(
std::string vm_name,
std::optional<std::string> container_username,
CrostiniResultCallback callback) {
if (vm_name.empty()) {
LOG(ERROR) << "vm_name is required";
std::move(callback).Run(CrostiniResult::CLIENT_ERROR);
return;
}
std::string username =
container_username.value_or(DefaultContainerUserNameForProfile(profile_));
vm_tools::concierge::SetUpVmUserRequest request;
request.set_vm_name(vm_name);
request.set_owner_id(owner_id_);
request.set_username(username);
request.add_group_names("audio");
request.add_group_names("cdrom");
request.add_group_names("dialout");
request.add_group_names("floppy");
request.add_group_names("kvm");
request.add_group_names("netdev");
request.add_group_names("sudo");
request.add_group_names("tss");
request.add_group_names("video");
GetConciergeClient()->SetUpVmUser(
std::move(request),
base::BindOnce(&CrostiniManager::OnSetUpBaguetteUser,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
namespace {
std::string GetImageServer() {
std::string image_server_url;
scoped_refptr<component_updater::ComponentManagerAsh> component_manager =
g_browser_process->platform_part()->component_manager_ash();
if (component_manager) {
image_server_url =
component_manager->GetCompatiblePath("cros-crostini-image-server-url")
.value();
}
return image_server_url.empty() ? kCrostiniDefaultImageServerUrl
: image_server_url;
}
std::string GetImageAlias() {
std::string debian_version;
auto* cmdline = base::CommandLine::ForCurrentProcess();
if (cmdline->HasSwitch(kCrostiniContainerFlag)) {
debian_version = cmdline->GetSwitchValueASCII(kCrostiniContainerFlag);
} else {
debian_version = kCrostiniContainerDefaultVersion;
}
return base::StringPrintf(kCrostiniImageAliasPattern, debian_version.c_str());
}
} // namespace
void CrostiniManager::CreateLxdContainer(
guest_os::GuestId container_id,
std::optional<std::string> opt_image_server_url,
std::optional<std::string> opt_image_alias,
CrostiniResultCallback callback) {
if (container_id.vm_name.empty()) {
LOG(ERROR) << "vm_name is required";
std::move(callback).Run(CrostiniResult::CLIENT_ERROR);
return;
}
if (container_id.container_name.empty()) {
LOG(ERROR) << "container_name is required";
std::move(callback).Run(CrostiniResult::CLIENT_ERROR);
return;
}
if (!GetCiceroneClient()->IsLxdContainerCreatedSignalConnected() ||
!GetCiceroneClient()->IsLxdContainerDownloadingSignalConnected()) {
LOG(ERROR)
<< "Async call to CreateLxdContainer can't complete when signals "
"are not connected.";
std::move(callback).Run(CrostiniResult::SIGNAL_NOT_CONNECTED);
return;
}
vm_tools::cicerone::CreateLxdContainerRequest request;
request.set_vm_name(container_id.vm_name);
request.set_container_name(container_id.container_name);
request.set_owner_id(owner_id_);
request.set_image_server(opt_image_server_url.value_or(GetImageServer()));
request.set_image_alias(opt_image_alias.value_or(GetImageAlias()));
VLOG(1) << "image_server_url = " << request.image_server()
<< ", image_alias = " << request.image_alias();
GetCiceroneClient()->CreateLxdContainer(
std::move(request),
base::BindOnce(&CrostiniManager::OnCreateLxdContainer,
weak_ptr_factory_.GetWeakPtr(), std::move(container_id),
std::move(callback)));
}
void CrostiniManager::DeleteLxdContainer(guest_os::GuestId container_id,
BoolCallback callback) {
if (container_id.vm_name.empty()) {
LOG(ERROR) << "vm_name is required";
std::move(callback).Run(/*success=*/false);
return;
}
if (container_id.container_name.empty()) {
LOG(ERROR) << "container_name is required";
std::move(callback).Run(/*success=*/false);
return;
}
if (!GetCiceroneClient()->IsLxdContainerDeletedSignalConnected()) {
LOG(ERROR)
<< "Async call to DeleteLxdContainer can't complete when signals "
"are not connected.";
std::move(callback).Run(/*success=*/false);
return;
}
vm_tools::cicerone::DeleteLxdContainerRequest request;
request.set_vm_name(container_id.vm_name);
request.set_container_name(container_id.container_name);
request.set_owner_id(owner_id_);
GetCiceroneClient()->DeleteLxdContainer(
std::move(request),
base::BindOnce(&CrostiniManager::OnDeleteLxdContainer,
weak_ptr_factory_.GetWeakPtr(), std::move(container_id),
std::move(callback)));
}
void CrostiniManager::OnDeleteLxdContainer(
const guest_os::GuestId& container_id,
BoolCallback callback,
std::optional<vm_tools::cicerone::DeleteLxdContainerResponse> response) {
if (!response) {
LOG(ERROR) << "Failed to delete lxd container in vm. Empty response.";
std::move(callback).Run(/*success=*/false);
return;
}
if (response->status() ==
vm_tools::cicerone::DeleteLxdContainerResponse::DELETING) {
VLOG(1) << "Awaiting LxdContainerDeletedSignal for " << container_id;
delete_lxd_container_callbacks_.emplace(container_id, std::move(callback));
} else if (response->status() ==
vm_tools::cicerone::DeleteLxdContainerResponse::DOES_NOT_EXIST) {
RemoveLxdContainerFromPrefs(profile_, container_id);
UnregisterContainer(container_id);
std::move(callback).Run(/*success=*/true);
} else {
LOG(ERROR) << "Failed to delete container: " << response->failure_reason();
std::move(callback).Run(/*success=*/false);
}
}
void CrostiniManager::StartLxdContainer(guest_os::GuestId container_id,
CrostiniResultCallback callback) {
if (container_id.vm_name.empty()) {
LOG(ERROR) << "vm_name is required";
std::move(callback).Run(CrostiniResult::CLIENT_ERROR);
return;
}
if (container_id.container_name.empty()) {
LOG(ERROR) << "container_name is required";
std::move(callback).Run(CrostiniResult::CLIENT_ERROR);
return;
}
if (!GetCiceroneClient()->IsContainerStartedSignalConnected() ||
!GetCiceroneClient()->IsContainerShutdownSignalConnected() ||
!GetCiceroneClient()->IsLxdContainerStartingSignalConnected()) {
LOG(ERROR) << "Async call to StartLxdContainer can't complete when signals "
"are not connected.";
std::move(callback).Run(CrostiniResult::SIGNAL_NOT_CONNECTED);
return;
}
vm_tools::cicerone::StartLxdContainerRequest request;
request.set_vm_name(container_id.vm_name);
request.set_container_name(container_id.container_name);
request.set_owner_id(owner_id_);
if (auto* integration_service =
drive::DriveIntegrationServiceFactory::GetForProfile(profile_)) {
request.set_drivefs_mount_path(
integration_service->GetMountPointPath().value());
}
GetCiceroneClient()->StartLxdContainer(
std::move(request),
base::BindOnce(&CrostiniManager::OnStartLxdContainer,
weak_ptr_factory_.GetWeakPtr(), std::move(container_id),
std::move(callback)));
}
void CrostiniManager::StopLxdContainer(guest_os::GuestId container_id,
CrostiniResultCallback callback) {
if (container_id.vm_name.empty()) {
LOG(ERROR) << "vm_name is required";
std::move(callback).Run(CrostiniResult::CLIENT_ERROR);
return;
}
if (container_id.container_name.empty()) {
LOG(ERROR) << "container_name is required";
std::move(callback).Run(CrostiniResult::CLIENT_ERROR);
return;
}
vm_tools::cicerone::StopLxdContainerRequest request;
request.set_vm_name(container_id.vm_name);
request.set_container_name(container_id.container_name);
request.set_owner_id(owner_id_);
GetCiceroneClient()->StopLxdContainer(
std::move(request),
base::BindOnce(&CrostiniManager::OnStopLxdContainer,
weak_ptr_factory_.GetWeakPtr(), std::move(container_id),
std::move(callback)));
}
void CrostiniManager::SetUpLxdContainerUser(guest_os::GuestId container_id,
std::string container_username,
BoolCallback callback) {
if (container_id.vm_name.empty()) {
LOG(ERROR) << "vm_name is required";
std::move(callback).Run(/*success=*/false);
return;
}
if (container_id.container_name.empty()) {
LOG(ERROR) << "container_name is required";
std::move(callback).Run(/*success=*/false);
return;
}
if (container_username.empty()) {
LOG(ERROR) << "container_username is required";
std::move(callback).Run(/*success=*/false);
return;
}
vm_tools::cicerone::SetUpLxdContainerUserRequest request;
request.set_vm_name(container_id.vm_name);
request.set_container_name(container_id.container_name);
request.set_owner_id(owner_id_);
request.set_container_username(std::move(container_username));
GetCiceroneClient()->SetUpLxdContainerUser(
std::move(request),
base::BindOnce(&CrostiniManager::OnSetUpLxdContainerUser,
weak_ptr_factory_.GetWeakPtr(), std::move(container_id),
std::move(callback)));
}
void CrostiniManager::ExportDiskImage(guest_os::GuestId vm_id,
std::string user_id_hash,
base::FilePath export_path,
bool force,
CrostiniResultCallback callback) {
if (vm_id.vm_name.empty()) {
LOG(ERROR) << "vm_name is required";
std::move(callback).Run(CrostiniResult::CLIENT_ERROR);
return;
}
if (user_id_hash.empty()) {
LOG(ERROR) << "user_id_hash is required";
std::move(callback).Run(CrostiniResult::CLIENT_ERROR);
return;
}
if (disk_image_callbacks_.find(vm_id) != disk_image_callbacks_.end()) {
LOG(ERROR) << "Disk image operation currently running for " << vm_id;
std::move(callback).Run(CrostiniResult::DISK_IMAGE_FAILED);
}
disk_image_callbacks_.emplace(vm_id, std::move(callback));
vm_tools::concierge::ExportDiskImageRequest request;
request.set_vm_name(vm_id.vm_name);
request.set_cryptohome_id(user_id_hash);
// Digest file is only used for pluginVM which will be deprecated soon.
request.set_generate_sha256_digest(false);
request.set_force(force);
std::vector<base::ScopedFD> fds;
base::File file(export_path,
base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
if (!file.IsValid()) {
LOG(ERROR) << "Failed to open " << export_path;
return;
}
fds.emplace_back(file.TakePlatformFile());
GetConciergeClient()->ExportDiskImage(
std::move(fds), std::move(request),
base::BindOnce(&CrostiniManager::OnExportDiskImage,
weak_ptr_factory_.GetWeakPtr(), vm_id));
}
void CrostiniManager::OnExportDiskImage(
guest_os::GuestId vm_id,
std::optional<vm_tools::concierge::ExportDiskImageResponse> response) {
auto it = disk_image_callbacks_.find(vm_id);
if (it == disk_image_callbacks_.end()) {
LOG(ERROR) << "No export callback for " << vm_id;
return;
}
if (!response) {
LOG(ERROR) << "Failed to export disk image. Empty response.";
std::move(it->second).Run(CrostiniResult::DISK_IMAGE_FAILED);
disk_image_callbacks_.erase(it);
return;
}
// If export has started, the callback will be invoked when the
// DiskImageProgressSignal signal indicates that export is
// complete, otherwise this is an error.
if (response->status() != vm_tools::concierge::DISK_STATUS_IN_PROGRESS) {
LOG(ERROR) << "Failed to export disk image: status=" << response->status()
<< ", failure_reason=" << response->failure_reason();
std::move(it->second).Run(CrostiniResult::DISK_IMAGE_FAILED);
disk_image_callbacks_.erase(it);
}
disk_image_uuid_to_guest_id_.emplace(response->command_uuid(), vm_id);
}
void CrostiniManager::ImportDiskImage(guest_os::GuestId vm_id,
std::string user_id_hash,
base::FilePath import_path,
CrostiniResultCallback callback) {
if (vm_id.vm_name.empty()) {
LOG(ERROR) << "vm_name is required";
std::move(callback).Run(CrostiniResult::CLIENT_ERROR);
return;
}
if (user_id_hash.empty()) {
LOG(ERROR) << "user_id_hash is required";
std::move(callback).Run(CrostiniResult::CLIENT_ERROR);
return;
}
if (disk_image_callbacks_.find(vm_id) != disk_image_callbacks_.end()) {
LOG(ERROR) << "Disk image operation currently running for " << vm_id;
std::move(callback).Run(CrostiniResult::DISK_IMAGE_FAILED);
}
disk_image_callbacks_.emplace(vm_id, std::move(callback));
base::File file(import_path, base::File::FLAG_OPEN | base::File::FLAG_READ);
if (!file.IsValid()) {
LOG(ERROR) << "Failed to open " << import_path;
return;
}
vm_tools::concierge::ImportDiskImageRequest request;
request.set_vm_name(vm_id.vm_name);
request.set_cryptohome_id(user_id_hash);
// All vm's are stored in root except pluginvm, which is not supported in this
// flow.
request.set_storage_location(vm_tools::concierge::STORAGE_CRYPTOHOME_ROOT);
request.set_source_size(file.GetLength());
GetConciergeClient()->ImportDiskImage(
base::ScopedFD(file.TakePlatformFile()), std::move(request),
base::BindOnce(&CrostiniManager::OnImportDiskImage,
weak_ptr_factory_.GetWeakPtr(), vm_id));
}
void CrostiniManager::OnImportDiskImage(
guest_os::GuestId vm_id,
std::optional<vm_tools::concierge::ImportDiskImageResponse> response) {
auto it = disk_image_callbacks_.find(vm_id);
if (it == disk_image_callbacks_.end()) {
LOG(ERROR) << "No import callback for " << vm_id;
return;
}
if (!response) {
LOG(ERROR) << "Failed to import disk image. Empty response.";
std::move(it->second).Run(CrostiniResult::DISK_IMAGE_FAILED);
disk_image_callbacks_.erase(it);
return;
}
// If import has started, the callback will be invoked when the
// DiskImageProgressSignal signal indicates that import is
// complete, otherwise this is an error.
if (response->status() != vm_tools::concierge::DISK_STATUS_IN_PROGRESS) {
LOG(ERROR) << "Failed to import image: status=" << response->status()
<< ", failure_reason=" << response->failure_reason();
std::move(it->second).Run(CrostiniResult::DISK_IMAGE_FAILED);
disk_image_callbacks_.erase(it);
}
disk_image_uuid_to_guest_id_.emplace(response->command_uuid(), vm_id);
}
void CrostiniManager::OnDiskImageProgress(
const vm_tools::concierge::DiskImageStatusResponse& signal) {
bool call_observers = false;
bool call_original_callback = false;
CrostiniResult result;
DiskImageProgressStatus status;
switch (signal.status()) {
case vm_tools::concierge::DISK_STATUS_IN_PROGRESS:
status = DiskImageProgressStatus::IN_PROGRESS;
call_observers = true;
break;
case vm_tools::concierge::DISK_STATUS_NOT_ENOUGH_SPACE:
status = DiskImageProgressStatus::FAILURE_SPACE;
result = CrostiniResult::DISK_IMAGE_FAILED_NO_SPACE;
call_observers = true;
call_original_callback = true;
break;
case vm_tools::concierge::DISK_STATUS_CREATED:
call_original_callback = true;
result = CrostiniResult::SUCCESS;
break;
default:
call_original_callback = true;
result = CrostiniResult::DISK_IMAGE_FAILED;
LOG(ERROR) << "Failed during disk image export: " << signal.status()
<< ", " << signal.failure_reason();
}
auto uuid_it = disk_image_uuid_to_guest_id_.find(signal.command_uuid());
if (uuid_it == disk_image_uuid_to_guest_id_.end()) {
LOG(ERROR) << "No GuestId mapping for command uuid: "
<< signal.command_uuid();
return;
}
if (call_observers) {
for (auto& observer : disk_image_progress_observers_) {
observer.OnDiskImageProgress(uuid_it->second, status, signal.progress());
}
}
if (call_original_callback) {
auto it = disk_image_callbacks_.find(uuid_it->second);
if (it == disk_image_callbacks_.end()) {
LOG(ERROR) << "No export callbacks for " << uuid_it->second;
}
std::move(it->second).Run(result);
// The callback and its uuid mapping are done now, remove
disk_image_callbacks_.erase(it);
disk_image_uuid_to_guest_id_.erase(uuid_it);
}
}
void CrostiniManager::ExportLxdContainer(
guest_os::GuestId container_id,
base::FilePath export_path,
ExportLxdContainerResultCallback callback) {
if (container_id.vm_name.empty()) {
LOG(ERROR) << "vm_name is required";
std::move(callback).Run(CrostiniResult::CLIENT_ERROR, 0, 0);
return;
}
if (container_id.container_name.empty()) {
LOG(ERROR) << "container_name is required";
std::move(callback).Run(CrostiniResult::CLIENT_ERROR, 0, 0);
return;
}
if (export_path.empty()) {
LOG(ERROR) << "export_path is required";
std::move(callback).Run(CrostiniResult::CLIENT_ERROR, 0, 0);
return;
}
if (export_lxd_container_callbacks_.find(container_id) !=
export_lxd_container_callbacks_.end()) {
LOG(ERROR) << "Export currently in progress for " << container_id;
std::move(callback).Run(CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED, 0,
0);
return;
}
export_lxd_container_callbacks_.emplace(container_id, std::move(callback));
vm_tools::cicerone::ExportLxdContainerRequest request;
request.set_vm_name(container_id.vm_name);
request.set_container_name(container_id.container_name);
request.set_owner_id(owner_id_);
request.set_export_path(export_path.value());
GetCiceroneClient()->ExportLxdContainer(
std::move(request),
base::BindOnce(&CrostiniManager::OnExportLxdContainer,
weak_ptr_factory_.GetWeakPtr(), std::move(container_id)));
}
void CrostiniManager::ImportLxdContainer(guest_os::GuestId container_id,
base::FilePath import_path,
CrostiniResultCallback callback) {
if (container_id.vm_name.empty()) {
LOG(ERROR) << "vm_name is required";
std::move(callback).Run(CrostiniResult::CLIENT_ERROR);
return;
}
if (container_id.container_name.empty()) {
LOG(ERROR) << "container_name is required";
std::move(callback).Run(CrostiniResult::CLIENT_ERROR);
return;
}
if (import_path.empty()) {
LOG(ERROR) << "import_path is required";
std::move(callback).Run(CrostiniResult::CLIENT_ERROR);
return;
}
if (import_lxd_container_callbacks_.find(container_id) !=
import_lxd_container_callbacks_.end()) {
LOG(ERROR) << "Import currently in progress for " << container_id;
std::move(callback).Run(CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED);
return;
}
import_lxd_container_callbacks_.emplace(container_id, std::move(callback));
vm_tools::cicerone::ImportLxdContainerRequest request;
request.set_vm_name(container_id.vm_name);
request.set_container_name(container_id.container_name);
request.set_owner_id(owner_id_);
request.set_import_path(import_path.value());
GetCiceroneClient()->ImportLxdContainer(
std::move(request),
base::BindOnce(&CrostiniManager::OnImportLxdContainer,
weak_ptr_factory_.GetWeakPtr(), std::move(container_id)));
}
void CrostiniManager::CancelDiskImageOp(guest_os::GuestId key) {
auto it = disk_image_callbacks_.find(key);
if (it == disk_image_callbacks_.end()) {
LOG(ERROR) << "No disk image operation currently in progress for " << key;
return;
}
auto uuid_it = std::find_if(
disk_image_uuid_to_guest_id_.begin(), disk_image_uuid_to_guest_id_.end(),
[&key](const auto& p) { return p.second == key; });
if (uuid_it == disk_image_uuid_to_guest_id_.end()) {
LOG(ERROR) << "No associated command UUID for " << key;
return;
}
vm_tools::concierge::CancelDiskImageRequest request;
request.set_command_uuid(uuid_it->first);
GetConciergeClient()->CancelDiskImageOperation(
std::move(request),
base::BindOnce(&CrostiniManager::OnCancelDiskImageOp,
weak_ptr_factory_.GetWeakPtr(), std::move(key)));
}
void CrostiniManager::CancelExportLxdContainer(guest_os::GuestId key) {
const auto& vm_name = key.vm_name;
const auto& container_name = key.container_name;
if (vm_name.empty()) {
LOG(ERROR) << "vm_name is required";
return;
}
if (container_name.empty()) {
LOG(ERROR) << "container_name is required";
return;
}
auto it = export_lxd_container_callbacks_.find(key);
if (it == export_lxd_container_callbacks_.end()) {
LOG(ERROR) << "No export currently in progress for " << key;
return;
}
vm_tools::cicerone::CancelExportLxdContainerRequest request;
request.set_vm_name(vm_name);
request.set_owner_id(owner_id_);
request.set_in_progress_container_name(container_name);
GetCiceroneClient()->CancelExportLxdContainer(
std::move(request),
base::BindOnce(&CrostiniManager::OnCancelExportLxdContainer,
weak_ptr_factory_.GetWeakPtr(), std::move(key)));
}
void CrostiniManager::CancelImportLxdContainer(guest_os::GuestId key) {
const auto& vm_name = key.vm_name;
const auto& container_name = key.container_name;
if (vm_name.empty()) {
LOG(ERROR) << "vm_name is required";
return;
}
if (container_name.empty()) {
LOG(ERROR) << "container_name is required";
return;
}
auto it = import_lxd_container_callbacks_.find(key);
if (it == import_lxd_container_callbacks_.end()) {
LOG(ERROR) << "No import currently in progress for " << key;
return;
}
vm_tools::cicerone::CancelImportLxdContainerRequest request;
request.set_vm_name(vm_name);
request.set_owner_id(owner_id_);
request.set_in_progress_container_name(container_name);
GetCiceroneClient()->CancelImportLxdContainer(
std::move(request),
base::BindOnce(&CrostiniManager::OnCancelImportLxdContainer,
weak_ptr_factory_.GetWeakPtr(), std::move(key)));
}
namespace {
vm_tools::cicerone::UpgradeContainerRequest::Version ConvertVersion(
ContainerVersion from) {
switch (from) {
case ContainerVersion::STRETCH:
return vm_tools::cicerone::UpgradeContainerRequest::DEBIAN_STRETCH;
case ContainerVersion::BUSTER:
return vm_tools::cicerone::UpgradeContainerRequest::DEBIAN_BUSTER;
case ContainerVersion::BULLSEYE:
return vm_tools::cicerone::UpgradeContainerRequest::DEBIAN_BULLSEYE;
case ContainerVersion::BOOKWORM:
return vm_tools::cicerone::UpgradeContainerRequest::DEBIAN_BOOKWORM;
case ContainerVersion::UNKNOWN:
default:
return vm_tools::cicerone::UpgradeContainerRequest::UNKNOWN;
}
}
} // namespace
void CrostiniManager::UpgradeContainer(const guest_os::GuestId& key,
ContainerVersion target_version,
CrostiniResultCallback callback) {
const auto& vm_name = key.vm_name;
const auto& container_name = key.container_name;
if (vm_name.empty()) {
LOG(ERROR) << "vm_name is required";
std::move(callback).Run(CrostiniResult::CLIENT_ERROR);
return;
}
if (container_name.empty()) {
LOG(ERROR) << "container_name is required";
std::move(callback).Run(CrostiniResult::CLIENT_ERROR);
return;
}
if (!GetCiceroneClient()->IsUpgradeContainerProgressSignalConnected()) {
// Technically we could still start the upgrade, but we wouldn't be able
// to detect when the upgrade completes, successfully or otherwise.
LOG(ERROR) << "Attempted to upgrade container when progress signal not "
"connected.";
std::move(callback).Run(CrostiniResult::UPGRADE_CONTAINER_FAILED);
return;
}
vm_tools::cicerone::UpgradeContainerRequest request;
request.set_owner_id(owner_id_);
request.set_vm_name(vm_name);
request.set_container_name(container_name);
request.set_target_version(ConvertVersion(target_version));
CrostiniResultCallback do_upgrade_container = base::BindOnce(
[](base::WeakPtr<CrostiniManager> crostini_manager,
vm_tools::cicerone::UpgradeContainerRequest request,
CrostiniResultCallback final_callback, CrostiniResult result) {
// When we fail to start the VM, we can't continue the upgrade.
if (result != CrostiniResult::SUCCESS &&
result != CrostiniResult::RESTART_ABORTED) {
LOG(ERROR) << "Failed to restart the vm before attempting container "
"upgrade. Result code "
<< static_cast<int>(result);
std::move(final_callback)
.Run(CrostiniResult::UPGRADE_CONTAINER_FAILED);
return;
}
GetCiceroneClient()->UpgradeContainer(
std::move(request),
base::BindOnce(&CrostiniManager::OnUpgradeContainer,
crostini_manager, std::move(final_callback)));
},
weak_ptr_factory_.GetWeakPtr(), std::move(request), std::move(callback));
if (!IsVmRunning(vm_name)) {
RestartCrostini(key, std::move(do_upgrade_container));
} else {
std::move(do_upgrade_container).Run(CrostiniResult::SUCCESS);
}
}
void CrostiniManager::CancelUpgradeContainer(const guest_os::GuestId& key,
CrostiniResultCallback callback) {
const auto& vm_name = key.vm_name;
const auto& container_name = key.container_name;
if (vm_name.empty()) {
LOG(ERROR) << "vm_name is required";
std::move(callback).Run(CrostiniResult::CLIENT_ERROR);
return;
}
if (container_name.empty()) {
LOG(ERROR) << "container_name is required";
std::move(callback).Run(CrostiniResult::CLIENT_ERROR);
return;
}
vm_tools::cicerone::CancelUpgradeContainerRequest request;
request.set_owner_id(owner_id_);
request.set_vm_name(vm_name);
request.set_container_name(container_name);
GetCiceroneClient()->CancelUpgradeContainer(
std::move(request),
base::BindOnce(&CrostiniManager::OnCancelUpgradeContainer,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void CrostiniManager::GetContainerAppIcons(
const guest_os::GuestId& container_id,
std::vector<std::string> desktop_file_ids,
int icon_size,
int scale,
GetContainerAppIconsCallback callback) {
vm_tools::cicerone::ContainerAppIconRequest request;
request.set_owner_id(owner_id_);
request.set_vm_name(container_id.vm_name);
request.set_container_name(container_id.container_name);
google::protobuf::RepeatedPtrField<std::string> ids(
std::make_move_iterator(desktop_file_ids.begin()),
std::make_move_iterator(desktop_file_ids.end()));
request.mutable_desktop_file_ids()->Swap(&ids);
request.set_size(icon_size);
request.set_scale(scale);
GetCiceroneClient()->GetContainerAppIcons(
std::move(request),
base::BindOnce(&CrostiniManager::OnGetContainerAppIcons,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void CrostiniManager::GetLinuxPackageInfo(
const guest_os::GuestId& container_id,
std::string package_path,
GetLinuxPackageInfoCallback callback) {
vm_tools::cicerone::LinuxPackageInfoRequest request;
request.set_owner_id(CryptohomeIdForProfile(profile_));
request.set_vm_name(container_id.vm_name);
request.set_container_name(container_id.container_name);
request.set_file_path(std::move(package_path));
GetCiceroneClient()->GetLinuxPackageInfo(
std::move(request),
base::BindOnce(&CrostiniManager::OnGetLinuxPackageInfo,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void CrostiniManager::InstallLinuxPackage(
const guest_os::GuestId& container_id,
std::string package_path,
InstallLinuxPackageCallback callback) {
if (!CrostiniFeatures::Get()->IsRootAccessAllowed(profile_)) {
LOG(ERROR) << "Attempted to install package when root access to Crostini "
"VM not allowed.";
std::move(callback).Run(CrostiniResult::INSTALL_LINUX_PACKAGE_FAILED);
return;
}
if (!GetCiceroneClient()->IsInstallLinuxPackageProgressSignalConnected()) {
// Technically we could still start the install, but we wouldn't be able
// to detect when the install completes, successfully or otherwise.
LOG(ERROR)
<< "Attempted to install package when progress signal not connected.";
std::move(callback).Run(CrostiniResult::INSTALL_LINUX_PACKAGE_FAILED);
return;
}
vm_tools::cicerone::InstallLinuxPackageRequest request;
request.set_owner_id(owner_id_);
request.set_vm_name(container_id.vm_name);
request.set_container_name(container_id.container_name);
request.set_file_path(std::move(package_path));
GetCiceroneClient()->InstallLinuxPackage(
std::move(request),
base::BindOnce(&CrostiniManager::OnInstallLinuxPackage,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void CrostiniManager::InstallLinuxPackageFromApt(
const guest_os::GuestId& container_id,
std::string package_id,
InstallLinuxPackageCallback callback) {
if (!GetCiceroneClient()->IsInstallLinuxPackageProgressSignalConnected()) {
// Technically we could still start the install, but we wouldn't be able
// to detect when the install completes, successfully or otherwise.
LOG(ERROR)
<< "Attempted to install package when progress signal not connected.";
std::move(callback).Run(CrostiniResult::INSTALL_LINUX_PACKAGE_FAILED);
return;
}
vm_tools::cicerone::InstallLinuxPackageRequest request;
request.set_owner_id(owner_id_);
request.set_vm_name(container_id.vm_name);
request.set_container_name(container_id.container_name);
request.set_package_id(std::move(package_id));
GetCiceroneClient()->InstallLinuxPackage(
std::move(request),
base::BindOnce(&CrostiniManager::OnInstallLinuxPackage,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void CrostiniManager::UninstallPackageOwningFile(
const guest_os::GuestId& container_id,
std::string desktop_file_id,
CrostiniResultCallback callback) {
if (!GetCiceroneClient()->IsUninstallPackageProgressSignalConnected()) {
// Technically we could still start the uninstall, but we wouldn't be able
// to detect when the uninstall completes, successfully or otherwise.
LOG(ERROR) << "Attempted to uninstall package when progress signal not "
"connected.";
std::move(callback).Run(CrostiniResult::UNINSTALL_PACKAGE_FAILED);
return;
}
vm_tools::cicerone::UninstallPackageOwningFileRequest request;
request.set_owner_id(owner_id_);
request.set_vm_name(container_id.vm_name);
request.set_container_name(container_id.container_name);
request.set_desktop_file_id(std::move(desktop_file_id));
GetCiceroneClient()->UninstallPackageOwningFile(
std::move(request),
base::BindOnce(&CrostiniManager::OnUninstallPackageOwningFile,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
bool CrostiniManager::GetCrostiniDialogStatus(DialogType dialog_type) const {
return open_crostini_dialogs_.count(dialog_type) == 1;
}
void CrostiniManager::SetCrostiniDialogStatus(DialogType dialog_type,
bool open) {
if (open) {
open_crostini_dialogs_.insert(dialog_type);
} else {
open_crostini_dialogs_.erase(dialog_type);
}
for (auto& observer : crostini_dialog_status_observers_) {
observer.OnCrostiniDialogStatusChanged(dialog_type, open);
}
}
void CrostiniManager::AddCrostiniDialogStatusObserver(
CrostiniDialogStatusObserver* observer) {
crostini_dialog_status_observers_.AddObserver(observer);
}
void CrostiniManager::RemoveCrostiniDialogStatusObserver(
CrostiniDialogStatusObserver* observer) {
crostini_dialog_status_observers_.RemoveObserver(observer);
}
void CrostiniManager::AddCrostiniContainerPropertiesObserver(
CrostiniContainerPropertiesObserver* observer) {
crostini_container_properties_observers_.AddObserver(observer);
}
void CrostiniManager::RemoveCrostiniContainerPropertiesObserver(
CrostiniContainerPropertiesObserver* observer) {
crostini_container_properties_observers_.RemoveObserver(observer);
}
void CrostiniManager::AddContainerShutdownObserver(
ContainerShutdownObserver* observer) {
container_shutdown_observers_.AddObserver(observer);
}
void CrostiniManager::RemoveContainerShutdownObserver(
ContainerShutdownObserver* observer) {
container_shutdown_observers_.RemoveObserver(observer);
}
CrostiniManager::RestartId CrostiniManager::RestartCrostini(
guest_os::GuestId container_id,
CrostiniResultCallback callback,
RestartObserver* observer) {
return RestartCrostiniWithOptions(std::move(container_id), RestartOptions(),
std::move(callback), observer);
}
CrostiniManager::RestartId CrostiniManager::RestartCrostiniWithOptions(
guest_os::GuestId container_id,
RestartOptions options,
CrostiniResultCallback callback,
RestartObserver* observer) {
if (GetCrostiniDialogStatus(DialogType::INSTALLER)) {
base::UmaHistogramBoolean("Crostini.Setup.Started", true);
} else {
base::UmaHistogramBoolean("Crostini.Restarter.Started", true);
}
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
// Currently, |remove_crostini_callbacks_| is only used just before running
// guest_os::GuestOsRemover. If that changes, then we should check for a
// currently running uninstaller in some other way.
if (!remove_crostini_callbacks_.empty()) {
LOG(ERROR)
<< "Tried to install crostini while crostini uninstaller is running";
std::move(callback).Run(CrostiniResult::CROSTINI_UNINSTALLER_RUNNING);
return kUninitializedRestartId;
}
// Initialize create_options which contains the stored CreateOptions.
RestartOptions create_options;
// Clone flags which we care about from the freshly given options.
create_options.start_vm_only = options.start_vm_only;
create_options.stop_after_lxd_available = options.stop_after_lxd_available;
bool obsolete_create_options = true;
// TODO(crbug.com/377377749) dont need this for baguette?
AddNewLxdContainerToPrefs(profile_, container_id);
RegisterContainer(container_id);
if (!RegisterCreateOptions(container_id, options)) {
// Do the path cloning only if we have to since this is more expensive than
// setting a boolean flag.
for (auto path : options.share_paths) {
create_options.share_paths.emplace_back(path);
}
obsolete_create_options = FetchCreateOptions(container_id, &create_options);
}
RestartId restart_id = next_restart_id_++;
restarters_by_id_.emplace(restart_id, container_id);
CrostiniRestarter::RestartRequest request = {
restart_id,
obsolete_create_options ? std::move(options) : std::move(create_options),
std::move(callback), observer};
auto it = restarters_by_container_.find(container_id);
if (it == restarters_by_container_.end()) {
VLOG(1) << "Creating new restarter for " << container_id;
restarters_by_container_[container_id] =
std::make_unique<CrostiniRestarter>(profile_, this, container_id,
std::move(request));
// In some cases this will synchronously finish the restart and cause it to
// be deleted and removed from the map.
restarters_by_container_[container_id]->Restart();
} else {
VLOG(1) << "Already restarting " << container_id;
if (request.options.container_username || request.options.disk_size_bytes ||
request.options.image_server_url || request.options.image_alias) {
LOG(ERROR)
<< "Crostini restart options for new containers will be ignored "
"as a restart is already in progress.";
}
it->second->AddRequest(std::move(request));
}
return restart_id;
}
void CrostiniManager::CancelRestartCrostini(
CrostiniManager::RestartId restart_id) {
auto container_it = restarters_by_id_.find(restart_id);
if (container_it == restarters_by_id_.end()) {
// Only tests execute this path at the time of writing but be defensive
// just in case.
LOG(ERROR)
<< "Cancelling a restarter that does not exist (already finished?)"
<< ", id = " << restart_id;
return;
}
auto restarter_it = restarters_by_container_.find(container_it->second);
DCHECK(restarter_it != restarters_by_container_.end());
restarter_it->second->CancelRequest(restart_id);
}
bool CrostiniManager::IsRestartPending(RestartId restart_id) {
return restarters_by_id_.find(restart_id) != restarters_by_id_.end();
}
bool CrostiniManager::HasRestarterForTesting(
const guest_os::GuestId& guest_id) {
return restarters_by_container_.find(guest_id) !=
restarters_by_container_.end();
}
void CrostiniManager::AddShutdownContainerCallback(
guest_os::GuestId container_id,
base::OnceClosure shutdown_callback) {
shutdown_container_callbacks_.emplace(std::move(container_id),
std::move(shutdown_callback));
}
void CrostiniManager::AddRemoveCrostiniCallback(
RemoveCrostiniCallback remove_callback) {
remove_crostini_callbacks_.emplace_back(std::move(remove_callback));
}
void CrostiniManager::AddLinuxPackageOperationProgressObserver(
LinuxPackageOperationProgressObserver* observer) {
linux_package_operation_progress_observers_.AddObserver(observer);
}
void CrostiniManager::RemoveLinuxPackageOperationProgressObserver(
LinuxPackageOperationProgressObserver* observer) {
linux_package_operation_progress_observers_.RemoveObserver(observer);
}
void CrostiniManager::AddPendingAppListUpdatesObserver(
PendingAppListUpdatesObserver* observer) {
pending_app_list_updates_observers_.AddObserver(observer);
}
void CrostiniManager::RemovePendingAppListUpdatesObserver(
PendingAppListUpdatesObserver* observer) {
pending_app_list_updates_observers_.RemoveObserver(observer);
}
void CrostiniManager::AddExportContainerProgressObserver(
ExportContainerProgressObserver* observer) {
export_container_progress_observers_.AddObserver(observer);
}
void CrostiniManager::RemoveExportContainerProgressObserver(
ExportContainerProgressObserver* observer) {
export_container_progress_observers_.RemoveObserver(observer);
}
void CrostiniManager::AddImportContainerProgressObserver(
ImportContainerProgressObserver* observer) {
import_container_progress_observers_.AddObserver(observer);
}
void CrostiniManager::RemoveImportContainerProgressObserver(
ImportContainerProgressObserver* observer) {
import_container_progress_observers_.RemoveObserver(observer);
}
void CrostiniManager::AddDiskImageProgressObserver(
DiskImageProgressObserver* observer) {
disk_image_progress_observers_.AddObserver(observer);
}
void CrostiniManager::RemoveDiskImageProgressObserver(
DiskImageProgressObserver* observer) {
disk_image_progress_observers_.RemoveObserver(observer);
}
void CrostiniManager::AddUpgradeContainerProgressObserver(
UpgradeContainerProgressObserver* observer) {
upgrade_container_progress_observers_.AddObserver(observer);
}
void CrostiniManager::RemoveUpgradeContainerProgressObserver(
UpgradeContainerProgressObserver* observer) {
upgrade_container_progress_observers_.RemoveObserver(observer);
}
void CrostiniManager::AddVmShutdownObserver(ash::VmShutdownObserver* observer) {
vm_shutdown_observers_.AddObserver(observer);
}
void CrostiniManager::RemoveVmShutdownObserver(
ash::VmShutdownObserver* observer) {
vm_shutdown_observers_.RemoveObserver(observer);
}
void CrostiniManager::AddVmStartingObserver(ash::VmStartingObserver* observer) {
vm_starting_observers_.AddObserver(observer);
}
void CrostiniManager::RemoveVmStartingObserver(
ash::VmStartingObserver* observer) {
vm_starting_observers_.RemoveObserver(observer);
}
void CrostiniManager::OnCreateDiskImage(
CreateDiskImageCallback callback,
std::optional<vm_tools::concierge::CreateDiskImageResponse> response) {
CrostiniResult result;
base::FilePath path;
if (!response) {
LOG(ERROR) << "Failed to create disk image. Empty response.";
result = CrostiniResult::CREATE_DISK_IMAGE_NO_RESPONSE;
} else if (response->status() == vm_tools::concierge::DISK_STATUS_CREATED) {
result = CrostiniResult::SUCCESS;
path = base::FilePath(response->disk_path());
} else if (response->status() == vm_tools::concierge::DISK_STATUS_EXISTS) {
result = CrostiniResult::CREATE_DISK_IMAGE_ALREADY_EXISTS;
path = base::FilePath(response->disk_path());
} else {
LOG(ERROR) << "Failed to create disk image. Error: "
<< static_cast<int>(response->status())
<< ", reason: " << response->failure_reason();
result = CrostiniResult::CREATE_DISK_IMAGE_FAILED;
}
std::move(callback).Run(result, path);
}
void CrostiniManager::OnStartTerminaVm(
std::string vm_name,
BoolCallback callback,
std::optional<vm_tools::concierge::StartVmResponse> response) {
if (!response) {
LOG(ERROR) << "Failed to start termina vm. Empty response.";
std::move(callback).Run(/*success=*/false);
return;
}
switch (response->mount_result()) {
case vm_tools::concierge::StartVmResponse::PARTIAL_DATA_LOSS:
EmitCorruptionStateMetric(CorruptionStates::MOUNT_ROLLED_BACK);
break;
case vm_tools::concierge::StartVmResponse::FAILURE:
EmitCorruptionStateMetric(CorruptionStates::MOUNT_FAILED);
break;
default:
break;
}
// The UI can only resize the default VM, so only (maybe) show the
// notification for the default VM, if we got a value, and if the value isn't
// an error (the API we call for space returns -1 on error).
if (vm_name == DefaultContainerId().vm_name &&
response->free_bytes_has_value() && response->free_bytes() >= 0) {
low_disk_notifier_->ShowNotificationIfAppropriate(response->free_bytes());
}
// If the vm is already marked "running" run the callback.
if (response->status() == vm_tools::concierge::VM_STATUS_RUNNING) {
running_vms_[vm_name] =
VmInfo{VmState::STARTED, std::move(response->vm_info())};
std::move(callback).Run(/*success=*/true);
return;
}
// Any pending callbacks must exist from a previously running VM, and should
// be marked as failed.
InvokeAndErasePendingCallbacks(
&export_lxd_container_callbacks_, vm_name,
CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED_VM_STARTED, 0, 0);
InvokeAndErasePendingCallbacks(&disk_image_callbacks_, vm_name,
CrostiniResult::DISK_IMAGE_FAILED);
InvokeAndErasePendingCallbacks(
&import_lxd_container_callbacks_, vm_name,
CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED_VM_STARTED);
// Same for mappings, no longer valid.
EraseCommandUuid(&disk_image_uuid_to_guest_id_, vm_name);
if (response->status() == vm_tools::concierge::VM_STATUS_FAILURE ||
response->status() == vm_tools::concierge::VM_STATUS_UNKNOWN) {
LOG(ERROR) << "Failed to start VM: " << response->failure_reason();
// If we thought vms and containers were running before, they aren't now.
running_vms_.erase(vm_name);
std::move(callback).Run(/*success=*/false);
return;
}
// Otherwise, record the vm start and run the callback after the VM
// starts.
DCHECK_EQ(response->status(), vm_tools::concierge::VM_STATUS_STARTING);
bool wait_for_tremplin = running_vms_.find(vm_name) == running_vms_.end();
uint32_t seneschal_server_handle =
response->vm_info().seneschal_server_handle();
running_vms_[vm_name] =
VmInfo{VmState::STARTING, std::move(response->vm_info())};
// If we thought a container was running for this VM, we're wrong. This can
// happen if the vm was formerly running, then stopped via crosh.
if (wait_for_tremplin) {
VLOG(1) << "Awaiting TremplinStartedSignal for " << owner_id_ << ", "
<< vm_name;
tremplin_started_callbacks_.emplace(
vm_name, base::BindOnce(&CrostiniManager::OnStartTremplin,
weak_ptr_factory_.GetWeakPtr(), vm_name,
seneschal_server_handle, std::move(callback)));
} else {
OnStartTremplin(vm_name, seneschal_server_handle, std::move(callback));
}
}
void CrostiniManager::OnStartTremplin(std::string vm_name,
uint32_t seneschal_server_handle,
BoolCallback callback) {
// Record the running vm.
VLOG(1) << "Received TremplinStartedSignal, VM: " << owner_id_ << ", "
<< vm_name;
UpdateVmState(vm_name, VmState::STARTED);
// TODO(timloh): These should probably either be in CrostiniRestarter
// alongside sharing non-persisted paths, or separated entirely from the
// restart flow and instead run for all Guest OS types whenever they start
// up. For fonts, this could be done directly in concierge (b/231252066).
// Share fonts directory with the VM but don't persist as a shared path.
guest_os::GuestOsSharePathFactory::GetForProfile(profile_)->SharePath(
vm_name, seneschal_server_handle,
base::FilePath(file_manager::util::kSystemFontsPath), base::DoNothing());
// Run the original callback.
std::move(callback).Run(/*success=*/true);
}
void CrostiniManager::OnStartLxdProgress(
const vm_tools::cicerone::StartLxdProgressSignal& signal) {
if (signal.owner_id() != owner_id_) {
return;
}
CrostiniResult result = CrostiniResult::UNKNOWN_ERROR;
switch (signal.status()) {
case vm_tools::cicerone::StartLxdProgressSignal::STARTED:
result = CrostiniResult::SUCCESS;
break;
case vm_tools::cicerone::StartLxdProgressSignal::STARTING:
case vm_tools::cicerone::StartLxdProgressSignal::RECOVERING:
// Still in-progress, keep waiting.
return;
case vm_tools::cicerone::StartLxdProgressSignal::FAILED:
result = CrostiniResult::START_LXD_FAILED_SIGNAL;
break;
default:
break;
}
if (result != CrostiniResult::SUCCESS) {
LOG(ERROR) << "Failed to create container. VM: " << signal.vm_name()
<< " reason: " << signal.failure_reason();
}
InvokeAndErasePendingCallbacks(&start_lxd_callbacks_, signal.vm_name(),
result);
}
void CrostiniManager::OnStopVm(
std::string vm_name,
CrostiniResultCallback callback,
std::optional<vm_tools::concierge::SuccessFailureResponse> response) {
if (!response) {
LOG(ERROR) << "Failed to stop termina vm. Empty response.";
std::move(callback).Run(CrostiniResult::STOP_VM_NO_RESPONSE);
return;
}
if (!response->success()) {
LOG(ERROR) << "Failed to stop VM: " << response->failure_reason();
std::move(callback).Run(CrostiniResult::VM_STOP_FAILED);
return;
}
std::move(callback).Run(CrostiniResult::SUCCESS);
}
void CrostiniManager::OnVmStoppedCleanup(const std::string& vm_name) {
for (auto& observer : vm_shutdown_observers_) {
observer.OnVmShutdown(vm_name);
}
// Check what state the VM was believed to be in before the stop signal was
// received.
//
// If it was in the STARTED state, it's an unexpected shutdown and we should
// log it here.
//
// If it was STARTING then the error is tracked as a restart failure, not
// here. If it was STOPPING then the stop was expected and not an error. If
// it wasn't tracked by CrostiniManager, then we don't care what happens to
// it.
//
// Therefore this stop signal is unexpected if-and-only-if IsVmRunning().
//
// This check must run before removing the VM from |running_vms_|.
if (IsVmRunning(vm_name)) {
guest_os_stability_monitor_->LogUnexpectedVmShutdown();
}
// Remove from running_vms_, and other vm-keyed state.
running_vms_.erase(vm_name);
EraseCommandUuid(&disk_image_uuid_to_guest_id_, vm_name);
InvokeAndErasePendingCallbacks(
&export_lxd_container_callbacks_, vm_name,
CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED_VM_STOPPED, 0, 0);
InvokeAndErasePendingCallbacks(&disk_image_callbacks_, vm_name,
CrostiniResult::DISK_IMAGE_FAILED);
InvokeAndErasePendingCallbacks(
&import_lxd_container_callbacks_, vm_name,
CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED_VM_STOPPED);
// After we shut down a VM, we are no longer in a state where we need to
// prompt for user cleanup.
is_unclean_startup_ = false;
}
void CrostiniManager::OnGetTerminaVmKernelVersion(
std::optional<vm_tools::concierge::GetVmEnterpriseReportingInfoResponse>
response) {
// If there is an error, (re)set the kernel version pref to the empty string.
std::string kernel_version;
if (!response) {
LOG(ERROR) << "No reply to GetVmEnterpriseReportingInfo";
} else if (!response->success()) {
LOG(ERROR) << "Error response for GetVmEnterpriseReportingInfo: "
<< response->failure_reason();
} else {
kernel_version = response->vm_kernel_version();
}
WriteTerminaVmKernelVersionToPrefsForReporting(profile_->GetPrefs(),
kernel_version);
}
void CrostiniManager::OnContainerStarted(
const vm_tools::cicerone::ContainerStartedSignal& signal) {
if (signal.owner_id() != owner_id_) {
return;
}
guest_os::GuestId container_id(kCrostiniDefaultVmType, signal.vm_name(),
signal.container_name());
auto* metrics_service =
CrostiniMetricsService::Factory::GetForProfile(profile_);
// This is null in unit tests.
if (metrics_service) {
metrics_service->SetBackgroundActive(true);
}
VLOG(1) << "Container " << signal.container_name() << " started";
InvokeAndErasePendingContainerCallbacks(
&start_container_callbacks_, container_id, CrostiniResult::SUCCESS);
if (signal.vm_name() == kCrostiniDefaultVmName) {
AddShutdownContainerCallback(
container_id,
base::BindOnce(
&CrostiniManager::DeallocateForwardedPortsCallback,
weak_ptr_factory_.GetWeakPtr(),
guest_os::GuestId(kCrostiniDefaultVmType, signal.vm_name(),
signal.container_name())));
}
}
void CrostiniManager::OnGuestFileCorruption(
const anomaly_detector::GuestFileCorruptionSignal& signal) {
EmitCorruptionStateMetric(CorruptionStates::OTHER_CORRUPTION);
}
void CrostiniManager::OnVmStarted(
const vm_tools::concierge::VmStartedSignal& signal) {}
void CrostiniManager::OnVmStopped(
const vm_tools::concierge::VmStoppedSignal& signal) {
if (signal.owner_id() != owner_id_) {
return;
}
if (running_vms_.find(signal.name()) == running_vms_.end()) {
LOG(WARNING) << "Ignoring VmStopped for " << signal.name();
return;
}
OnVmStoppedCleanup(signal.name());
}
void CrostiniManager::OnVmStopping(
const vm_tools::concierge::VmStoppingSignal& signal) {
if (signal.owner_id() != owner_id_) {
return;
}
auto iter = running_vms_.find(signal.name());
if (iter == running_vms_.end()) {
LOG(WARNING) << "Ignoring VmStopping for " << signal.name();
return;
}
iter->second.state = VmState::STOPPING;
}
void CrostiniManager::OnContainerShutdown(
const vm_tools::cicerone::ContainerShutdownSignal& signal) {
if (signal.owner_id() != owner_id_) {
return;
}
guest_os::GuestId container_id(kCrostiniDefaultVmType, signal.vm_name(),
signal.container_name());
// Find the callbacks to call, then erase them from the map.
auto range_callbacks =
shutdown_container_callbacks_.equal_range(container_id);
for (auto it = range_callbacks.first; it != range_callbacks.second; ++it) {
std::move(it->second).Run();
}
shutdown_container_callbacks_.erase(range_callbacks.first,
range_callbacks.second);
HandleContainerShutdown(container_id);
}
void CrostiniManager::OnInstallLinuxPackageProgress(
const vm_tools::cicerone::InstallLinuxPackageProgressSignal& signal) {
if (signal.owner_id() != owner_id_) {
return;
}
if (signal.progress_percent() < 0 || signal.progress_percent() > 100) {
LOG(ERROR) << "Received install progress with invalid progress of "
<< signal.progress_percent() << "%.";
return;
}
InstallLinuxPackageProgressStatus status;
std::string error_message;
switch (signal.status()) {
case vm_tools::cicerone::InstallLinuxPackageProgressSignal::SUCCEEDED:
status = InstallLinuxPackageProgressStatus::SUCCEEDED;
break;
case vm_tools::cicerone::InstallLinuxPackageProgressSignal::FAILED:
LOG(ERROR) << "Install failed: " << signal.failure_details();
status = InstallLinuxPackageProgressStatus::FAILED;
error_message = signal.failure_details();
break;
case vm_tools::cicerone::InstallLinuxPackageProgressSignal::DOWNLOADING:
status = InstallLinuxPackageProgressStatus::DOWNLOADING;
break;
case vm_tools::cicerone::InstallLinuxPackageProgressSignal::INSTALLING:
status = InstallLinuxPackageProgressStatus::INSTALLING;
break;
default:
NOTREACHED();
}
guest_os::GuestId container_id(kCrostiniDefaultVmType, signal.vm_name(),
signal.container_name());
for (auto& observer : linux_package_operation_progress_observers_) {
observer.OnInstallLinuxPackageProgress(
container_id, status, signal.progress_percent(), error_message);
}
}
void CrostiniManager::OnUninstallPackageProgress(
const vm_tools::cicerone::UninstallPackageProgressSignal& signal) {
if (signal.owner_id() != owner_id_) {
return;
}
if (signal.progress_percent() < 0 || signal.progress_percent() > 100) {
LOG(ERROR) << "Received uninstall progress with invalid progress of "
<< signal.progress_percent() << "%.";
return;
}
UninstallPackageProgressStatus status;
switch (signal.status()) {
case vm_tools::cicerone::UninstallPackageProgressSignal::SUCCEEDED:
status = UninstallPackageProgressStatus::SUCCEEDED;
break;
case vm_tools::cicerone::UninstallPackageProgressSignal::FAILED:
status = UninstallPackageProgressStatus::FAILED;
LOG(ERROR) << "Uninstalled failed: " << signal.failure_details();
break;
case vm_tools::cicerone::UninstallPackageProgressSignal::UNINSTALLING:
status = UninstallPackageProgressStatus::UNINSTALLING;
break;
default:
NOTREACHED();
}
guest_os::GuestId container_id(kCrostiniDefaultVmType, signal.vm_name(),
signal.container_name());
for (auto& observer : linux_package_operation_progress_observers_) {
observer.OnUninstallPackageProgress(container_id, status,
signal.progress_percent());
}
}
void CrostiniManager::OnApplyAnsiblePlaybookProgress(
const vm_tools::cicerone::ApplyAnsiblePlaybookProgressSignal& signal) {
if (signal.owner_id() != owner_id_) {
return;
}
// TODO(okalitova): Add an observer.
AnsibleManagementServiceFactory::GetForProfile(profile_)
->OnApplyAnsiblePlaybookProgress(signal);
}
void CrostiniManager::OnUpgradeContainerProgress(
const vm_tools::cicerone::UpgradeContainerProgressSignal& signal) {
if (signal.owner_id() != owner_id_) {
return;
}
UpgradeContainerProgressStatus status;
switch (signal.status()) {
case vm_tools::cicerone::UpgradeContainerProgressSignal::SUCCEEDED:
status = UpgradeContainerProgressStatus::SUCCEEDED;
break;
case vm_tools::cicerone::UpgradeContainerProgressSignal::UNKNOWN:
case vm_tools::cicerone::UpgradeContainerProgressSignal::FAILED:
status = UpgradeContainerProgressStatus::FAILED;
LOG(ERROR) << "Upgrade failed: " << signal.failure_reason();
break;
case vm_tools::cicerone::UpgradeContainerProgressSignal::IN_PROGRESS:
status = UpgradeContainerProgressStatus::UPGRADING;
break;
default:
NOTREACHED();
}
std::vector<std::string> progress_messages;
progress_messages.reserve(signal.progress_messages().size());
for (const auto& msg : signal.progress_messages()) {
if (!msg.empty()) {
// Blank lines aren't sent to observers.
progress_messages.push_back(msg);
}
}
guest_os::GuestId container_id(kCrostiniDefaultVmType, signal.vm_name(),
signal.container_name());
for (auto& observer : upgrade_container_progress_observers_) {
observer.OnUpgradeContainerProgress(container_id, status,
progress_messages);
}
}
void CrostiniManager::OnUninstallPackageOwningFile(
CrostiniResultCallback callback,
std::optional<vm_tools::cicerone::UninstallPackageOwningFileResponse>
response) {
if (!response) {
LOG(ERROR) << "Failed to uninstall Linux package. Empty response.";
std::move(callback).Run(CrostiniResult::UNINSTALL_PACKAGE_FAILED);
return;
}
if (response->status() ==
vm_tools::cicerone::UninstallPackageOwningFileResponse::FAILED) {
LOG(ERROR) << "Failed to uninstall Linux package: "
<< response->failure_reason();
std::move(callback).Run(CrostiniResult::UNINSTALL_PACKAGE_FAILED);
return;
}
if (response->status() ==
vm_tools::cicerone::UninstallPackageOwningFileResponse::
BLOCKING_OPERATION_IN_PROGRESS) {
LOG(WARNING) << "Failed to uninstall Linux package, another operation is "
"already active.";
std::move(callback).Run(CrostiniResult::BLOCKING_OPERATION_ALREADY_ACTIVE);
return;
}
std::move(callback).Run(CrostiniResult::SUCCESS);
}
void CrostiniManager::OnStartLxd(
std::string vm_name,
CrostiniResultCallback callback,
std::optional<vm_tools::cicerone::StartLxdResponse> response) {
if (!response) {
LOG(ERROR) << "Failed to start lxd in vm. Empty response.";
std::move(callback).Run(CrostiniResult::START_LXD_FAILED);
return;
}
switch (response->status()) {
case vm_tools::cicerone::StartLxdResponse::STARTING:
VLOG(1) << "Awaiting OnStartLxdProgressSignal for " << owner_id_ << ", "
<< vm_name;
// The callback will be called when we receive the LxdContainerCreated
// signal.
start_lxd_callbacks_.emplace(std::move(vm_name), std::move(callback));
break;
case vm_tools::cicerone::StartLxdResponse::ALREADY_RUNNING:
std::move(callback).Run(CrostiniResult::SUCCESS);
break;
default:
LOG(ERROR) << "Failed to start LXD: " << response->failure_reason();
std::move(callback).Run(CrostiniResult::START_LXD_FAILED);
}
}
void CrostiniManager::OnSetUpBaguetteUser(
CrostiniResultCallback callback,
std::optional<vm_tools::concierge::SetUpVmUserResponse> response) {
if (!response) {
LOG(ERROR) << "Failed to set up user in vm. Empty response.";
std::move(callback).Run(CrostiniResult::CONTAINER_SETUP_FAILED);
return;
}
if (response->success()) {
std::move(callback).Run(CrostiniResult::SUCCESS);
} else {
LOG(ERROR) << "Failed to set up baguette user: "
<< response->failure_reason();
std::move(callback).Run(CrostiniResult::CONTAINER_SETUP_FAILED);
}
}
void CrostiniManager::OnCreateLxdContainer(
const guest_os::GuestId& container_id,
CrostiniResultCallback callback,
std::optional<vm_tools::cicerone::CreateLxdContainerResponse> response) {
if (!response) {
LOG(ERROR) << "Failed to create lxd container in vm. Empty response.";
std::move(callback).Run(CrostiniResult::CONTAINER_CREATE_FAILED);
return;
}
switch (response->status()) {
case vm_tools::cicerone::CreateLxdContainerResponse::CREATING:
VLOG(1) << "Awaiting LxdContainerCreatedSignal for " << owner_id_ << ", "
<< container_id;
// The callback will be called when we receive the LxdContainerCreated
// signal.
create_lxd_container_callbacks_.emplace(container_id,
std::move(callback));
break;
case vm_tools::cicerone::CreateLxdContainerResponse::EXISTS:
// Containers are registered in OnContainerCreated() when created via the
// UI. But for any created manually also register now (crbug.com/1330168).
AddNewLxdContainerToPrefs(profile_, container_id);
RegisterContainer(container_id);
SetCreateOptionsUsed(container_id);
std::move(callback).Run(CrostiniResult::SUCCESS);
break;
default:
LOG(ERROR) << "Failed to create container: "
<< response->failure_reason();
// Remove all create options and the existence of this container.
if (IsPendingCreation(container_id) &&
container_id != DefaultContainerId()) {
RemoveLxdContainerFromPrefs(profile_, container_id);
UnregisterContainer(container_id);
}
std::move(callback).Run(CrostiniResult::CONTAINER_CREATE_FAILED);
}
}
void CrostiniManager::OnStartLxdContainer(
const guest_os::GuestId& container_id,
CrostiniResultCallback callback,
std::optional<vm_tools::cicerone::StartLxdContainerResponse> response) {
if (!response) {
LOG(ERROR) << "Failed to start lxd container in vm. Empty response.";
std::move(callback).Run(CrostiniResult::CONTAINER_START_FAILED);
return;
}
VLOG(1) << "Got StartLxdContainer response status: " << response->status();
switch (response->status()) {
case vm_tools::cicerone::StartLxdContainerResponse::UNKNOWN:
case vm_tools::cicerone::StartLxdContainerResponse::FAILED:
LOG(ERROR) << "Failed to start container: " << response->failure_reason();
std::move(callback).Run(CrostiniResult::CONTAINER_START_FAILED);
break;
case vm_tools::cicerone::StartLxdContainerResponse::STARTED:
case vm_tools::cicerone::StartLxdContainerResponse::RUNNING:
std::move(callback).Run(CrostiniResult::SUCCESS);
break;
case vm_tools::cicerone::StartLxdContainerResponse::REMAPPING:
// Run the update container dialog to warn users of delays.
// The callback will be called when we receive the LxdContainerStarting
// signal.
PrepareShowCrostiniUpdateFilesystemView(profile_,
CrostiniUISurface::kAppList);
// Then perform the same steps as for starting.
[[fallthrough]];
case vm_tools::cicerone::StartLxdContainerResponse::STARTING: {
VLOG(1) << "Awaiting LxdContainerStartingSignal for " << owner_id_ << ", "
<< container_id;
// The callback will be called when we receive the LxdContainerStarting
// signal and (if successful) the ContainerStarted signal from Garcon.
start_container_callbacks_.emplace(container_id, std::move(callback));
break;
}
default:
NOTREACHED();
}
if (response->has_os_release()) {
SetContainerOsRelease(container_id, response->os_release());
}
}
void CrostiniManager::OnStopLxdContainer(
const guest_os::GuestId& container_id,
CrostiniResultCallback callback,
std::optional<vm_tools::cicerone::StopLxdContainerResponse> response) {
if (!response) {
LOG(ERROR) << "Failed to stop lxd container in vm. Empty response.";
std::move(callback).Run(CrostiniResult::CONTAINER_STOP_FAILED);
return;
}
switch (response->status()) {
case vm_tools::cicerone::StopLxdContainerResponse::UNKNOWN:
case vm_tools::cicerone::StopLxdContainerResponse::FAILED:
LOG(ERROR) << "Failed to stop container: " << response->failure_reason();
std::move(callback).Run(CrostiniResult::CONTAINER_STOP_FAILED);
break;
case vm_tools::cicerone::StopLxdContainerResponse::STOPPED:
HandleContainerShutdown(container_id);
std::move(callback).Run(CrostiniResult::SUCCESS);
break;
case vm_tools::cicerone::StopLxdContainerResponse::STOPPING:
VLOG(1) << "Awaiting ContainerShutdownSignal for " << owner_id_ << ", "
<< container_id;
shutdown_container_callbacks_.emplace(
container_id,
base::BindOnce(std::move(callback), CrostiniResult::SUCCESS));
break;
case vm_tools::cicerone::StopLxdContainerResponse::DOES_NOT_EXIST:
LOG(ERROR) << "Container does not exist " << container_id;
std::move(callback).Run(CrostiniResult::CONTAINER_STOP_FAILED);
break;
default:
NOTREACHED();
}
}
void CrostiniManager::OnSetUpLxdContainerUser(
const guest_os::GuestId& container_id,
BoolCallback callback,
std::optional<vm_tools::cicerone::SetUpLxdContainerUserResponse> response) {
if (!response) {
LOG(ERROR) << "Failed to set up lxd container user. Empty response.";
std::move(callback).Run(/*success=*/false);
return;
}
switch (response->status()) {
case vm_tools::cicerone::SetUpLxdContainerUserResponse::UNKNOWN:
// If we hit this then we don't know if users are set up or not; a
// possible cause is we weren't able to read the /etc/passwd file.
// We're in one of the following cases:
// - Users are already set up but hit a transient error reading the file
// e.g. crbug/1216305. This would be a no-op so safe to continue.
// - The container is in a bad state e.g. file is missing entirely.
// Once we start the container (next step) the system will try to repair
// this. It won't recover enough for restart to succeed, but it will
// give us a valid passwd file so that next launch we'll set up users
// and all will be good again. If we errored out here then we'd never
// repair the file and the container is borked for good.
// - Lastly and least likely, it could be a transient issue but users
// aren't set up correctly. The container will either fail to start,
// or start but won't completely work (e.g. maybe adb sideloading will
// fail). Either way, restarting the container should get them back into
// a good state.
// Note that if the user's account is missing then garcon won't start,
// which combined with crbug/1197416 means launch will hang forever (well,
// it's a 5 day timeout so not forever but may as well be). They would
// have to be incredibly unlucky and restarting will fix things so that's
// acceptable.
base::UmaHistogramBoolean("Crostini.SetUpLxdContainerUser.UnknownResult",
true);
LOG(ERROR) << "Failed to set up container user: "
<< response->failure_reason();
std::move(callback).Run(/*success=*/true);
break;
case vm_tools::cicerone::SetUpLxdContainerUserResponse::SUCCESS:
case vm_tools::cicerone::SetUpLxdContainerUserResponse::EXISTS:
base::UmaHistogramBoolean("Crostini.SetUpLxdContainerUser.UnknownResult",
false);
std::move(callback).Run(/*success=*/true);
break;
case vm_tools::cicerone::SetUpLxdContainerUserResponse::FAILED:
LOG(ERROR) << "Failed to set up container user: "
<< response->failure_reason();
base::UmaHistogramBoolean("Crostini.SetUpLxdContainerUser.UnknownResult",
false);
std::move(callback).Run(/*success=*/false);
break;
default:
NOTREACHED();
}
}
void CrostiniManager::OnLxdContainerCreated(
const vm_tools::cicerone::LxdContainerCreatedSignal& signal) {
if (signal.owner_id() != owner_id_) {
return;
}
guest_os::GuestId container_id(kCrostiniDefaultVmType, signal.vm_name(),
signal.container_name());
CrostiniResult result;
switch (signal.status()) {
case vm_tools::cicerone::LxdContainerCreatedSignal::UNKNOWN:
result = CrostiniResult::UNKNOWN_ERROR;
break;
case vm_tools::cicerone::LxdContainerCreatedSignal::CREATED:
SetCreateOptionsUsed(container_id);
result = CrostiniResult::SUCCESS;
break;
case vm_tools::cicerone::LxdContainerCreatedSignal::DOWNLOAD_TIMED_OUT:
result = CrostiniResult::CONTAINER_DOWNLOAD_TIMED_OUT;
break;
case vm_tools::cicerone::LxdContainerCreatedSignal::CANCELLED:
result = CrostiniResult::CONTAINER_CREATE_CANCELLED;
break;
case vm_tools::cicerone::LxdContainerCreatedSignal::FAILED:
result = CrostiniResult::CONTAINER_CREATE_FAILED_SIGNAL;
break;
default:
result = CrostiniResult::UNKNOWN_ERROR;
break;
}
if (result != CrostiniResult::SUCCESS) {
LOG(ERROR) << "Failed to create container. ID: " << container_id
<< " reason: " << signal.failure_reason();
if (IsPendingCreation(container_id) &&
container_id != DefaultContainerId()) {
RemoveLxdContainerFromPrefs(profile_, container_id);
UnregisterContainer(container_id);
}
}
InvokeAndErasePendingContainerCallbacks(&create_lxd_container_callbacks_,
container_id, result);
}
void CrostiniManager::OnLxdContainerDeleted(
const vm_tools::cicerone::LxdContainerDeletedSignal& signal) {
if (signal.owner_id() != owner_id_) {
return;
}
guest_os::GuestId container_id(kCrostiniDefaultVmType, signal.vm_name(),
signal.container_name());
bool success =
signal.status() == vm_tools::cicerone::LxdContainerDeletedSignal::DELETED;
if (success) {
RemoveLxdContainerFromPrefs(profile_, container_id);
UnregisterContainer(container_id);
} else {
LOG(ERROR) << "Failed to delete container " << container_id << " : "
<< signal.failure_reason();
}
// Find the callbacks to call, then erase them from the map.
auto range = delete_lxd_container_callbacks_.equal_range(container_id);
for (auto it = range.first; it != range.second; ++it) {
std::move(it->second).Run(success);
}
delete_lxd_container_callbacks_.erase(range.first, range.second);
}
void CrostiniManager::OnLxdContainerDownloading(
const vm_tools::cicerone::LxdContainerDownloadingSignal& signal) {
if (owner_id_ != signal.owner_id()) {
return;
}
guest_os::GuestId container_id(kCrostiniDefaultVmType, signal.vm_name(),
signal.container_name());
auto iter = restarters_by_container_.find(container_id);
if (iter != restarters_by_container_.end()) {
iter->second->OnContainerDownloading(signal.download_progress());
}
}
void CrostiniManager::OnTremplinStarted(
const vm_tools::cicerone::TremplinStartedSignal& signal) {
if (signal.owner_id() != owner_id_) {
return;
}
// If this VM is not yet known in running_vms_, put it there in state
// STARTING. This can happen if tremplin starts up faster than concierge can
// finish its other startup work.
if (running_vms_.find(signal.vm_name()) == running_vms_.end()) {
running_vms_[signal.vm_name()] =
VmInfo{VmState::STARTING, vm_tools::concierge::VmInfo{}};
}
// Find the callbacks to call, then erase them from the map.
auto range = tremplin_started_callbacks_.equal_range(signal.vm_name());
for (auto it = range.first; it != range.second; ++it) {
std::move(it->second).Run();
}
tremplin_started_callbacks_.erase(range.first, range.second);
}
void CrostiniManager::OnLxdContainerStarting(
const vm_tools::cicerone::LxdContainerStartingSignal& signal) {
VLOG(1) << "Received OnLxdContainerStarting message with status: "
<< signal.status() << " for container " << signal.container_name();
if (signal.owner_id() != owner_id_) {
return;
}
guest_os::GuestId container_id(kCrostiniDefaultVmType, signal.vm_name(),
signal.container_name());
CrostiniResult result;
switch (signal.status()) {
case vm_tools::cicerone::LxdContainerStartingSignal::UNKNOWN:
result = CrostiniResult::UNKNOWN_ERROR;
break;
case vm_tools::cicerone::LxdContainerStartingSignal::CANCELLED:
result = CrostiniResult::CONTAINER_START_CANCELLED;
break;
case vm_tools::cicerone::LxdContainerStartingSignal::STARTED:
result = CrostiniResult::SUCCESS;
break;
case vm_tools::cicerone::LxdContainerStartingSignal::FAILED:
result = CrostiniResult::CONTAINER_START_FAILED;
break;
case vm_tools::cicerone::LxdContainerStartingSignal::STARTING: {
auto iter = restarters_by_container_.find(container_id);
if (iter != restarters_by_container_.end()) {
iter->second->OnLxdContainerStarting(signal.status());
}
return;
}
default:
result = CrostiniResult::UNKNOWN_ERROR;
break;
}
if (result != CrostiniResult::SUCCESS) {
LOG(ERROR) << "Failed to start container. ID: " << container_id
<< " reason: " << signal.failure_reason();
}
bool running = guest_os::GuestOsSessionTrackerFactory::GetForProfile(profile_)
->IsRunning(container_id);
if (result == CrostiniResult::SUCCESS && !running) {
VLOG(1) << "Awaiting ContainerStarted signal from Garcon, did not yet have "
"information for container "
<< container_id.container_name;
return;
}
if (signal.has_os_release()) {
SetContainerOsRelease(container_id, signal.os_release());
}
InvokeAndErasePendingContainerCallbacks(&start_container_callbacks_,
container_id, result);
}
void CrostiniManager::OnGetContainerAppIcons(
GetContainerAppIconsCallback callback,
std::optional<vm_tools::cicerone::ContainerAppIconResponse> response) {
std::vector<Icon> icons;
if (!response) {
LOG(ERROR) << "Failed to get container application icons. Empty response.";
std::move(callback).Run(/*success=*/false, icons);
return;
}
for (auto& icon : *response->mutable_icons()) {
icons.emplace_back(
Icon{.desktop_file_id = std::move(*icon.mutable_desktop_file_id()),
.content = std::move(*icon.mutable_icon()),
.format = icon.format()});
}
std::move(callback).Run(/*success=*/true, icons);
}
void CrostiniManager::OnGetLinuxPackageInfo(
GetLinuxPackageInfoCallback callback,
std::optional<vm_tools::cicerone::LinuxPackageInfoResponse> response) {
LinuxPackageInfo result;
if (!response) {
LOG(ERROR) << "Failed to get Linux package info. Empty response.";
result.success = false;
// The error message is currently only used in a console message. If we
// want to display it to the user, we'd need to localize this.
result.failure_reason = "D-Bus response was empty.";
std::move(callback).Run(result);
return;
}
if (!response->success()) {
LOG(ERROR) << "Failed to get Linux package info: "
<< response->failure_reason();
result.success = false;
result.failure_reason = response->failure_reason();
std::move(callback).Run(result);
return;
}
// The |package_id| field is formatted like "name;version;arch;data". We're
// currently only interested in name and version.
std::vector<std::string> split = base::SplitString(
response->package_id(), ";", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
if (split.size() < 2 || split[0].empty() || split[1].empty()) {
LOG(ERROR) << "Linux package info contained invalid package id: \""
<< response->package_id() << '"';
result.success = false;
result.failure_reason = "Linux package info contained invalid package id.";
std::move(callback).Run(result);
return;
}
result.success = true;
result.package_id = response->package_id();
result.name = split[0];
result.version = split[1];
result.description = response->description();
result.summary = response->summary();
std::move(callback).Run(result);
}
void CrostiniManager::OnInstallLinuxPackage(
InstallLinuxPackageCallback callback,
std::optional<vm_tools::cicerone::InstallLinuxPackageResponse> response) {
if (!response) {
LOG(ERROR) << "Failed to install Linux package. Empty response.";
std::move(callback).Run(CrostiniResult::INSTALL_LINUX_PACKAGE_FAILED);
return;
}
if (response->status() ==
vm_tools::cicerone::InstallLinuxPackageResponse::FAILED) {
LOG(ERROR) << "Failed to install Linux package: "
<< response->failure_reason();
std::move(callback).Run(CrostiniResult::INSTALL_LINUX_PACKAGE_FAILED);
return;
}
if (response->status() ==
vm_tools::cicerone::InstallLinuxPackageResponse::INSTALL_ALREADY_ACTIVE) {
LOG(WARNING) << "Failed to install Linux package, install already active.";
std::move(callback).Run(CrostiniResult::BLOCKING_OPERATION_ALREADY_ACTIVE);
return;
}
std::move(callback).Run(CrostiniResult::SUCCESS);
}
void CrostiniManager::RemoveCrostini(std::string vm_name,
RemoveCrostiniCallback callback) {
AddRemoveCrostiniCallback(std::move(callback));
auto crostini_remover = base::MakeRefCounted<guest_os::GuestOsRemover>(
profile_, guest_os::VmType::TERMINA, std::move(vm_name),
base::BindOnce(&CrostiniManager::OnRemoveCrostini,
weak_ptr_factory_.GetWeakPtr()));
auto abort_callback = base::BarrierClosure(
restarters_by_container_.size(),
base::BindOnce(
[](scoped_refptr<guest_os::GuestOsRemover> remover) {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&guest_os::GuestOsRemover::RemoveVm, remover));
},
crostini_remover));
for (const auto& iter : restarters_by_container_) {
iter.second->Abort(abort_callback);
}
}
void CrostiniManager::OnRemoveCrostini(
guest_os::GuestOsRemover::Result result) {
switch (result) {
case guest_os::GuestOsRemover::Result::kStopVmNoResponse:
FinishUninstall(CrostiniResult::STOP_VM_NO_RESPONSE);
return;
case guest_os::GuestOsRemover::Result::kStopVmFailed:
FinishUninstall(CrostiniResult::VM_STOP_FAILED);
return;
case guest_os::GuestOsRemover::Result::kDestroyDiskImageFailed:
FinishUninstall(CrostiniResult::DESTROY_DISK_IMAGE_FAILED);
return;
case guest_os::GuestOsRemover::Result::kSuccess:
// Keep going instead of finishing now.
break;
}
UninstallTermina(base::BindOnce(&CrostiniManager::OnRemoveTermina,
weak_ptr_factory_.GetWeakPtr()));
}
void CrostiniManager::OnRemoveTermina(bool success) {
if (!success) {
LOG(ERROR) << "Failed to uninstall Termina";
FinishUninstall(CrostiniResult::UNINSTALL_TERMINA_FAILED);
return;
}
if (base::FeatureList::IsEnabled(ash::features::kCrostiniContainerless)) {
// container prefs seem to be wiped as some part of lxd container removal
// callbacks in the regular flow, so we must remove them manually here for
// baguette.
profile_->GetPrefs()->ClearPref(guest_os::prefs::kGuestOsContainers);
}
profile_->GetPrefs()->SetBoolean(prefs::kCrostiniEnabled, false);
profile_->GetPrefs()->ClearPref(prefs::kCrostiniLastDiskSize);
guest_os::RemoveVmFromPrefs(profile_, kCrostiniDefaultVmType);
profile_->GetPrefs()->ClearPref(prefs::kCrostiniDefaultContainerConfigured);
UnregisterAllContainers();
FinishUninstall(CrostiniResult::SUCCESS);
}
void CrostiniManager::FinishUninstall(CrostiniResult result) {
base::UmaHistogramEnumeration("Crostini.UninstallResult.Reason", result);
for (auto& callback : remove_crostini_callbacks_) {
std::move(callback).Run(result);
}
remove_crostini_callbacks_.clear();
}
void CrostiniManager::RemoveRestartId(RestartId restart_id) {
// restarters_by_container_ is handled in RestartCompleted()
restarters_by_id_.erase(restart_id);
}
void CrostiniManager::RestartCompleted(CrostiniRestarter* restarter,
base::OnceClosure closure) {
guest_os::GuestId container_id = restarter->container_id();
restarter = nullptr;
// Destroy the restarter.
restarters_by_container_.erase(container_id);
if (ShouldWarnAboutExpiredVersion(container_id)) {
CrostiniExpiredContainerWarningView::Show(profile_, std::move(closure));
} else {
std::move(closure).Run();
}
}
void CrostiniManager::OnExportLxdContainer(
const guest_os::GuestId& container_id,
std::optional<vm_tools::cicerone::ExportLxdContainerResponse> response) {
auto it = export_lxd_container_callbacks_.find(container_id);
if (it == export_lxd_container_callbacks_.end()) {
LOG(ERROR) << "No export callback for " << container_id;
return;
}
if (!response) {
LOG(ERROR) << "Failed to export lxd container. Empty response.";
std::move(it->second)
.Run(CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED, 0, 0);
export_lxd_container_callbacks_.erase(it);
return;
}
// If export has started, the callback will be invoked when the
// ExportLxdContainerProgressSignal signal indicates that export is
// complete, otherwise this is an error.
if (response->status() !=
vm_tools::cicerone::ExportLxdContainerResponse::EXPORTING) {
LOG(ERROR) << "Failed to export container: status=" << response->status()
<< ", failure_reason=" << response->failure_reason();
std::move(it->second)
.Run(CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED, 0, 0);
export_lxd_container_callbacks_.erase(it);
}
}
void CrostiniManager::OnExportLxdContainerProgress(
const vm_tools::cicerone::ExportLxdContainerProgressSignal& signal) {
using ProgressSignal = vm_tools::cicerone::ExportLxdContainerProgressSignal;
if (signal.owner_id() != owner_id_) {
return;
}
const guest_os::GuestId container_id(kCrostiniDefaultVmType, signal.vm_name(),
signal.container_name());
CrostiniResult result;
switch (signal.status()) {
case ProgressSignal::EXPORTING_STREAMING: {
const StreamingExportStatus status{
.total_files = signal.total_input_files(),
.total_bytes = signal.total_input_bytes(),
.exported_files = signal.input_files_streamed(),
.exported_bytes = signal.input_bytes_streamed()};
for (auto& observer : export_container_progress_observers_) {
observer.OnExportContainerProgress(container_id, status);
}
return;
}
case ProgressSignal::CANCELLED:
result = CrostiniResult::CONTAINER_EXPORT_IMPORT_CANCELLED;
break;
case ProgressSignal::DONE:
result = CrostiniResult::SUCCESS;
break;
default:
result = CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED;
LOG(ERROR) << "Failed during export container: " << signal.status()
<< ", " << signal.failure_reason();
}
// Invoke original callback with either success or failure.
auto it = export_lxd_container_callbacks_.find(container_id);
if (it == export_lxd_container_callbacks_.end()) {
LOG(ERROR) << "No export callback for " << container_id;
return;
}
std::move(it->second)
.Run(result, signal.input_bytes_streamed(), signal.bytes_exported());
export_lxd_container_callbacks_.erase(it);
}
void CrostiniManager::OnImportLxdContainer(
const guest_os::GuestId& container_id,
std::optional<vm_tools::cicerone::ImportLxdContainerResponse> response) {
auto it = import_lxd_container_callbacks_.find(container_id);
if (it == import_lxd_container_callbacks_.end()) {
LOG(ERROR) << "No import callback for " << container_id;
return;
}
if (!response) {
LOG(ERROR) << "Failed to import lxd container. Empty response.";
std::move(it->second).Run(CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED);
import_lxd_container_callbacks_.erase(it);
return;
}
// If import has started, the callback will be invoked when the
// ImportLxdContainerProgressSignal signal indicates that import is
// complete, otherwise this is an error.
if (response->status() !=
vm_tools::cicerone::ImportLxdContainerResponse::IMPORTING) {
LOG(ERROR) << "Failed to import container: " << response->failure_reason();
std::move(it->second).Run(CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED);
import_lxd_container_callbacks_.erase(it);
}
}
void CrostiniManager::OnImportLxdContainerProgress(
const vm_tools::cicerone::ImportLxdContainerProgressSignal& signal) {
if (signal.owner_id() != owner_id_) {
return;
}
bool call_observers = false;
bool call_original_callback = false;
ImportContainerProgressStatus status;
CrostiniResult result;
switch (signal.status()) {
case vm_tools::cicerone::ImportLxdContainerProgressSignal::IMPORTING_UPLOAD:
call_observers = true;
status = ImportContainerProgressStatus::UPLOAD;
break;
case vm_tools::cicerone::ImportLxdContainerProgressSignal::IMPORTING_UNPACK:
call_observers = true;
status = ImportContainerProgressStatus::UNPACK;
break;
case vm_tools::cicerone::ImportLxdContainerProgressSignal::CANCELLED:
call_original_callback = true;
result = CrostiniResult::CONTAINER_EXPORT_IMPORT_CANCELLED;
break;
case vm_tools::cicerone::ImportLxdContainerProgressSignal::DONE:
call_original_callback = true;
result = CrostiniResult::SUCCESS;
break;
case vm_tools::cicerone::ImportLxdContainerProgressSignal::
FAILED_ARCHITECTURE:
call_observers = true;
status = ImportContainerProgressStatus::FAILURE_ARCHITECTURE;
call_original_callback = true;
result = CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED_ARCHITECTURE;
break;
case vm_tools::cicerone::ImportLxdContainerProgressSignal::FAILED_SPACE:
call_observers = true;
status = ImportContainerProgressStatus::FAILURE_SPACE;
call_original_callback = true;
result = CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED_SPACE;
break;
default:
call_original_callback = true;
result = CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED;
LOG(ERROR) << "Failed during import container: " << signal.status()
<< ", " << signal.failure_reason();
}
const guest_os::GuestId container_id(kCrostiniDefaultVmType, signal.vm_name(),
signal.container_name());
if (call_observers) {
for (auto& observer : import_container_progress_observers_) {
observer.OnImportContainerProgress(
container_id, status, signal.progress_percent(),
signal.progress_speed(), signal.architecture_device(),
signal.architecture_container(), signal.available_space(),
signal.min_required_space());
}
}
// Invoke original callback with either success or failure.
if (call_original_callback) {
auto it = import_lxd_container_callbacks_.find(container_id);
if (it == import_lxd_container_callbacks_.end()) {
LOG(ERROR) << "No import callback for " << container_id;
return;
}
std::move(it->second).Run(result);
import_lxd_container_callbacks_.erase(it);
}
}
void CrostiniManager::OnCancelDiskImageOp(
const guest_os::GuestId& key,
std::optional<vm_tools::concierge::SuccessFailureResponse> response) {
auto it = disk_image_callbacks_.find(key);
if (it == disk_image_callbacks_.end()) {
LOG(ERROR) << "No export callback for " << key;
return;
}
if (!response) {
LOG(ERROR) << "Failed to cancel disk image operation. Empty response.";
return;
}
if (!response->success()) {
LOG(ERROR) << "Failed to cancel disk image operation, failure_reason="
<< response->failure_reason();
}
auto cb_it = disk_image_callbacks_.find(key);
if (cb_it == disk_image_callbacks_.end()) {
LOG(ERROR) << "No export callback for " << key;
return;
}
std::move(cb_it->second).Run(CrostiniResult::DISK_IMAGE_CANCELLED);
disk_image_callbacks_.erase(cb_it);
EraseCommandUuid(&disk_image_uuid_to_guest_id_, key.vm_name);
}
void CrostiniManager::OnCancelExportLxdContainer(
const guest_os::GuestId& key,
std::optional<vm_tools::cicerone::CancelExportLxdContainerResponse>
response) {
auto it = export_lxd_container_callbacks_.find(key);
if (it == export_lxd_container_callbacks_.end()) {
LOG(ERROR) << "No export callback for " << key;
return;
}
if (!response) {
LOG(ERROR) << "Failed to cancel lxd container export. Empty response.";
return;
}
if (response->status() !=
vm_tools::cicerone::CancelExportLxdContainerResponse::CANCEL_QUEUED) {
LOG(ERROR) << "Failed to cancel lxd container export:" << " status="
<< response->status()
<< ", failure_reason=" << response->failure_reason();
}
}
void CrostiniManager::OnCancelImportLxdContainer(
const guest_os::GuestId& key,
std::optional<vm_tools::cicerone::CancelImportLxdContainerResponse>
response) {
auto it = import_lxd_container_callbacks_.find(key);
if (it == import_lxd_container_callbacks_.end()) {
LOG(ERROR) << "No import callback for " << key;
return;
}
if (!response) {
LOG(ERROR) << "Failed to cancel lxd container import. Empty response.";
return;
}
if (response->status() !=
vm_tools::cicerone::CancelImportLxdContainerResponse::CANCEL_QUEUED) {
LOG(ERROR) << "Failed to cancel lxd container import:" << " status="
<< response->status()
<< ", failure_reason=" << response->failure_reason();
}
}
void CrostiniManager::OnUpgradeContainer(
CrostiniResultCallback callback,
std::optional<vm_tools::cicerone::UpgradeContainerResponse> response) {
if (!response) {
LOG(ERROR) << "Failed to start upgrading container. Empty response";
std::move(callback).Run(CrostiniResult::UPGRADE_CONTAINER_FAILED);
return;
}
CrostiniResult result = CrostiniResult::SUCCESS;
switch (response->status()) {
case vm_tools::cicerone::UpgradeContainerResponse::STARTED:
break;
case vm_tools::cicerone::UpgradeContainerResponse::ALREADY_RUNNING:
result = CrostiniResult::UPGRADE_CONTAINER_ALREADY_RUNNING;
LOG(ERROR) << "Upgrade already running. Nothing to do.";
break;
case vm_tools::cicerone::UpgradeContainerResponse::ALREADY_UPGRADED:
LOG(ERROR) << "Container already upgraded. Nothing to do.";
result = CrostiniResult::UPGRADE_CONTAINER_ALREADY_UPGRADED;
break;
case vm_tools::cicerone::UpgradeContainerResponse::NOT_SUPPORTED:
result = CrostiniResult::UPGRADE_CONTAINER_NOT_SUPPORTED;
break;
case vm_tools::cicerone::UpgradeContainerResponse::UNKNOWN:
case vm_tools::cicerone::UpgradeContainerResponse::FAILED:
default:
result = CrostiniResult::UPGRADE_CONTAINER_FAILED;
break;
}
if (!response->failure_reason().empty()) {
LOG(ERROR) << "Upgrade container failed. Failure reason: "
<< response->failure_reason();
}
std::move(callback).Run(result);
}
void CrostiniManager::OnCancelUpgradeContainer(
CrostiniResultCallback callback,
std::optional<vm_tools::cicerone::CancelUpgradeContainerResponse>
response) {
if (!response) {
LOG(ERROR) << "Failed to cancel upgrading container. Empty response";
std::move(callback).Run(CrostiniResult::CANCEL_UPGRADE_CONTAINER_FAILED);
return;
}
CrostiniResult result = CrostiniResult::SUCCESS;
switch (response->status()) {
case vm_tools::cicerone::CancelUpgradeContainerResponse::CANCELLED:
case vm_tools::cicerone::CancelUpgradeContainerResponse::NOT_RUNNING:
break;
case vm_tools::cicerone::CancelUpgradeContainerResponse::UNKNOWN:
case vm_tools::cicerone::CancelUpgradeContainerResponse::FAILED:
default:
LOG(ERROR) << "Cancel upgrade container failed. Failure reason "
<< response->failure_reason();
result = CrostiniResult::CANCEL_UPGRADE_CONTAINER_FAILED;
break;
}
std::move(callback).Run(result);
}
void CrostiniManager::OnPendingAppListUpdates(
const vm_tools::cicerone::PendingAppListUpdatesSignal& signal) {
guest_os::GuestId container_id(kCrostiniDefaultVmType, signal.vm_name(),
signal.container_name());
for (auto& observer : pending_app_list_updates_observers_) {
observer.OnPendingAppListUpdates(container_id, signal.count());
}
}
// TODO(danielng): Consider handling instant tethering.
void CrostiniManager::ActiveNetworksChanged(
const std::vector<const ash::NetworkState*>& active_networks) {
ash::NetworkStateHandler::NetworkStateList active_physical_networks;
ash::NetworkHandler::Get()
->network_state_handler()
->GetActiveNetworkListByType(ash::NetworkTypePattern::Physical(),
&active_physical_networks);
if (active_physical_networks.empty()) {
return;
}
const ash::NetworkState* network = active_physical_networks.at(0);
if (!network) {
return;
}
const ash::DeviceState* device =
ash::NetworkHandler::Get()->network_state_handler()->GetDeviceState(
network->device_path());
if (!device) {
return;
}
if (CrostiniFeatures::Get()->IsPortForwardingAllowed(profile_)) {
crostini::CrostiniPortForwarderFactory::GetForProfile(profile_)
->ActiveNetworksChanged(device->interface(), network->GetIpAddress());
}
}
void CrostiniManager::OnShuttingDown() {
network_state_handler_observer_.Reset();
}
void CrostiniManager::SuspendImminent(
power_manager::SuspendImminent::Reason reason) {
if (!crostini_sshfs_->IsSshfsMounted(DefaultContainerId())) {
return;
}
// Block suspend and try to unmount sshfs (https://crbug.com/968060).
auto token = base::UnguessableToken::Create();
chromeos::PowerManagerClient::Get()->BlockSuspend(token, "CrostiniManager");
crostini_sshfs_->UnmountCrostiniFiles(
DefaultContainerId(),
base::BindOnce(&CrostiniManager::OnRemoveSshfsCrostiniVolume,
weak_ptr_factory_.GetWeakPtr(), token));
}
void CrostiniManager::SuspendDone(base::TimeDelta sleep_duration) {
// https://crbug.com/968060. Sshfs is unmounted before suspend,
// call RestartCrostini to force remount if container is running.
guest_os::GuestId container_id = DefaultContainerId();
bool running = guest_os::GuestOsSessionTrackerFactory::GetForProfile(profile_)
->IsRunning(container_id);
if (running) {
// TODO(crbug/1142321): Double-check if anything breaks if we change this
// to just remount the sshfs mounts, in particular check 9p mounts.
RestartCrostini(container_id, base::DoNothing());
}
}
void CrostiniManager::OnRemoveSshfsCrostiniVolume(
base::UnguessableToken power_manager_suspend_token,
bool result) {
// Need to let the device suspend after cleaning up. Even if we failed we
// still unblock suspend since there's nothing else we can do at this point.
// TODO(crbug/1142321): Success metrics
chromeos::PowerManagerClient::Get()->UnblockSuspend(
power_manager_suspend_token);
}
void CrostiniManager::RemoveUncleanSshfsMounts() {
// TODO(crbug/1142321): Success metrics
crostini_sshfs_->UnmountCrostiniFiles(DefaultContainerId(),
base::DoNothing());
}
void CrostiniManager::DeallocateForwardedPortsCallback(
const guest_os::GuestId& container_id) {
crostini::CrostiniPortForwarderFactory::GetForProfile(profile_)
->DeactivateAllActivePorts(container_id);
}
void CrostiniManager::EmitVmDiskTypeMetric(const std::string& vm_name) {
if ((time_of_last_disk_type_metric_ + base::Hours(12)) > base::Time::Now()) {
// Only bother doing this once every 12 hours. We care about the number of
// users in each histogram bucket, not the number of times restarted. We
// do this 12-hourly instead of only at first launch since Crostini can
// last for a while, and we want to ensure that e.g. looking at N-day
// aggregation doesn't miss people who've got a long-running session.
return;
}
time_of_last_disk_type_metric_ = base::Time::Now();
vm_tools::concierge::ListVmDisksRequest request;
request.set_cryptohome_id(CryptohomeIdForProfile(profile_));
request.set_storage_location(vm_tools::concierge::STORAGE_CRYPTOHOME_ROOT);
request.set_vm_name(vm_name);
GetConciergeClient()->ListVmDisks(
std::move(request),
base::BindOnce(
[](std::optional<vm_tools::concierge::ListVmDisksResponse> response) {
if (response) {
if (response.value().images().size() != 1) {
LOG(ERROR) << "Got " << response.value().images().size()
<< " disks for image, don't know how to proceed";
base::UmaHistogramEnumeration(
"Crostini.DiskType", CrostiniDiskImageType::kMultiDisk);
return;
}
auto image = response.value().images().Get(0);
if (image.image_type() ==
vm_tools::concierge::DiskImageType::DISK_IMAGE_QCOW2) {
base::UmaHistogramEnumeration(
"Crostini.DiskType", CrostiniDiskImageType::kQCow2Sparse);
} else if (image.image_type() ==
vm_tools::concierge::DiskImageType::DISK_IMAGE_RAW) {
if (image.user_chosen_size()) {
base::UmaHistogramEnumeration(
"Crostini.DiskType",
CrostiniDiskImageType::kRawPreallocated);
} else {
base::UmaHistogramEnumeration(
"Crostini.DiskType", CrostiniDiskImageType::kRawSparse);
}
} else {
// We shouldn't get back the other disk types for Crostini
// disks.
base::UmaHistogramEnumeration("Crostini.DiskType",
CrostiniDiskImageType::kUnknown);
}
}
}));
}
void CrostiniManager::MountCrostiniFiles(guest_os::GuestId container_id,
CrostiniResultCallback callback,
bool background) {
crostini_sshfs_->MountCrostiniFiles(
container_id,
base::BindOnce(
[](CrostiniResultCallback callback, bool success) {
std::move(callback).Run(success
? CrostiniResult::SUCCESS
: CrostiniResult::SSHFS_MOUNT_ERROR);
},
std::move(callback)),
background);
}
void CrostiniManager::MountCrostiniFilesBackground(guest_os::GuestInfo info) {
MountCrostiniFiles(info.guest_id, base::DoNothing(), true);
}
void CrostiniManager::GetInstallLocation(
base::OnceCallback<void(base::FilePath)> callback) {
if (!crostini::CrostiniFeatures::Get()->IsEnabled(profile_)) {
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), base::FilePath()));
return;
}
InstallTermina(base::BindOnce(
[](base::WeakPtr<CrostiniManager> weak_this,
base::OnceCallback<void(base::FilePath)> callback,
CrostiniResult result) {
if (result != CrostiniResult::SUCCESS || !weak_this) {
std::move(callback).Run(base::FilePath());
} else {
std::move(callback).Run(
weak_this->termina_installer_.GetInstallLocation());
}
},
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void CrostiniManager::CallRestarterStartLxdContainerFinishedForTesting(
CrostiniManager::RestartId id,
CrostiniResult result) {
auto container_it = restarters_by_id_.find(id);
DCHECK(container_it != restarters_by_id_.end());
auto restarter_it = restarters_by_container_.find(container_it->second);
DCHECK(restarter_it != restarters_by_container_.end());
restarter_it->second->StartLxdContainerFinished(result);
}
void CrostiniManager::HandleContainerShutdown(
const guest_os::GuestId& container_id) {
// Run all ContainerShutdown observers
for (auto& observer : container_shutdown_observers_) {
observer.OnContainerShutdown(container_id);
}
if (!IsVmRunning(kCrostiniDefaultVmName)) {
auto* metrics_service =
CrostiniMetricsService::Factory::GetForProfile(profile_);
// This is null in unit tests.
if (metrics_service) {
metrics_service->SetBackgroundActive(false);
}
}
}
void CrostiniManager::RegisterContainerTerminal(
const guest_os::GuestId& container_id) {
if (terminal_provider_ids_.find(container_id) ==
terminal_provider_ids_.end()) {
auto* registry = guest_os::GuestOsServiceFactory::GetForProfile(profile_)
->TerminalProviderRegistry();
terminal_provider_ids_[container_id] = registry->Register(
std::make_unique<CrostiniTerminalProvider>(profile_, container_id));
}
}
void CrostiniManager::RegisterContainer(const guest_os::GuestId& container_id) {
RegisterContainerTerminal(container_id);
if (CrostiniFeatures::Get()->IsMultiContainerAllowed(profile_) &&
container_id != DefaultContainerId()) {
// TODO(b/217469540): The default container is still using sshfs for now,
// so start off using this approach only for non-default.
if (mount_provider_ids_.find(container_id) == mount_provider_ids_.end()) {
auto* registry = guest_os::GuestOsServiceFactory::GetForProfile(profile_)
->MountProviderRegistry();
mount_provider_ids_[container_id] = registry->Register(
std::make_unique<CrostiniMountProvider>(profile_, container_id));
}
}
guest_os::GuestOsSharePathFactory::GetForProfile(profile_)->RegisterGuest(
container_id);
}
void CrostiniManager::UnregisterContainer(
const guest_os::GuestId& container_id) {
auto* terminal_registry =
guest_os::GuestOsServiceFactory::GetForProfile(profile_)
->TerminalProviderRegistry();
auto it = terminal_provider_ids_.find(container_id);
if (it != terminal_provider_ids_.end()) {
terminal_registry->Unregister(it->second);
terminal_provider_ids_.erase(it);
}
auto* mount_registry =
guest_os::GuestOsServiceFactory::GetForProfile(profile_)
->MountProviderRegistry();
it = mount_provider_ids_.find(container_id);
if (it != mount_provider_ids_.end()) {
mount_registry->Unregister(it->second);
mount_provider_ids_.erase(it);
}
guest_os::GuestOsSharePathFactory::GetForProfile(profile_)->UnregisterGuest(
container_id);
if (container_id == DefaultContainerId()) {
// For now the upgrade notification only supports the default container. If
// we're removing that container then destroy any notification we might have
// for it.
upgrade_available_notification_.reset();
}
}
void CrostiniManager::UnregisterAllContainers() {
auto* terminal_registry =
guest_os::GuestOsServiceFactory::GetForProfile(profile_)
->TerminalProviderRegistry();
for (const auto& pair : terminal_provider_ids_) {
terminal_registry->Unregister(pair.second);
}
terminal_provider_ids_.clear();
auto* mount_registry =
guest_os::GuestOsServiceFactory::GetForProfile(profile_)
->MountProviderRegistry();
for (const auto& pair : mount_provider_ids_) {
mount_registry->Unregister(pair.second);
}
mount_provider_ids_.clear();
auto* share_service =
guest_os::GuestOsSharePathFactory::GetForProfile(profile_);
// Copy the list since we're going to iterate+mutate.
auto guests = base::flat_set<guest_os::GuestId>(share_service->ListGuests());
for (const auto& guest : guests) {
if (guest.vm_type == kCrostiniDefaultVmType) {
share_service->UnregisterGuest(guest);
}
}
upgrade_available_notification_.reset();
}
bool CrostiniManager::RegisterCreateOptions(
const guest_os::GuestId& container_id,
const RestartOptions& options) {
if (guest_os::GetContainerPrefValue(
profile_, container_id, guest_os::prefs::kContainerCreateOptions) !=
nullptr) {
return false;
}
base::Value::Dict new_create_options;
base::Value::List share_paths;
for (const base::FilePath& path : options.share_paths) {
share_paths.Append(path.value());
}
new_create_options.Set(prefs::kCrostiniCreateOptionsSharePathsKey,
std::move(share_paths));
if (options.container_username.has_value()) {
new_create_options.Set(prefs::kCrostiniCreateOptionsContainerUsernameKey,
base::Value(options.container_username.value()));
}
if (options.disk_size_bytes.has_value()) {
new_create_options.Set(
prefs::kCrostiniCreateOptionsDiskSizeBytesKey,
base::Value(base::NumberToString(options.disk_size_bytes.value())));
}
if (options.image_server_url.has_value()) {
new_create_options.Set(prefs::kCrostiniCreateOptionsImageServerUrlKey,
base::Value(options.image_server_url.value()));
}
if (options.image_alias.has_value()) {
new_create_options.Set(prefs::kCrostiniCreateOptionsImageAliasKey,
base::Value(options.image_alias.value()));
}
if (options.ansible_playbook.has_value()) {
new_create_options.Set(
prefs::kCrostiniCreateOptionsAnsiblePlaybookKey,
base::Value(options.ansible_playbook.value().value()));
}
new_create_options.Set(prefs::kCrostiniCreateOptionsUsedKey,
base::Value(false));
guest_os::UpdateContainerPref(profile_, container_id,
guest_os::prefs::kContainerCreateOptions,
base::Value(std::move(new_create_options)));
return true;
}
bool CrostiniManager::IsPendingCreation(const guest_os::GuestId& container_id) {
const base::Value* create_options = guest_os::GetContainerPrefValue(
profile_, container_id, guest_os::prefs::kContainerCreateOptions);
if (create_options == nullptr) {
// Will only reach here if it's a vmc-started container. Treat it as if the
// create options have already been used.
return false;
}
return !(*create_options->GetDict().FindBool(
prefs::kCrostiniCreateOptionsUsedKey));
}
void CrostiniManager::SetCreateOptionsUsed(
const guest_os::GuestId& container_id) {
const base::Value* create_options_val = guest_os::GetContainerPrefValue(
profile_, container_id, guest_os::prefs::kContainerCreateOptions);
if (create_options_val == nullptr) {
// Should never reach here.
LOG(ERROR)
<< "create_options_val in SetCreateOptionsUsed is pointing to null.";
return;
}
base::Value::Dict mutable_create_options =
create_options_val->GetDict().Clone();
mutable_create_options.Set(prefs::kCrostiniCreateOptionsUsedKey,
base::Value(true));
guest_os::UpdateContainerPref(profile_, container_id,
guest_os::prefs::kContainerCreateOptions,
base::Value(std::move(mutable_create_options)));
}
bool CrostiniManager::FetchCreateOptions(const guest_os::GuestId& container_id,
RestartOptions* options) {
DCHECK(options != nullptr);
const base::Value* create_options_val = guest_os::GetContainerPrefValue(
profile_, container_id, guest_os::prefs::kContainerCreateOptions);
if (create_options_val == nullptr) {
// Should never reach here. If we somehow do, just restart with the given
// options.
LOG(ERROR)
<< "create_options_val in FetchCreateOptions is pointing to null.";
return true;
}
const base::Value::Dict& create_options = create_options_val->GetDict();
for (const auto& path :
*create_options.FindList(prefs::kCrostiniCreateOptionsSharePathsKey)) {
options->share_paths.emplace_back(path.GetString());
}
if (create_options.Find(prefs::kCrostiniCreateOptionsContainerUsernameKey)) {
options->container_username = *create_options.FindString(
prefs::kCrostiniCreateOptionsContainerUsernameKey);
}
if (create_options.Find(prefs::kCrostiniCreateOptionsDiskSizeBytesKey)) {
int64_t size;
base::StringToInt64(*create_options.FindString(
prefs::kCrostiniCreateOptionsDiskSizeBytesKey),
&size);
options->disk_size_bytes = size;
}
if (create_options.Find(prefs::kCrostiniCreateOptionsImageServerUrlKey)) {
options->image_server_url = *create_options.FindString(
prefs::kCrostiniCreateOptionsImageServerUrlKey);
}
if (create_options.Find(prefs::kCrostiniCreateOptionsImageAliasKey)) {
options->image_alias =
*create_options.FindString(prefs::kCrostiniCreateOptionsImageAliasKey);
}
if (create_options.Find(prefs::kCrostiniCreateOptionsAnsiblePlaybookKey)) {
options->ansible_playbook = base::FilePath(*create_options.FindString(
prefs::kCrostiniCreateOptionsAnsiblePlaybookKey));
}
return *create_options.FindBool(prefs::kCrostiniCreateOptionsUsedKey);
}
bool CrostiniManager::ShouldWarnAboutExpiredVersion(
const guest_os::GuestId& container_id) {
if (already_warned_expired_version_) {
return false;
}
if (!CrostiniFeatures::Get()->IsContainerUpgradeUIAllowed(profile_)) {
return false;
}
if (container_id != DefaultContainerId()) {
return false;
}
// If the warning dialog is already open we can add more callbacks to it, but
// if we've moved to the upgrade dialog proper we should run them now as they
// may be part of the upgrade process.
if (ash::SystemWebDialogDelegate::FindInstance(
GURL{chrome::kChromeUICrostiniUpgraderUrl}.spec())) {
return false;
}
if (!IsContainerVersionExpired(profile_, container_id)) {
return false;
}
already_warned_expired_version_ = true;
return true;
}
} // namespace crostini
|