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
|
package conformance
import (
"archive/tar"
"bytes"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"io/fs"
"maps"
"os"
"path"
"path/filepath"
"reflect"
"regexp"
"slices"
"strconv"
"strings"
"sync"
"syscall"
"testing"
"text/tabwriter"
"time"
"github.com/containers/buildah"
"github.com/containers/buildah/copier"
"github.com/containers/buildah/define"
"github.com/containers/buildah/imagebuildah"
"github.com/containers/buildah/internal/config"
"github.com/containers/image/v5/docker/daemon"
"github.com/containers/image/v5/image"
"github.com/containers/image/v5/manifest"
"github.com/containers/image/v5/pkg/compression"
is "github.com/containers/image/v5/storage"
istorage "github.com/containers/image/v5/storage"
"github.com/containers/image/v5/transports"
"github.com/containers/image/v5/transports/alltransports"
"github.com/containers/image/v5/types"
"github.com/containers/storage"
"github.com/containers/storage/pkg/archive"
"github.com/containers/storage/pkg/idtools"
"github.com/containers/storage/pkg/ioutils"
"github.com/containers/storage/pkg/reexec"
dockertypes "github.com/docker/docker/api/types"
dockerdockerclient "github.com/docker/docker/client"
docker "github.com/fsouza/go-dockerclient"
digest "github.com/opencontainers/go-digest"
rspec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/openshift/imagebuilder"
"github.com/openshift/imagebuilder/dockerclient"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const (
// See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html#tag_20_92_13_06, from archive/tar
cISUID = 0o4000 // Set uid, from archive/tar
cISGID = 0o2000 // Set gid, from archive/tar
cISVTX = 0o1000 // Save text (sticky bit), from archive/tar
// xattrs in the PAXRecords map are namespaced with this prefix
xattrPAXRecordNamespace = "SCHILY.xattr."
)
var (
originalSkip = []string{
"created",
"container",
"docker_version",
"container_config:hostname",
"config:hostname",
"config:image",
"container_config:cmd",
"container_config:image",
"history",
"rootfs:diff_ids",
"moby.buildkit.buildinfo.v1",
}
ociSkip = []string{
"created",
"history",
"rootfs:diff_ids",
}
fsSkip = []string{
// things that we volume mount or synthesize for RUN statements that currently bleed through
"(dir):etc:mtime",
"(dir):etc:(dir):hosts",
"(dir):etc:(dir):resolv.conf",
"(dir):run",
"(dir):run:mtime",
"(dir):run:(dir):.containerenv",
"(dir):run:(dir):secrets",
"(dir):proc",
"(dir):proc:mtime",
"(dir):sys",
"(dir):sys:mtime",
}
testDate = time.Unix(1485449953, 0)
compareLayers = false
compareImagebuilder = false
testDataDir = ""
dockerDir = ""
imagebuilderDir = ""
buildahDir = ""
contextCanDoXattrs *bool
storageCanDoXattrs *bool
)
func TestMain(m *testing.M) {
var logLevel string
if reexec.Init() {
return
}
cwd, err := os.Getwd()
if err != nil {
logrus.Fatalf("error finding current directory: %v", err)
}
testDataDir = filepath.Join(cwd, "testdata")
flag.StringVar(&logLevel, "log-level", "error", "buildah logging log level")
flag.BoolVar(&compareLayers, "compare-layers", compareLayers, "compare instruction-by-instruction")
flag.BoolVar(&compareImagebuilder, "compare-imagebuilder", compareImagebuilder, "also compare using imagebuilder")
flag.StringVar(&testDataDir, "testdata", testDataDir, "location of conformance testdata")
flag.StringVar(&dockerDir, "docker-dir", dockerDir, "location to save docker build results")
flag.StringVar(&imagebuilderDir, "imagebuilder-dir", imagebuilderDir, "location to save imagebuilder build results")
flag.StringVar(&buildahDir, "buildah-dir", buildahDir, "location to save buildah build results")
flag.Parse()
var tempdir string
if buildahDir == "" || dockerDir == "" || imagebuilderDir == "" {
if tempdir == "" {
if tempdir, err = os.MkdirTemp("", "conformance"); err != nil {
logrus.Fatalf("creating temporary directory: %v", err)
os.Exit(1)
}
}
}
if buildahDir == "" {
buildahDir = filepath.Join(tempdir, "buildah")
}
if dockerDir == "" {
dockerDir = filepath.Join(tempdir, "docker")
}
if imagebuilderDir == "" {
imagebuilderDir = filepath.Join(tempdir, "imagebuilder")
}
level, err := logrus.ParseLevel(logLevel)
if err != nil {
logrus.Fatalf("error parsing log level %q: %v", logLevel, err)
}
logrus.SetLevel(level)
result := m.Run()
if err = os.RemoveAll(tempdir); err != nil {
logrus.Errorf("removing temporary directory %q: %v", tempdir, err)
}
os.Exit(result)
}
func TestConformance(t *testing.T) {
dateStamp := fmt.Sprintf("%d", time.Now().UnixNano())
for i := range internalTestCases {
t.Run(internalTestCases[i].name, func(t *testing.T) {
if internalTestCases[i].testUsingSetParent {
t.Run("new-set-parent", func(t *testing.T) {
testConformanceInternal(t, dateStamp, i, func(test *testCase) {
test.dockerBuilderVersion = docker.BuilderBuildKit
test.compatSetParent = types.OptionalBoolFalse
test.compatScratchConfig = types.OptionalBoolFalse
})
})
t.Run("old-set-parent", func(t *testing.T) {
testConformanceInternal(t, dateStamp, i, func(test *testCase) {
test.dockerBuilderVersion = docker.BuilderV1
test.compatSetParent = types.OptionalBoolTrue
test.compatScratchConfig = types.OptionalBoolTrue
})
})
} else if internalTestCases[i].testUsingVolumes {
t.Run("new-volumes", func(t *testing.T) {
testConformanceInternal(t, dateStamp, i, func(test *testCase) {
test.dockerBuilderVersion = docker.BuilderBuildKit
test.compatVolumes = types.OptionalBoolFalse
test.compatScratchConfig = types.OptionalBoolFalse
})
})
t.Run("old-volumes", func(t *testing.T) {
testConformanceInternal(t, dateStamp, i, func(test *testCase) {
test.dockerBuilderVersion = docker.BuilderV1
test.compatVolumes = types.OptionalBoolTrue
test.compatScratchConfig = types.OptionalBoolTrue
})
})
} else {
testConformanceInternal(t, dateStamp, i, nil)
}
})
}
}
func testConformanceInternal(t *testing.T, dateStamp string, testIndex int, mutate func(*testCase)) {
test := internalTestCases[testIndex]
if mutate != nil {
mutate(&test)
}
ctx := context.TODO()
cwd, err := os.Getwd()
require.NoError(t, err, "error finding current directory")
// create a temporary directory to hold our build context
tempdir := t.TempDir()
// create subdirectories to use as the build context and for buildah storage
contextDir := filepath.Join(tempdir, "context")
rootDir := filepath.Join(tempdir, "root")
runrootDir := filepath.Join(tempdir, "runroot")
// check if we can test xattrs where we're storing build contexts
if contextCanDoXattrs == nil {
testDir := filepath.Join(tempdir, "test")
if err := os.Mkdir(testDir, 0o700); err != nil {
require.NoErrorf(t, err, "error creating test directory to check if xattrs are testable: %v", err)
}
testFile := filepath.Join(testDir, "testfile")
if err := os.WriteFile(testFile, []byte("whatever"), 0o600); err != nil {
require.NoErrorf(t, err, "error creating test file to check if xattrs are testable: %v", err)
}
can := false
if err := copier.Lsetxattrs(testFile, map[string]string{"user.test": "test"}); err == nil {
can = true
}
contextCanDoXattrs = &can
}
// copy either a directory or just a Dockerfile into the temporary directory
pipeReader, pipeWriter := io.Pipe()
var getErr, putErr error
var wg sync.WaitGroup
wg.Add(1)
go func() {
if test.contextDir != "" {
getErr = copier.Get("", testDataDir, copier.GetOptions{}, []string{test.contextDir}, pipeWriter)
} else if test.dockerfile != "" {
getErr = copier.Get("", testDataDir, copier.GetOptions{}, []string{test.dockerfile}, pipeWriter)
}
pipeWriter.Close()
wg.Done()
}()
wg.Add(1)
go func() {
if test.contextDir != "" || test.dockerfile != "" {
putErr = copier.Put("", contextDir, copier.PutOptions{}, pipeReader)
} else {
putErr = os.Mkdir(contextDir, 0o755)
}
pipeReader.Close()
wg.Done()
}()
wg.Wait()
assert.NoErrorf(t, getErr, "error reading build info from %q", filepath.Join("testdata", test.dockerfile))
assert.NoErrorf(t, putErr, "error writing build info to %q", contextDir)
if t.Failed() {
t.FailNow()
}
// construct the names that we want to assign to the images. these should be reasonably unique
buildahImage := fmt.Sprintf("conformance-buildah:%s-%d", dateStamp, testIndex)
dockerImage := fmt.Sprintf("conformance-docker:%s-%d", dateStamp, testIndex)
imagebuilderImage := fmt.Sprintf("conformance-imagebuilder:%s-%d", dateStamp, testIndex)
if mutate != nil {
buildahImage += path.Base(t.Name())
dockerImage += path.Base(t.Name())
imagebuilderImage += path.Base(t.Name())
}
// compute the name of the Dockerfile in the build context directory
var dockerfileName string
if test.dockerfile != "" {
dockerfileName = filepath.Join(contextDir, test.dockerfile)
} else {
dockerfileName = filepath.Join(contextDir, "Dockerfile")
}
// read the Dockerfile, for inclusion in failure messages
dockerfileContents := []byte(test.dockerfileContents)
if len(dockerfileContents) == 0 {
// no inlined contents -> read them from the specified location
contents, err := os.ReadFile(dockerfileName)
require.NoErrorf(t, err, "error reading Dockerfile %q", filepath.Join(tempdir, dockerfileName))
dockerfileContents = contents
}
// initialize storage for buildah
options := storage.StoreOptions{
GraphDriverName: os.Getenv("STORAGE_DRIVER"),
GraphRoot: rootDir,
RunRoot: runrootDir,
RootlessStoragePath: rootDir,
}
store, err := storage.GetStore(options)
require.NoErrorf(t, err, "error creating buildah storage at %q", rootDir)
defer func() {
if store != nil {
_, err := store.Shutdown(true)
require.NoError(t, err, "error shutting down storage for buildah")
}
}()
storageDriver := store.GraphDriverName()
storageRoot := store.GraphRoot()
// now that we have a Store, check if we can test xattrs in storage layers
if storageCanDoXattrs == nil {
layer, err := store.CreateLayer("", "", nil, "", true, nil)
if err != nil {
require.NoErrorf(t, err, "error creating test layer to check if xattrs are testable: %v", err)
}
mountPoint, err := store.Mount(layer.ID, "")
if err != nil {
require.NoErrorf(t, err, "error mounting test layer to check if xattrs are testable: %v", err)
}
testFile := filepath.Join(mountPoint, "testfile")
if err := os.WriteFile(testFile, []byte("whatever"), 0o600); err != nil {
require.NoErrorf(t, err, "error creating file in test layer to check if xattrs are testable: %v", err)
}
can := false
if err := copier.Lsetxattrs(testFile, map[string]string{"user.test": "test"}); err == nil {
can = true
}
storageCanDoXattrs = &can
err = store.DeleteLayer(layer.ID)
if err != nil {
require.NoErrorf(t, err, "error removing test layer after checking if xattrs are testable: %v", err)
}
}
// connect to dockerd using the docker client library
dockerClient, err := dockerdockerclient.NewClientWithOpts(dockerdockerclient.FromEnv)
require.NoError(t, err, "unable to initialize docker.client")
dockerClient.NegotiateAPIVersion(ctx)
if test.dockerUseBuildKit || test.dockerBuilderVersion != "" {
if err := dockerClient.NewVersionError(ctx, "1.38", "buildkit"); err != nil {
t.Skipf("%v", err)
}
}
// connect to dockerd using go-dockerclient
client, err := docker.NewClientFromEnv()
require.NoError(t, err, "unable to initialize docker client")
var dockerVersion []string
if version, err := client.Version(); err == nil {
if version != nil {
for _, s := range *version {
dockerVersion = append(dockerVersion, s)
}
}
} else {
require.NoError(t, err, "unable to connect to docker daemon")
}
// make any last-minute tweaks to the build context directory that this test requires
if test.tweakContextDir != nil {
err = test.tweakContextDir(t, contextDir, storageDriver, storageRoot)
require.NoErrorf(t, err, "error tweaking context directory using test-specific callback: %v", err)
}
// decide whether we're building just one image for this Dockerfile, or
// one for each line in it after the first, which we'll assume is a FROM
if compareLayers {
// build and compare one line at a time
line := 1
for i := range dockerfileContents {
// scan the byte slice for newlines or the end of the slice, and build using the contents up to that point
if i == len(dockerfileContents)-1 || (dockerfileContents[i] == '\n' && (i == 0 || dockerfileContents[i-1] != '\\')) {
if line > 1 || !bytes.HasPrefix(dockerfileContents, []byte("FROM ")) {
// hack: skip trying to build just the first FROM line
t.Run(fmt.Sprintf("%d", line), func(t *testing.T) {
testConformanceInternalBuild(ctx, t, cwd, store, client, dockerClient, fmt.Sprintf("%s.%d", buildahImage, line), fmt.Sprintf("%s.%d", dockerImage, line), fmt.Sprintf("%s.%d", imagebuilderImage, line), contextDir, dockerfileName, dockerfileContents[:i+1], test, line, i == len(dockerfileContents)-1, dockerVersion)
})
}
line++
}
}
} else {
// build to completion
testConformanceInternalBuild(ctx, t, cwd, store, client, dockerClient, buildahImage, dockerImage, imagebuilderImage, contextDir, dockerfileName, dockerfileContents, test, 0, true, dockerVersion)
}
}
func testConformanceInternalBuild(ctx context.Context, t *testing.T, cwd string, store storage.Store, client *docker.Client, dockerClient *dockerdockerclient.Client, buildahImage, dockerImage, imagebuilderImage, contextDir, dockerfileName string, dockerfileContents []byte, test testCase, line int, finalOfSeveral bool, dockerVersion []string) {
var buildahLog, dockerLog, imagebuilderLog []byte
var buildahRef, dockerRef, imagebuilderRef types.ImageReference
// overwrite the Dockerfile in the build context for this run using the
// contents we were passed, which may only be an initial subset of the
// original file, or inlined information, in which case the file didn't
// necessarily exist
err := os.WriteFile(dockerfileName, dockerfileContents, 0o644)
require.NoErrorf(t, err, "error writing Dockerfile at %q", dockerfileName)
err = os.Chtimes(dockerfileName, testDate, testDate)
require.NoErrorf(t, err, "error resetting timestamp on Dockerfile at %q", dockerfileName)
err = os.Chtimes(contextDir, testDate, testDate)
require.NoErrorf(t, err, "error resetting timestamp on context directory at %q", contextDir)
defer func() {
if t.Failed() {
if test.contextDir != "" {
t.Logf("Context %q", filepath.Join(cwd, "testdata", test.contextDir))
}
if test.dockerfile != "" {
if test.contextDir != "" {
t.Logf("Dockerfile: %q", filepath.Join(cwd, "testdata", test.contextDir, test.dockerfile))
} else {
t.Logf("Dockerfile: %q", filepath.Join(cwd, "testdata", test.dockerfile))
}
}
if !bytes.HasSuffix(dockerfileContents, []byte{'\n'}) && !bytes.HasSuffix(dockerfileContents, []byte{'\r'}) {
dockerfileContents = append(dockerfileContents, []byte("\n(no final end-of-line)")...)
}
t.Logf("Dockerfile contents:\n%s", dockerfileContents)
if dockerignoreContents, err := os.ReadFile(filepath.Join(contextDir, ".dockerignore")); err == nil {
t.Logf(".dockerignore contents:\n%s", string(dockerignoreContents))
}
}
}()
// build using docker
if !test.withoutDocker {
dockerRef, dockerLog = buildUsingDocker(ctx, t, client, dockerClient, test, dockerImage, contextDir, dockerfileName, line, finalOfSeveral)
if dockerRef != nil {
defer func() {
err := client.RemoveImageExtended(dockerImage, docker.RemoveImageOptions{
Context: ctx,
Force: true,
})
assert.Nil(t, err, "error deleting newly-built-by-docker image %q", dockerImage)
}()
}
saveReport(ctx, t, dockerRef, filepath.Join(dockerDir, t.Name()), dockerfileContents, dockerLog, dockerVersion)
if finalOfSeveral && compareLayers {
saveReport(ctx, t, dockerRef, filepath.Join(dockerDir, t.Name(), ".."), dockerfileContents, dockerLog, dockerVersion)
}
}
if t.Failed() {
t.FailNow()
}
// build using imagebuilder if we're testing with it, too
if compareImagebuilder && !test.withoutImagebuilder {
imagebuilderRef, imagebuilderLog = buildUsingImagebuilder(t, client, test, imagebuilderImage, contextDir, dockerfileName, line, finalOfSeveral)
if imagebuilderRef != nil {
defer func() {
err := client.RemoveImageExtended(imagebuilderImage, docker.RemoveImageOptions{
Context: ctx,
Force: true,
})
assert.Nil(t, err, "error deleting newly-built-by-imagebuilder image %q", imagebuilderImage)
}()
}
saveReport(ctx, t, imagebuilderRef, filepath.Join(imagebuilderDir, t.Name()), dockerfileContents, imagebuilderLog, dockerVersion)
if finalOfSeveral && compareLayers {
saveReport(ctx, t, imagebuilderRef, filepath.Join(imagebuilderDir, t.Name(), ".."), dockerfileContents, imagebuilderLog, dockerVersion)
}
}
if t.Failed() {
t.FailNow()
}
// always build using buildah
buildahRef, buildahLog = buildUsingBuildah(ctx, t, store, test, buildahImage, contextDir, dockerfileName, line, finalOfSeveral)
if buildahRef != nil {
defer func() {
err := buildahRef.DeleteImage(ctx, nil)
assert.Nil(t, err, "error deleting newly-built-by-buildah image %q", buildahImage)
}()
}
saveReport(ctx, t, buildahRef, filepath.Join(buildahDir, t.Name()), dockerfileContents, buildahLog, nil)
if finalOfSeveral && compareLayers {
saveReport(ctx, t, buildahRef, filepath.Join(buildahDir, t.Name(), ".."), dockerfileContents, buildahLog, nil)
}
if t.Failed() {
t.FailNow()
}
if test.shouldFailAt != 0 {
// the build is expected to fail, so there's no point in comparing information about any images
return
}
// the report on the buildah image should always be there
_, originalBuildahConfig, ociBuildahConfig, fsBuildah := readReport(t, filepath.Join(buildahDir, t.Name()))
if t.Failed() {
t.FailNow()
}
deleteIdentityLabel := func(config map[string]interface{}) {
for _, configName := range []string{"config", "container_config"} {
if configStruct, ok := config[configName]; ok {
if configMap, ok := configStruct.(map[string]interface{}); ok {
if labels, ok := configMap["Labels"]; ok {
if labelMap, ok := labels.(map[string]interface{}); ok {
delete(labelMap, buildah.BuilderIdentityAnnotation)
}
}
}
}
}
}
deleteIdentityLabel(originalBuildahConfig)
deleteIdentityLabel(ociBuildahConfig)
var originalDockerConfig, ociDockerConfig, fsDocker map[string]interface{}
// the report on the docker image should be there if we expected the build to succeed
if !test.withoutDocker {
var mediaType string
mediaType, originalDockerConfig, ociDockerConfig, fsDocker = readReport(t, filepath.Join(dockerDir, t.Name()))
assert.Equal(t, manifest.DockerV2Schema2MediaType, mediaType, "Image built by docker build didn't use Docker MIME type - tests require update")
if t.Failed() {
t.FailNow()
}
// Some of the base images for our tests were built with buildah, too
deleteIdentityLabel(originalDockerConfig)
deleteIdentityLabel(ociDockerConfig)
miss, left, diff, same := compareJSON(originalDockerConfig, originalBuildahConfig, originalSkip)
if !same {
assert.Failf(t, "Image configurations differ as committed in Docker format", configCompareResult(miss, left, diff, "buildah"))
}
miss, left, diff, same = compareJSON(ociDockerConfig, ociBuildahConfig, ociSkip)
if !same {
assert.Failf(t, "Image configurations differ when converted to OCI format", configCompareResult(miss, left, diff, "buildah"))
}
miss, left, diff, same = compareJSON(fsDocker, fsBuildah, append(fsSkip, test.fsSkip...))
if !same {
assert.Failf(t, "Filesystem contents differ", fsCompareResult(miss, left, diff, "buildah"))
}
}
// the report on the imagebuilder image should be there if we expected the build to succeed
if compareImagebuilder && !test.withoutImagebuilder {
_, originalDockerConfig, ociDockerConfig, fsDocker = readReport(t, filepath.Join(dockerDir, t.Name()))
if t.Failed() {
t.FailNow()
}
_, originalImagebuilderConfig, ociImagebuilderConfig, fsImagebuilder := readReport(t, filepath.Join(imagebuilderDir, t.Name()))
if t.Failed() {
t.FailNow()
}
// compare the reports between docker and imagebuilder
miss, left, diff, same := compareJSON(originalDockerConfig, originalImagebuilderConfig, originalSkip)
if !same {
assert.Failf(t, "Image configurations differ as committed in Docker format", configCompareResult(miss, left, diff, "imagebuilder"))
}
miss, left, diff, same = compareJSON(ociDockerConfig, ociImagebuilderConfig, ociSkip)
if !same {
assert.Failf(t, "Image configurations differ when converted to OCI format", configCompareResult(miss, left, diff, "imagebuilder"))
}
miss, left, diff, same = compareJSON(fsDocker, fsImagebuilder, append(fsSkip, test.fsSkip...))
if !same {
assert.Failf(t, "Filesystem contents differ", fsCompareResult(miss, left, diff, "imagebuilder"))
}
}
}
func buildUsingBuildah(ctx context.Context, t *testing.T, store storage.Store, test testCase, buildahImage, contextDir, dockerfileName string, line int, finalOfSeveral bool) (buildahRef types.ImageReference, buildahLog []byte) {
// buildah tests might be using transient mounts. replace "@@TEMPDIR@@"
// in such specifications with the path of the context directory
var transientMounts []string
for _, mount := range test.transientMounts {
transientMounts = append(transientMounts, strings.Replace(mount, "@@TEMPDIR@@", contextDir, 1))
}
// set up build options
output := &bytes.Buffer{}
if test.compatSetParent != types.OptionalBoolUndefined {
compat := "default"
switch test.compatSetParent {
case types.OptionalBoolFalse:
compat = "false"
case types.OptionalBoolTrue:
compat = "true"
}
t.Logf("using buildah flag CompatSetParent = %s", compat)
}
if test.compatVolumes != types.OptionalBoolUndefined {
compat := "default"
switch test.compatVolumes {
case types.OptionalBoolFalse:
compat = "false"
case types.OptionalBoolTrue:
compat = "true"
}
t.Logf("using buildah flag CompatVolumes = %s", compat)
}
if test.compatScratchConfig != types.OptionalBoolUndefined {
compat := "default"
switch test.compatScratchConfig {
case types.OptionalBoolFalse:
compat = "false"
case types.OptionalBoolTrue:
compat = "true"
}
t.Logf("using buildah flag CompatScratchConfig = %s", compat)
}
options := define.BuildOptions{
ContextDirectory: contextDir,
CommonBuildOpts: &define.CommonBuildOptions{},
NamespaceOptions: []define.NamespaceOption{{
Name: string(rspec.NetworkNamespace),
Host: true,
}},
TransientMounts: transientMounts,
Output: buildahImage,
OutputFormat: buildah.Dockerv2ImageManifest,
Out: output,
Err: output,
Layers: true,
NoCache: true,
RemoveIntermediateCtrs: true,
ForceRmIntermediateCtrs: true,
CompatSetParent: test.compatSetParent,
CompatVolumes: test.compatVolumes,
CompatScratchConfig: test.compatScratchConfig,
Args: maps.Clone(test.buildArgs),
}
// build the image and gather output. log the output if the build part of the test failed
imageID, _, err := imagebuildah.BuildDockerfiles(ctx, store, options, dockerfileName)
if err != nil {
output.WriteString("\n" + err.Error())
}
outputString := output.String()
defer func() {
if t.Failed() {
t.Logf("buildah output:\n%s", outputString)
}
}()
buildPost(t, test, err, "buildah", outputString, test.buildahRegex, test.buildahErrRegex, line, finalOfSeveral)
// return a reference to the new image, if we succeeded
if err == nil {
buildahRef, err = istorage.Transport.ParseStoreReference(store, imageID)
assert.Nil(t, err, "error parsing reference to newly-built image with ID %q", imageID)
}
return buildahRef, []byte(outputString)
}
func pullImageIfMissing(t *testing.T, client *docker.Client, image string) {
if _, err := client.InspectImage(image); err != nil {
repository, tag := docker.ParseRepositoryTag(image)
if tag == "" {
tag = "latest"
}
pullOptions := docker.PullImageOptions{
Repository: repository,
Tag: tag,
}
pullAuths := docker.AuthConfiguration{}
if err := client.PullImage(pullOptions, pullAuths); err != nil {
t.Fatalf("while pulling %q: %v", image, err)
}
}
}
func buildUsingDocker(ctx context.Context, t *testing.T, client *docker.Client, dockerClient *dockerdockerclient.Client, test testCase, dockerImage, contextDir, dockerfileName string, line int, finalOfSeveral bool) (dockerRef types.ImageReference, dockerLog []byte) {
// compute the path of the dockerfile relative to the build context
dockerfileRelativePath, err := filepath.Rel(contextDir, dockerfileName)
require.NoErrorf(t, err, "unable to compute path of dockerfile %q relative to context directory %q", dockerfileName, contextDir)
// read the Dockerfile so that we can pull base images
dockerfileContent, err := os.ReadFile(dockerfileName)
require.NoErrorf(t, err, "reading dockerfile %q", dockerfileName)
for _, line := range strings.Split(string(dockerfileContent), "\n") {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "# syntax=") {
pullImageIfMissing(t, client, strings.TrimPrefix(line, "# syntax="))
}
}
parsed, err := imagebuilder.ParseDockerfile(bytes.NewReader(dockerfileContent))
require.NoErrorf(t, err, "parsing dockerfile %q", dockerfileName)
dummyBuilder := imagebuilder.NewBuilder(nil)
stages, err := imagebuilder.NewStages(parsed, dummyBuilder)
require.NoErrorf(t, err, "breaking dockerfile %q up into stages", dockerfileName)
for i := range stages {
stageBase, err := dummyBuilder.From(stages[i].Node)
require.NoErrorf(t, err, "parsing base image for stage %d in %q", i, dockerfileName)
if stageBase == "" || stageBase == imagebuilder.NoBaseImageSpecifier {
continue
}
needToEnsureBase := true
for j := 0; j < i; j++ {
if stageBase == stages[j].Name {
needToEnsureBase = false
}
}
if !needToEnsureBase {
continue
}
pullImageIfMissing(t, client, stageBase)
}
excludes, err := imagebuilder.ParseDockerignore(contextDir)
require.NoErrorf(t, err, "parsing ignores file in %q", contextDir)
excludes = append(excludes, "!"+dockerfileRelativePath, "!.dockerignore")
tarOptions := &archive.TarOptions{
ExcludePatterns: excludes,
ChownOpts: &idtools.IDPair{UID: 0, GID: 0},
}
input, err := archive.TarWithOptions(contextDir, tarOptions)
require.NoErrorf(t, err, "archiving context directory %q", contextDir)
defer input.Close()
var buildArgs []docker.BuildArg
for k, v := range test.buildArgs {
buildArgs = append(buildArgs, docker.BuildArg{Name: k, Value: v})
}
// set up build options
output := &bytes.Buffer{}
options := docker.BuildImageOptions{
Context: ctx,
Dockerfile: dockerfileRelativePath,
InputStream: input,
OutputStream: output,
Name: dockerImage,
NoCache: true,
RmTmpContainer: true,
ForceRmTmpContainer: true,
BuildArgs: buildArgs,
}
if test.dockerUseBuildKit || test.dockerBuilderVersion != "" {
if test.dockerBuilderVersion != "" {
var version string
switch test.dockerBuilderVersion {
case docker.BuilderBuildKit:
version = "BuildKit"
case docker.BuilderV1:
version = "V1 (classic)"
default:
version = "(unknown)"
}
t.Logf("requesting docker builder %s", version)
options.Version = test.dockerBuilderVersion
} else {
t.Log("requesting docker builder BuildKit")
options.Version = docker.BuilderBuildKit
}
}
// build the image and gather output. log the output if the build part of the test failed
err = client.BuildImage(options)
if err != nil {
output.WriteString("\n" + err.Error())
}
if _, err := dockerClient.BuildCachePrune(ctx, dockertypes.BuildCachePruneOptions{All: true}); err != nil {
t.Logf("docker build cache prune: %v", err)
}
outputString := output.String()
defer func() {
if t.Failed() {
t.Logf("docker build output:\n%s", outputString)
}
}()
buildPost(t, test, err, "docker build", outputString, test.dockerRegex, test.dockerErrRegex, line, finalOfSeveral)
// return a reference to the new image, if we succeeded
if err == nil {
dockerRef, err = daemon.ParseReference(dockerImage)
assert.Nil(t, err, "error parsing reference to newly-built image with name %q", dockerImage)
}
return dockerRef, []byte(outputString)
}
func buildUsingImagebuilder(t *testing.T, client *docker.Client, test testCase, imagebuilderImage, contextDir, dockerfileName string, line int, finalOfSeveral bool) (imagebuilderRef types.ImageReference, imagebuilderLog []byte) {
// compute the path of the dockerfile relative to the build context
dockerfileRelativePath, err := filepath.Rel(contextDir, dockerfileName)
require.NoErrorf(t, err, "unable to compute path of dockerfile %q relative to context directory %q", dockerfileName, contextDir)
// set up build options
output := &bytes.Buffer{}
executor := dockerclient.NewClientExecutor(client)
executor.Directory = contextDir
executor.Tag = imagebuilderImage
executor.AllowPull = true
executor.Out = output
executor.ErrOut = output
executor.LogFn = func(format string, args ...interface{}) {
fmt.Fprintf(output, "--> %s\n", fmt.Sprintf(format, args...))
}
// buildah tests might be using transient mounts. replace "@@TEMPDIR@@"
// in such specifications with the path of the context directory
for _, mount := range test.transientMounts {
var src, dest string
mountSpec := strings.SplitN(strings.Replace(mount, "@@TEMPDIR@@", contextDir, 1), ":", 2)
if len(mountSpec) > 1 {
src = mountSpec[0]
}
dest = mountSpec[len(mountSpec)-1]
executor.TransientMounts = append(executor.TransientMounts, dockerclient.Mount{
SourcePath: src,
DestinationPath: dest,
})
}
// build the image and gather output. log the output if the build part of the test failed
builder := imagebuilder.NewBuilder(maps.Clone(test.buildArgs))
node, err := imagebuilder.ParseFile(filepath.Join(contextDir, dockerfileRelativePath))
if err != nil {
assert.Nil(t, err, "error parsing Dockerfile: %v", err)
}
if _, err = os.Stat(filepath.Join(contextDir, ".dockerignore")); err == nil {
if builder.Excludes, err = imagebuilder.ParseDockerignore(contextDir); err != nil {
assert.Nil(t, err, "error parsing .dockerignore file: %v", err)
}
}
stages, err := imagebuilder.NewStages(node, builder)
if err != nil {
assert.Nil(t, err, "error breaking Dockerfile into stages")
} else {
if finalExecutor, err := executor.Stages(builder, stages, ""); err != nil {
output.WriteString("\n" + err.Error())
} else {
if err = finalExecutor.Commit(stages[len(stages)-1].Builder); err != nil {
assert.Nil(t, err, "error committing final stage: %v", err)
}
}
}
outputString := output.String()
defer func() {
if t.Failed() {
t.Logf("imagebuilder build output:\n%s", outputString)
}
for err := range executor.Release() {
t.Logf("imagebuilder build post-error: %v", err)
}
}()
buildPost(t, test, err, "imagebuilder", outputString, test.imagebuilderRegex, test.imagebuilderErrRegex, line, finalOfSeveral)
// return a reference to the new image, if we succeeded
if err == nil {
imagebuilderRef, err = daemon.ParseReference(imagebuilderImage)
assert.Nil(t, err, "error parsing reference to newly-built image with name %q", imagebuilderImage)
}
return imagebuilderRef, []byte(outputString)
}
func buildPost(t *testing.T, test testCase, err error, buildTool, outputString, stdoutRegex, stderrRegex string, line int, finalOfSeveral bool) {
// check if the build succeeded or failed, whichever was expected
if test.shouldFailAt != 0 && (line == 0 || line >= test.shouldFailAt) {
// this is expected to fail, and we're either at/past
// the line where it should fail, or we're not going
// line-by-line
assert.NotNil(t, err, fmt.Sprintf("%s build was expected to fail, but succeeded", buildTool))
} else {
assert.Nil(t, err, fmt.Sprintf("%s build was expected to succeed, but failed", buildTool))
}
// if the build failed, and we have an error message we expected, check for it
if err != nil && test.failureRegex != "" {
outputTokens := strings.Join(strings.Fields(err.Error()), " ")
assert.Regexpf(t, regexp.MustCompile(test.failureRegex), outputTokens, "build failure did not match %q", test.failureRegex)
}
// if this is the last image we're building for this case, we can scan
// the build log for expected messages
if finalOfSeveral {
outputTokens := strings.Join(strings.Fields(outputString), " ")
// check for expected output
if stdoutRegex != "" {
assert.Regexpf(t, regexp.MustCompile(stdoutRegex), outputTokens, "build output did not match %q", stdoutRegex)
}
if stderrRegex != "" {
assert.Regexpf(t, regexp.MustCompile(stderrRegex), outputTokens, "build error did not match %q", stderrRegex)
}
}
}
// FSTree holds the information we have about an image's filesystem
type FSTree struct {
Layers []Layer `json:"layers,omitempty"`
Tree FSEntry `json:"tree,omitempty"`
}
// Layer keeps track of the digests and contents of a layer blob
type Layer struct {
UncompressedDigest digest.Digest `json:"uncompressed-digest,omitempty"`
CompressedDigest digest.Digest `json:"compressed-digest,omitempty"`
Headers []FSHeader `json:"-,omitempty"`
}
// FSHeader is the parts of the tar.Header for an entry in a layer blob that
// are relevant
type FSHeader struct {
Typeflag byte `json:"typeflag,omitempty"`
Name string `json:"name,omitempty"`
Linkname string `json:"linkname,omitempty"`
Size int64 `json:"size"`
Mode int64 `json:"mode,omitempty"`
UID int `json:"uid"`
GID int `json:"gid"`
ModTime time.Time `json:"mtime,omitempty"`
Devmajor int64 `json:"devmajor,omitempty"`
Devminor int64 `json:"devminor,omitempty"`
Xattrs map[string]string `json:"xattrs,omitempty"`
Digest digest.Digest `json:"digest,omitempty"`
}
// FSEntry stores one item in a filesystem tree. If it represents a directory,
// its contents are stored as its children
type FSEntry struct {
FSHeader
Children map[string]*FSEntry `json:"(dir),omitempty"`
}
// fsHeaderForEntry converts a tar header to an FSHeader, in the process
// discarding some fields which we don't care to compare
func fsHeaderForEntry(hdr *tar.Header) FSHeader {
return FSHeader{
Typeflag: hdr.Typeflag,
Name: hdr.Name,
Linkname: hdr.Linkname,
Size: hdr.Size,
Mode: (hdr.Mode & int64(fs.ModePerm)),
UID: hdr.Uid,
GID: hdr.Gid,
ModTime: hdr.ModTime,
Devmajor: hdr.Devmajor,
Devminor: hdr.Devminor,
Xattrs: hdr.Xattrs, // nolint:staticcheck
}
}
// save information about the specified image to the specified directory
func saveReport(ctx context.Context, t *testing.T, ref types.ImageReference, directory string, dockerfileContents []byte, buildLog []byte, version []string) {
imageName := ""
// make sure the directory exists
err := os.MkdirAll(directory, 0o755)
require.NoErrorf(t, err, "error ensuring directory %q exists for storing a report", directory)
// save the Dockerfile that was used to generate the image
err = os.WriteFile(filepath.Join(directory, "Dockerfile"), dockerfileContents, 0o644)
require.NoErrorf(t, err, "error saving Dockerfile for image %q", imageName)
// save the log generated while building the image
err = os.WriteFile(filepath.Join(directory, "build.log"), buildLog, 0o644)
require.NoErrorf(t, err, "error saving build log for image %q", imageName)
// save the version information
if len(version) > 0 {
err = os.WriteFile(filepath.Join(directory, "version"), []byte(strings.Join(version, "\n")+"\n"), 0o644)
require.NoErrorf(t, err, "error saving builder version information for image %q", imageName)
}
// open the image for reading
if ref == nil {
return
}
imageName = transports.ImageName(ref)
src, err := ref.NewImageSource(ctx, nil)
require.NoErrorf(t, err, "error opening image %q as source to read its configuration", imageName)
closer := io.Closer(src)
defer func() {
closer.Close()
}()
img, err := image.FromSource(ctx, nil, src)
require.NoErrorf(t, err, "error opening image %q to read its configuration", imageName)
closer = img
// read the manifest in its original form
rawManifest, _, err := src.GetManifest(ctx, nil)
require.NoErrorf(t, err, "error reading raw manifest from image %q", imageName)
// read the config blob in its original form
rawConfig, err := img.ConfigBlob(ctx)
require.NoErrorf(t, err, "error reading configuration from image %q", imageName)
// read the config blob, converted to OCI format by the image library, and re-encode it
ociConfig, err := img.OCIConfig(ctx)
require.NoErrorf(t, err, "error reading OCI-format configuration from image %q", imageName)
encodedConfig, err := json.Marshal(ociConfig)
require.NoErrorf(t, err, "error encoding OCI-format configuration from image %q for saving", imageName)
// save the manifest in its original form
err = os.WriteFile(filepath.Join(directory, "manifest.json"), rawManifest, 0o644)
require.NoErrorf(t, err, "error saving original manifest from image %q", imageName)
// save the config blob in the OCI format
err = os.WriteFile(filepath.Join(directory, "oci-config.json"), encodedConfig, 0o644)
require.NoErrorf(t, err, "error saving OCI-format configuration from image %q", imageName)
// save the config blob in its original format
err = os.WriteFile(filepath.Join(directory, "config.json"), rawConfig, 0o644)
require.NoErrorf(t, err, "error saving original configuration from image %q", imageName)
// start pulling layer information
layerBlobInfos, err := img.LayerInfosForCopy(ctx)
require.NoErrorf(t, err, "error reading blob infos for image %q", imageName)
if len(layerBlobInfos) == 0 {
layerBlobInfos = img.LayerInfos()
}
fstree := FSTree{Tree: FSEntry{Children: make(map[string]*FSEntry)}}
// grab digest and header information from the layer blob
for _, layerBlobInfo := range layerBlobInfos {
rc, _, err := src.GetBlob(ctx, layerBlobInfo, nil)
require.NoErrorf(t, err, "error reading blob %+v for image %q", layerBlobInfo, imageName)
defer rc.Close()
layer := summarizeLayer(t, imageName, layerBlobInfo, rc)
fstree.Layers = append(fstree.Layers, layer)
}
// apply the header information from blobs, in the order they're listed
// in the config blob, to produce what we think the filesystem tree
// would look like
for _, diffID := range ociConfig.RootFS.DiffIDs {
var layer *Layer
for i := range fstree.Layers {
if fstree.Layers[i].CompressedDigest == diffID {
layer = &fstree.Layers[i]
break
}
if fstree.Layers[i].UncompressedDigest == diffID {
layer = &fstree.Layers[i]
break
}
}
if layer == nil {
require.Failf(t, "missing layer diff", "config for image %q specifies a layer with diffID %q, but we found no layer blob matching that digest", imageName, diffID)
}
applyLayerToFSTree(t, layer, &fstree.Tree)
}
// encode the filesystem tree information and save it to a file,
// discarding the layer summaries because different tools may choose
// between marking a directory as opaque and removing each of its
// contents individually, which would produce the same result, so
// there's no point in saving them for comparison later
encodedFSTree, err := json.Marshal(fstree.Tree)
require.NoErrorf(t, err, "error encoding filesystem tree from image %q for saving", imageName)
err = os.WriteFile(filepath.Join(directory, "fs.json"), encodedFSTree, 0o644)
require.NoErrorf(t, err, "error saving filesystem tree from image %q", imageName)
}
// summarizeLayer reads a blob and returns a summary of the parts of its contents that we care about
func summarizeLayer(t *testing.T, imageName string, blobInfo types.BlobInfo, reader io.Reader) (layer Layer) {
compressedDigest := digest.Canonical.Digester()
counter := ioutils.NewWriteCounter(compressedDigest.Hash())
compressionAlgorithm, _, reader, err := compression.DetectCompressionFormat(reader)
require.NoErrorf(t, err, "error checking if blob %+v for image %q is compressed", blobInfo, imageName)
uncompressedBlob, wasCompressed, err := compression.AutoDecompress(io.TeeReader(reader, counter))
require.NoErrorf(t, err, "error decompressing blob %+v for image %q", blobInfo, imageName)
defer uncompressedBlob.Close()
uncompressedDigest := digest.Canonical.Digester()
tarToRead := io.TeeReader(uncompressedBlob, uncompressedDigest.Hash())
tr := tar.NewReader(tarToRead)
hdr, err := tr.Next()
for err == nil {
header := fsHeaderForEntry(hdr)
if hdr.Size != 0 {
contentDigest := digest.Canonical.Digester()
n, err := io.Copy(contentDigest.Hash(), tr)
require.NoErrorf(t, err, "error digesting contents of %q from layer %+v for image %q", hdr.Name, blobInfo, imageName)
require.Equal(t, hdr.Size, n, "error reading contents of %q from layer %+v for image %q: wrong size", hdr.Name, blobInfo, imageName)
header.Digest = contentDigest.Digest()
}
layer.Headers = append(layer.Headers, header)
hdr, err = tr.Next()
}
require.Equal(t, io.EOF, err, "unexpected error reading layer contents %+v for image %q", blobInfo, imageName)
_, err = io.Copy(io.Discard, tarToRead)
require.NoError(t, err, "reading out any not-usually-present zero padding at the end")
layer.CompressedDigest = compressedDigest.Digest()
blobFormatDescription := "uncompressed"
if wasCompressed {
if compressionAlgorithm.Name() != "" {
blobFormatDescription = "compressed with " + compressionAlgorithm.Name()
} else {
blobFormatDescription = "compressed (?)"
}
}
require.Equalf(t, blobInfo.Digest, layer.CompressedDigest, "calculated digest of %s blob didn't match expected digest (expected length %d, actual length %d)", blobFormatDescription, blobInfo.Size, counter.Count)
layer.UncompressedDigest = uncompressedDigest.Digest()
return layer
}
// applyLayerToFSTree updates the in-memory summary of a tree to incorporate
// changes described in the layer. This is a little naive, in that we don't
// expect the pathname to include symlinks, which we don't resolve, as
// components, but tools that currently generate layer diffs don't create
// those.
func applyLayerToFSTree(t *testing.T, layer *Layer, root *FSEntry) {
for i, entry := range layer.Headers {
if entry.Typeflag == tar.TypeLink {
// if the entry is a hard link, replace it with the
// contents of the hard-linked file
replaced := false
name := entry.Name
for j, otherEntry := range layer.Headers {
if j >= i {
break
}
if otherEntry.Name == entry.Linkname {
entry = otherEntry
entry.Name = name
replaced = true
break
}
}
if !replaced {
require.Fail(t, "layer diff error", "hardlink entry referenced a file that isn't in the layer")
}
}
// parse the name from the entry, and don't get tripped up by a final '/'
dirEntry := root
components := strings.Split(strings.Trim(entry.Name, string(os.PathSeparator)), string(os.PathSeparator))
require.NotEmpty(t, entry.Name, "layer diff error", "entry has no name")
require.NotZerof(t, len(components), "entry name %q has no components", entry.Name)
require.NotZerof(t, components[0], "entry name %q has no components", entry.Name)
// "split" the final part of the path from the rest
base := components[len(components)-1]
components = components[:len(components)-1]
// find the directory that contains this entry
for i, component := range components {
// this should be a parent directory, so check if it looks like a parent directory
if dirEntry.Children == nil {
require.Failf(t, "layer diff error", "layer diff %q includes entry for %q, but %q is not a directory", layer.UncompressedDigest, entry.Name, strings.Join(components[:i], string(os.PathSeparator)))
}
// if the directory is already there, move into it
if child, ok := dirEntry.Children[component]; ok {
dirEntry = child
continue
}
// if the directory should be there, but we haven't
// created it yet, blame the tool that generated this
// layer diff
require.Failf(t, "layer diff error", "layer diff %q includes entry for %q, but %q doesn't exist", layer.UncompressedDigest, entry.Name, strings.Join(components[:i], string(os.PathSeparator)))
}
// if the current directory is marked as "opaque", remove all
// of its contents
if base == ".wh..opq" {
dirEntry.Children = make(map[string]*FSEntry)
continue
}
// if the item is a whiteout, strip the "this is a whiteout
// entry" prefix and remove the item it names
if strings.HasPrefix(base, ".wh.") {
delete(dirEntry.Children, strings.TrimPrefix(base, ".wh."))
continue
}
// if the item already exists, make sure we don't get confused
// by replacing a directory with a non-directory or vice-versa
if child, ok := dirEntry.Children[base]; ok {
if child.Children != nil {
// it's a directory
if entry.Typeflag == tar.TypeDir {
// new entry is a directory, too. no
// sweat, just update the metadata
child.FSHeader = entry
continue
}
// nope, a directory no longer
} else {
// it's not a directory
if entry.Typeflag != tar.TypeDir {
// new entry is not a directory, too.
// no sweat, just update the metadata
dirEntry.Children[base].FSHeader = entry
continue
}
// well, it's a directory now
}
}
// the item doesn't already exist, or it needs to be replaced, so we need to add it
var children map[string]*FSEntry
if entry.Typeflag == tar.TypeDir {
// only directory entries can hold items
children = make(map[string]*FSEntry)
}
dirEntry.Children[base] = &FSEntry{FSHeader: entry, Children: children}
}
}
// read information about the specified image from the specified directory
func readReport(t *testing.T, directory string) (manifestType string, original, oci, fs map[string]interface{}) {
// read the manifest in the as-committed format, whatever that is
originalManifest, err := os.ReadFile(filepath.Join(directory, "manifest.json"))
require.NoErrorf(t, err, "error reading manifest %q", filepath.Join(directory, "manifest.json"))
// dump it into a map
manifest := make(map[string]interface{})
err = json.Unmarshal(originalManifest, &manifest)
require.NoErrorf(t, err, "error decoding manifest %q", filepath.Join(directory, "manifest.json"))
if str, ok := manifest["mediaType"].(string); ok {
manifestType = str
}
// read the config in the as-committed (docker) format
originalConfig, err := os.ReadFile(filepath.Join(directory, "config.json"))
require.NoErrorf(t, err, "error reading configuration file %q", filepath.Join(directory, "config.json"))
// dump it into a map
original = make(map[string]interface{})
err = json.Unmarshal(originalConfig, &original)
require.NoErrorf(t, err, "error decoding configuration from file %q", filepath.Join(directory, "config.json"))
// read the config in converted-to-OCI format
ociConfig, err := os.ReadFile(filepath.Join(directory, "oci-config.json"))
require.NoErrorf(t, err, "error reading OCI configuration file %q", filepath.Join(directory, "oci-config.json"))
// dump it into a map
oci = make(map[string]interface{})
err = json.Unmarshal(ociConfig, &oci)
require.NoErrorf(t, err, "error decoding OCI configuration from file %q", filepath.Join(directory, "oci.json"))
// read the filesystem
fsInfo, err := os.ReadFile(filepath.Join(directory, "fs.json"))
require.NoErrorf(t, err, "error reading filesystem summary file %q", filepath.Join(directory, "fs.json"))
// dump it into a map for comparison
fs = make(map[string]interface{})
err = json.Unmarshal(fsInfo, &fs)
require.NoErrorf(t, err, "error decoding filesystem summary from file %q", filepath.Join(directory, "fs.json"))
// return both
return manifestType, original, oci, fs
}
// contains is used to check if item exists in []string or not, ignoring case
func contains(slice []string, item string) bool {
for _, s := range slice {
if strings.EqualFold(s, item) {
return true
}
}
return false
}
// addPrefix prepends the given prefix to each string in []string.
// The prefix and the string are joined with ":"
func addPrefix(a []string, prefix string) []string {
b := make([]string, 0, len(a))
for _, s := range a {
b = append(b, prefix+":"+s)
}
return b
}
// diffDebug returns a row for a tabwriter that summarizes a field name and the
// values for that field in two documents
func diffDebug(k string, a, b interface{}) string {
if k == "mode" {
// force modes to be displayed in octal instead of decimal
a, aok := a.(float64)
b, bok := b.(float64)
if aok && bok {
return fmt.Sprintf("%v\t0%o\t0%o\n", k, int64(a), int64(b))
}
}
return fmt.Sprintf("%v\t%v\t%v\n", k, a, b)
}
// compareJSON compares two parsed JSON structures. missKeys and leftKeys are
// lists of field names present only in the first map or the second,
// respectively, while diffKeys is a list of items which are present in both
// maps, but which have different values, formatted with diffDebug.
func compareJSON(a, b map[string]interface{}, skip []string) (missKeys, leftKeys, diffKeys []string, isSame bool) {
isSame = true
for k, v := range a {
vb, ok := b[k]
if ok {
// remove this item from b. when we're done, all that's
// left in b will be the items that weren't also in a.
delete(b, k)
}
if contains(skip, k) {
continue
}
if !ok {
// key is in a, but not in b
missKeys = append(missKeys, k)
isSame = false
continue
}
if reflect.TypeOf(v) != reflect.TypeOf(vb) {
if reflect.TypeOf(v) == nil && reflect.ValueOf(vb).Len() == 0 {
continue
}
if reflect.TypeOf(vb) == nil && reflect.ValueOf(v).Len() == 0 {
continue
}
diffKeys = append(diffKeys, diffDebug(k, v, vb))
isSame = false
continue
}
switch v.(type) {
case map[string]interface{}:
// this field in the object is itself an object (e.g.
// "config" or "container_config"), so recursively
// compare them
var nextSkip []string
prefix := k + ":"
for _, s := range skip {
if strings.HasPrefix(s, prefix) {
nextSkip = append(nextSkip, strings.TrimPrefix(s, prefix))
}
}
submiss, subleft, subdiff, ok := compareJSON(v.(map[string]interface{}), vb.(map[string]interface{}), nextSkip)
missKeys = append(missKeys, addPrefix(submiss, k)...)
leftKeys = append(leftKeys, addPrefix(subleft, k)...)
diffKeys = append(diffKeys, addPrefix(subdiff, k)...)
if !ok {
isSame = false
}
case []interface{}:
// this field in the object is an array; make sure both
// arrays have the same set of elements, which is more
// or less correct for labels and environment
// variables.
// this will break if it tries to compare an array of
// objects like "history", since maps, slices, and
// functions can't be used as keys in maps
tmpa := v.([]interface{})
tmpb := vb.([]interface{})
if len(tmpa) != len(tmpb) {
diffKeys = append(diffKeys, diffDebug(k, v, vb))
isSame = false
break
}
m := make(map[interface{}]struct{})
for i := 0; i < len(tmpb); i++ {
m[tmpb[i]] = struct{}{}
}
for i := 0; i < len(tmpa); i++ {
if _, ok := m[tmpa[i]]; !ok {
diffKeys = append(diffKeys, diffDebug(k, v, vb))
isSame = false
break
}
}
default:
// this field in the object is neither an object nor an
// array, so assume it's a scalar item
if !reflect.DeepEqual(v, vb) {
diffKeys = append(diffKeys, diffDebug(k, v, vb))
isSame = false
}
}
}
if len(b) > 0 {
for k := range b {
if !contains(skip, k) {
leftKeys = append(leftKeys, k)
}
}
}
return slices.Clone(missKeys), slices.Clone(leftKeys), slices.Clone(diffKeys), isSame
}
// configCompareResult summarizes the output of compareJSON for display
func configCompareResult(miss, left, diff []string, notDocker string) string {
var buffer bytes.Buffer
if len(miss) > 0 {
buffer.WriteString(fmt.Sprintf("Fields missing from %s version: %s\n", notDocker, strings.Join(miss, " ")))
}
if len(left) > 0 {
buffer.WriteString(fmt.Sprintf("Fields which only exist in %s version: %s\n", notDocker, strings.Join(left, " ")))
}
if len(diff) > 0 {
buffer.WriteString("Fields present in both versions have different values:\n")
tw := tabwriter.NewWriter(&buffer, 1, 1, 8, ' ', 0)
if _, err := tw.Write([]byte(fmt.Sprintf("Field\tDocker\t%s\n", notDocker))); err != nil {
panic(err)
}
for _, d := range diff {
if _, err := tw.Write([]byte(d)); err != nil {
panic(err)
}
}
tw.Flush()
}
return buffer.String()
}
// fsCompareResult summarizes the output of compareJSON for display
func fsCompareResult(miss, left, diff []string, notDocker string) string {
var buffer bytes.Buffer
fixup := func(names []string) []string {
n := make([]string, 0, len(names))
for _, name := range names {
n = append(n, strings.ReplaceAll(strings.ReplaceAll(name, ":(dir):", "/"), "(dir):", "/"))
}
return n
}
if len(miss) > 0 {
buffer.WriteString(fmt.Sprintf("Content missing from %s version: %s\n", notDocker, strings.Join(fixup(miss), " ")))
}
if len(left) > 0 {
buffer.WriteString(fmt.Sprintf("Content which only exists in %s version: %s\n", notDocker, strings.Join(fixup(left), " ")))
}
if len(diff) > 0 {
buffer.WriteString("File attributes in both versions have different values:\n")
tw := tabwriter.NewWriter(&buffer, 1, 1, 8, ' ', 0)
if _, err := tw.Write([]byte(fmt.Sprintf("File:attr\tDocker\t%s\n", notDocker))); err != nil {
panic(err)
}
for _, d := range fixup(diff) {
if _, err := tw.Write([]byte(d)); err != nil {
panic(err)
}
}
tw.Flush()
}
return buffer.String()
}
type (
testCaseTweakContextDirFn func(*testing.T, string, string, string) error
testCase struct {
name string // name of the test
dockerfileContents string // inlined Dockerfile content to use instead of possible file in the build context
dockerfile string // name of the Dockerfile, relative to contextDir, if not Dockerfile
contextDir string // name of context subdirectory, if there is one to be copied
tweakContextDir testCaseTweakContextDirFn // callback to make updates to the temporary build context before we build it
shouldFailAt int // line where a build is expected to fail (starts with 1, 0 if it should succeed
buildahRegex string // if set, expect this to be present in output
dockerRegex string // if set, expect this to be present in output
imagebuilderRegex string // if set, expect this to be present in output
buildahErrRegex string // if set, expect this to be present in output
dockerErrRegex string // if set, expect this to be present in output
imagebuilderErrRegex string // if set, expect this to be present in output
failureRegex string // if set, expect this to be present in output when the build fails
withoutImagebuilder bool // don't build this with imagebuilder, because it depends on a buildah-specific feature
withoutDocker bool // don't build this with docker, because it depends on a buildah-specific feature
dockerUseBuildKit bool // if building with docker, request that dockerd use buildkit
dockerBuilderVersion docker.BuilderVersion // if building with docker, request the specific builder
testUsingSetParent bool // test both with old (gets set) and new (left blank) config.Parent behavior
compatSetParent types.OptionalBool // placeholder for a value to set for the buildah compatSetParent flag
testUsingVolumes bool // test both with old (preserved) and new (just a config note) volume behavior
compatVolumes types.OptionalBool // placeholder for a value to set for the buildah compatVolumes flag
compatScratchConfig types.OptionalBool // placeholder for a value to set for the buildah compatScratchConfig flag
transientMounts []string // one possible buildah-specific feature
fsSkip []string // expected filesystem differences, typically timestamps on files or directories we create or modify during the build and don't reset
buildArgs map[string]string // build args to supply, as if --build-arg was used
}
)
var internalTestCases = []testCase{
{
name: "shell test",
dockerfile: "Dockerfile.shell",
buildahRegex: "(?s)[0-9a-z]+(.*)--",
dockerRegex: "(?s)RUN env.*?Running in [0-9a-z]+(.*?)---",
},
{
name: "copy-escape-glob",
contextDir: "copy-escape-glob",
fsSkip: []string{"(dir):app:mtime", "(dir):app2:mtime", "(dir):app3:mtime", "(dir):app4:mtime", "(dir):app5:mtime"},
tweakContextDir: func(t *testing.T, contextDir, _, _ string) error {
appDir := filepath.Join(contextDir, "app")
jklDir := filepath.Join(appDir, "jkl?")
require.NoError(t, os.Mkdir(jklDir, 0o700))
jklFile := filepath.Join(jklDir, "file.txt")
require.NoError(t, os.WriteFile(jklFile, []byte("another"), 0o600))
nopeDir := filepath.Join(appDir, "n?pe")
require.NoError(t, os.Mkdir(nopeDir, 0o700))
nopeFile := filepath.Join(nopeDir, "file.txt")
require.NoError(t, os.WriteFile(nopeFile, []byte("and also"), 0o600))
stuvDir := filepath.Join(appDir, "st*uv")
require.NoError(t, os.Mkdir(stuvDir, 0o700))
stuvFile := filepath.Join(stuvDir, "file.txt")
require.NoError(t, os.WriteFile(stuvFile, []byte("and yet"), 0o600))
return nil
},
dockerUseBuildKit: true,
},
{
name: "copy file to root",
dockerfile: "Dockerfile.copyfrom_1",
buildahRegex: "[-rw]+.*?/a",
fsSkip: []string{"(dir):a:mtime"},
},
{
name: "copy file to same file",
dockerfile: "Dockerfile.copyfrom_2",
buildahRegex: "[-rw]+.*?/a",
fsSkip: []string{"(dir):a:mtime"},
},
{
name: "copy file to workdir",
dockerfile: "Dockerfile.copyfrom_3",
buildahRegex: "[-rw]+.*?/b/a",
fsSkip: []string{"(dir):b:mtime", "(dir):b:(dir):a:mtime"},
},
{
name: "copy file to workdir rename",
dockerfile: "Dockerfile.copyfrom_3_1",
buildahRegex: "[-rw]+.*?/b/b",
fsSkip: []string{"(dir):b:mtime", "(dir):b:(dir):a:mtime"},
},
{
name: "copy folder contents to higher level",
dockerfile: "Dockerfile.copyfrom_4",
buildahRegex: "(?s)[-rw]+.*?/b/1.*?[-rw]+.*?/b/2.*?/b.*?[-rw]+.*?1.*?[-rw]+.*?2",
buildahErrRegex: "/a: No such file or directory",
fsSkip: []string{"(dir):b:mtime"},
},
{
name: "copy wildcard folder contents to higher level",
dockerfile: "Dockerfile.copyfrom_5",
buildahRegex: "(?s)[-rw]+.*?/b/1.*?[-rw]+.*?/b/2.*?/b.*?[-rw]+.*?1.*?[-rw]+.*?2",
buildahErrRegex: "(?s)/a: No such file or directory.*?/b/a: No such file or directory.*?/b/b: No such file or director",
fsSkip: []string{"(dir):b:mtime", "(dir):b:(dir):1:mtime", "(dir):b:(dir):2:mtime"},
},
{
name: "copy folder with dot contents to higher level",
dockerfile: "Dockerfile.copyfrom_6",
buildahRegex: "(?s)[-rw]+.*?/b/1.*?[-rw]+.*?/b/2.*?/b.*?[-rw]+.*?1.*?[-rw]+.*?2",
buildahErrRegex: "(?s)/a: No such file or directory.*?/b/a: No such file or directory.*?/b/b: No such file or director",
fsSkip: []string{"(dir):b:mtime", "(dir):b:(dir):1:mtime", "(dir):b:(dir):2:mtime"},
},
{
name: "copy root file to different root name",
dockerfile: "Dockerfile.copyfrom_7",
buildahRegex: "[-rw]+.*?/a",
buildahErrRegex: "/b: No such file or directory",
fsSkip: []string{"(dir):a:mtime"},
},
{
name: "copy nested file to different root name",
dockerfile: "Dockerfile.copyfrom_8",
buildahRegex: "[-rw]+.*?/a",
buildahErrRegex: "/b: No such file or directory",
fsSkip: []string{"(dir):a:mtime"},
},
{
name: "copy file to deeper directory with explicit slash",
dockerfile: "Dockerfile.copyfrom_9",
buildahRegex: "[-rw]+.*?/a/b/c/1",
buildahErrRegex: "/a/b/1: No such file or directory",
fsSkip: []string{"(dir):a:mtime", "(dir):a:(dir):b:mtime", "(dir):a:(dir):b:(dir):c:mtime", "(dir):a:(dir):b:(dir):c:(dir):1:mtime"},
},
{
name: "copy file to deeper directory without explicit slash",
dockerfile: "Dockerfile.copyfrom_10",
buildahRegex: "[-rw]+.*?/a/b/c",
buildahErrRegex: "/a/b/1: No such file or directory",
fsSkip: []string{"(dir):a:mtime", "(dir):a:(dir):b:mtime", "(dir):a:(dir):b:(dir):c:mtime"},
},
{
name: "copy directory to deeper directory without explicit slash",
dockerfile: "Dockerfile.copyfrom_11",
buildahRegex: "[-rw]+.*?/a/b/c/1",
buildahErrRegex: "/a/b/1: No such file or directory",
fsSkip: []string{
"(dir):a:mtime", "(dir):a:(dir):b:mtime", "(dir):a:(dir):b:(dir):c:mtime",
"(dir):a:(dir):b:(dir):c:(dir):1:mtime",
},
},
{
name: "copy directory to root without explicit slash",
dockerfile: "Dockerfile.copyfrom_12",
buildahRegex: "[-rw]+.*?/a/1",
buildahErrRegex: "/a/a: No such file or directory",
fsSkip: []string{"(dir):a:mtime", "(dir):a:(dir):1:mtime"},
},
{
name: "copy directory trailing to root without explicit slash",
dockerfile: "Dockerfile.copyfrom_13",
buildahRegex: "[-rw]+.*?/a/1",
buildahErrRegex: "/a/a: No such file or directory",
fsSkip: []string{"(dir):a:mtime", "(dir):a:(dir):1:mtime"},
},
{
name: "multi stage base",
dockerfile: "Dockerfile.reusebase",
buildahRegex: "[0-9a-z]+ /1",
fsSkip: []string{"(dir):1:mtime"},
},
{
name: "directory",
contextDir: "dir",
fsSkip: []string{"(dir):dir:mtime", "(dir):test:mtime"},
},
{
name: "copy to dir",
contextDir: "copy",
fsSkip: []string{"(dir):usr:(dir):bin:mtime"},
},
{
name: "copy dir",
contextDir: "copydir",
fsSkip: []string{"(dir):dir"},
},
{
name: "copy from symlink source",
contextDir: "copysymlink",
},
{
name: "copy-symlink-2",
contextDir: "copysymlink",
dockerfile: "Dockerfile2",
},
{
name: "copy from subdir to new directory",
contextDir: "copydir",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY dir/file /subdir/",
}, "\n"),
fsSkip: []string{"(dir):subdir"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "copy to renamed file",
contextDir: "copyrename",
fsSkip: []string{"(dir):usr:(dir):bin:mtime"},
},
{
name: "copy with --chown",
contextDir: "copychown",
fsSkip: []string{"(dir):usr:(dir):bin:mtime", "(dir):usr:(dir):local:(dir):bin:mtime"},
},
{
name: "directory with slash",
contextDir: "overlapdirwithslash",
},
{
name: "directory without slash",
contextDir: "overlapdirwithoutslash",
},
{
name: "environment",
dockerfile: "Dockerfile.env",
shouldFailAt: 12,
},
{
name: "edgecases",
dockerfile: "Dockerfile.edgecases",
fsSkip: []string{
"(dir):test:mtime", "(dir):test:(dir):copy:mtime", "(dir):test2:mtime", "(dir):test3:mtime",
"(dir):test3:(dir):copy:mtime",
"(dir):test3:(dir):test:mtime", "(dir):tmp:mtime", "(dir):tmp:(dir):passwd:mtime",
},
},
{
name: "exposed default",
dockerfile: "Dockerfile.exposedefault",
testUsingSetParent: true,
},
{
name: "add",
dockerfile: "Dockerfile.add",
fsSkip: []string{"(dir):b:mtime", "(dir):tmp:mtime"},
},
{
name: "run with JSON",
dockerfile: "Dockerfile.run.args",
buildahRegex: "(first|third|fifth|inner) (second|fourth|sixth|outer)",
dockerRegex: "Running in [0-9a-z]+.*?(first|third|fifth|inner) (second|fourth|sixth|outer)",
},
{
name: "wildcard",
contextDir: "wildcard",
fsSkip: []string{"(dir):usr:mtime", "(dir):usr:(dir):test:mtime"},
},
{
name: "volume",
contextDir: "volume",
fsSkip: []string{"(dir):var:mtime", "(dir):var:(dir):www:mtime"},
testUsingVolumes: true,
},
{
name: "volumerun",
contextDir: "volumerun",
fsSkip: []string{"(dir):var:mtime", "(dir):var:(dir):www:mtime"},
testUsingVolumes: true,
},
{
name: "mount",
contextDir: "mount",
buildahRegex: "/tmp/test/file.*?regular file.*?/tmp/test/file2.*?regular file",
withoutDocker: true,
transientMounts: []string{"@@TEMPDIR@@:/tmp/test" + selinuxMountFlag()},
},
{
name: "transient-mount",
contextDir: "transientmount",
buildahRegex: "file2.*?FROM mirror.gcr.io/busybox ENV name value",
withoutDocker: true,
transientMounts: []string{
"@@TEMPDIR@@:/mountdir" + selinuxMountFlag(),
"@@TEMPDIR@@/Dockerfile.env:/mountfile" + selinuxMountFlag(),
},
},
{
// from internal team chat
name: "ci-pipeline-modified",
dockerfileContents: strings.Join([]string{
"FROM mirror.gcr.io/busybox",
"WORKDIR /go/src/github.com/openshift/ocp-release-operator-sdk/",
"ENV GOPATH=/go",
"RUN env | grep -E -v '^(HOSTNAME|OLDPWD)=' | LANG=C sort | tee /env-contents.txt\n",
}, "\n"),
fsSkip: []string{
"(dir):go:mtime",
"(dir):go:(dir):src:mtime",
"(dir):go:(dir):src:(dir):github.com:mtime",
"(dir):go:(dir):src:(dir):github.com:(dir):openshift:mtime",
"(dir):go:(dir):src:(dir):github.com:(dir):openshift:(dir):ocp-release-operator-sdk:mtime",
"(dir):env-contents.txt:mtime",
},
},
{
name: "add-permissions",
withoutDocker: true,
dockerfileContents: strings.Join([]string{
"FROM scratch",
"# Does ADD preserve permissions differently for archives and files?",
"ADD archive.tar subdir1/",
"ADD archive/ subdir2/",
}, "\n"),
tweakContextDir: func(_ *testing.T, contextDir, _, _ string) (err error) {
content := []byte("test content")
if err := os.Mkdir(filepath.Join(contextDir, "archive"), 0o755); err != nil {
return fmt.Errorf("creating subdirectory of temporary context directory: %w", err)
}
filename := filepath.Join(contextDir, "archive", "should-be-owned-by-root")
if err = os.WriteFile(filename, content, 0o640); err != nil {
return fmt.Errorf("creating file owned by root in temporary context directory: %w", err)
}
if err = os.Chown(filename, 0, 0); err != nil {
return fmt.Errorf("setting ownership on file owned by root in temporary context directory: %w", err)
}
if err = os.Chtimes(filename, testDate, testDate); err != nil {
return fmt.Errorf("setting date on file owned by root file in temporary context directory: %w", err)
}
filename = filepath.Join(contextDir, "archive", "should-be-owned-by-99")
if err = os.WriteFile(filename, content, 0o640); err != nil {
return fmt.Errorf("creating file owned by 99 in temporary context directory: %w", err)
}
if err = os.Chown(filename, 99, 99); err != nil {
return fmt.Errorf("setting ownership on file owned by 99 in temporary context directory: %w", err)
}
if err = os.Chtimes(filename, testDate, testDate); err != nil {
return fmt.Errorf("setting date on file owned by 99 in temporary context directory: %w", err)
}
filename = filepath.Join(contextDir, "archive.tar")
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
return fmt.Errorf("creating archive file: %w", err)
}
defer f.Close()
tw := tar.NewWriter(f)
defer tw.Close()
err = tw.WriteHeader(&tar.Header{
Name: "archive/should-be-owned-by-root",
Typeflag: tar.TypeReg,
Size: int64(len(content)),
ModTime: testDate,
Mode: 0o640,
Uid: 0,
Gid: 0,
})
if err != nil {
return fmt.Errorf("writing archive file header: %w", err)
}
n, err := tw.Write(content)
if err != nil {
return fmt.Errorf("writing archive file contents: %w", err)
}
if n != len(content) {
return errors.New("short write writing archive file contents")
}
err = tw.WriteHeader(&tar.Header{
Name: "archive/should-be-owned-by-99",
Typeflag: tar.TypeReg,
Size: int64(len(content)),
ModTime: testDate,
Mode: 0o640,
Uid: 99,
Gid: 99,
})
if err != nil {
return fmt.Errorf("writing archive file header: %w", err)
}
n, err = tw.Write(content)
if err != nil {
return fmt.Errorf("writing archive file contents: %w", err)
}
if n != len(content) {
return errors.New("short write writing archive file contents")
}
return nil
},
fsSkip: []string{"(dir):subdir1:mtime", "(dir):subdir2:mtime"},
},
{
name: "copy-permissions",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"# Does COPY --chown change permissions on already-present directories?",
"COPY subdir/ subdir/",
"COPY --chown=99:99 subdir/ subdir/",
}, "\n"),
tweakContextDir: func(_ *testing.T, contextDir, _, _ string) (err error) {
content := []byte("test content")
if err := os.Mkdir(filepath.Join(contextDir, "subdir"), 0o755); err != nil {
return fmt.Errorf("creating subdirectory of temporary context directory: %w", err)
}
filename := filepath.Join(contextDir, "subdir", "would-be-owned-by-root")
if err = os.WriteFile(filename, content, 0o640); err != nil {
return fmt.Errorf("creating file owned by root in temporary context directory: %w", err)
}
if err = os.Chown(filename, 0, 0); err != nil {
return fmt.Errorf("setting ownership on file owned by root in temporary context directory: %w", err)
}
if err = os.Chtimes(filename, testDate, testDate); err != nil {
return fmt.Errorf("setting date on file owned by root file in temporary context directory: %w", err)
}
filename = filepath.Join(contextDir, "subdir", "would-be-owned-by-99")
if err = os.WriteFile(filename, content, 0o640); err != nil {
return fmt.Errorf("creating file owned by 99 in temporary context directory: %w", err)
}
if err = os.Chown(filename, 99, 99); err != nil {
return fmt.Errorf("setting ownership on file owned by 99 in temporary context directory: %w", err)
}
if err = os.Chtimes(filename, testDate, testDate); err != nil {
return fmt.Errorf("setting date on file owned by 99 in temporary context directory: %w", err)
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "copy-permissions-implicit",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"# Does COPY --chown change permissions on already-present directories?",
"COPY --chown=99:99 subdir/ subdir/",
"COPY subdir/ subdir/",
}, "\n"),
tweakContextDir: func(_ *testing.T, contextDir, _, _ string) (err error) {
content := []byte("test content")
if err := os.Mkdir(filepath.Join(contextDir, "subdir"), 0o755); err != nil {
return fmt.Errorf("creating subdirectory of temporary context directory: %w", err)
}
filename := filepath.Join(contextDir, "subdir", "would-be-owned-by-root")
if err = os.WriteFile(filename, content, 0o640); err != nil {
return fmt.Errorf("creating file owned by root in temporary context directory: %w", err)
}
if err = os.Chown(filename, 0, 0); err != nil {
return fmt.Errorf("setting ownership on file owned by root in temporary context directory: %w", err)
}
if err = os.Chtimes(filename, testDate, testDate); err != nil {
return fmt.Errorf("setting date on file owned by root file in temporary context directory: %w", err)
}
filename = filepath.Join(contextDir, "subdir", "would-be-owned-by-99")
if err = os.WriteFile(filename, content, 0o640); err != nil {
return fmt.Errorf("creating file owned by 99 in temporary context directory: %w", err)
}
if err = os.Chown(filename, 99, 99); err != nil {
return fmt.Errorf("setting ownership on file owned by 99 in temporary context directory: %w", err)
}
if err = os.Chtimes(filename, testDate, testDate); err != nil {
return fmt.Errorf("setting date on file owned by 99 in temporary context directory: %w", err)
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
// the digest just ensures that we can handle a digest
// reference to a manifest list; the digest of any manifest
// list in the image repository would do
name: "stage-container-as-source-plus-hardlinks",
dockerfileContents: strings.Join([]string{
"FROM mirror.gcr.io/busybox@sha256:9ae97d36d26566ff84e8893c64a6dc4fe8ca6d1144bf5b87b2b85a32def253c7 AS build",
"RUN mkdir -p /target/subdir",
"RUN cp -p /etc/passwd /target/",
"RUN ln /target/passwd /target/subdir/passwd",
"RUN ln /target/subdir/passwd /target/subdir/passwd2",
"FROM scratch",
"COPY --from=build /target/subdir /subdir",
}, "\n"),
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "dockerfile-in-subdirectory",
dockerfile: "subdir/Dockerfile",
contextDir: "subdir",
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "setuid-file-in-context",
dockerfileContents: strings.Join([]string{
"FROM scratch",
fmt.Sprintf("# Does the setuid file (0%o) in the context dir end up setuid in the image?", syscall.S_ISUID),
"COPY . subdir1",
"ADD . subdir2",
}, "\n"),
tweakContextDir: func(_ *testing.T, contextDir, _, _ string) (err error) {
filename := filepath.Join(contextDir, "should-be-setuid-file")
if err = os.WriteFile(filename, []byte("test content"), 0o644); err != nil {
return fmt.Errorf("creating setuid test file in temporary context directory: %w", err)
}
if err = syscall.Chmod(filename, syscall.S_ISUID|0o755); err != nil {
return fmt.Errorf("setting setuid bit on test file in temporary context directory: %w", err)
}
if err = os.Chtimes(filename, testDate, testDate); err != nil {
return fmt.Errorf("setting date on setuid test file in temporary context directory: %w", err)
}
filename = filepath.Join(contextDir, "should-be-setgid-file")
if err = os.WriteFile(filename, []byte("test content"), 0o644); err != nil {
return fmt.Errorf("creating setgid test file in temporary context directory: %w", err)
}
if err = syscall.Chmod(filename, syscall.S_ISGID|0o755); err != nil {
return fmt.Errorf("setting setgid bit on test file in temporary context directory: %w", err)
}
if err = os.Chtimes(filename, testDate, testDate); err != nil {
return fmt.Errorf("setting date on setgid test file in temporary context directory: %w", err)
}
filename = filepath.Join(contextDir, "should-be-sticky-file")
if err = os.WriteFile(filename, []byte("test content"), 0o644); err != nil {
return fmt.Errorf("creating sticky test file in temporary context directory: %w", err)
}
if err = syscall.Chmod(filename, syscall.S_ISVTX|0o755); err != nil {
return fmt.Errorf("setting permissions on sticky test file in temporary context directory: %w", err)
}
if err = os.Chtimes(filename, testDate, testDate); err != nil {
return fmt.Errorf("setting date on sticky test file in temporary context directory: %w", err)
}
filename = filepath.Join(contextDir, "should-not-be-setuid-setgid-sticky-file")
if err = os.WriteFile(filename, []byte("test content"), 0o644); err != nil {
return fmt.Errorf("creating non-suid non-sgid non-sticky test file in temporary context directory: %w", err)
}
if err = syscall.Chmod(filename, 0o640); err != nil {
return fmt.Errorf("setting permissions on plain test file in temporary context directory: %w", err)
}
if err = os.Chtimes(filename, testDate, testDate); err != nil {
return fmt.Errorf("setting date on plain test file in temporary context directory: %w", err)
}
return nil
},
fsSkip: []string{"(dir):subdir1:mtime", "(dir):subdir2:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "xattrs-file-in-context",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"# Do the xattrs on a file in the context dir end up in the image?",
"COPY . subdir1",
"ADD . subdir2",
}, "\n"),
tweakContextDir: func(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
if !*contextCanDoXattrs {
t.Skipf("test context directory %q doesn't support xattrs", contextDir)
}
if !*storageCanDoXattrs {
t.Skipf("test storage driver %q and directory %q don't support xattrs together", storageDriver, storageRoot)
}
filename := filepath.Join(contextDir, "xattrs-file")
if err = os.WriteFile(filename, []byte("test content"), 0o644); err != nil {
return fmt.Errorf("creating test file with xattrs in temporary context directory: %w", err)
}
if err = copier.Lsetxattrs(filename, map[string]string{"user.a": "test"}); err != nil {
return fmt.Errorf("setting xattrs on test file in temporary context directory: %w", err)
}
if err = syscall.Chmod(filename, 0o640); err != nil {
return fmt.Errorf("setting permissions on test file in temporary context directory: %w", err)
}
if err = os.Chtimes(filename, testDate, testDate); err != nil {
return fmt.Errorf("setting date on test file in temporary context directory: %w", err)
}
return nil
},
fsSkip: []string{"(dir):subdir1:mtime", "(dir):subdir2:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "setuid-file-in-archive",
dockerfileContents: strings.Join([]string{
"FROM scratch",
fmt.Sprintf("# Do the setuid/setgid/sticky files in this archive end up setuid(0%o)/setgid(0%o)/sticky(0%o)?", syscall.S_ISUID, syscall.S_ISGID, syscall.S_ISVTX),
"ADD archive.tar .",
}, "\n"),
tweakContextDir: func(_ *testing.T, contextDir, _, _ string) (err error) {
filename := filepath.Join(contextDir, "archive.tar")
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
return fmt.Errorf("creating new archive file in temporary context directory: %w", err)
}
defer f.Close()
tw := tar.NewWriter(f)
defer tw.Close()
hdr := tar.Header{
Name: "setuid-file",
Uid: 0,
Gid: 0,
Typeflag: tar.TypeReg,
Size: 8,
Mode: cISUID | 0o755,
ModTime: testDate,
}
if err = tw.WriteHeader(&hdr); err != nil {
return fmt.Errorf("writing tar archive header: %w", err)
}
if _, err = io.Copy(tw, bytes.NewReader([]byte("whatever"))); err != nil {
return fmt.Errorf("writing tar archive content: %w", err)
}
hdr = tar.Header{
Name: "setgid-file",
Uid: 0,
Gid: 0,
Typeflag: tar.TypeReg,
Size: 8,
Mode: cISGID | 0o755,
ModTime: testDate,
}
if err = tw.WriteHeader(&hdr); err != nil {
return fmt.Errorf("writing tar archive header: %w", err)
}
if _, err = io.Copy(tw, bytes.NewReader([]byte("whatever"))); err != nil {
return fmt.Errorf("writing tar archive content: %w", err)
}
hdr = tar.Header{
Name: "sticky-file",
Uid: 0,
Gid: 0,
Typeflag: tar.TypeReg,
Size: 8,
Mode: cISVTX | 0o755,
ModTime: testDate,
}
if err = tw.WriteHeader(&hdr); err != nil {
return fmt.Errorf("writing tar archive header: %w", err)
}
if _, err = io.Copy(tw, bytes.NewReader([]byte("whatever"))); err != nil {
return fmt.Errorf("writing tar archive content: %w", err)
}
hdr = tar.Header{
Name: "setuid-dir",
Uid: 0,
Gid: 0,
Typeflag: tar.TypeDir,
Size: 0,
Mode: cISUID | 0o755,
ModTime: testDate,
}
if err = tw.WriteHeader(&hdr); err != nil {
return fmt.Errorf("error writing tar archive header: %w", err)
}
hdr = tar.Header{
Name: "setgid-dir",
Uid: 0,
Gid: 0,
Typeflag: tar.TypeDir,
Size: 0,
Mode: cISGID | 0o755,
ModTime: testDate,
}
if err = tw.WriteHeader(&hdr); err != nil {
return fmt.Errorf("error writing tar archive header: %w", err)
}
hdr = tar.Header{
Name: "sticky-dir",
Uid: 0,
Gid: 0,
Typeflag: tar.TypeDir,
Size: 0,
Mode: cISVTX | 0o755,
ModTime: testDate,
}
if err = tw.WriteHeader(&hdr); err != nil {
return fmt.Errorf("error writing tar archive header: %w", err)
}
return nil
},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "xattrs-file-in-archive",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"# Do the xattrs on a file in an archive end up in the image?",
"ADD archive.tar .",
}, "\n"),
tweakContextDir: func(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
if !*contextCanDoXattrs {
t.Skipf("test context directory %q doesn't support xattrs", contextDir)
}
if !*storageCanDoXattrs {
t.Skipf("test storage driver %q and directory %q don't support xattrs together", storageDriver, storageRoot)
}
filename := filepath.Join(contextDir, "archive.tar")
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
return fmt.Errorf("creating new archive file in temporary context directory: %w", err)
}
defer f.Close()
tw := tar.NewWriter(f)
defer tw.Close()
hdr := tar.Header{
Name: "xattr-file",
Uid: 0,
Gid: 0,
Typeflag: tar.TypeReg,
Size: 8,
Mode: 0o640,
ModTime: testDate,
PAXRecords: map[string]string{
xattrPAXRecordNamespace + "user.a": "test",
},
}
if err = tw.WriteHeader(&hdr); err != nil {
return fmt.Errorf("writing tar archive header: %w", err)
}
if _, err = io.Copy(tw, bytes.NewReader([]byte("whatever"))); err != nil {
return fmt.Errorf("writing tar archive content: %w", err)
}
return nil
},
fsSkip: []string{"(dir):subdir1:mtime", "(dir):subdir2:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
// docker build apparently stopped preserving this bit somewhere between 18.09.7 and 19.03,
// possibly around https://github.com/moby/moby/pull/38599
name: "setuid-file-in-other-stage",
dockerfileContents: strings.Join([]string{
"FROM mirror.gcr.io/busybox",
"RUN mkdir /a && echo whatever > /a/setuid && chmod u+xs /a/setuid && touch -t @1485449953 /a/setuid",
"RUN mkdir /b && echo whatever > /b/setgid && chmod g+xs /b/setgid && touch -t @1485449953 /b/setgid",
"RUN mkdir /c && echo whatever > /c/sticky && chmod o+x /c/sticky && chmod +t /c/sticky && touch -t @1485449953 /c/sticky",
"FROM scratch",
fmt.Sprintf("# Does this setuid/setgid/sticky file copied from another stage end up setuid/setgid/sticky (0%o/0%o/0%o)?", syscall.S_ISUID, syscall.S_ISGID, syscall.S_ISVTX),
"COPY --from=0 /a/setuid /b/setgid /c/sticky /",
}, "\n"),
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "xattrs-file-in-other-stage",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY . .",
"FROM scratch",
"# Do the xattrs on a file in another stage end up in the image?",
"COPY --from=0 /xattrs-file /",
}, "\n"),
tweakContextDir: func(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
if !*contextCanDoXattrs {
t.Skipf("test context directory %q doesn't support xattrs", contextDir)
}
if !*storageCanDoXattrs {
t.Skipf("test storage driver %q and directory %q don't support xattrs together", storageDriver, storageRoot)
}
filename := filepath.Join(contextDir, "xattrs-file")
if err = os.WriteFile(filename, []byte("test content"), 0o644); err != nil {
return fmt.Errorf("creating test file with xattrs in temporary context directory: %w", err)
}
if err = copier.Lsetxattrs(filename, map[string]string{"user.a": "test"}); err != nil {
return fmt.Errorf("setting xattrs on test file in temporary context directory: %w", err)
}
if err = syscall.Chmod(filename, 0o640); err != nil {
return fmt.Errorf("setting permissions on test file in temporary context directory: %w", err)
}
if err = os.Chtimes(filename, testDate, testDate); err != nil {
return fmt.Errorf("setting date on test file in temporary context directory: %w", err)
}
return nil
},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "copy-multiple-some-missing",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY file-a.txt subdir-a file-z.txt subdir-z subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
shouldFailAt: 2,
},
{
name: "copy-multiple-missing-file-with-glob",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY file-z.txt subdir-* subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
shouldFailAt: 2,
},
{
name: "copy-multiple-missing-file-with-nomatch-on-glob",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY missing* subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
shouldFailAt: 2,
},
{
name: "copy-multiple-some-missing-glob",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY file-a.txt subdir-* file-?.txt missing* subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "file-in-workdir-in-other-stage",
dockerfileContents: strings.Join([]string{
"FROM scratch AS base",
"COPY . /subdir/",
"WORKDIR /subdir",
"FROM base",
"COPY --from=base . .", // --from=otherstage ignores that stage's WORKDIR
}, "\n"),
contextDir: "dockerignore/populated",
fsSkip: []string{"(dir):subdir:mtime", "(dir):subdir:(dir):subdir:mtime"},
},
{
name: "copy-integration1",
contextDir: "dockerignore/integration1",
shouldFailAt: 3,
failureRegex: "(no such file or directory)|(file not found)|(file does not exist)",
},
{
name: "copy-integration2",
contextDir: "dockerignore/integration2",
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "copy-integration3",
contextDir: "dockerignore/integration3",
shouldFailAt: 4,
failureRegex: "(no such file or directory)|(file not found)|(file does not exist)",
},
{
name: "copy-empty-1",
contextDir: "copyempty",
dockerfile: "Dockerfile",
fsSkip: []string{"(dir):usr:(dir):local:mtime", "(dir):usr:(dir):local:(dir):tmp:mtime"},
},
{
name: "copy-empty-2",
contextDir: "copyempty",
dockerfile: "Dockerfile2",
fsSkip: []string{"(dir):usr:(dir):local:mtime", "(dir):usr:(dir):local:(dir):tmp:mtime"},
},
{
name: "copy-absolute-directory-1",
contextDir: "copyblahblub",
dockerfile: "Dockerfile",
fsSkip: []string{"(dir):var:mtime"},
},
{
name: "copy-absolute-directory-2",
contextDir: "copyblahblub",
dockerfile: "Dockerfile2",
fsSkip: []string{"(dir):var:mtime"},
},
{
name: "copy-absolute-directory-3",
contextDir: "copyblahblub",
dockerfile: "Dockerfile3",
fsSkip: []string{"(dir):var:mtime"},
},
{
name: "multi-stage-through-base",
dockerfileContents: strings.Join([]string{
"FROM mirror.gcr.io/alpine AS base",
"RUN touch -t @1485449953 /1",
"ENV LOCAL=/1",
"RUN find $LOCAL",
"FROM base",
"RUN find $LOCAL",
}, "\n"),
fsSkip: []string{"(dir):root:mtime", "(dir):1:mtime"},
},
{
name: "multi-stage-derived", // from #2415
dockerfileContents: strings.Join([]string{
"FROM mirror.gcr.io/busybox as layer",
"RUN touch /root/layer",
"FROM layer as derived",
"RUN touch -t @1485449953 /root/derived ; rm /root/layer",
"FROM mirror.gcr.io/busybox AS output",
"COPY --from=layer /root /root",
}, "\n"),
fsSkip: []string{"(dir):root:mtime", "(dir):root:(dir):layer:mtime"},
},
{
name: "dockerignore-minimal-test", // from #2237
contextDir: "dockerignore/minimal_test",
withoutDocker: true,
fsSkip: []string{"(dir):tmp:mtime", "(dir):tmp:(dir):stuff:mtime"},
},
{
name: "dockerignore-is-even-there",
contextDir: "dockerignore/empty",
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "dockerignore-irrelevant",
contextDir: "dockerignore/empty",
tweakContextDir: func(_ *testing.T, contextDir, _, _ string) (err error) {
dockerignore := []byte(strings.Join([]string{"**/*-a", "!**/*-c"}, "\n"))
if err := os.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0o600); err != nil {
return fmt.Errorf("writing .dockerignore file: %w", err)
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return fmt.Errorf("setting date on .dockerignore file in temporary context directory: %w", err)
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "dockerignore-exceptions-dot",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY . subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(_ *testing.T, contextDir, _, _ string) (err error) {
dockerignore := []byte(strings.Join([]string{"**/*-a", "!**/*-c"}, "\n"))
if err := os.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0o644); err != nil {
return fmt.Errorf("writing .dockerignore file: %w", err)
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return fmt.Errorf("setting date on .dockerignore file in temporary context directory: %w", err)
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "dockerignore-extensions-star",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY * subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(_ *testing.T, contextDir, _, _ string) (err error) {
dockerignore := []byte(strings.Join([]string{"**/*-a", "!**/*-c"}, "\n"))
if err := os.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0o600); err != nil {
return fmt.Errorf("writing .dockerignore file: %w", err)
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return fmt.Errorf("setting date on .dockerignore file in temporary context directory: %w", err)
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "dockerignore-includes-dot",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY . subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(_ *testing.T, contextDir, _, _ string) (err error) {
dockerignore := []byte(strings.Join([]string{"!**/*-c"}, "\n"))
if err := os.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0o640); err != nil {
return fmt.Errorf("writing .dockerignore file: %w", err)
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return fmt.Errorf("setting date on .dockerignore file in temporary context directory: %w", err)
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "add--exclude-includes-star",
dockerfileContents: strings.Join([]string{
"# syntax=docker/dockerfile:1.9-labs",
"FROM scratch",
"ADD --exclude=**/*-c ./ subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolFalse,
dockerUseBuildKit: true,
},
{
name: "add--exclude-includes-slash",
dockerfileContents: strings.Join([]string{
"# syntax=docker/dockerfile:1.9-labs",
"FROM scratch",
"ADD --exclude=*.txt / subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolFalse,
dockerUseBuildKit: true,
},
{
name: "add--exclude-includes-dot",
dockerfileContents: strings.Join([]string{
"# syntax=docker/dockerfile:1.9-labs",
"FROM scratch",
"ADD --exclude=*-c . subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolFalse,
dockerUseBuildKit: true,
},
{
name: "copy--exclude-includes-subdir-slash",
dockerfileContents: strings.Join([]string{
"# syntax=docker/dockerfile:1.9-labs",
"FROM scratch",
"COPY --exclude=**/*-c / subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolFalse,
dockerUseBuildKit: true,
},
{
name: "copy--exclude-includes-dot-slash",
dockerfileContents: strings.Join([]string{
"# syntax=docker/dockerfile:1.9-labs",
"FROM scratch",
"COPY --exclude='!**/*-c' ./ subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolFalse,
dockerUseBuildKit: true,
},
{
name: "copy--exclude-includes-slash",
dockerfileContents: strings.Join([]string{
"# syntax=docker/dockerfile:1.9-labs",
"FROM scratch",
"COPY --exclude='!**/*-c' . subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolFalse,
dockerUseBuildKit: true,
},
{
name: "dockerignore-includes-star",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY * subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(_ *testing.T, contextDir, _, _ string) (err error) {
dockerignore := []byte("!**/*-c\n")
if err := os.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0o100); err != nil {
return fmt.Errorf("writing .dockerignore file: %w", err)
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return fmt.Errorf("setting date on .dockerignore file in temporary context directory: %w", err)
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "dockerignore-exclude-plain-dot",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY . subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(_ *testing.T, contextDir, _, _ string) (err error) {
dockerignore := []byte("subdir-c")
if err := os.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0o200); err != nil {
return fmt.Errorf("writing .dockerignore file: %w", err)
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return fmt.Errorf("setting date on .dockerignore file in temporary context directory: %w", err)
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "dockerignore-exclude-plain-star",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY * subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(_ *testing.T, contextDir, _, _ string) (err error) {
dockerignore := []byte("subdir-c")
if err := os.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0o400); err != nil {
return fmt.Errorf("writing .dockerignore file: %w", err)
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return fmt.Errorf("setting date on .dockerignore file in temporary context directory: %w", err)
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "dockerignore-exclude-plain-dot",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY . subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(_ *testing.T, contextDir, _, _ string) (err error) {
dockerignore := []byte("**/subdir-c")
if err := os.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0o200); err != nil {
return fmt.Errorf("writing .dockerignore file: %w", err)
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return fmt.Errorf("setting date on .dockerignore file in temporary context directory: %w", err)
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "dockerignore-exclude-plain-star",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY * subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(_ *testing.T, contextDir, _, _ string) (err error) {
dockerignore := []byte("**/subdir-c")
if err := os.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0o400); err != nil {
return fmt.Errorf("writing .dockerignore file: %w", err)
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return fmt.Errorf("setting date on .dockerignore file in temporary context directory: %w", err)
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "dockerignore-exclude-wildcard-dot",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY . subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(_ *testing.T, contextDir, _, _ string) (err error) {
dockerignore := []byte("subdir-*")
if err := os.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0o000); err != nil {
return fmt.Errorf("writing .dockerignore file: %w", err)
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return fmt.Errorf("setting date on .dockerignore file in temporary context directory: %w", err)
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "dockerignore-exclude-wildcard-star",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY * subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(_ *testing.T, contextDir, _, _ string) (err error) {
dockerignore := []byte("subdir-*")
if err := os.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0o660); err != nil {
return fmt.Errorf("writing .dockerignore file: %w", err)
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return fmt.Errorf("setting date on .dockerignore file in temporary context directory: %w", err)
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "dockerignore-exclude-deep-wildcard-dot",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY . subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(_ *testing.T, contextDir, _, _ string) (err error) {
dockerignore := []byte("**/subdir-*")
if err := os.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0o000); err != nil {
return fmt.Errorf("writing .dockerignore file: %w", err)
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return fmt.Errorf("setting date on .dockerignore file in temporary context directory: %w", err)
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "dockerignore-exclude-deep-wildcard-star",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY * subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(_ *testing.T, contextDir, _, _ string) (err error) {
dockerignore := []byte("**/subdir-*")
if err := os.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0o660); err != nil {
return fmt.Errorf("writing .dockerignore file: %w", err)
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return fmt.Errorf("setting date on .dockerignore file in temporary context directory: %w", err)
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "dockerignore-exclude-deep-subdir-dot",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY . subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(_ *testing.T, contextDir, _, _ string) (err error) {
dockerignore := []byte("**/subdir-f")
if err := os.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0o666); err != nil {
return fmt.Errorf("writing .dockerignore file: %w", err)
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return fmt.Errorf("setting date on .dockerignore file in temporary context directory: %w", err)
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "dockerignore-exclude-deep-subdir-star",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY * subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(_ *testing.T, contextDir, _, _ string) (err error) {
dockerignore := []byte("**/subdir-f")
if err := os.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0o640); err != nil {
return fmt.Errorf("writing .dockerignore file: %w", err)
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return fmt.Errorf("setting date on .dockerignore file in temporary context directory: %w", err)
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "dockerignore-exclude-not-so-deep-subdir-dot",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY . subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(_ *testing.T, contextDir, _, _ string) (err error) {
dockerignore := []byte("**/subdir-b")
if err := os.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0o705); err != nil {
return fmt.Errorf("writing .dockerignore file: %w", err)
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return fmt.Errorf("setting date on .dockerignore file in temporary context directory: %w", err)
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "dockerignore-exclude-not-so-deep-subdir-star",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY * subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(_ *testing.T, contextDir, _, _ string) (err error) {
dockerignore := []byte("**/subdir-b")
if err := os.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0o750); err != nil {
return fmt.Errorf("writing .dockerignore file: %w", err)
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return fmt.Errorf("setting date on .dockerignore file in temporary context directory: %w", err)
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "dockerignore-exclude-kind-of-deep-subdir-dot",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY . subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(_ *testing.T, contextDir, _, _ string) (err error) {
dockerignore := []byte(strings.Join([]string{"**/subdir-e", "!**/subdir-f"}, "\n"))
if err := os.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0o750); err != nil {
return fmt.Errorf("writing .dockerignore file: %w", err)
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return fmt.Errorf("setting date on .dockerignore file in temporary context directory: %w", err)
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "dockerignore-exclude-kind-of-deep-subdir-star",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY * subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(_ *testing.T, contextDir, _, _ string) (err error) {
dockerignore := []byte(strings.Join([]string{"**/subdir-e", "!**/subdir-f"}, "\n"))
if err := os.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0o750); err != nil {
return fmt.Errorf("writing .dockerignore file: %w", err)
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return fmt.Errorf("setting date on .dockerignore file in temporary context directory: %w", err)
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "dockerignore-exclude-deep-subdir-dot",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY . subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(_ *testing.T, contextDir, _, _ string) (err error) {
dockerignore := []byte(strings.Join([]string{"**/subdir-f", "!**/subdir-g"}, "\n"))
if err := os.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0o750); err != nil {
return fmt.Errorf("writing .dockerignore file: %w", err)
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return fmt.Errorf("setting date on .dockerignore file in temporary context directory: %w", err)
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "dockerignore-exclude-deep-subdir-star",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY * subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(_ *testing.T, contextDir, _, _ string) (err error) {
dockerignore := []byte(strings.Join([]string{"**/subdir-f", "!**/subdir-g"}, "\n"))
if err := os.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0o750); err != nil {
return fmt.Errorf("writing .dockerignore file: %w", err)
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return fmt.Errorf("setting date on .dockerignore file in temporary context directory: %w", err)
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "env-whitespace",
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM scratch`,
`COPY script .`,
`ENV name value`,
}, "\n"),
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "env-simple",
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM scratch`,
`COPY script .`,
`ENV name=value`,
}, "\n"),
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "env-unquoted-list",
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM scratch`,
`COPY script .`,
`ENV name=value name2=value2`,
}, "\n"),
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "env-dquoted-list",
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM scratch`,
`COPY script .`,
`ENV name="value value1"`,
}, "\n"),
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "env-escaped-value",
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM scratch`,
`COPY script .`,
`ENV name=value\ value2`,
}, "\n"),
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "env-squote-in-dquote",
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM scratch`,
`COPY script .`,
`ENV name="value'quote space'value2"`,
}, "\n"),
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "env-dquote-in-squote",
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM scratch`,
`COPY script .`,
`ENV name='value"double quote"value2'`,
}, "\n"),
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "env-escaped-list",
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM scratch`,
`COPY script .`,
`ENV name=value\ value2 name2=value2\ value3`,
}, "\n"),
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "env-eddquote",
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM scratch`,
`COPY script .`,
`ENV name="a\"b"`,
}, "\n"),
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "env-invalid-ssquote",
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM scratch`,
`COPY script .`,
`ENV name='a\'b'`,
}, "\n"),
shouldFailAt: 3,
},
{
name: "env-esdquote",
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM scratch`,
`COPY script .`,
`ENV name="a\'b"`,
}, "\n"),
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "env-essquote",
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM scratch`,
`COPY script .`,
`ENV name='a\'b''`,
}, "\n"),
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "env-edsquote",
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM scratch`,
`COPY script .`,
`ENV name='a\"b'`,
}, "\n"),
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "env-empty-squote-in-empty-dquote",
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM scratch`,
`COPY script .`,
`ENV name="''"`,
}, "\n"),
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "env-multiline",
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM scratch`,
`COPY script .`,
`# don't put anything after the next line - it must be the last line of the`,
`# Dockerfile and it must end with \`,
`ENV name=value \`,
` name1=value1 \`,
` name2="value2a \`,
` value2b" \`,
` name3="value3a\n\"value3b\"" \`,
` name4="value4a\\nvalue4b" \`,
}, "\n"),
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "copy-from-owner", // from issue #2518
dockerfileContents: strings.Join([]string{
`FROM mirror.gcr.io/alpine`,
`RUN set -ex; touch -t @1485449953 /test; chown 65:65 /test`,
`FROM scratch`,
`USER 66:66`,
`COPY --from=0 /test /test`,
}, "\n"),
fsSkip: []string{"test:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "copy-from-owner-with-chown", // issue #2518, but with chown to override
dockerfileContents: strings.Join([]string{
`FROM mirror.gcr.io/alpine`,
`RUN set -ex; touch -t @1485449953 /test; chown 65:65 /test`,
`FROM scratch`,
`USER 66:66`,
`COPY --from=0 --chown=1:1 /test /test`,
}, "\n"),
fsSkip: []string{"test:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "copy-for-user", // flip side of issue #2518
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM mirror.gcr.io/alpine`,
`USER 66:66`,
`COPY /script /script`,
}, "\n"),
},
{
name: "copy-for-user-with-chown", // flip side of issue #2518, but with chown to override
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM mirror.gcr.io/alpine`,
`USER 66:66`,
`COPY --chown=1:1 /script /script`,
}, "\n"),
},
{
name: "add-parent-symlink",
contextDir: "add/parent-symlink",
fsSkip: []string{"(dir):testsubdir:mtime", "(dir):testsubdir:(dir):etc:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "add-parent-dangling",
contextDir: "add/parent-dangling",
fsSkip: []string{"(dir):symlink:mtime", "(dir):symlink-target:mtime", "(dir):symlink-target:(dir):subdirectory:mtime"},
},
{
name: "add-parent-clean",
contextDir: "add/parent-clean",
fsSkip: []string{"(dir):symlink:mtime", "(dir):symlink-target:mtime", "(dir):symlink-target:(dir):subdirectory:mtime"},
},
{
name: "add-archive-1",
contextDir: "add/archive",
dockerfile: "Dockerfile.1",
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "add-archive-2",
contextDir: "add/archive",
dockerfile: "Dockerfile.2",
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "add-archive-3",
contextDir: "add/archive",
dockerfile: "Dockerfile.3",
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "add-archive-4",
contextDir: "add/archive",
dockerfile: "Dockerfile.4",
fsSkip: []string{"(dir):sub:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "add-archive-5",
contextDir: "add/archive",
dockerfile: "Dockerfile.5",
fsSkip: []string{"(dir):sub:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "add-archive-6",
contextDir: "add/archive",
dockerfile: "Dockerfile.6",
fsSkip: []string{"(dir):sub:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "add-archive-7",
contextDir: "add/archive",
dockerfile: "Dockerfile.7",
fsSkip: []string{"(dir):sub:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "add-dir-not-dir",
contextDir: "add/dir-not-dir",
},
{
name: "add-not-dir-dir",
contextDir: "add/not-dir-dir",
},
{
name: "add-populated-dir-not-dir",
contextDir: "add/populated-dir-not-dir",
},
{
name: "dockerignore-allowlist-subdir-nofile-dir",
contextDir: "dockerignore/allowlist/subdir-nofile",
shouldFailAt: 2,
failureRegex: "(no such file or directory)|(file not found)|(file does not exist)",
},
{
name: "dockerignore-allowlist-subdir-nofile-file",
contextDir: "dockerignore/allowlist/subdir-nofile",
shouldFailAt: 2,
failureRegex: "(no such file or directory)|(file not found)|(file does not exist)",
},
{
name: "dockerignore-allowlist-subdir-file-dir",
contextDir: "dockerignore/allowlist/subdir-file",
fsSkip: []string{"(dir):f1:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "dockerignore-allowlist-subdir-file-file",
contextDir: "dockerignore/allowlist/subdir-file",
fsSkip: []string{"(dir):f1:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "dockerignore-allowlist-nothing-dot",
contextDir: "dockerignore/allowlist/nothing-dot",
fsSkip: []string{"file:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "dockerignore-allowlist-nothing-slash",
contextDir: "dockerignore/allowlist/nothing-slash",
fsSkip: []string{"file:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
// the directories are excluded, so entries for them don't get
// included in the build context archive, so they only get
// created implicitly when extracted, so there's no point in us
// trying to preserve any of that, either
name: "dockerignore-allowlist-subsubdir-file",
contextDir: "dockerignore/allowlist/subsubdir-file",
withoutDocker: true,
fsSkip: []string{"(dir):folder:mtime", "(dir):folder:(dir):subfolder:mtime", "file:mtime"},
},
{
name: "dockerignore-allowlist-subsubdir-nofile",
contextDir: "dockerignore/allowlist/subsubdir-nofile",
fsSkip: []string{"file:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "dockerignore-allowlist-subsubdir-nosubdir",
contextDir: "dockerignore/allowlist/subsubdir-nosubdir",
fsSkip: []string{"file:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "dockerignore-allowlist-alternating",
contextDir: "dockerignore/allowlist/alternating",
withoutDocker: true,
fsSkip: []string{
"(dir):subdir1:mtime",
"(dir):subdir1:(dir):subdir2:(dir):subdir3:mtime",
"(dir):subdir1:(dir):subdir2:(dir):subdir3:(dir):subdir4:(dir):subdir5:mtime",
"(dir):subdir2:(dir):subdir3:mtime",
"(dir):subdir2:(dir):subdir3:(dir):subdir4:(dir):subdir5:mtime",
"(dir):subdir3:mtime",
"(dir):subdir3:(dir):subdir4:(dir):subdir5:mtime",
"(dir):subdir4:(dir):subdir5:mtime",
"(dir):subdir5:mtime",
},
},
{
name: "dockerignore-allowlist-alternating-nothing",
contextDir: "dockerignore/allowlist/alternating-nothing",
shouldFailAt: 7,
failureRegex: "(no such file or directory)|(file not found)|(file does not exist)",
},
{
name: "dockerignore-allowlist-alternating-other",
contextDir: "dockerignore/allowlist/alternating-other",
shouldFailAt: 7,
failureRegex: "(no such file or directory)|(file not found)|(file does not exist)",
},
{
name: "tar-g",
contextDir: "tar-g",
withoutDocker: true,
fsSkip: []string{"(dir):tmp:mtime"},
},
{
name: "dockerignore-exceptions-skip",
contextDir: "dockerignore/exceptions-skip",
fsSkip: []string{"(dir):volume:mtime"},
},
{
name: "dockerignore-exceptions-weirdness-1",
contextDir: "dockerignore/exceptions-weirdness-1",
fsSkip: []string{"(dir):newdir:mtime", "(dir):newdir:(dir):subdir:mtime"},
},
{
name: "dockerignore-exceptions-weirdness-2",
contextDir: "dockerignore/exceptions-weirdness-2",
fsSkip: []string{"(dir):newdir:mtime", "(dir):newdir:(dir):subdir:mtime"},
},
{
name: "multistage-builtin-args",
dockerfile: "Dockerfile.margs",
dockerUseBuildKit: true,
},
{
name: "heredoc-copy",
dockerfile: "Dockerfile.heredoc_copy",
dockerUseBuildKit: true,
contextDir: "heredoc",
fsSkip: []string{
"(dir):test:mtime",
"(dir):test2:mtime",
"(dir):test:(dir):humans.txt:mtime",
"(dir):test:(dir):robots.txt:mtime",
"(dir):test2:(dir):humans.txt:mtime",
"(dir):test2:(dir):robots.txt:mtime",
"(dir):test2:(dir):image_file:mtime",
"(dir):etc:(dir):hostname", /* buildkit does not contains /etc/hostname like buildah */
},
},
{
name: "replace-symlink-with-directory",
contextDir: "replace/symlink-with-directory",
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "replace-directory-with-symlink",
contextDir: "replace/symlink-with-directory",
dockerfile: "Dockerfile.2",
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "replace-symlink-with-directory-subdir",
contextDir: "replace/symlink-with-directory",
dockerfile: "Dockerfile.3",
fsSkip: []string{"(dir):tree:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "replace-directory-with-symlink-subdir",
contextDir: "replace/symlink-with-directory",
dockerfile: "Dockerfile.4",
fsSkip: []string{"(dir):tree:mtime"},
compatScratchConfig: types.OptionalBoolTrue,
},
{
name: "workdir-owner", // from issue #3620
dockerfileContents: strings.Join([]string{
`# syntax=docker/dockerfile:1.4`,
`FROM mirror.gcr.io/alpine`,
`USER daemon`,
`WORKDIR /created/directory`,
`RUN ls /created`,
}, "\n"),
fsSkip: []string{"(dir):created:mtime", "(dir):created:(dir):directory:mtime"},
dockerUseBuildKit: true,
},
{
name: "env-precedence",
contextDir: "env/precedence",
dockerUseBuildKit: true,
},
{
name: "multistage-copyback",
contextDir: "multistage/copyback",
dockerUseBuildKit: true,
},
{
name: "heredoc-quoting",
dockerfile: "Dockerfile.heredoc-quoting",
dockerUseBuildKit: true,
fsSkip: []string{"(dir):etc:(dir):hostname"}, // buildkit does not create a phantom /etc/hostname
},
{
name: "workdir with trailing separator",
dockerfileContents: strings.Join([]string{
"FROM mirror.gcr.io/busybox",
"USER daemon",
"WORKDIR /tmp/",
}, "\n"),
},
{
name: "workdir without trailing separator",
dockerfileContents: strings.Join([]string{
"FROM mirror.gcr.io/busybox",
"USER daemon",
"WORKDIR /tmp",
}, "\n"),
},
{
name: "chown-volume", // from podman #22530
contextDir: "chown-volume",
testUsingVolumes: true,
},
{
name: "builtins",
contextDir: "builtins",
dockerUseBuildKit: true,
buildArgs: map[string]string{"SOURCE": "source", "BUSYBOX": "mirror.gcr.io/busybox", "ALPINE": "mirror.gcr.io/alpine", "OWNERID": "0", "SECONDBASE": "localhost/no-such-image"},
},
{
name: "header-builtin",
contextDir: "header-builtin",
dockerUseBuildKit: true,
},
{
name: "copyglob-1",
contextDir: "copyglob",
dockerUseBuildKit: true,
buildArgs: map[string]string{"SOURCE": "**/*.txt"},
},
{
name: "copyglob-2",
contextDir: "copyglob",
dockerUseBuildKit: true,
buildArgs: map[string]string{"SOURCE": "**/sub/*.txt"},
},
{
name: "copyglob-3",
contextDir: "copyglob",
dockerUseBuildKit: true,
buildArgs: map[string]string{"SOURCE": "e/**/*sub/*.txt"},
},
{
name: "copyglob-4",
contextDir: "copyglob",
dockerUseBuildKit: true,
buildArgs: map[string]string{"SOURCE": "e/**/**/*sub/*.txt"},
},
}
func TestCommit(t *testing.T) {
testCases := []struct {
description string
baseImage string
changes, derivedChanges []string
config, derivedConfig *docker.Config
}{
{
description: "defaults",
baseImage: "mirror.gcr.io/busybox",
},
{
description: "empty change",
baseImage: "mirror.gcr.io/busybox",
changes: []string{""},
},
{
description: "empty config",
baseImage: "mirror.gcr.io/busybox",
config: &docker.Config{},
},
{
description: "cmd just changes",
baseImage: "mirror.gcr.io/busybox",
changes: []string{"CMD /bin/imaginarySh"},
},
{
description: "cmd just config",
baseImage: "mirror.gcr.io/busybox",
config: &docker.Config{
Cmd: []string{"/usr/bin/imaginarySh"},
},
},
{
description: "cmd conflict",
baseImage: "mirror.gcr.io/busybox",
changes: []string{"CMD /bin/imaginarySh"},
config: &docker.Config{
Cmd: []string{"/usr/bin/imaginarySh"},
},
},
{
description: "entrypoint just changes",
baseImage: "mirror.gcr.io/busybox",
changes: []string{"ENTRYPOINT /bin/imaginarySh"},
},
{
description: "entrypoint just config",
baseImage: "mirror.gcr.io/busybox",
config: &docker.Config{
Entrypoint: []string{"/usr/bin/imaginarySh"},
},
},
{
description: "entrypoint conflict",
baseImage: "mirror.gcr.io/busybox",
changes: []string{"ENTRYPOINT /bin/imaginarySh"},
config: &docker.Config{
Entrypoint: []string{"/usr/bin/imaginarySh"},
},
},
{
description: "environment just changes",
baseImage: "mirror.gcr.io/busybox",
changes: []string{"ENV A=1", "ENV C=2"},
},
{
description: "environment just config",
baseImage: "mirror.gcr.io/busybox",
config: &docker.Config{
Env: []string{"A=B"},
},
},
{
description: "environment with conflict union",
baseImage: "mirror.gcr.io/busybox",
changes: []string{"ENV A=1", "ENV C=2"},
config: &docker.Config{
Env: []string{"A=B"},
},
},
{
description: "expose just changes",
baseImage: "mirror.gcr.io/busybox",
changes: []string{"EXPOSE 12345"},
},
{
description: "expose just config",
baseImage: "mirror.gcr.io/busybox",
config: &docker.Config{
ExposedPorts: map[docker.Port]struct{}{"23456": {}},
},
},
{
description: "expose union",
baseImage: "mirror.gcr.io/busybox",
changes: []string{"EXPOSE 12345"},
config: &docker.Config{
ExposedPorts: map[docker.Port]struct{}{"23456": {}},
},
},
{
description: "healthcheck just changes",
baseImage: "mirror.gcr.io/busybox",
changes: []string{`HEALTHCHECK --interval=1s --timeout=1s --start-period=1s --retries=1 CMD ["/bin/false"]`},
},
{
description: "healthcheck just config",
baseImage: "mirror.gcr.io/busybox",
config: &docker.Config{
Healthcheck: &docker.HealthConfig{
Test: []string{"/bin/true"},
Interval: 2 * time.Second,
Timeout: 2 * time.Second,
StartPeriod: 2 * time.Second,
Retries: 2,
},
},
},
{
description: "healthcheck conflict",
baseImage: "mirror.gcr.io/busybox",
changes: []string{`HEALTHCHECK --interval=1s --timeout=1s --start-period=1s --retries=1 CMD ["/bin/false"]`},
config: &docker.Config{
Healthcheck: &docker.HealthConfig{
Test: []string{"/bin/true"},
Interval: 2 * time.Second,
Timeout: 2 * time.Second,
StartPeriod: 2 * time.Second,
Retries: 2,
},
},
},
{
description: "label just changes",
baseImage: "mirror.gcr.io/busybox",
changes: []string{"LABEL A=1 C=2"},
},
{
description: "label just config",
baseImage: "mirror.gcr.io/busybox",
config: &docker.Config{
Labels: map[string]string{"A": "B"},
},
},
{
description: "label with conflict union",
baseImage: "mirror.gcr.io/busybox",
changes: []string{"LABEL A=1 C=2"},
config: &docker.Config{
Labels: map[string]string{"A": "B"},
},
},
// n.b. dockerd didn't like a MAINTAINER change, so no test for it, and it's not in a config blob
{
description: "onbuild just changes",
baseImage: "mirror.gcr.io/busybox",
changes: []string{"ONBUILD USER alice", "ONBUILD LABEL A=1"},
derivedChanges: []string{"LABEL C=3"},
},
{
description: "onbuild just config",
baseImage: "mirror.gcr.io/busybox",
config: &docker.Config{
OnBuild: []string{"USER bob", `CMD ["/bin/smash"]`, "LABEL B=2"},
},
derivedChanges: []string{"LABEL C=3"},
},
{
description: "onbuild conflict",
baseImage: "mirror.gcr.io/busybox",
changes: []string{"ONBUILD USER alice", "ONBUILD LABEL A=1"},
config: &docker.Config{
OnBuild: []string{"USER bob", `CMD ["/bin/smash"]`, "LABEL B=2"},
},
derivedChanges: []string{"LABEL C=3"},
},
// n.b. dockerd didn't like a SHELL change, so no test for it or a conflict with a config blob
{
description: "shell just config",
baseImage: "mirror.gcr.io/busybox",
config: &docker.Config{
Shell: []string{"/usr/bin/imaginarySh"},
},
},
{
description: "stop signal conflict",
baseImage: "mirror.gcr.io/busybox",
changes: []string{"STOPSIGNAL SIGTERM"},
config: &docker.Config{
StopSignal: "SIGKILL",
},
},
{
description: "stop timeout=0",
baseImage: "mirror.gcr.io/busybox",
config: &docker.Config{
StopTimeout: 0,
},
},
{
description: "stop timeout=15",
baseImage: "mirror.gcr.io/busybox",
config: &docker.Config{
StopTimeout: 15,
},
},
{
description: "stop timeout=15, then 0",
baseImage: "mirror.gcr.io/busybox",
config: &docker.Config{
StopTimeout: 15,
},
derivedConfig: &docker.Config{
StopTimeout: 0,
},
},
{
description: "stop timeout=0, then 15",
baseImage: "mirror.gcr.io/busybox",
config: &docker.Config{
StopTimeout: 0,
},
derivedConfig: &docker.Config{
StopTimeout: 15,
},
},
{
description: "user just changes",
baseImage: "mirror.gcr.io/busybox",
changes: []string{"USER 1001:1001"},
},
{
description: "user just config",
baseImage: "mirror.gcr.io/busybox",
config: &docker.Config{
User: "1000:1000",
},
},
{
description: "user with conflict",
baseImage: "mirror.gcr.io/busybox",
changes: []string{"USER 1001:1001"},
config: &docker.Config{
User: "1000:1000",
},
},
{
description: "volume just changes",
baseImage: "mirror.gcr.io/busybox",
changes: []string{"VOLUME /a-volume"},
},
{
description: "volume just config",
baseImage: "mirror.gcr.io/busybox",
config: &docker.Config{
Volumes: map[string]struct{}{"/b-volume": {}},
},
},
{
description: "volume union",
baseImage: "mirror.gcr.io/busybox",
changes: []string{"VOLUME /a-volume"},
config: &docker.Config{
Volumes: map[string]struct{}{"/b-volume": {}},
},
},
{
description: "workdir just changes",
baseImage: "mirror.gcr.io/busybox",
changes: []string{"WORKDIR /yeah"},
},
{
description: "workdir just config",
baseImage: "mirror.gcr.io/busybox",
config: &docker.Config{
WorkingDir: "/naw",
},
},
{
description: "workdir with conflict",
baseImage: "mirror.gcr.io/busybox",
changes: []string{"WORKDIR /yeah"},
config: &docker.Config{
WorkingDir: "/naw",
},
},
}
var tempdir string
buildahDir := buildahDir
if buildahDir == "" {
if tempdir == "" {
tempdir = t.TempDir()
}
buildahDir = filepath.Join(tempdir, "buildah")
}
dockerDir := dockerDir
if dockerDir == "" {
if tempdir == "" {
tempdir = t.TempDir()
}
dockerDir = filepath.Join(tempdir, "docker")
}
ctx := context.TODO()
// connect to dockerd using go-dockerclient
client, err := docker.NewClientFromEnv()
require.NoErrorf(t, err, "unable to initialize docker client")
var dockerVersion []string
if version, err := client.Version(); err == nil {
if version != nil {
for _, s := range *version {
dockerVersion = append(dockerVersion, s)
}
}
} else {
require.NoErrorf(t, err, "unable to connect to docker daemon")
}
// find a new place to store buildah builds
tempdir = t.TempDir()
// create subdirectories to use for buildah storage
rootDir := filepath.Join(tempdir, "root")
runrootDir := filepath.Join(tempdir, "runroot")
// initialize storage for buildah
options := storage.StoreOptions{
GraphDriverName: os.Getenv("STORAGE_DRIVER"),
GraphRoot: rootDir,
RunRoot: runrootDir,
RootlessStoragePath: rootDir,
}
store, err := storage.GetStore(options)
require.NoErrorf(t, err, "error creating buildah storage at %q", rootDir)
defer func() {
if store != nil {
_, err := store.Shutdown(true)
require.NoErrorf(t, err, "error shutting down storage for buildah")
}
}()
// walk through test cases
for testIndex, testCase := range testCases {
t.Run(testCase.description, func(t *testing.T) {
test := testCases[testIndex]
// create the test container, then commit it, using the docker client
baseImage := test.baseImage
repository, tag := docker.ParseRepositoryTag(baseImage)
if tag == "" {
tag = "latest"
}
baseImage = repository + ":" + tag
if _, err := client.InspectImage(test.baseImage); err != nil && errors.Is(err, docker.ErrNoSuchImage) {
// oh, we need to pull the base image
err = client.PullImage(docker.PullImageOptions{
Repository: repository,
Tag: tag,
}, docker.AuthConfiguration{})
require.NoErrorf(t, err, "pulling base image")
}
container, err := client.CreateContainer(docker.CreateContainerOptions{
Context: ctx,
Config: &docker.Config{
Image: baseImage,
},
})
require.NoErrorf(t, err, "creating the working container with docker")
if err == nil {
defer func(containerName string) {
err := client.RemoveContainer(docker.RemoveContainerOptions{
ID: containerName,
Force: true,
})
assert.Nil(t, err, "error deleting working docker container %q", containerName)
}(container.ID)
}
dockerImageName := "committed:" + strconv.Itoa(testIndex)
dockerImage, err := client.CommitContainer(docker.CommitContainerOptions{
Container: container.ID,
Changes: test.changes,
Run: test.config,
Repository: dockerImageName,
})
assert.NoErrorf(t, err, "committing the working container with docker")
if err == nil {
defer func(dockerImageName string) {
err := client.RemoveImageExtended(dockerImageName, docker.RemoveImageOptions{
Context: ctx,
Force: true,
})
assert.Nil(t, err, "error deleting newly-built docker image %q", dockerImage.ID)
}(dockerImageName)
}
dockerRef, err := alltransports.ParseImageName("docker-daemon:" + dockerImageName)
assert.NoErrorf(t, err, "parsing name of newly-committed docker image")
if len(test.derivedChanges) > 0 || test.derivedConfig != nil {
container, err := client.CreateContainer(docker.CreateContainerOptions{
Context: ctx,
Config: &docker.Config{
Image: dockerImage.ID,
},
})
require.NoErrorf(t, err, "creating the derived container with docker")
if err == nil {
defer func(containerName string) {
err := client.RemoveContainer(docker.RemoveContainerOptions{
ID: containerName,
Force: true,
})
assert.Nil(t, err, "error deleting derived docker container %q", containerName)
}(container.ID)
}
derivedImageName := "derived:" + strconv.Itoa(testIndex)
derivedImage, err := client.CommitContainer(docker.CommitContainerOptions{
Container: container.ID,
Changes: test.derivedChanges,
Run: test.derivedConfig,
Repository: derivedImageName,
})
assert.NoErrorf(t, err, "committing the derived container with docker")
defer func(derivedImageName string) {
err := client.RemoveImageExtended(derivedImageName, docker.RemoveImageOptions{
Context: ctx,
Force: true,
})
assert.Nil(t, err, "error deleting newly-derived docker image %q", derivedImage.ID)
}(derivedImageName)
dockerRef, err = alltransports.ParseImageName("docker-daemon:" + derivedImageName)
assert.NoErrorf(t, err, "parsing name of newly-derived docker image")
}
// create the test container, then commit it, using the buildah API
builder, err := buildah.NewBuilder(ctx, store, buildah.BuilderOptions{
FromImage: baseImage,
})
require.NoErrorf(t, err, "creating the working container with buildah")
defer func(builder *buildah.Builder) {
err := builder.Delete()
assert.NoErrorf(t, err, "removing the working container")
}(builder)
var overrideConfig *manifest.Schema2Config
if test.config != nil {
overrideConfig = config.Schema2ConfigFromGoDockerclientConfig(test.config)
}
buildahID, _, _, err := builder.Commit(ctx, nil, buildah.CommitOptions{
PreferredManifestType: manifest.DockerV2Schema2MediaType,
OverrideChanges: test.changes,
OverrideConfig: overrideConfig,
})
assert.NoErrorf(t, err, "committing buildah image")
buildahRef, err := is.Transport.NewStoreReference(store, nil, buildahID)
assert.NoErrorf(t, err, "parsing name of newly-built buildah image")
if len(test.derivedChanges) > 0 || test.derivedConfig != nil {
derivedBuilder, err := buildah.NewBuilder(ctx, store, buildah.BuilderOptions{
FromImage: buildahID,
})
require.NoErrorf(t, err, "creating the derived container with buildah")
defer func(builder *buildah.Builder) {
err := builder.Delete()
assert.NoErrorf(t, err, "removing the derived container")
}(derivedBuilder)
var overrideConfig *manifest.Schema2Config
if test.derivedConfig != nil {
overrideConfig = config.Schema2ConfigFromGoDockerclientConfig(test.derivedConfig)
}
derivedID, _, _, err := builder.Commit(ctx, nil, buildah.CommitOptions{
PreferredManifestType: manifest.DockerV2Schema2MediaType,
OverrideChanges: test.derivedChanges,
OverrideConfig: overrideConfig,
})
assert.NoErrorf(t, err, "committing derived buildah image")
buildahRef, err = is.Transport.NewStoreReference(store, nil, derivedID)
assert.NoErrorf(t, err, "parsing name of newly-derived buildah image")
}
// scan the images
saveReport(ctx, t, dockerRef, filepath.Join(dockerDir, t.Name()), []byte{}, []byte{}, dockerVersion)
saveReport(ctx, t, buildahRef, filepath.Join(buildahDir, t.Name()), []byte{}, []byte{}, dockerVersion)
// compare the scans
_, originalDockerConfig, ociDockerConfig, fsDocker := readReport(t, filepath.Join(dockerDir, t.Name()))
_, originalBuildahConfig, ociBuildahConfig, fsBuildah := readReport(t, filepath.Join(buildahDir, t.Name()))
miss, left, diff, same := compareJSON(originalDockerConfig, originalBuildahConfig, originalSkip)
if !same {
assert.Failf(t, "Image configurations differ as committed in Docker format", configCompareResult(miss, left, diff, "buildah"))
}
miss, left, diff, same = compareJSON(ociDockerConfig, ociBuildahConfig, ociSkip)
if !same {
assert.Failf(t, "Image configurations differ when converted to OCI format", configCompareResult(miss, left, diff, "buildah"))
}
miss, left, diff, same = compareJSON(fsDocker, fsBuildah, fsSkip)
if !same {
assert.Failf(t, "Filesystem contents differ", fsCompareResult(miss, left, diff, "buildah"))
}
})
}
}
|