/usr/share/gocode/src/github.com/lxc/lxd/lxd/container_lxc.go is in golang-github-lxc-lxd-dev 2.0.2-0ubuntu1~16.04.1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 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 | package main
import (
"archive/tar"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"os/exec"
"path"
"path/filepath"
"reflect"
"strconv"
"strings"
"sync"
"syscall"
"time"
"gopkg.in/flosch/pongo2.v3"
"gopkg.in/lxc/go-lxc.v2"
"gopkg.in/yaml.v2"
"github.com/lxc/lxd/shared"
log "gopkg.in/inconshreveable/log15.v2"
)
// Global variables
var lxcStoppingContainersLock sync.Mutex
var lxcStoppingContainers map[int]*sync.WaitGroup = make(map[int]*sync.WaitGroup)
// Helper functions
func lxcSetConfigItem(c *lxc.Container, key string, value string) error {
if c == nil {
return fmt.Errorf("Uninitialized go-lxc struct")
}
err := c.SetConfigItem(key, value)
if err != nil {
return fmt.Errorf("Failed to set LXC config: %s=%s", key, value)
}
return nil
}
func lxcValidConfig(rawLxc string) error {
for _, line := range strings.Split(rawLxc, "\n") {
// Ignore empty lines
if len(line) == 0 {
continue
}
// Ignore comments
if strings.HasPrefix(line, "#") {
continue
}
// Ensure the format is valid
membs := strings.SplitN(line, "=", 2)
if len(membs) != 2 {
return fmt.Errorf("Invalid raw.lxc line: %s", line)
}
key := strings.ToLower(strings.Trim(membs[0], " \t"))
// Blacklist some keys
if key == "lxc.logfile" {
return fmt.Errorf("Setting lxc.logfile is not allowed")
}
if strings.HasPrefix(key, "lxc.network.") {
fields := strings.Split(key, ".")
if len(fields) == 4 && shared.StringInSlice(fields[3], []string{"ipv4", "ipv6"}) {
continue
}
if len(fields) == 5 && shared.StringInSlice(fields[3], []string{"ipv4", "ipv6"}) && fields[4] == "gateway" {
continue
}
return fmt.Errorf("Only interface-specific ipv4/ipv6 lxc.network keys are allowed")
}
}
return nil
}
// Loader functions
func containerLXCCreate(d *Daemon, args containerArgs) (container, error) {
// Create the container struct
c := &containerLXC{
daemon: d,
id: args.Id,
name: args.Name,
ephemeral: args.Ephemeral,
architecture: args.Architecture,
cType: args.Ctype,
stateful: args.Stateful,
creationDate: args.CreationDate,
profiles: args.Profiles,
localConfig: args.Config,
localDevices: args.Devices,
}
// No need to detect storage here, its a new container.
c.storage = d.Storage
// Load the config
err := c.init()
if err != nil {
c.Delete()
return nil, err
}
// Look for a rootfs entry
rootfs := false
for _, m := range c.expandedDevices {
if m["type"] == "disk" && m["path"] == "/" {
rootfs = true
break
}
}
if !rootfs {
deviceName := "root"
for {
if c.expandedDevices[deviceName] == nil {
break
}
deviceName += "_"
}
c.localDevices[deviceName] = shared.Device{"type": "disk", "path": "/"}
updateArgs := containerArgs{
Architecture: c.architecture,
Config: c.localConfig,
Devices: c.localDevices,
Ephemeral: c.ephemeral,
Profiles: c.profiles,
}
err = c.Update(updateArgs, false)
if err != nil {
c.Delete()
return nil, err
}
}
// Validate expanded config
err = containerValidConfig(c.expandedConfig, false, true)
if err != nil {
c.Delete()
return nil, err
}
err = containerValidDevices(c.expandedDevices, false, true)
if err != nil {
c.Delete()
return nil, err
}
// Setup initial idmap config
idmap := c.IdmapSet()
var jsonIdmap string
if idmap != nil {
idmapBytes, err := json.Marshal(idmap.Idmap)
if err != nil {
c.Delete()
return nil, err
}
jsonIdmap = string(idmapBytes)
} else {
jsonIdmap = "[]"
}
err = c.ConfigKeySet("volatile.last_state.idmap", jsonIdmap)
if err != nil {
c.Delete()
return nil, err
}
return c, nil
}
func containerLXCLoad(d *Daemon, args containerArgs) (container, error) {
// Create the container struct
c := &containerLXC{
daemon: d,
id: args.Id,
name: args.Name,
ephemeral: args.Ephemeral,
architecture: args.Architecture,
cType: args.Ctype,
creationDate: args.CreationDate,
profiles: args.Profiles,
localConfig: args.Config,
localDevices: args.Devices,
stateful: args.Stateful}
// Detect the storage backend
s, err := storageForFilename(d, shared.VarPath("containers", strings.Split(c.name, "/")[0]))
if err != nil {
return nil, err
}
c.storage = s
// Load the config
err = c.init()
if err != nil {
return nil, err
}
return c, nil
}
// The LXC container driver
type containerLXC struct {
// Properties
architecture int
cType containerType
creationDate time.Time
ephemeral bool
id int
name string
stateful bool
// Config
expandedConfig map[string]string
expandedDevices shared.Devices
fromHook bool
localConfig map[string]string
localDevices shared.Devices
profiles []string
// Cache
c *lxc.Container
daemon *Daemon
idmapset *shared.IdmapSet
storage storage
}
func (c *containerLXC) init() error {
// Compute the expanded config and device list
err := c.expandConfig()
if err != nil {
return err
}
err = c.expandDevices()
if err != nil {
return err
}
// Setup the Idmap
if !c.IsPrivileged() {
if c.daemon.IdmapSet == nil {
return fmt.Errorf("LXD doesn't have a uid/gid allocation. In this mode, only privileged containers are supported.")
}
c.idmapset = c.daemon.IdmapSet
}
return nil
}
func (c *containerLXC) initLXC() error {
// No need to go through all that for snapshots
if c.IsSnapshot() {
return nil
}
// Check if being called from a hook
if c.fromHook {
return fmt.Errorf("You can't use go-lxc from inside a LXC hook.")
}
// Check if already initialized
if c.c != nil {
return nil
}
// Load the go-lxc struct
cc, err := lxc.NewContainer(c.Name(), c.daemon.lxcpath)
if err != nil {
return err
}
// Base config
err = lxcSetConfigItem(cc, "lxc.cap.drop", "mac_admin mac_override sys_time sys_module sys_rawio")
if err != nil {
return err
}
// Set an appropriate /proc, /sys/ and /sys/fs/cgroup
mounts := []string{}
if c.IsPrivileged() && !runningInUserns {
mounts = append(mounts, "proc:mixed")
mounts = append(mounts, "sys:mixed")
} else {
mounts = append(mounts, "proc:rw")
mounts = append(mounts, "sys:rw")
}
if !shared.PathExists("/proc/self/ns/cgroup") {
mounts = append(mounts, "cgroup:mixed")
}
err = lxcSetConfigItem(cc, "lxc.mount.auto", strings.Join(mounts, " "))
if err != nil {
return err
}
err = lxcSetConfigItem(cc, "lxc.autodev", "1")
if err != nil {
return err
}
err = lxcSetConfigItem(cc, "lxc.pts", "1024")
if err != nil {
return err
}
bindMounts := []string{
"/proc/sys/fs/binfmt_misc",
"/sys/firmware/efi/efivars",
"/sys/fs/fuse/connections",
"/sys/fs/pstore",
"/sys/kernel/debug",
"/sys/kernel/security"}
if c.IsPrivileged() && !runningInUserns {
err = lxcSetConfigItem(cc, "lxc.mount.entry", "mqueue dev/mqueue mqueue rw,relatime,create=dir,optional")
if err != nil {
return err
}
} else {
bindMounts = append(bindMounts, "/dev/mqueue")
}
for _, mnt := range bindMounts {
err = lxcSetConfigItem(cc, "lxc.mount.entry", fmt.Sprintf("%s %s none rbind,create=dir,optional", mnt, strings.TrimPrefix(mnt, "/")))
if err != nil {
return err
}
}
// For lxcfs
templateConfDir := os.Getenv("LXD_LXC_TEMPLATE_CONFIG")
if templateConfDir == "" {
templateConfDir = "/usr/share/lxc/config"
}
if shared.PathExists(fmt.Sprintf("%s/common.conf.d/", templateConfDir)) {
err = lxcSetConfigItem(cc, "lxc.include", fmt.Sprintf("%s/common.conf.d/", templateConfDir))
if err != nil {
return err
}
}
// Configure devices cgroup
if c.IsPrivileged() && !runningInUserns && cgDevicesController {
err = lxcSetConfigItem(cc, "lxc.cgroup.devices.deny", "a")
if err != nil {
return err
}
for _, dev := range []string{"c *:* m", "b *:* m", "c 5:0 rwm", "c 5:1 rwm", "c 1:5 rwm", "c 1:7 rwm", "c 1:3 rwm", "c 1:8 rwm", "c 1:9 rwm", "c 5:2 rwm", "c 136:* rwm"} {
err = lxcSetConfigItem(cc, "lxc.cgroup.devices.allow", dev)
if err != nil {
return err
}
}
}
if c.IsNesting() {
/*
* mount extra /proc and /sys to work around kernel
* restrictions on remounting them when covered
*/
err = lxcSetConfigItem(cc, "lxc.mount.entry", "proc dev/.lxc/proc proc create=dir,optional")
if err != nil {
return err
}
err = lxcSetConfigItem(cc, "lxc.mount.entry", "sys dev/.lxc/sys sysfs create=dir,optional")
if err != nil {
return err
}
}
// Setup logging
logfile := c.LogFilePath()
err = cc.SetLogFile(logfile)
if err != nil {
return err
}
err = lxcSetConfigItem(cc, "lxc.loglevel", "0")
if err != nil {
return err
}
// Setup architecture
personality, err := shared.ArchitecturePersonality(c.architecture)
if err != nil {
personality, err = shared.ArchitecturePersonality(c.daemon.architectures[0])
if err != nil {
return err
}
}
err = lxcSetConfigItem(cc, "lxc.arch", personality)
if err != nil {
return err
}
// Setup the hooks
err = lxcSetConfigItem(cc, "lxc.hook.pre-start", fmt.Sprintf("%s callhook %s %d start", execPath, shared.VarPath(""), c.id))
if err != nil {
return err
}
err = lxcSetConfigItem(cc, "lxc.hook.post-stop", fmt.Sprintf("%s callhook %s %d stop", execPath, shared.VarPath(""), c.id))
if err != nil {
return err
}
// Setup the console
err = lxcSetConfigItem(cc, "lxc.tty", "0")
if err != nil {
return err
}
// Setup the hostname
err = lxcSetConfigItem(cc, "lxc.utsname", c.Name())
if err != nil {
return err
}
// Setup devlxd
err = lxcSetConfigItem(cc, "lxc.mount.entry", fmt.Sprintf("%s dev/lxd none bind,create=dir 0 0", shared.VarPath("devlxd")))
if err != nil {
return err
}
// Setup AppArmor
if aaAvailable {
if aaConfined || !aaAdmin {
// If confined but otherwise able to use AppArmor, use our own profile
curProfile := aaProfile()
curProfile = strings.TrimSuffix(curProfile, " (enforce)")
err = lxcSetConfigItem(cc, "lxc.aa_profile", curProfile)
if err != nil {
return err
}
} else {
// If not currently confined, use the container's profile
err := lxcSetConfigItem(cc, "lxc.aa_profile", AAProfileFull(c))
if err != nil {
return err
}
}
}
// Setup Seccomp
err = lxcSetConfigItem(cc, "lxc.seccomp", SeccompProfilePath(c))
if err != nil {
return err
}
// Setup idmap
if c.idmapset != nil {
lines := c.idmapset.ToLxcString()
for _, line := range lines {
err := lxcSetConfigItem(cc, "lxc.id_map", strings.TrimSuffix(line, "\n"))
if err != nil {
return err
}
}
}
// Setup environment
for k, v := range c.expandedConfig {
if strings.HasPrefix(k, "environment.") {
err = lxcSetConfigItem(cc, "lxc.environment", fmt.Sprintf("%s=%s", strings.TrimPrefix(k, "environment."), v))
if err != nil {
return err
}
}
}
// Memory limits
if cgMemoryController {
memory := c.expandedConfig["limits.memory"]
memoryEnforce := c.expandedConfig["limits.memory.enforce"]
memorySwap := c.expandedConfig["limits.memory.swap"]
memorySwapPriority := c.expandedConfig["limits.memory.swap.priority"]
// Configure the memory limits
if memory != "" {
var valueInt int64
if strings.HasSuffix(memory, "%") {
percent, err := strconv.ParseInt(strings.TrimSuffix(memory, "%"), 10, 64)
if err != nil {
return err
}
memoryTotal, err := deviceTotalMemory()
if err != nil {
return err
}
valueInt = int64((memoryTotal / 100) * percent)
} else {
valueInt, err = shared.ParseByteSizeString(memory)
if err != nil {
return err
}
}
if memoryEnforce == "soft" {
err = lxcSetConfigItem(cc, "lxc.cgroup.memory.soft_limit_in_bytes", fmt.Sprintf("%d", valueInt))
if err != nil {
return err
}
} else {
if cgSwapAccounting && (memorySwap == "" || shared.IsTrue(memorySwap)) {
err = lxcSetConfigItem(cc, "lxc.cgroup.memory.limit_in_bytes", fmt.Sprintf("%d", valueInt))
if err != nil {
return err
}
err = lxcSetConfigItem(cc, "lxc.cgroup.memory.memsw.limit_in_bytes", fmt.Sprintf("%d", valueInt))
if err != nil {
return err
}
} else {
err = lxcSetConfigItem(cc, "lxc.cgroup.memory.limit_in_bytes", fmt.Sprintf("%d", valueInt))
if err != nil {
return err
}
}
}
}
// Configure the swappiness
if memorySwap != "" && !shared.IsTrue(memorySwap) {
err = lxcSetConfigItem(cc, "lxc.cgroup.memory.swappiness", "0")
if err != nil {
return err
}
} else if memorySwapPriority != "" {
priority, err := strconv.Atoi(memorySwapPriority)
if err != nil {
return err
}
err = lxcSetConfigItem(cc, "lxc.cgroup.memory.swappiness", fmt.Sprintf("%d", 60-10+priority))
if err != nil {
return err
}
}
}
// CPU limits
cpuPriority := c.expandedConfig["limits.cpu.priority"]
cpuAllowance := c.expandedConfig["limits.cpu.allowance"]
if (cpuPriority != "" || cpuAllowance != "") && cgCpuController {
cpuShares, cpuCfsQuota, cpuCfsPeriod, err := deviceParseCPU(cpuAllowance, cpuPriority)
if err != nil {
return err
}
if cpuShares != "1024" {
err = lxcSetConfigItem(cc, "lxc.cgroup.cpu.shares", cpuShares)
if err != nil {
return err
}
}
if cpuCfsPeriod != "-1" {
err = lxcSetConfigItem(cc, "lxc.cgroup.cpu.cfs_period_us", cpuCfsPeriod)
if err != nil {
return err
}
}
if cpuCfsQuota != "-1" {
err = lxcSetConfigItem(cc, "lxc.cgroup.cpu.cfs_quota_us", cpuCfsQuota)
if err != nil {
return err
}
}
}
// Disk limits
if cgBlkioController {
diskPriority := c.expandedConfig["limits.disk.priority"]
if diskPriority != "" {
priorityInt, err := strconv.Atoi(diskPriority)
if err != nil {
return err
}
err = lxcSetConfigItem(cc, "lxc.cgroup.blkio.weight", fmt.Sprintf("%d", priorityInt*100))
if err != nil {
return err
}
}
hasDiskLimits := false
for _, m := range c.expandedDevices {
if m["type"] != "disk" {
continue
}
if m["limits.read"] != "" || m["limits.write"] != "" || m["limits.max"] != "" {
hasDiskLimits = true
break
}
}
if hasDiskLimits {
diskLimits, err := c.getDiskLimits()
if err != nil {
return err
}
for block, limit := range diskLimits {
if limit.readBps > 0 {
err = lxcSetConfigItem(cc, "lxc.cgroup.blkio.throttle.read_bps_device", fmt.Sprintf("%s %d", block, limit.readBps))
if err != nil {
return err
}
}
if limit.readIops > 0 {
err = lxcSetConfigItem(cc, "lxc.cgroup.blkio.throttle.read_iops_device", fmt.Sprintf("%s %d", block, limit.readIops))
if err != nil {
return err
}
}
if limit.writeBps > 0 {
err = lxcSetConfigItem(cc, "lxc.cgroup.blkio.throttle.write_bps_device", fmt.Sprintf("%s %d", block, limit.writeBps))
if err != nil {
return err
}
}
if limit.writeIops > 0 {
err = lxcSetConfigItem(cc, "lxc.cgroup.blkio.throttle.write_iops_device", fmt.Sprintf("%s %d", block, limit.writeIops))
if err != nil {
return err
}
}
}
}
}
// Processes
if cgPidsController {
processes := c.expandedConfig["limits.processes"]
if processes != "" {
valueInt, err := strconv.ParseInt(processes, 10, 64)
if err != nil {
return err
}
err = lxcSetConfigItem(cc, "lxc.cgroup.pids.max", fmt.Sprintf("%d", valueInt))
if err != nil {
return err
}
}
}
// Setup devices
for k, m := range c.expandedDevices {
if shared.StringInSlice(m["type"], []string{"unix-char", "unix-block"}) {
// Prepare all the paths
srcPath := m["path"]
tgtPath := strings.TrimPrefix(srcPath, "/")
devName := fmt.Sprintf("unix.%s", strings.Replace(tgtPath, "/", "-", -1))
devPath := filepath.Join(c.DevicesPath(), devName)
// Set the bind-mount entry
err = lxcSetConfigItem(cc, "lxc.mount.entry", fmt.Sprintf("%s %s none bind,create=file", devPath, tgtPath))
if err != nil {
return err
}
} else if m["type"] == "nic" {
// Fill in some fields from volatile
m, err = c.fillNetworkDevice(k, m)
if err != nil {
return err
}
// Interface type specific configuration
if shared.StringInSlice(m["nictype"], []string{"bridged", "p2p"}) {
err = lxcSetConfigItem(cc, "lxc.network.type", "veth")
if err != nil {
return err
}
} else if m["nictype"] == "physical" {
err = lxcSetConfigItem(cc, "lxc.network.type", "phys")
if err != nil {
return err
}
} else if m["nictype"] == "macvlan" {
err = lxcSetConfigItem(cc, "lxc.network.type", "macvlan")
if err != nil {
return err
}
err = lxcSetConfigItem(cc, "lxc.network.macvlan.mode", "bridge")
if err != nil {
return err
}
}
err = lxcSetConfigItem(cc, "lxc.network.flags", "up")
if err != nil {
return err
}
if shared.StringInSlice(m["nictype"], []string{"bridged", "physical", "macvlan"}) {
err = lxcSetConfigItem(cc, "lxc.network.link", m["parent"])
if err != nil {
return err
}
}
// Host Virtual NIC name
if m["host_name"] != "" {
err = lxcSetConfigItem(cc, "lxc.network.veth.pair", m["host_name"])
if err != nil {
return err
}
}
// MAC address
if m["hwaddr"] != "" {
err = lxcSetConfigItem(cc, "lxc.network.hwaddr", m["hwaddr"])
if err != nil {
return err
}
}
// MTU
if m["mtu"] != "" {
err = lxcSetConfigItem(cc, "lxc.network.mtu", m["mtu"])
if err != nil {
return err
}
}
// Name
if m["name"] != "" {
err = lxcSetConfigItem(cc, "lxc.network.name", m["name"])
if err != nil {
return err
}
}
} else if m["type"] == "disk" {
// Prepare all the paths
srcPath := m["source"]
tgtPath := strings.TrimPrefix(m["path"], "/")
devName := fmt.Sprintf("disk.%s", strings.Replace(tgtPath, "/", "-", -1))
devPath := filepath.Join(c.DevicesPath(), devName)
// Various option checks
isOptional := shared.IsTrue(m["optional"])
isReadOnly := shared.IsTrue(m["readonly"])
isRecursive := shared.IsTrue(m["recursive"])
isFile := !shared.IsDir(srcPath) && !deviceIsBlockdev(srcPath)
// Deal with a rootfs
if tgtPath == "" {
// Set the rootfs backend type if supported (must happen before any other lxc.rootfs)
err := lxcSetConfigItem(cc, "lxc.rootfs.backend", "dir")
if err == nil {
value := cc.ConfigItem("lxc.rootfs.backend")
if len(value) == 0 || value[0] != "dir" {
lxcSetConfigItem(cc, "lxc.rootfs.backend", "")
}
}
// Set the rootfs path
err = lxcSetConfigItem(cc, "lxc.rootfs", c.RootfsPath())
if err != nil {
return err
}
// Read-only rootfs (unlikely to work very well)
if isReadOnly {
err = lxcSetConfigItem(cc, "lxc.rootfs.options", "ro")
if err != nil {
return err
}
}
} else {
rbind := ""
options := []string{}
if isReadOnly {
options = append(options, "ro")
}
if isOptional {
options = append(options, "optional")
}
if isRecursive {
rbind = "r"
}
if isFile {
options = append(options, "create=file")
} else {
options = append(options, "create=dir")
}
err = lxcSetConfigItem(cc, "lxc.mount.entry", fmt.Sprintf("%s %s none %sbind,%s", devPath, tgtPath, rbind, strings.Join(options, ",")))
if err != nil {
return err
}
}
}
}
// Setup shmounts
err = lxcSetConfigItem(cc, "lxc.mount.entry", fmt.Sprintf("%s dev/.lxd-mounts none bind,create=dir 0 0", shared.VarPath("shmounts", c.Name())))
if err != nil {
return err
}
// Apply raw.lxc
if lxcConfig, ok := c.expandedConfig["raw.lxc"]; ok {
f, err := ioutil.TempFile("", "lxd_config_")
if err != nil {
return err
}
err = shared.WriteAll(f, []byte(lxcConfig))
f.Close()
defer os.Remove(f.Name())
if err != nil {
return err
}
if err := cc.LoadConfigFile(f.Name()); err != nil {
return fmt.Errorf("Failed to load raw.lxc")
}
}
c.c = cc
return nil
}
// Config handling
func (c *containerLXC) expandConfig() error {
config := map[string]string{}
// Apply all the profiles
for _, name := range c.profiles {
profileConfig, err := dbProfileConfig(c.daemon.db, name)
if err != nil {
return err
}
for k, v := range profileConfig {
config[k] = v
}
}
// Stick the local config on top
for k, v := range c.localConfig {
config[k] = v
}
c.expandedConfig = config
return nil
}
func (c *containerLXC) expandDevices() error {
devices := shared.Devices{}
// Apply all the profiles
for _, p := range c.profiles {
profileDevices, err := dbDevices(c.daemon.db, p, true)
if err != nil {
return err
}
for k, v := range profileDevices {
devices[k] = v
}
}
// Stick local devices on top
for k, v := range c.localDevices {
devices[k] = v
}
c.expandedDevices = devices
return nil
}
// Start functions
func (c *containerLXC) startCommon() (string, error) {
// Load the go-lxc struct
err := c.initLXC()
if err != nil {
return "", err
}
// Check that we're not already running
if c.IsRunning() {
return "", fmt.Errorf("The container is already running")
}
// Load any required kernel modules
kernelModules := c.expandedConfig["linux.kernel_modules"]
if kernelModules != "" {
for _, module := range strings.Split(kernelModules, ",") {
module = strings.TrimPrefix(module, " ")
out, err := exec.Command("modprobe", module).CombinedOutput()
if err != nil {
return "", fmt.Errorf("Failed to load kernel module '%s': %s", module, out)
}
}
}
/* Deal with idmap changes */
idmap := c.IdmapSet()
lastIdmap, err := c.LastIdmapSet()
if err != nil {
return "", err
}
var jsonIdmap string
if idmap != nil {
idmapBytes, err := json.Marshal(idmap.Idmap)
if err != nil {
return "", err
}
jsonIdmap = string(idmapBytes)
} else {
jsonIdmap = "[]"
}
if !reflect.DeepEqual(idmap, lastIdmap) {
shared.Debugf("Container idmap changed, remapping")
err := c.StorageStart()
if err != nil {
return "", err
}
if lastIdmap != nil {
err = lastIdmap.UnshiftRootfs(c.RootfsPath())
if err != nil {
c.StorageStop()
return "", err
}
}
if idmap != nil {
err = idmap.ShiftRootfs(c.RootfsPath())
if err != nil {
c.StorageStop()
return "", err
}
}
var mode os.FileMode
var uid int
var gid int
if c.IsPrivileged() {
mode = 0700
} else {
mode = 0755
if idmap != nil {
uid, gid = idmap.ShiftIntoNs(0, 0)
}
}
err = os.Chmod(c.Path(), mode)
if err != nil {
return "", err
}
err = os.Chown(c.Path(), uid, gid)
if err != nil {
return "", err
}
err = c.StorageStop()
if err != nil {
return "", err
}
}
err = c.ConfigKeySet("volatile.last_state.idmap", jsonIdmap)
if err != nil {
return "", err
}
// Generate the Seccomp profile
if err := SeccompCreateProfile(c); err != nil {
return "", err
}
// Cleanup any existing leftover devices
c.removeUnixDevices()
c.removeDiskDevices()
// Create the devices
for k, m := range c.expandedDevices {
if shared.StringInSlice(m["type"], []string{"unix-char", "unix-block"}) {
// Unix device
devPath, err := c.createUnixDevice(k, m)
if err != nil {
return "", err
}
// Add the new device cgroup rule
dType, dMajor, dMinor, err := deviceGetAttributes(devPath)
if err != nil {
return "", err
}
err = lxcSetConfigItem(c.c, "lxc.cgroup.devices.allow", fmt.Sprintf("%s %d:%d rwm", dType, dMajor, dMinor))
if err != nil {
return "", fmt.Errorf("Failed to add cgroup rule for device")
}
} else if m["type"] == "disk" {
// Disk device
if m["path"] != "/" {
_, err := c.createDiskDevice(k, m)
if err != nil {
return "", err
}
}
}
}
// Create any missing directory
err = os.MkdirAll(c.LogPath(), 0700)
if err != nil {
return "", err
}
err = os.MkdirAll(shared.VarPath("devices", c.Name()), 0711)
if err != nil {
return "", err
}
err = os.MkdirAll(shared.VarPath("shmounts", c.Name()), 0711)
if err != nil {
return "", err
}
// Cleanup any leftover volatile entries
netNames := []string{}
for k, v := range c.expandedDevices {
if v["type"] == "nic" {
netNames = append(netNames, k)
}
}
for k, _ := range c.localConfig {
// We only care about volatile
if !strings.HasPrefix(k, "volatile.") {
continue
}
// Confirm it's a key of format volatile.<device>.<key>
fields := strings.SplitN(k, ".", 3)
if len(fields) != 3 {
continue
}
// The only device keys we care about are name and hwaddr
if !shared.StringInSlice(fields[2], []string{"name", "hwaddr"}) {
continue
}
// Check if the device still exists
if shared.StringInSlice(fields[1], netNames) {
// Don't remove the volatile entry if the device doesn't have the matching field set
if c.expandedDevices[fields[1]][fields[2]] == "" {
continue
}
}
// Remove the volatile key from the DB
err := dbContainerConfigRemove(c.daemon.db, c.id, k)
if err != nil {
return "", err
}
// Remove the volatile key from the in-memory configs
delete(c.localConfig, k)
delete(c.expandedConfig, k)
}
// Rotate the log file
logfile := c.LogFilePath()
if shared.PathExists(logfile) {
os.Remove(logfile + ".old")
err := os.Rename(logfile, logfile+".old")
if err != nil {
return "", err
}
}
// Generate the LXC config
configPath := filepath.Join(c.LogPath(), "lxc.conf")
err = c.c.SaveConfigFile(configPath)
if err != nil {
os.Remove(configPath)
return "", err
}
return configPath, nil
}
func (c *containerLXC) Start(stateful bool) error {
// Wait for container tear down to finish
lxcStoppingContainersLock.Lock()
wgStopping, stopping := lxcStoppingContainers[c.id]
lxcStoppingContainersLock.Unlock()
if stopping {
wgStopping.Wait()
}
if err := setupSharedMounts(); err != nil {
return fmt.Errorf("Daemon failed to setup shared mounts base: %s.\nDoes security.nesting need to be turned on?", err)
}
// Run the shared start code
configPath, err := c.startCommon()
if err != nil {
return err
}
// If stateful, restore now
if stateful {
if !c.stateful {
return fmt.Errorf("Container has no existing state to restore.")
}
if err := findCriu("snapshot"); err != nil {
return err
}
if !c.IsPrivileged() {
if err := c.IdmapSet().ShiftRootfs(c.StatePath()); err != nil {
return err
}
}
out, err := exec.Command(
execPath,
"forkmigrate",
c.name,
c.daemon.lxcpath,
configPath,
c.StatePath()).CombinedOutput()
if string(out) != "" {
for _, line := range strings.Split(strings.TrimRight(string(out), "\n"), "\n") {
shared.Debugf("forkmigrate: %s", line)
}
}
CollectCRIULogFile(c, c.StatePath(), "snapshot", "restore")
if err != nil && !c.IsRunning() {
return err
}
os.RemoveAll(c.StatePath())
c.stateful = false
return dbContainerSetStateful(c.daemon.db, c.id, false)
} else if c.stateful {
/* stateless start required when we have state, let's delete it */
err := os.RemoveAll(c.StatePath())
if err != nil {
return err
}
c.stateful = false
err = dbContainerSetStateful(c.daemon.db, c.id, false)
if err != nil {
return err
}
}
// Start the LXC container
out, err := exec.Command(
execPath,
"forkstart",
c.name,
c.daemon.lxcpath,
configPath).CombinedOutput()
if string(out) != "" {
for _, line := range strings.Split(strings.TrimRight(string(out), "\n"), "\n") {
shared.Debugf("forkstart: %s", line)
}
}
if err != nil && !c.IsRunning() {
return fmt.Errorf(
"Error calling 'lxd forkstart %s %s %s': err='%v'",
c.name,
c.daemon.lxcpath,
filepath.Join(c.LogPath(), "lxc.conf"),
err)
}
return nil
}
func (c *containerLXC) StartFromMigration(imagesDir string) error {
// Run the shared start code
configPath, err := c.startCommon()
if err != nil {
return err
}
// Start the LXC container
out, err := exec.Command(
execPath,
"forkmigrate",
c.name,
c.daemon.lxcpath,
configPath,
imagesDir).CombinedOutput()
if string(out) != "" {
for _, line := range strings.Split(strings.TrimRight(string(out), "\n"), "\n") {
shared.Debugf("forkmigrate: %s", line)
}
}
if err != nil && !c.IsRunning() {
return fmt.Errorf(
"Error calling 'lxd forkmigrate %s %s %s %s': err='%v'",
c.name,
c.daemon.lxcpath,
filepath.Join(c.LogPath(), "lxc.conf"),
imagesDir,
err)
}
return nil
}
func (c *containerLXC) OnStart() error {
// Make sure we can't call go-lxc functions by mistake
c.fromHook = true
// Start the storage for this container
err := c.StorageStart()
if err != nil {
return err
}
// Load the container AppArmor profile
err = AALoadProfile(c)
if err != nil {
c.StorageStop()
return err
}
// Template anything that needs templating
key := "volatile.apply_template"
if c.localConfig[key] != "" {
// Run any template that needs running
err = c.templateApplyNow(c.localConfig[key])
if err != nil {
c.StorageStop()
return err
}
// Remove the volatile key from the DB
err := dbContainerConfigRemove(c.daemon.db, c.id, key)
if err != nil {
c.StorageStop()
return err
}
}
err = c.templateApplyNow("start")
if err != nil {
c.StorageStop()
return err
}
// Trigger a rebalance
deviceTaskSchedulerTrigger("container", c.name, "started")
// Apply network priority
if c.expandedConfig["limits.network.priority"] != "" {
go func(c *containerLXC) {
c.fromHook = false
err := c.setNetworkPriority()
if err != nil {
shared.Log.Error("Failed to apply network priority", log.Ctx{"container": c.name, "err": err})
}
}(c)
}
// Apply network limits
for name, m := range c.expandedDevices {
if m["type"] != "nic" {
continue
}
if m["limits.max"] == "" && m["limits.ingress"] == "" && m["limits.egress"] == "" {
continue
}
go func(c *containerLXC, name string, m shared.Device) {
c.fromHook = false
err = c.setNetworkLimits(name, m)
if err != nil {
shared.Log.Error("Failed to apply network limits", log.Ctx{"container": c.name, "err": err})
}
}(c, name, m)
}
return nil
}
// Container shutdown locking
func (c *containerLXC) setupStopping() *sync.WaitGroup {
// Handle locking
lxcStoppingContainersLock.Lock()
defer lxcStoppingContainersLock.Unlock()
// Existing entry
wg, stopping := lxcStoppingContainers[c.id]
if stopping {
return wg
}
// Setup new entry
lxcStoppingContainers[c.id] = &sync.WaitGroup{}
go func(wg *sync.WaitGroup, id int) {
wg.Wait()
lxcStoppingContainersLock.Lock()
defer lxcStoppingContainersLock.Unlock()
delete(lxcStoppingContainers, id)
}(lxcStoppingContainers[c.id], c.id)
return lxcStoppingContainers[c.id]
}
// Stop functions
func (c *containerLXC) Stop(stateful bool) error {
// Handle stateful stop
if stateful {
if err := findCriu("snapshot"); err != nil {
return err
}
// Cleanup any existing state
stateDir := c.StatePath()
os.RemoveAll(stateDir)
err := os.MkdirAll(stateDir, 0700)
if err != nil {
return err
}
// Checkpoint
opts := lxc.CheckpointOptions{Directory: stateDir, Stop: true, Verbose: true}
err = c.Checkpoint(opts)
err2 := CollectCRIULogFile(c, stateDir, "snapshot", "dump")
if err2 != nil {
shared.Log.Warn("failed to collect criu log file", log.Ctx{"error": err2})
}
if err != nil {
return err
}
c.stateful = true
err = dbContainerSetStateful(c.daemon.db, c.id, true)
if err != nil {
return err
}
return nil
}
// Load the go-lxc struct
err := c.initLXC()
if err != nil {
return err
}
// Attempt to freeze the container first, helps massively with fork bombs
c.Freeze()
// Handle locking
wg := c.setupStopping()
// Stop the container
wg.Add(1)
if err := c.c.Stop(); err != nil {
wg.Done()
return err
}
// Mark ourselves as done
wg.Done()
// Wait for any other teardown routines to finish
wg.Wait()
return nil
}
func (c *containerLXC) Shutdown(timeout time.Duration) error {
// Load the go-lxc struct
err := c.initLXC()
if err != nil {
return err
}
// Handle locking
wg := c.setupStopping()
// Shutdown the container
wg.Add(1)
if err := c.c.Shutdown(timeout); err != nil {
wg.Done()
return err
}
// Mark ourselves as done
wg.Done()
// Wait for any other teardown routines to finish
wg.Wait()
return nil
}
func (c *containerLXC) OnStop(target string) error {
// Get locking
lxcStoppingContainersLock.Lock()
wg, stopping := lxcStoppingContainers[c.id]
lxcStoppingContainersLock.Unlock()
if wg != nil {
wg.Add(1)
}
// Make sure we can't call go-lxc functions by mistake
c.fromHook = true
// Stop the storage for this container
err := c.StorageStop()
if err != nil {
wg.Done()
return err
}
// Unload the apparmor profile
AAUnloadProfile(c)
// FIXME: The go routine can go away once we can rely on LXC_TARGET
go func(c *containerLXC, target string, wg *sync.WaitGroup) {
c.fromHook = false
// Unlock on return
if wg != nil {
defer wg.Done()
}
if target == "unknown" && stopping {
target = "stop"
}
if target == "unknown" {
time.Sleep(5 * time.Second)
newContainer, err := containerLoadByName(c.daemon, c.Name())
if err != nil {
return
}
if newContainer.Id() != c.id {
return
}
if newContainer.IsRunning() {
return
}
}
// Clean all the unix devices
err = c.removeUnixDevices()
if err != nil {
shared.Log.Error("Unable to remove unix devices", log.Ctx{"err": err})
}
// Clean all the disk devices
err = c.removeDiskDevices()
if err != nil {
shared.Log.Error("Unable to remove disk devices", log.Ctx{"err": err})
}
// Reboot the container
if target == "reboot" {
/* This part is a hack to workaround a LXC bug where a
failure from a post-stop script doesn't prevent the container to restart. */
ephemeral := c.ephemeral
args := containerArgs{
Architecture: c.Architecture(),
Config: c.LocalConfig(),
Devices: c.LocalDevices(),
Ephemeral: false,
Profiles: c.Profiles(),
}
c.Update(args, false)
c.Stop(false)
args.Ephemeral = ephemeral
c.Update(args, true)
// Start the container again
c.Start(false)
return
}
// Trigger a rebalance
deviceTaskSchedulerTrigger("container", c.name, "stopped")
// Destroy ephemeral containers
if c.ephemeral {
c.Delete()
}
}(c, target, wg)
return nil
}
// Freezer functions
func (c *containerLXC) Freeze() error {
// Load the go-lxc struct
err := c.initLXC()
if err != nil {
return err
}
return c.c.Freeze()
}
func (c *containerLXC) Unfreeze() error {
// Load the go-lxc struct
err := c.initLXC()
if err != nil {
return err
}
return c.c.Unfreeze()
}
var LxcMonitorStateError = fmt.Errorf("Monitor is hung")
// Get lxc container state, with 1 second timeout
// If we don't get a reply, assume the lxc monitor is hung
func (c *containerLXC) getLxcState() (lxc.State, error) {
if c.IsSnapshot() {
return lxc.StateMap["STOPPED"], nil
}
monitor := make(chan lxc.State, 1)
go func(c *lxc.Container) {
monitor <- c.State()
}(c.c)
select {
case state := <-monitor:
return state, nil
case <-time.After(5 * time.Second):
return lxc.StateMap["FROZEN"], LxcMonitorStateError
}
}
func (c *containerLXC) Render() (interface{}, error) {
// Load the go-lxc struct
err := c.initLXC()
if err != nil {
return nil, err
}
// Ignore err as the arch string on error is correct (unknown)
architectureName, _ := shared.ArchitectureName(c.architecture)
if c.IsSnapshot() {
return &shared.SnapshotInfo{
Architecture: architectureName,
Config: c.localConfig,
CreationDate: c.creationDate,
Devices: c.localDevices,
Ephemeral: c.ephemeral,
ExpandedConfig: c.expandedConfig,
ExpandedDevices: c.expandedDevices,
Name: c.name,
Profiles: c.profiles,
Stateful: c.stateful,
}, nil
} else {
// FIXME: Render shouldn't directly access the go-lxc struct
cState, err := c.getLxcState()
if err != nil {
return nil, err
}
statusCode := shared.FromLXCState(int(cState))
return &shared.ContainerInfo{
Architecture: architectureName,
Config: c.localConfig,
CreationDate: c.creationDate,
Devices: c.localDevices,
Ephemeral: c.ephemeral,
ExpandedConfig: c.expandedConfig,
ExpandedDevices: c.expandedDevices,
Name: c.name,
Profiles: c.profiles,
Status: statusCode.String(),
StatusCode: statusCode,
Stateful: c.stateful,
}, nil
}
}
func (c *containerLXC) RenderState() (*shared.ContainerState, error) {
// Load the go-lxc struct
err := c.initLXC()
if err != nil {
return nil, err
}
cState, err := c.getLxcState()
if err != nil {
return nil, err
}
statusCode := shared.FromLXCState(int(cState))
status := shared.ContainerState{
Status: statusCode.String(),
StatusCode: statusCode,
}
if c.IsRunning() {
pid := c.InitPID()
status.Disk = c.diskState()
status.Memory = c.memoryState()
status.Network = c.networkState()
status.Pid = int64(pid)
status.Processes = c.processesState()
}
return &status, nil
}
func (c *containerLXC) Snapshots() ([]container, error) {
// Get all the snapshots
snaps, err := dbContainerGetSnapshots(c.daemon.db, c.name)
if err != nil {
return nil, err
}
// Build the snapshot list
containers := []container{}
for _, snapName := range snaps {
snap, err := containerLoadByName(c.daemon, snapName)
if err != nil {
return nil, err
}
containers = append(containers, snap)
}
return containers, nil
}
func (c *containerLXC) Restore(sourceContainer container) error {
// Check if we can restore the container
err := c.storage.ContainerCanRestore(c, sourceContainer)
if err != nil {
return err
}
/* let's also check for CRIU if necessary, before doing a bunch of
* filesystem manipulations
*/
if shared.PathExists(c.StatePath()) {
if err := findCriu("snapshot"); err != nil {
return err
}
}
// Stop the container
wasRunning := false
if c.IsRunning() {
wasRunning = true
if err := c.Stop(false); err != nil {
shared.Log.Error(
"Could not stop container",
log.Ctx{
"container": c.Name(),
"err": err})
return err
}
}
// Restore the rootfs
err = c.storage.ContainerRestore(c, sourceContainer)
if err != nil {
shared.Log.Error("Restoring the filesystem failed",
log.Ctx{
"source": sourceContainer.Name(),
"destination": c.Name()})
return err
}
// Restore the configuration
args := containerArgs{
Architecture: sourceContainer.Architecture(),
Config: sourceContainer.LocalConfig(),
Devices: sourceContainer.LocalDevices(),
Ephemeral: sourceContainer.IsEphemeral(),
Profiles: sourceContainer.Profiles(),
}
err = c.Update(args, false)
if err != nil {
shared.Log.Error("Restoring the configuration failed",
log.Ctx{
"source": sourceContainer.Name(),
"destination": c.Name()})
return err
}
// If the container wasn't running but was stateful, should we restore
// it as running?
if shared.PathExists(c.StatePath()) {
configPath, err := c.startCommon()
if err != nil {
return err
}
if !c.IsPrivileged() {
if err := c.IdmapSet().ShiftRootfs(c.StatePath()); err != nil {
return err
}
}
out, err := exec.Command(
execPath,
"forkmigrate",
c.name,
c.daemon.lxcpath,
configPath,
c.StatePath()).CombinedOutput()
if string(out) != "" {
for _, line := range strings.Split(strings.TrimRight(string(out), "\n"), "\n") {
shared.Debugf("forkmigrate: %s", line)
}
}
CollectCRIULogFile(c, c.StatePath(), "snapshot", "restore")
if err != nil {
return err
}
// Remove the state from the parent container; we only keep
// this in snapshots.
err2 := os.RemoveAll(c.StatePath())
if err2 != nil {
shared.Log.Error("failed to delete snapshot state", "path", c.StatePath(), "err", err2)
}
if err != nil {
return err
}
return nil
}
// Restart the container
if wasRunning {
return c.Start(false)
}
return nil
}
func (c *containerLXC) cleanup() {
// Unmount any leftovers
c.removeUnixDevices()
c.removeDiskDevices()
// Remove the security profiles
AADeleteProfile(c)
SeccompDeleteProfile(c)
// Remove the devices path
os.Remove(c.DevicesPath())
// Remove the shmounts path
os.RemoveAll(shared.VarPath("shmounts", c.Name()))
}
func (c *containerLXC) Delete() error {
if c.IsSnapshot() {
// Remove the snapshot
if err := c.storage.ContainerSnapshotDelete(c); err != nil {
shared.Log.Warn("failed to delete snapshot", "name", c.Name(), "err", err)
}
} else {
// Remove all snapshot
if err := containerDeleteSnapshots(c.daemon, c.Name()); err != nil {
shared.Log.Warn("failed to delete snapshots", "name", c.Name(), "err", err)
}
// Clean things up
c.cleanup()
// Delete the container from disk
if shared.PathExists(c.Path()) {
if err := c.storage.ContainerDelete(c); err != nil {
return err
}
}
}
// Remove the database record
if err := dbContainerRemove(c.daemon.db, c.Name()); err != nil {
return err
}
return nil
}
func (c *containerLXC) Rename(newName string) error {
oldName := c.Name()
// Sanity checks
if !c.IsSnapshot() && !shared.ValidHostname(newName) {
return fmt.Errorf("Invalid container name")
}
if c.IsRunning() {
return fmt.Errorf("renaming of running container not allowed")
}
// Clean things up
c.cleanup()
// Rename the logging path
os.RemoveAll(shared.LogPath(newName))
if shared.PathExists(c.LogPath()) {
err := os.Rename(c.LogPath(), shared.LogPath(newName))
if err != nil {
return err
}
}
// Rename the storage entry
if c.IsSnapshot() {
if err := c.storage.ContainerSnapshotRename(c, newName); err != nil {
return err
}
} else {
if err := c.storage.ContainerRename(c, newName); err != nil {
return err
}
}
// Rename the database entry
if err := dbContainerRename(c.daemon.db, oldName, newName); err != nil {
return err
}
if !c.IsSnapshot() {
// Rename all the snapshots
results, err := dbContainerGetSnapshots(c.daemon.db, oldName)
if err != nil {
return err
}
for _, sname := range results {
// Rename the snapshot
baseSnapName := filepath.Base(sname)
newSnapshotName := newName + shared.SnapshotDelimiter + baseSnapName
if err := dbContainerRename(c.daemon.db, sname, newSnapshotName); err != nil {
return err
}
}
}
// Set the new name in the struct
c.name = newName
// Invalidate the go-lxc cache
c.c = nil
return nil
}
func (c *containerLXC) CGroupGet(key string) (string, error) {
// Load the go-lxc struct
err := c.initLXC()
if err != nil {
return "", err
}
// Make sure the container is running
if !c.IsRunning() {
return "", fmt.Errorf("Can't get cgroups on a stopped container")
}
value := c.c.CgroupItem(key)
return strings.Join(value, "\n"), nil
}
func (c *containerLXC) CGroupSet(key string, value string) error {
// Load the go-lxc struct
err := c.initLXC()
if err != nil {
return err
}
// Make sure the container is running
if !c.IsRunning() {
return fmt.Errorf("Can't set cgroups on a stopped container")
}
err = c.c.SetCgroupItem(key, value)
if err != nil {
return fmt.Errorf("Failed to set cgroup %s=\"%s\": %s", key, value, err)
}
return nil
}
func (c *containerLXC) ConfigKeySet(key string, value string) error {
c.localConfig[key] = value
args := containerArgs{
Architecture: c.architecture,
Config: c.localConfig,
Devices: c.localDevices,
Ephemeral: c.ephemeral,
Profiles: c.profiles,
}
return c.Update(args, false)
}
func (c *containerLXC) Update(args containerArgs, userRequested bool) error {
// Set sane defaults for unset keys
if args.Architecture == 0 {
args.Architecture = c.architecture
}
if args.Config == nil {
args.Config = map[string]string{}
}
if args.Devices == nil {
args.Devices = shared.Devices{}
}
if args.Profiles == nil {
args.Profiles = []string{}
}
// Validate the new config
err := containerValidConfig(args.Config, false, false)
if err != nil {
return err
}
// Validate the new devices
err = containerValidDevices(args.Devices, false, false)
if err != nil {
return err
}
// Validate the new profiles
profiles, err := dbProfiles(c.daemon.db)
if err != nil {
return err
}
for _, name := range args.Profiles {
if !shared.StringInSlice(name, profiles) {
return fmt.Errorf("Profile doesn't exist: %s", name)
}
}
// Validate the new architecture
if args.Architecture != 0 {
_, err = shared.ArchitectureName(args.Architecture)
if err != nil {
return fmt.Errorf("Invalid architecture id: %s", err)
}
}
// Check that volatile wasn't modified
if userRequested {
for k, v := range args.Config {
if strings.HasPrefix(k, "volatile.") && c.localConfig[k] != v {
return fmt.Errorf("Volatile keys are read-only.")
}
}
for k, v := range c.localConfig {
if strings.HasPrefix(k, "volatile.") && args.Config[k] != v {
return fmt.Errorf("Volatile keys are read-only.")
}
}
}
// Get a copy of the old configuration
oldArchitecture := 0
err = shared.DeepCopy(&c.architecture, &oldArchitecture)
if err != nil {
return err
}
oldEphemeral := false
err = shared.DeepCopy(&c.ephemeral, &oldEphemeral)
if err != nil {
return err
}
oldExpandedDevices := shared.Devices{}
err = shared.DeepCopy(&c.expandedDevices, &oldExpandedDevices)
if err != nil {
return err
}
oldExpandedConfig := map[string]string{}
err = shared.DeepCopy(&c.expandedConfig, &oldExpandedConfig)
if err != nil {
return err
}
oldLocalDevices := shared.Devices{}
err = shared.DeepCopy(&c.localDevices, &oldLocalDevices)
if err != nil {
return err
}
oldLocalConfig := map[string]string{}
err = shared.DeepCopy(&c.localConfig, &oldLocalConfig)
if err != nil {
return err
}
oldProfiles := []string{}
err = shared.DeepCopy(&c.profiles, &oldProfiles)
if err != nil {
return err
}
// Define a function which reverts everything
undoChanges := func() {
c.architecture = oldArchitecture
c.ephemeral = oldEphemeral
c.expandedConfig = oldExpandedConfig
c.expandedDevices = oldExpandedDevices
c.localConfig = oldLocalConfig
c.localDevices = oldLocalDevices
c.profiles = oldProfiles
c.initLXC()
deviceTaskSchedulerTrigger("container", c.name, "changed")
}
// Apply the various changes
c.architecture = args.Architecture
c.ephemeral = args.Ephemeral
c.localConfig = args.Config
c.localDevices = args.Devices
c.profiles = args.Profiles
// Expand the config and refresh the LXC config
err = c.expandConfig()
if err != nil {
undoChanges()
return err
}
err = c.expandDevices()
if err != nil {
undoChanges()
return err
}
err = c.initLXC()
if err != nil {
undoChanges()
return err
}
// Diff the configurations
changedConfig := []string{}
for key, _ := range oldExpandedConfig {
if oldExpandedConfig[key] != c.expandedConfig[key] {
if !shared.StringInSlice(key, changedConfig) {
changedConfig = append(changedConfig, key)
}
}
}
for key, _ := range c.expandedConfig {
if oldExpandedConfig[key] != c.expandedConfig[key] {
if !shared.StringInSlice(key, changedConfig) {
changedConfig = append(changedConfig, key)
}
}
}
// Diff the devices
removeDevices, addDevices, updateDevices := oldExpandedDevices.Update(c.expandedDevices)
// Do some validation of the config diff
err = containerValidConfig(c.expandedConfig, false, true)
if err != nil {
undoChanges()
return err
}
// Do some validation of the devices diff
err = containerValidDevices(c.expandedDevices, false, true)
if err != nil {
undoChanges()
return err
}
// If apparmor changed, re-validate the apparmor profile
for _, key := range changedConfig {
if key == "raw.apparmor" || key == "security.nesting" {
err = AAParseProfile(c)
if err != nil {
undoChanges()
return err
}
}
}
// Apply disk quota changes
for _, m := range addDevices {
var oldRootfsSize string
for _, m := range oldExpandedDevices {
if m["type"] == "disk" && m["path"] == "/" {
oldRootfsSize = m["size"]
break
}
}
if m["size"] != oldRootfsSize {
size, err := shared.ParseByteSizeString(m["size"])
if err != nil {
undoChanges()
return err
}
err = c.storage.ContainerSetQuota(c, size)
if err != nil {
undoChanges()
return err
}
}
}
// Apply the live changes
if c.IsRunning() {
// Confirm that the rootfs source didn't change
var oldRootfs shared.Device
for _, m := range oldExpandedDevices {
if m["type"] == "disk" && m["path"] == "/" {
oldRootfs = m
break
}
}
var newRootfs shared.Device
for _, m := range c.expandedDevices {
if m["type"] == "disk" && m["path"] == "/" {
newRootfs = m
break
}
}
if oldRootfs["source"] != newRootfs["source"] {
undoChanges()
return fmt.Errorf("Cannot change the rootfs path of a running container")
}
// Live update the container config
for _, key := range changedConfig {
value := c.expandedConfig[key]
if key == "raw.apparmor" || key == "security.nesting" {
// Update the AppArmor profile
err = AALoadProfile(c)
if err != nil {
undoChanges()
return err
}
} else if key == "linux.kernel_modules" && value != "" {
for _, module := range strings.Split(value, ",") {
module = strings.TrimPrefix(module, " ")
out, err := exec.Command("modprobe", module).CombinedOutput()
if err != nil {
undoChanges()
return fmt.Errorf("Failed to load kernel module '%s': %s", module, out)
}
}
} else if key == "limits.disk.priority" {
if !cgBlkioController {
continue
}
priorityInt := 5
diskPriority := c.expandedConfig["limits.disk.priority"]
if diskPriority != "" {
priorityInt, err = strconv.Atoi(diskPriority)
if err != nil {
return err
}
}
err = c.CGroupSet("blkio.weight", fmt.Sprintf("%d", priorityInt*100))
if err != nil {
return err
}
} else if key == "limits.memory" || strings.HasPrefix(key, "limits.memory.") {
// Skip if no memory CGroup
if !cgMemoryController {
continue
}
// Set the new memory limit
memory := c.expandedConfig["limits.memory"]
memoryEnforce := c.expandedConfig["limits.memory.enforce"]
memorySwap := c.expandedConfig["limits.memory.swap"]
// Parse memory
if memory == "" {
memory = "-1"
} else if strings.HasSuffix(memory, "%") {
percent, err := strconv.ParseInt(strings.TrimSuffix(memory, "%"), 10, 64)
if err != nil {
return err
}
memoryTotal, err := deviceTotalMemory()
if err != nil {
return err
}
memory = fmt.Sprintf("%d", int64((memoryTotal/100)*percent))
} else {
valueInt, err := shared.ParseByteSizeString(memory)
if err != nil {
undoChanges()
return err
}
memory = fmt.Sprintf("%d", valueInt)
}
// Reset everything
if cgSwapAccounting {
err = c.CGroupSet("memory.memsw.limit_in_bytes", "-1")
if err != nil {
undoChanges()
return err
}
}
err = c.CGroupSet("memory.limit_in_bytes", "-1")
if err != nil {
undoChanges()
return err
}
err = c.CGroupSet("memory.soft_limit_in_bytes", "-1")
if err != nil {
undoChanges()
return err
}
// Set the new values
if memoryEnforce == "soft" {
// Set new limit
err = c.CGroupSet("memory.soft_limit_in_bytes", memory)
if err != nil {
undoChanges()
return err
}
} else {
if cgSwapAccounting && (memorySwap == "" || shared.IsTrue(memorySwap)) {
err = c.CGroupSet("memory.limit_in_bytes", memory)
if err != nil {
undoChanges()
return err
}
err = c.CGroupSet("memory.memsw.limit_in_bytes", memory)
if err != nil {
undoChanges()
return err
}
} else {
err = c.CGroupSet("memory.limit_in_bytes", memory)
if err != nil {
undoChanges()
return err
}
}
}
// Configure the swappiness
if key == "limits.memory.swap" || key == "limits.memory.swap.priority" {
memorySwap := c.expandedConfig["limits.memory.swap"]
memorySwapPriority := c.expandedConfig["limits.memory.swap.priority"]
if memorySwap != "" && !shared.IsTrue(memorySwap) {
err = c.CGroupSet("memory.swappiness", "0")
if err != nil {
undoChanges()
return err
}
} else {
priority := 0
if memorySwapPriority != "" {
priority, err = strconv.Atoi(memorySwapPriority)
if err != nil {
undoChanges()
return err
}
}
err = c.CGroupSet("memory.swappiness", fmt.Sprintf("%d", 60-10+priority))
if err != nil {
undoChanges()
return err
}
}
}
} else if key == "limits.network.priority" {
err := c.setNetworkPriority()
if err != nil {
return err
}
} else if key == "limits.cpu" {
// Trigger a scheduler re-run
deviceTaskSchedulerTrigger("container", c.name, "changed")
} else if key == "limits.cpu.priority" || key == "limits.cpu.allowance" {
// Skip if no cpu CGroup
if !cgCpuController {
continue
}
// Apply new CPU limits
cpuShares, cpuCfsQuota, cpuCfsPeriod, err := deviceParseCPU(c.expandedConfig["limits.cpu.allowance"], c.expandedConfig["limits.cpu.priority"])
if err != nil {
undoChanges()
return err
}
err = c.CGroupSet("cpu.shares", cpuShares)
if err != nil {
undoChanges()
return err
}
err = c.CGroupSet("cpu.cfs_period_us", cpuCfsPeriod)
if err != nil {
undoChanges()
return err
}
err = c.CGroupSet("cpu.cfs_quota_us", cpuCfsQuota)
if err != nil {
undoChanges()
return err
}
} else if key == "limits.processes" {
if !cgPidsController {
continue
}
if value == "" {
err = c.CGroupSet("pids.max", "max")
if err != nil {
undoChanges()
return err
}
} else {
valueInt, err := strconv.ParseInt(value, 10, 64)
if err != nil {
undoChanges()
return err
}
err = c.CGroupSet("pids.max", fmt.Sprintf("%d", valueInt))
if err != nil {
undoChanges()
return err
}
}
}
}
// Live update the devices
for k, m := range removeDevices {
if shared.StringInSlice(m["type"], []string{"unix-char", "unix-block"}) {
err = c.removeUnixDevice(k, m)
if err != nil {
undoChanges()
return err
}
} else if m["type"] == "disk" && m["path"] != "/" {
err = c.removeDiskDevice(k, m)
if err != nil {
undoChanges()
return err
}
} else if m["type"] == "nic" {
err = c.removeNetworkDevice(k, m)
if err != nil {
undoChanges()
return err
}
}
}
for k, m := range addDevices {
if shared.StringInSlice(m["type"], []string{"unix-char", "unix-block"}) {
err = c.insertUnixDevice(k, m)
if err != nil {
undoChanges()
return err
}
} else if m["type"] == "disk" && m["path"] != "/" {
err = c.insertDiskDevice(k, m)
if err != nil {
undoChanges()
return err
}
} else if m["type"] == "nic" {
err = c.insertNetworkDevice(k, m)
if err != nil {
undoChanges()
return err
}
}
}
updateDiskLimit := false
for k, m := range updateDevices {
if m["type"] == "disk" {
updateDiskLimit = true
} else if m["type"] == "nic" {
err = c.setNetworkLimits(k, m)
if err != nil {
undoChanges()
return err
}
}
}
// Disk limits parse all devices, so just apply them once
if updateDiskLimit && cgBlkioController {
diskLimits, err := c.getDiskLimits()
if err != nil {
undoChanges()
return err
}
for block, limit := range diskLimits {
err = c.CGroupSet("blkio.throttle.read_bps_device", fmt.Sprintf("%s %d", block, limit.readBps))
if err != nil {
undoChanges()
return err
}
err = c.CGroupSet("blkio.throttle.read_iops_device", fmt.Sprintf("%s %d", block, limit.readIops))
if err != nil {
undoChanges()
return err
}
err = c.CGroupSet("blkio.throttle.write_bps_device", fmt.Sprintf("%s %d", block, limit.writeBps))
if err != nil {
undoChanges()
return err
}
err = c.CGroupSet("blkio.throttle.write_iops_device", fmt.Sprintf("%s %d", block, limit.writeIops))
if err != nil {
undoChanges()
return err
}
}
}
}
// Finally, apply the changes to the database
tx, err := dbBegin(c.daemon.db)
if err != nil {
undoChanges()
return err
}
err = dbContainerConfigClear(tx, c.id)
if err != nil {
tx.Rollback()
undoChanges()
return err
}
err = dbContainerConfigInsert(tx, c.id, args.Config)
if err != nil {
tx.Rollback()
undoChanges()
return err
}
err = dbContainerProfilesInsert(tx, c.id, args.Profiles)
if err != nil {
tx.Rollback()
undoChanges()
return err
}
err = dbDevicesAdd(tx, "container", int64(c.id), args.Devices)
if err != nil {
tx.Rollback()
undoChanges()
return err
}
err = dbContainerUpdate(tx, c.id, c.architecture, c.ephemeral)
if err != nil {
tx.Rollback()
undoChanges()
return err
}
if err := txCommit(tx); err != nil {
undoChanges()
return err
}
return nil
}
func (c *containerLXC) Export(w io.Writer) error {
if c.IsRunning() {
return fmt.Errorf("Cannot export a running container as an image")
}
// Start the storage
err := c.StorageStart()
if err != nil {
return err
}
defer c.StorageStop()
// Unshift the container
idmap, err := c.LastIdmapSet()
if err != nil {
return err
}
if idmap != nil {
if err := idmap.UnshiftRootfs(c.RootfsPath()); err != nil {
return err
}
defer idmap.ShiftRootfs(c.RootfsPath())
}
// Create the tarball
tw := tar.NewWriter(w)
// Keep track of the first path we saw for each path with nlink>1
linkmap := map[uint64]string{}
cDir := c.Path()
// Path inside the tar image is the pathname starting after cDir
offset := len(cDir) + 1
writeToTar := func(path string, fi os.FileInfo, err error) error {
if err := c.tarStoreFile(linkmap, offset, tw, path, fi); err != nil {
shared.Debugf("Error tarring up %s: %s", path, err)
return err
}
return nil
}
// Look for metadata.yaml
fnam := filepath.Join(cDir, "metadata.yaml")
if !shared.PathExists(fnam) {
// Generate a new metadata.yaml
f, err := ioutil.TempFile("", "lxd_lxd_metadata_")
if err != nil {
tw.Close()
return err
}
defer os.Remove(f.Name())
// Get the container's architecture
var arch string
if c.IsSnapshot() {
parentName := strings.SplitN(c.name, shared.SnapshotDelimiter, 2)[0]
parent, err := containerLoadByName(c.daemon, parentName)
if err != nil {
tw.Close()
return err
}
arch, _ = shared.ArchitectureName(parent.Architecture())
} else {
arch, _ = shared.ArchitectureName(c.architecture)
}
if arch == "" {
arch, err = shared.ArchitectureName(c.daemon.architectures[0])
if err != nil {
return err
}
}
// Fill in the metadata
meta := imageMetadata{}
meta.Architecture = arch
meta.CreationDate = time.Now().UTC().Unix()
data, err := yaml.Marshal(&meta)
if err != nil {
tw.Close()
return err
}
// Write the actual file
f.Write(data)
f.Close()
fi, err := os.Lstat(f.Name())
if err != nil {
tw.Close()
return err
}
tmpOffset := len(path.Dir(f.Name())) + 1
if err := c.tarStoreFile(linkmap, tmpOffset, tw, f.Name(), fi); err != nil {
shared.Debugf("Error writing to tarfile: %s", err)
tw.Close()
return err
}
fnam = f.Name()
} else {
// Include metadata.yaml in the tarball
fi, err := os.Lstat(fnam)
if err != nil {
shared.Debugf("Error statting %s during export", fnam)
tw.Close()
return err
}
if err := c.tarStoreFile(linkmap, offset, tw, fnam, fi); err != nil {
shared.Debugf("Error writing to tarfile: %s", err)
tw.Close()
return err
}
}
// Include all the rootfs files
fnam = c.RootfsPath()
filepath.Walk(fnam, writeToTar)
// Include all the templates
fnam = c.TemplatesPath()
if shared.PathExists(fnam) {
filepath.Walk(fnam, writeToTar)
}
return tw.Close()
}
func (c *containerLXC) Checkpoint(opts lxc.CheckpointOptions) error {
// Load the go-lxc struct
err := c.initLXC()
if err != nil {
return err
}
return c.c.Checkpoint(opts)
}
func (c *containerLXC) TemplateApply(trigger string) error {
// "create" and "copy" are deferred until next start
if shared.StringInSlice(trigger, []string{"create", "copy"}) {
// The two events are mutually exclusive so only keep the last one
err := c.ConfigKeySet("volatile.apply_template", trigger)
if err != nil {
return err
}
}
return c.templateApplyNow(trigger)
}
func (c *containerLXC) templateApplyNow(trigger string) error {
// If there's no metadata, just return
fname := filepath.Join(c.Path(), "metadata.yaml")
if !shared.PathExists(fname) {
return nil
}
// Parse the metadata
content, err := ioutil.ReadFile(fname)
if err != nil {
return err
}
metadata := new(imageMetadata)
err = yaml.Unmarshal(content, &metadata)
if err != nil {
return fmt.Errorf("Could not parse %s: %v", fname, err)
}
// Go through the templates
for templatePath, template := range metadata.Templates {
var w *os.File
// Check if the template should be applied now
found := false
for _, tplTrigger := range template.When {
if tplTrigger == trigger {
found = true
break
}
}
if !found {
continue
}
// Open the file to template, create if needed
fullpath := filepath.Join(c.RootfsPath(), strings.TrimLeft(templatePath, "/"))
if shared.PathExists(fullpath) {
if template.CreateOnly {
continue
}
// Open the existing file
w, err = os.Create(fullpath)
if err != nil {
return err
}
} else {
// Create a new one
uid := 0
gid := 0
// Get the right uid and gid for the container
if !c.IsPrivileged() {
uid, gid = c.idmapset.ShiftIntoNs(0, 0)
}
// Create the directories leading to the file
shared.MkdirAllOwner(path.Dir(fullpath), 0755, uid, gid)
// Create the file itself
w, err = os.Create(fullpath)
if err != nil {
return err
}
// Fix ownership and mode
if !c.IsPrivileged() {
w.Chown(uid, gid)
}
w.Chmod(0644)
}
defer w.Close()
// Read the template
tplString, err := ioutil.ReadFile(filepath.Join(c.TemplatesPath(), template.Template))
if err != nil {
return err
}
tpl, err := pongo2.FromString("{% autoescape off %}" + string(tplString) + "{% endautoescape %}")
if err != nil {
return err
}
// Figure out the architecture
arch, err := shared.ArchitectureName(c.architecture)
if err != nil {
arch, err = shared.ArchitectureName(c.daemon.architectures[0])
if err != nil {
return err
}
}
// Generate the metadata
containerMeta := make(map[string]string)
containerMeta["name"] = c.name
containerMeta["architecture"] = arch
if c.ephemeral {
containerMeta["ephemeral"] = "true"
} else {
containerMeta["ephemeral"] = "false"
}
if c.IsPrivileged() {
containerMeta["privileged"] = "true"
} else {
containerMeta["privileged"] = "false"
}
configGet := func(confKey, confDefault *pongo2.Value) *pongo2.Value {
val, ok := c.expandedConfig[confKey.String()]
if !ok {
return confDefault
}
return pongo2.AsValue(strings.TrimRight(val, "\r\n"))
}
// Render the template
tpl.ExecuteWriter(pongo2.Context{"trigger": trigger,
"path": templatePath,
"container": containerMeta,
"config": c.expandedConfig,
"devices": c.expandedDevices,
"properties": template.Properties,
"config_get": configGet}, w)
}
return nil
}
func (c *containerLXC) FilePull(srcpath string, dstpath string) (int, int, os.FileMode, error) {
// Setup container storage if needed
if !c.IsRunning() {
err := c.StorageStart()
if err != nil {
return -1, -1, 0, err
}
}
// Get the file from the container
out, err := exec.Command(
execPath,
"forkgetfile",
c.RootfsPath(),
fmt.Sprintf("%d", c.InitPID()),
dstpath,
srcpath,
).CombinedOutput()
// Tear down container storage if needed
if !c.IsRunning() {
err := c.StorageStop()
if err != nil {
return -1, -1, 0, err
}
}
uid := -1
gid := -1
mode := -1
// Process forkgetfile response
for _, line := range strings.Split(strings.TrimRight(string(out), "\n"), "\n") {
if line == "" {
continue
}
// Extract errors
if strings.HasPrefix(line, "error: ") {
return -1, -1, 0, fmt.Errorf(strings.TrimPrefix(line, "error: "))
}
// Extract the uid
if strings.HasPrefix(line, "uid: ") {
uid, err = strconv.Atoi(strings.TrimPrefix(line, "uid: "))
if err != nil {
return -1, -1, 0, err
}
continue
}
// Extract the gid
if strings.HasPrefix(line, "gid: ") {
gid, err = strconv.Atoi(strings.TrimPrefix(line, "gid: "))
if err != nil {
return -1, -1, 0, err
}
continue
}
// Extract the mode
if strings.HasPrefix(line, "mode: ") {
mode, err = strconv.Atoi(strings.TrimPrefix(line, "mode: "))
if err != nil {
return -1, -1, 0, err
}
continue
}
shared.Debugf("forkgetfile: %s", line)
}
if err != nil {
return -1, -1, 0, fmt.Errorf(
"Error calling 'lxd forkgetfile %s %d %s': err='%v'",
dstpath,
c.InitPID(),
srcpath,
err)
}
// Unmap uid and gid if needed
idmapset, err := c.LastIdmapSet()
if err != nil {
return -1, -1, 0, err
}
if idmapset != nil {
uid, gid = idmapset.ShiftFromNs(uid, gid)
}
return uid, gid, os.FileMode(mode), nil
}
func (c *containerLXC) FilePush(srcpath string, dstpath string, uid int, gid int, mode int) error {
var rootUid = 0
var rootGid = 0
// Map uid and gid if needed
idmapset, err := c.LastIdmapSet()
if err != nil {
return err
}
if idmapset != nil {
uid, gid = idmapset.ShiftIntoNs(uid, gid)
rootUid, rootGid = idmapset.ShiftIntoNs(0, 0)
}
// Setup container storage if needed
if !c.IsRunning() {
err := c.StorageStart()
if err != nil {
return err
}
}
// Push the file to the container
out, err := exec.Command(
execPath,
"forkputfile",
c.RootfsPath(),
fmt.Sprintf("%d", c.InitPID()),
srcpath,
dstpath,
fmt.Sprintf("%d", uid),
fmt.Sprintf("%d", gid),
fmt.Sprintf("%d", mode),
fmt.Sprintf("%d", rootUid),
fmt.Sprintf("%d", rootGid),
fmt.Sprintf("%d", int(os.FileMode(0640)&os.ModePerm)),
).CombinedOutput()
// Tear down container storage if needed
if !c.IsRunning() {
err := c.StorageStop()
if err != nil {
return err
}
}
// Process forkputfile response
if string(out) != "" {
if strings.HasPrefix(string(out), "error:") {
return fmt.Errorf(strings.TrimPrefix(strings.TrimSuffix(string(out), "\n"), "error: "))
}
for _, line := range strings.Split(strings.TrimRight(string(out), "\n"), "\n") {
shared.Debugf("forkgetfile: %s", line)
}
}
if err != nil {
return fmt.Errorf(
"Error calling 'lxd forkputfile %s %d %s %d %d %d': err='%v'",
srcpath,
c.InitPID(),
dstpath,
uid,
gid,
mode,
err)
}
return nil
}
func (c *containerLXC) Exec(command []string, env map[string]string, stdin *os.File, stdout *os.File, stderr *os.File) (int, error) {
envSlice := []string{}
for k, v := range env {
envSlice = append(envSlice, fmt.Sprintf("%s=%s", k, v))
}
args := []string{execPath, "forkexec", c.name, c.daemon.lxcpath, filepath.Join(c.LogPath(), "lxc.conf")}
args = append(args, "--")
args = append(args, "env")
args = append(args, envSlice...)
args = append(args, "--")
args = append(args, "cmd")
args = append(args, command...)
cmd := exec.Cmd{}
cmd.Path = execPath
cmd.Args = args
cmd.Stdin = stdin
cmd.Stdout = stdout
cmd.Stderr = stderr
err := cmd.Run()
if err != nil {
exitErr, ok := err.(*exec.ExitError)
if ok {
status, ok := exitErr.Sys().(syscall.WaitStatus)
if ok {
return status.ExitStatus(), nil
}
}
return -1, err
}
return 0, nil
}
func (c *containerLXC) diskState() map[string]shared.ContainerStateDisk {
disk := map[string]shared.ContainerStateDisk{}
for name, d := range c.expandedDevices {
if d["type"] != "disk" {
continue
}
if d["path"] != "/" {
continue
}
usage, err := c.storage.ContainerGetUsage(c)
if err != nil {
continue
}
disk[name] = shared.ContainerStateDisk{Usage: usage}
}
return disk
}
func (c *containerLXC) memoryState() shared.ContainerStateMemory {
memory := shared.ContainerStateMemory{}
if !cgMemoryController {
return memory
}
// Memory in bytes
value, err := c.CGroupGet("memory.usage_in_bytes")
valueInt, err := strconv.ParseInt(value, 10, 64)
if err != nil {
valueInt = -1
}
memory.Usage = valueInt
// Memory peak in bytes
value, err = c.CGroupGet("memory.max_usage_in_bytes")
valueInt, err = strconv.ParseInt(value, 10, 64)
if err != nil {
valueInt = -1
}
memory.UsagePeak = valueInt
if cgSwapAccounting {
// Swap in bytes
value, err := c.CGroupGet("memory.memsw.usage_in_bytes")
valueInt, err := strconv.ParseInt(value, 10, 64)
if err != nil {
valueInt = -1
}
memory.SwapUsage = valueInt - memory.Usage
// Swap peak in bytes
value, err = c.CGroupGet("memory.memsw.max_usage_in_bytes")
valueInt, err = strconv.ParseInt(value, 10, 64)
if err != nil {
valueInt = -1
}
memory.SwapUsagePeak = valueInt - memory.UsagePeak
}
return memory
}
func (c *containerLXC) networkState() map[string]shared.ContainerStateNetwork {
result := map[string]shared.ContainerStateNetwork{}
pid := c.InitPID()
if pid < 1 {
return result
}
// Get the network state from the container
out, err := exec.Command(
execPath,
"forkgetnet",
fmt.Sprintf("%d", pid)).CombinedOutput()
// Process forkgetnet response
if err != nil {
shared.Log.Error("Error calling 'lxd forkgetnet", log.Ctx{"container": c.name, "output": string(out), "pid": pid})
return result
}
networks := map[string]shared.ContainerStateNetwork{}
err = json.Unmarshal(out, &networks)
if err != nil {
shared.Log.Error("Failure to read forkgetnet json", log.Ctx{"container": c.name, "err": err})
return result
}
// Add HostName field
for netName, net := range networks {
net.HostName = c.getHostInterface(netName)
result[netName] = net
}
return result
}
func (c *containerLXC) processesState() int64 {
// Return 0 if not running
pid := c.InitPID()
if pid == -1 {
return 0
}
if cgPidsController {
value, err := c.CGroupGet("pids.current")
valueInt, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return -1
}
return valueInt
}
pids := []int64{int64(pid)}
// Go through the pid list, adding new pids at the end so we go through them all
for i := 0; i < len(pids); i++ {
fname := fmt.Sprintf("/proc/%d/task/%d/children", pids[i], pids[i])
fcont, err := ioutil.ReadFile(fname)
if err != nil {
// the process terminated during execution of this loop
continue
}
content := strings.Split(string(fcont), " ")
for j := 0; j < len(content); j++ {
pid, err := strconv.ParseInt(content[j], 10, 64)
if err == nil {
pids = append(pids, pid)
}
}
}
return int64(len(pids))
}
func (c *containerLXC) tarStoreFile(linkmap map[uint64]string, offset int, tw *tar.Writer, path string, fi os.FileInfo) error {
var err error
var major, minor, nlink int
var ino uint64
link := ""
if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
link, err = os.Readlink(path)
if err != nil {
return err
}
}
hdr, err := tar.FileInfoHeader(fi, link)
if err != nil {
return err
}
hdr.Name = path[offset:]
if fi.IsDir() || fi.Mode()&os.ModeSymlink == os.ModeSymlink {
hdr.Size = 0
} else {
hdr.Size = fi.Size()
}
hdr.Uid, hdr.Gid, major, minor, ino, nlink, err = shared.GetFileStat(path)
if err != nil {
return fmt.Errorf("error getting file info: %s", err)
}
// Unshift the id under /rootfs/ for unpriv containers
if !c.IsPrivileged() && strings.HasPrefix(hdr.Name, "/rootfs") {
hdr.Uid, hdr.Gid = c.idmapset.ShiftFromNs(hdr.Uid, hdr.Gid)
if hdr.Uid == -1 || hdr.Gid == -1 {
return nil
}
}
if major != -1 {
hdr.Devmajor = int64(major)
hdr.Devminor = int64(minor)
}
// If it's a hardlink we've already seen use the old name
if fi.Mode().IsRegular() && nlink > 1 {
if firstpath, found := linkmap[ino]; found {
hdr.Typeflag = tar.TypeLink
hdr.Linkname = firstpath
hdr.Size = 0
} else {
linkmap[ino] = hdr.Name
}
}
// TODO: handle xattrs
if err := tw.WriteHeader(hdr); err != nil {
return fmt.Errorf("error writing header: %s", err)
}
if hdr.Typeflag == tar.TypeReg {
f, err := os.Open(path)
if err != nil {
return fmt.Errorf("tarStoreFile: error opening file: %s", err)
}
defer f.Close()
if _, err := io.Copy(tw, f); err != nil {
return fmt.Errorf("error copying file %s", err)
}
}
return nil
}
// Storage functions
func (c *containerLXC) Storage() storage {
return c.storage
}
func (c *containerLXC) StorageStart() error {
if c.IsSnapshot() {
return c.storage.ContainerSnapshotStart(c)
}
return c.storage.ContainerStart(c)
}
func (c *containerLXC) StorageStop() error {
if c.IsSnapshot() {
return c.storage.ContainerSnapshotStop(c)
}
return c.storage.ContainerStop(c)
}
// Mount handling
func (c *containerLXC) insertMount(source, target, fstype string, flags int) error {
var err error
// Get the init PID
pid := c.InitPID()
if pid == -1 {
// Container isn't running
return fmt.Errorf("Can't insert mount into stopped container")
}
// Create the temporary mount target
var tmpMount string
if shared.IsDir(source) {
tmpMount, err = ioutil.TempDir(shared.VarPath("shmounts", c.name), "lxdmount_")
if err != nil {
return fmt.Errorf("Failed to create shmounts path: %s", err)
}
} else {
f, err := ioutil.TempFile(shared.VarPath("shmounts", c.name), "lxdmount_")
if err != nil {
return fmt.Errorf("Failed to create shmounts path: %s", err)
}
tmpMount = f.Name()
f.Close()
}
defer os.Remove(tmpMount)
// Mount the filesystem
err = syscall.Mount(source, tmpMount, fstype, uintptr(flags), "")
if err != nil {
return fmt.Errorf("Failed to setup temporary mount: %s", err)
}
defer syscall.Unmount(tmpMount, syscall.MNT_DETACH)
// Move the mount inside the container
mntsrc := filepath.Join("/dev/.lxd-mounts", filepath.Base(tmpMount))
pidStr := fmt.Sprintf("%d", pid)
out, err := exec.Command(execPath, "forkmount", pidStr, mntsrc, target).CombinedOutput()
if string(out) != "" {
for _, line := range strings.Split(strings.TrimRight(string(out), "\n"), "\n") {
shared.Debugf("forkmount: %s", line)
}
}
if err != nil {
return fmt.Errorf(
"Error calling 'lxd forkmount %s %s %s': err='%v'",
pidStr,
mntsrc,
target,
err)
}
return nil
}
func (c *containerLXC) removeMount(mount string) error {
// Get the init PID
pid := c.InitPID()
if pid == -1 {
// Container isn't running
return fmt.Errorf("Can't remove mount from stopped container")
}
// Remove the mount from the container
pidStr := fmt.Sprintf("%d", pid)
out, err := exec.Command(execPath, "forkumount", pidStr, mount).CombinedOutput()
if string(out) != "" {
for _, line := range strings.Split(strings.TrimRight(string(out), "\n"), "\n") {
shared.Debugf("forkumount: %s", line)
}
}
if err != nil {
return fmt.Errorf(
"Error calling 'lxd forkumount %s %s': err='%v'",
pidStr,
mount,
err)
}
return nil
}
// Unix devices handling
func (c *containerLXC) createUnixDevice(name string, m shared.Device) (string, error) {
var err error
var major, minor int
// Our device paths
srcPath := m["path"]
tgtPath := strings.TrimPrefix(srcPath, "/")
devName := fmt.Sprintf("unix.%s", strings.Replace(tgtPath, "/", "-", -1))
devPath := filepath.Join(c.DevicesPath(), devName)
// Get the major/minor of the device we want to create
if m["major"] == "" && m["minor"] == "" {
// If no major and minor are set, use those from the device on the host
_, major, minor, err = deviceGetAttributes(srcPath)
if err != nil {
return "", fmt.Errorf("Failed to get device attributes: %s", err)
}
} else if m["major"] == "" || m["minor"] == "" {
return "", fmt.Errorf("Both major and minor must be supplied for devices")
} else {
major, err = strconv.Atoi(m["major"])
if err != nil {
return "", fmt.Errorf("Bad major %s in device %s", m["major"], m["path"])
}
minor, err = strconv.Atoi(m["minor"])
if err != nil {
return "", fmt.Errorf("Bad minor %s in device %s", m["minor"], m["path"])
}
}
// Get the device mode
mode := os.FileMode(0660)
if m["mode"] != "" {
tmp, err := deviceModeOct(m["mode"])
if err != nil {
return "", fmt.Errorf("Bad mode %s in device %s", m["mode"], m["path"])
}
mode = os.FileMode(tmp)
}
if m["type"] == "unix-block" {
mode |= syscall.S_IFBLK
} else {
mode |= syscall.S_IFCHR
}
// Get the device owner
uid := 0
gid := 0
if m["uid"] != "" {
uid, err = strconv.Atoi(m["uid"])
if err != nil {
return "", fmt.Errorf("Invalid uid %s in device %s", m["uid"], m["path"])
}
}
if m["gid"] != "" {
gid, err = strconv.Atoi(m["gid"])
if err != nil {
return "", fmt.Errorf("Invalid gid %s in device %s", m["gid"], m["path"])
}
}
// Create the devices directory if missing
if !shared.PathExists(c.DevicesPath()) {
os.Mkdir(c.DevicesPath(), 0711)
if err != nil {
return "", fmt.Errorf("Failed to create devices path: %s", err)
}
}
// Clean any existing entry
if shared.PathExists(devPath) {
err = os.Remove(devPath)
if err != nil {
return "", fmt.Errorf("Failed to remove existing entry: %s", err)
}
}
// Create the new entry
if err := syscall.Mknod(devPath, uint32(mode), minor|(major<<8)); err != nil {
return "", fmt.Errorf("Failed to create device %s for %s: %s", devPath, m["path"], err)
}
if err := os.Chown(devPath, uid, gid); err != nil {
return "", fmt.Errorf("Failed to chown device %s: %s", devPath, err)
}
// Needed as mknod respects the umask
if err := os.Chmod(devPath, mode); err != nil {
return "", fmt.Errorf("Failed to chmod device %s: %s", devPath, err)
}
if c.idmapset != nil {
if err := c.idmapset.ShiftFile(devPath); err != nil {
// uidshift failing is weird, but not a big problem. Log and proceed
shared.Debugf("Failed to uidshift device %s: %s\n", m["path"], err)
}
}
return devPath, nil
}
func (c *containerLXC) insertUnixDevice(name string, m shared.Device) error {
// Check that the container is running
if !c.IsRunning() {
return fmt.Errorf("Can't insert device into stopped container")
}
// Create the device on the host
devPath, err := c.createUnixDevice(name, m)
if err != nil {
return fmt.Errorf("Failed to setup device: %s", err)
}
// Bind-mount it into the container
tgtPath := strings.TrimSuffix(m["path"], "/")
err = c.insertMount(devPath, tgtPath, "none", syscall.MS_BIND)
if err != nil {
return fmt.Errorf("Failed to add mount for device: %s", err)
}
// Add the new device cgroup rule
dType, dMajor, dMinor, err := deviceGetAttributes(devPath)
if err != nil {
return fmt.Errorf("Failed to get device attributes: %s", err)
}
if err := c.CGroupSet("devices.allow", fmt.Sprintf("%s %d:%d rwm", dType, dMajor, dMinor)); err != nil {
return fmt.Errorf("Failed to add cgroup rule for device")
}
return nil
}
func (c *containerLXC) removeUnixDevice(name string, m shared.Device) error {
// Check that the container is running
pid := c.InitPID()
if pid == -1 {
return fmt.Errorf("Can't remove device from stopped container")
}
// Figure out the paths
srcPath := m["path"]
tgtPath := strings.TrimPrefix(srcPath, "/")
devName := fmt.Sprintf("unix.%s", strings.Replace(tgtPath, "/", "-", -1))
devPath := filepath.Join(c.DevicesPath(), devName)
// Remove the device cgroup rule
dType, dMajor, dMinor, err := deviceGetAttributes(devPath)
if err != nil {
return err
}
err = c.CGroupSet("devices.deny", fmt.Sprintf("%s %d:%d rwm", dType, dMajor, dMinor))
if err != nil {
return err
}
// Remove the bind-mount from the container
ctnPath := fmt.Sprintf("/proc/%d/root/%s", pid, tgtPath)
if shared.PathExists(ctnPath) {
err = c.removeMount(m["path"])
if err != nil {
return fmt.Errorf("Error unmounting the device: %s", err)
}
err = os.Remove(ctnPath)
if err != nil {
return fmt.Errorf("Error removing the device: %s", err)
}
}
// Remove the host side
err = os.Remove(devPath)
if err != nil {
return err
}
return nil
}
func (c *containerLXC) removeUnixDevices() error {
// Check that we indeed have devices to remove
if !shared.PathExists(c.DevicesPath()) {
return nil
}
// Load the directory listing
dents, err := ioutil.ReadDir(c.DevicesPath())
if err != nil {
return err
}
// Go through all the unix devices
for _, f := range dents {
// Skip non-Unix devices
if !strings.HasPrefix(f.Name(), "unix.") {
continue
}
// Remove the entry
devicePath := filepath.Join(c.DevicesPath(), f.Name())
err := os.Remove(devicePath)
if err != nil {
shared.Log.Error("failed removing unix device", log.Ctx{"err": err, "path": devicePath})
}
}
return nil
}
// Network device handling
func (c *containerLXC) createNetworkDevice(name string, m shared.Device) (string, error) {
var dev, n1 string
if shared.StringInSlice(m["nictype"], []string{"bridged", "p2p", "macvlan"}) {
// Host Virtual NIC name
if m["host_name"] != "" {
n1 = m["host_name"]
} else {
n1 = deviceNextVeth()
}
}
// Handle bridged and p2p
if shared.StringInSlice(m["nictype"], []string{"bridged", "p2p"}) {
n2 := deviceNextVeth()
err := exec.Command("ip", "link", "add", n1, "type", "veth", "peer", "name", n2).Run()
if err != nil {
return "", fmt.Errorf("Failed to create the veth interface: %s", err)
}
err = exec.Command("ip", "link", "set", n1, "up").Run()
if err != nil {
return "", fmt.Errorf("Failed to bring up the veth interface %s: %s", n1, err)
}
if m["nictype"] == "bridged" {
err = exec.Command("ip", "link", "set", n1, "master", m["parent"]).Run()
if err != nil {
deviceRemoveInterface(n2)
return "", fmt.Errorf("Failed to add interface to bridge: %s", err)
}
}
dev = n2
}
// Handle physical
if m["nictype"] == "physical" {
dev = m["parent"]
}
// Handle macvlan
if m["nictype"] == "macvlan" {
err := exec.Command("ip", "link", "add", n1, "link", m["parent"], "type", "macvlan", "mode", "bridge").Run()
if err != nil {
return "", fmt.Errorf("Failed to create the new macvlan interface: %s", err)
}
dev = n1
}
// Set the MAC address
if m["hwaddr"] != "" {
err := exec.Command("ip", "link", "set", "dev", dev, "address", m["hwaddr"]).Run()
if err != nil {
deviceRemoveInterface(dev)
return "", fmt.Errorf("Failed to set the MAC address: %s", err)
}
}
// Bring the interface up
err := exec.Command("ip", "link", "set", "dev", dev, "up").Run()
if err != nil {
deviceRemoveInterface(dev)
return "", fmt.Errorf("Failed to bring up the interface: %s", err)
}
return dev, nil
}
func (c *containerLXC) fillNetworkDevice(name string, m shared.Device) (shared.Device, error) {
newDevice := shared.Device{}
err := shared.DeepCopy(&m, &newDevice)
if err != nil {
return nil, err
}
// Function to try and guess an available name
nextInterfaceName := func() (string, error) {
devNames := []string{}
// Include all static interface names
for _, v := range c.expandedDevices {
if v["name"] != "" && !shared.StringInSlice(v["name"], devNames) {
devNames = append(devNames, v["name"])
}
}
// Include all currently allocated interface names
for k, v := range c.expandedConfig {
if !strings.HasPrefix(k, "volatile.") {
continue
}
fields := strings.SplitN(k, ".", 3)
if len(fields) != 3 {
continue
}
if fields[2] != "name" || shared.StringInSlice(v, devNames) {
continue
}
devNames = append(devNames, v)
}
// Attempt to include all existing interfaces
cc, err := lxc.NewContainer(c.Name(), c.daemon.lxcpath)
if err == nil {
interfaces, err := cc.Interfaces()
if err == nil {
for _, name := range interfaces {
if shared.StringInSlice(name, devNames) {
continue
}
devNames = append(devNames, name)
}
}
}
// Find a free ethX device
i := 0
for {
name := fmt.Sprintf("eth%d", i)
if !shared.StringInSlice(name, devNames) {
return name, nil
}
i += 1
}
}
// Fill in the MAC address
if m["nictype"] != "physical" && m["hwaddr"] == "" {
configKey := fmt.Sprintf("volatile.%s.hwaddr", name)
volatileHwaddr := c.localConfig[configKey]
if volatileHwaddr == "" {
// Generate a new MAC address
volatileHwaddr, err = deviceNextInterfaceHWAddr()
if err != nil {
return nil, err
}
c.localConfig[configKey] = volatileHwaddr
c.expandedConfig[configKey] = volatileHwaddr
// Update the database
tx, err := dbBegin(c.daemon.db)
if err != nil {
return nil, err
}
err = dbContainerConfigInsert(tx, c.id, map[string]string{configKey: volatileHwaddr})
if err != nil {
tx.Rollback()
return nil, err
}
err = txCommit(tx)
if err != nil {
return nil, err
}
}
newDevice["hwaddr"] = volatileHwaddr
}
// File in the name
if m["name"] == "" {
configKey := fmt.Sprintf("volatile.%s.name", name)
volatileName := c.localConfig[configKey]
if volatileName == "" {
// Generate a new interface name
volatileName, err = nextInterfaceName()
if err != nil {
return nil, err
}
c.localConfig[configKey] = volatileName
c.expandedConfig[configKey] = volatileName
// Update the database
tx, err := dbBegin(c.daemon.db)
if err != nil {
return nil, err
}
err = dbContainerConfigInsert(tx, c.id, map[string]string{configKey: volatileName})
if err != nil {
tx.Rollback()
return nil, err
}
err = txCommit(tx)
if err != nil {
return nil, err
}
}
newDevice["name"] = volatileName
}
return newDevice, nil
}
func (c *containerLXC) insertNetworkDevice(name string, m shared.Device) error {
// Load the go-lxc struct
err := c.initLXC()
if err != nil {
return nil
}
// Fill in some fields from volatile
m, err = c.fillNetworkDevice(name, m)
if err != nil {
return nil
}
if m["hwaddr"] == "" || m["name"] == "" {
return fmt.Errorf("wtf? hwaddr=%s name=%s", m["hwaddr"], m["name"])
}
// Return empty list if not running
if !c.IsRunning() {
return fmt.Errorf("Can't insert device into stopped container")
}
// Create the interface
devName, err := c.createNetworkDevice(name, m)
if err != nil {
return err
}
// Add the interface to the container
err = c.c.AttachInterface(devName, m["name"])
if err != nil {
return fmt.Errorf("Failed to attach interface: %s: %s", devName, err)
}
return nil
}
func (c *containerLXC) removeNetworkDevice(name string, m shared.Device) error {
// Load the go-lxc struct
err := c.initLXC()
if err != nil {
return nil
}
// Fill in some fields from volatile
m, err = c.fillNetworkDevice(name, m)
if err != nil {
return nil
}
// Return empty list if not running
if !c.IsRunning() {
return fmt.Errorf("Can't insert device into stopped container")
}
// Get a temporary device name
var hostName string
if m["nictype"] == "physical" {
hostName = m["parent"]
} else {
hostName = deviceNextVeth()
}
// For some reason, having network config confuses detach, so get our own go-lxc struct
cc, err := lxc.NewContainer(c.Name(), c.daemon.lxcpath)
if err != nil {
return err
}
// Remove the interface from the container
err = cc.DetachInterfaceRename(m["name"], hostName)
if err != nil {
return fmt.Errorf("Failed to detach interface: %s: %s", m["name"], err)
}
// If a veth, destroy it
if m["nictype"] != "physical" {
deviceRemoveInterface(hostName)
}
return nil
}
// Disk device handling
func (c *containerLXC) createDiskDevice(name string, m shared.Device) (string, error) {
// Prepare all the paths
srcPath := m["source"]
tgtPath := strings.TrimPrefix(m["path"], "/")
devName := fmt.Sprintf("disk.%s", strings.Replace(tgtPath, "/", "-", -1))
devPath := filepath.Join(c.DevicesPath(), devName)
// Check if read-only
isOptional := shared.IsTrue(m["optional"])
isReadOnly := shared.IsTrue(m["readonly"])
isRecursive := shared.IsTrue(m["recursive"])
isFile := !shared.IsDir(srcPath) && !deviceIsBlockdev(srcPath)
// Check if the source exists
if !shared.PathExists(srcPath) {
if isOptional {
return "", nil
}
return "", fmt.Errorf("Source path doesn't exist")
}
// Create the devices directory if missing
if !shared.PathExists(c.DevicesPath()) {
err := os.Mkdir(c.DevicesPath(), 0711)
if err != nil {
return "", err
}
}
// Clean any existing entry
if shared.PathExists(devPath) {
err := os.Remove(devPath)
if err != nil {
return "", err
}
}
// Create the mount point
if isFile {
f, err := os.Create(devPath)
if err != nil {
return "", err
}
f.Close()
} else {
err := os.Mkdir(devPath, 0700)
if err != nil {
return "", err
}
}
// Mount the fs
err := deviceMountDisk(srcPath, devPath, isReadOnly, isRecursive)
if err != nil {
return "", err
}
return devPath, nil
}
func (c *containerLXC) insertDiskDevice(name string, m shared.Device) error {
// Check that the container is running
if !c.IsRunning() {
return fmt.Errorf("Can't insert device into stopped container")
}
isRecursive := shared.IsTrue(m["recursive"])
// Create the device on the host
devPath, err := c.createDiskDevice(name, m)
if err != nil {
return fmt.Errorf("Failed to setup device: %s", err)
}
flags := syscall.MS_BIND
if isRecursive {
flags |= syscall.MS_REC
}
// Bind-mount it into the container
tgtPath := strings.TrimSuffix(m["path"], "/")
err = c.insertMount(devPath, tgtPath, "none", flags)
if err != nil {
return fmt.Errorf("Failed to add mount for device: %s", err)
}
return nil
}
func (c *containerLXC) removeDiskDevice(name string, m shared.Device) error {
// Check that the container is running
pid := c.InitPID()
if pid == -1 {
return fmt.Errorf("Can't remove device from stopped container")
}
// Figure out the paths
tgtPath := strings.TrimPrefix(m["path"], "/")
devName := fmt.Sprintf("disk.%s", strings.Replace(tgtPath, "/", "-", -1))
devPath := filepath.Join(c.DevicesPath(), devName)
// Remove the bind-mount from the container
ctnPath := fmt.Sprintf("/proc/%d/root/%s", pid, tgtPath)
if shared.PathExists(ctnPath) {
err := c.removeMount(m["path"])
if err != nil {
return fmt.Errorf("Error unmounting the device: %s", err)
}
}
// Unmount the host side
err := syscall.Unmount(devPath, syscall.MNT_DETACH)
if err != nil {
return err
}
// Remove the host side
err = os.Remove(devPath)
if err != nil {
return err
}
return nil
}
func (c *containerLXC) removeDiskDevices() error {
// Check that we indeed have devices to remove
if !shared.PathExists(c.DevicesPath()) {
return nil
}
// Load the directory listing
dents, err := ioutil.ReadDir(c.DevicesPath())
if err != nil {
return err
}
// Go through all the unix devices
for _, f := range dents {
// Skip non-Unix devices
if !strings.HasPrefix(f.Name(), "disk.") {
continue
}
// Always try to unmount the host side
_ = syscall.Unmount(filepath.Join(c.DevicesPath(), f.Name()), syscall.MNT_DETACH)
// Remove the entry
diskPath := filepath.Join(c.DevicesPath(), f.Name())
err := os.Remove(diskPath)
if err != nil {
shared.Log.Error("Failed to remove disk device path", log.Ctx{"err": err, "path": diskPath})
}
}
return nil
}
// Block I/O limits
func (c *containerLXC) getDiskLimits() (map[string]deviceBlockLimit, error) {
result := map[string]deviceBlockLimit{}
// Build a list of all valid block devices
validBlocks := []string{}
dents, err := ioutil.ReadDir("/sys/class/block/")
if err != nil {
return nil, err
}
for _, f := range dents {
fPath := filepath.Join("/sys/class/block/", f.Name())
if shared.PathExists(fmt.Sprintf("%s/partition", fPath)) {
continue
}
if !shared.PathExists(fmt.Sprintf("%s/dev", fPath)) {
continue
}
block, err := ioutil.ReadFile(fmt.Sprintf("%s/dev", fPath))
if err != nil {
return nil, err
}
validBlocks = append(validBlocks, strings.TrimSuffix(string(block), "\n"))
}
// Process all the limits
blockLimits := map[string][]deviceBlockLimit{}
for _, m := range c.expandedDevices {
if m["type"] != "disk" {
continue
}
// Apply max limit
if m["limits.max"] != "" {
m["limits.read"] = m["limits.max"]
m["limits.write"] = m["limits.max"]
}
// Parse the user input
readBps, readIops, writeBps, writeIops, err := deviceParseDiskLimit(m["limits.read"], m["limits.write"])
if err != nil {
return nil, err
}
// Set the source path
source := m["source"]
if source == "" {
source = c.RootfsPath()
}
// Get the backing block devices (major:minor)
blocks, err := deviceGetParentBlocks(source)
if err != nil {
if readBps == 0 && readIops == 0 && writeBps == 0 && writeIops == 0 {
// If the device doesn't exist, there is no limit to clear so ignore the failure
continue
} else {
return nil, err
}
}
device := deviceBlockLimit{readBps: readBps, readIops: readIops, writeBps: writeBps, writeIops: writeIops}
for _, block := range blocks {
blockStr := ""
if shared.StringInSlice(block, validBlocks) {
// Straightforward entry (full block device)
blockStr = block
} else {
// Attempt to deal with a partition (guess its parent)
fields := strings.SplitN(block, ":", 2)
fields[1] = "0"
if shared.StringInSlice(fmt.Sprintf("%s:%s", fields[0], fields[1]), validBlocks) {
blockStr = fmt.Sprintf("%s:%s", fields[0], fields[1])
}
}
if blockStr == "" {
return nil, fmt.Errorf("Block device doesn't support quotas: %s", block)
}
if blockLimits[blockStr] == nil {
blockLimits[blockStr] = []deviceBlockLimit{}
}
blockLimits[blockStr] = append(blockLimits[blockStr], device)
}
}
// Average duplicate limits
for block, limits := range blockLimits {
var readBpsCount, readBpsTotal, readIopsCount, readIopsTotal, writeBpsCount, writeBpsTotal, writeIopsCount, writeIopsTotal int64
for _, limit := range limits {
if limit.readBps > 0 {
readBpsCount += 1
readBpsTotal += limit.readBps
}
if limit.readIops > 0 {
readIopsCount += 1
readIopsTotal += limit.readIops
}
if limit.writeBps > 0 {
writeBpsCount += 1
writeBpsTotal += limit.writeBps
}
if limit.writeIops > 0 {
writeIopsCount += 1
writeIopsTotal += limit.writeIops
}
}
device := deviceBlockLimit{}
if readBpsCount > 0 {
device.readBps = readBpsTotal / readBpsCount
}
if readIopsCount > 0 {
device.readIops = readIopsTotal / readIopsCount
}
if writeBpsCount > 0 {
device.writeBps = writeBpsTotal / writeBpsCount
}
if writeIopsCount > 0 {
device.writeIops = writeIopsTotal / writeIopsCount
}
result[block] = device
}
return result, nil
}
// Network I/O limits
func (c *containerLXC) setNetworkPriority() error {
// Check that the container is running
if !c.IsRunning() {
return fmt.Errorf("Can't set network priority on stopped container")
}
// Don't bother if the cgroup controller doesn't exist
if !cgNetPrioController {
return nil
}
// Extract the current priority
networkPriority := c.expandedConfig["limits.network.priority"]
if networkPriority == "" {
networkPriority = "0"
}
networkInt, err := strconv.Atoi(networkPriority)
if err != nil {
return err
}
// Get all the interfaces
netifs, err := net.Interfaces()
if err != nil {
return err
}
// Check that we at least succeeded to set an entry
success := false
var last_error error
for _, netif := range netifs {
err = c.CGroupSet("net_prio.ifpriomap", fmt.Sprintf("%s %d", netif.Name, networkInt))
if err == nil {
success = true
} else {
last_error = err
}
}
if !success {
return fmt.Errorf("Failed to set network device priority: %s", last_error)
}
return nil
}
func (c *containerLXC) getHostInterface(name string) string {
if c.IsRunning() {
for i := 0; i < len(c.c.ConfigItem("lxc.network")); i++ {
nicName := c.c.RunningConfigItem(fmt.Sprintf("lxc.network.%d.name", i))[0]
if nicName != name {
continue
}
veth := c.c.RunningConfigItem(fmt.Sprintf("lxc.network.%d.veth.pair", i))[0]
if veth != "" {
return veth
}
}
}
for k, dev := range c.expandedDevices {
if dev["type"] != "nic" {
continue
}
m, err := c.fillNetworkDevice(k, dev)
if err != nil {
m = dev
}
if m["name"] != name {
continue
}
return m["host_name"]
}
return ""
}
func (c *containerLXC) setNetworkLimits(name string, m shared.Device) error {
// We can only do limits on some network type
if m["nictype"] != "bridged" && m["nictype"] != "p2p" {
return fmt.Errorf("Network limits are only supported on bridged and p2p interfaces")
}
// Load the go-lxc struct
err := c.initLXC()
if err != nil {
return err
}
// Check that the container is running
if !c.IsRunning() {
return fmt.Errorf("Can't set network limits on stopped container")
}
// Fill in some fields from volatile
m, err = c.fillNetworkDevice(name, m)
if err != nil {
return nil
}
// Look for the host side interface name
veth := c.getHostInterface(m["name"])
if veth == "" {
return fmt.Errorf("LXC doesn't now about this device and the host_name property isn't set, can't find host side veth name")
}
// Apply max limit
if m["limits.max"] != "" {
m["limits.ingress"] = m["limits.max"]
m["limits.egress"] = m["limits.max"]
}
// Parse the values
var ingressInt int64
if m["limits.ingress"] != "" {
ingressInt, err = shared.ParseBitSizeString(m["limits.ingress"])
if err != nil {
return err
}
}
var egressInt int64
if m["limits.egress"] != "" {
egressInt, err = shared.ParseBitSizeString(m["limits.egress"])
if err != nil {
return err
}
}
// Clean any existing entry
_ = exec.Command("tc", "qdisc", "del", "dev", veth, "root").Run()
_ = exec.Command("tc", "qdisc", "del", "dev", veth, "ingress").Run()
// Apply new limits
if m["limits.ingress"] != "" {
out, err := exec.Command("tc", "qdisc", "add", "dev", veth, "root", "handle", "1:0", "htb", "default", "10").CombinedOutput()
if err != nil {
return fmt.Errorf("Failed to create root tc qdisc: %s", out)
}
out, err = exec.Command("tc", "class", "add", "dev", veth, "parent", "1:0", "classid", "1:10", "htb", "rate", fmt.Sprintf("%dbit", ingressInt)).CombinedOutput()
if err != nil {
return fmt.Errorf("Failed to create limit tc class: %s", out)
}
out, err = exec.Command("tc", "filter", "add", "dev", veth, "parent", "1:0", "protocol", "all", "u32", "match", "u32", "0", "0", "flowid", "1:1").CombinedOutput()
if err != nil {
return fmt.Errorf("Failed to create tc filter: %s", out)
}
}
if m["limits.egress"] != "" {
out, err := exec.Command("tc", "qdisc", "add", "dev", veth, "handle", "ffff:0", "ingress").CombinedOutput()
if err != nil {
return fmt.Errorf("Failed to create ingress tc qdisc: %s", out)
}
out, err = exec.Command("tc", "filter", "add", "dev", veth, "parent", "ffff:0", "protocol", "all", "u32", "match", "u32", "0", "0", "police", "rate", fmt.Sprintf("%dbit", egressInt), "burst", "1024k", "mtu", "64kb", "drop", "flowid", ":1").CombinedOutput()
if err != nil {
return fmt.Errorf("Failed to create ingress tc qdisc: %s", out)
}
}
return nil
}
// Various state query functions
func (c *containerLXC) IsStateful() bool {
return c.stateful
}
func (c *containerLXC) IsEphemeral() bool {
return c.ephemeral
}
func (c *containerLXC) IsFrozen() bool {
return c.State() == "FROZEN"
}
func (c *containerLXC) IsNesting() bool {
return shared.IsTrue(c.expandedConfig["security.nesting"])
}
func (c *containerLXC) IsPrivileged() bool {
return shared.IsTrue(c.expandedConfig["security.privileged"])
}
func (c *containerLXC) IsRunning() bool {
state := c.State()
return state != "BROKEN" && state != "STOPPED"
}
func (c *containerLXC) IsSnapshot() bool {
return c.cType == cTypeSnapshot
}
// Various property query functions
func (c *containerLXC) Architecture() int {
return c.architecture
}
func (c *containerLXC) CreationDate() time.Time {
return c.creationDate
}
func (c *containerLXC) ExpandedConfig() map[string]string {
return c.expandedConfig
}
func (c *containerLXC) ExpandedDevices() shared.Devices {
return c.expandedDevices
}
func (c *containerLXC) Id() int {
return c.id
}
func (c *containerLXC) IdmapSet() *shared.IdmapSet {
return c.idmapset
}
func (c *containerLXC) InitPID() int {
// Load the go-lxc struct
err := c.initLXC()
if err != nil {
return -1
}
return c.c.InitPid()
}
func (c *containerLXC) LocalConfig() map[string]string {
return c.localConfig
}
func (c *containerLXC) LocalDevices() shared.Devices {
return c.localDevices
}
func (c *containerLXC) LastIdmapSet() (*shared.IdmapSet, error) {
lastJsonIdmap := c.LocalConfig()["volatile.last_state.idmap"]
if lastJsonIdmap == "" {
return c.IdmapSet(), nil
}
lastIdmap := new(shared.IdmapSet)
err := json.Unmarshal([]byte(lastJsonIdmap), &lastIdmap.Idmap)
if err != nil {
return nil, err
}
if len(lastIdmap.Idmap) == 0 {
return nil, nil
}
return lastIdmap, nil
}
func (c *containerLXC) Daemon() *Daemon {
// FIXME: This function should go away
return c.daemon
}
func (c *containerLXC) Name() string {
return c.name
}
func (c *containerLXC) Profiles() []string {
return c.profiles
}
func (c *containerLXC) State() string {
// Load the go-lxc struct
err := c.initLXC()
if err != nil {
return "BROKEN"
}
state, err := c.getLxcState()
if err != nil {
return shared.Error.String()
}
return state.String()
}
// Various container paths
func (c *containerLXC) Path() string {
return containerPath(c.Name(), c.IsSnapshot())
}
func (c *containerLXC) DevicesPath() string {
return shared.VarPath("devices", c.Name())
}
func (c *containerLXC) LogPath() string {
return shared.LogPath(c.Name())
}
func (c *containerLXC) LogFilePath() string {
return filepath.Join(c.LogPath(), "lxc.log")
}
func (c *containerLXC) RootfsPath() string {
return filepath.Join(c.Path(), "rootfs")
}
func (c *containerLXC) TemplatesPath() string {
return filepath.Join(c.Path(), "templates")
}
func (c *containerLXC) StatePath() string {
/* FIXME: backwards compatibility: we used to use Join(RootfsPath(),
* "state"), which was bad. Let's just check to see if that directory
* exists.
*/
oldStatePath := filepath.Join(c.RootfsPath(), "state")
if shared.IsDir(oldStatePath) {
return oldStatePath
}
return filepath.Join(c.Path(), "state")
}
|