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
|
package conformance
import (
"archive/tar"
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"regexp"
"strings"
"sync"
"syscall"
"testing"
"text/tabwriter"
"time"
"github.com/containers/buildah"
"github.com/containers/buildah/copier"
"github.com/containers/buildah/imagebuildah"
"github.com/containers/image/v5/docker/daemon"
"github.com/containers/image/v5/image"
"github.com/containers/image/v5/pkg/compression"
istorage "github.com/containers/image/v5/storage"
"github.com/containers/image/v5/transports"
"github.com/containers/image/v5/types"
"github.com/containers/storage"
"github.com/containers/storage/pkg/reexec"
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/pkg/errors"
"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 = 04000 // Set uid, from archive/tar
cISGID = 02000 // Set gid, from archive/tar
cISVTX = 01000 // Save text (sticky bit), from archive/tar
)
var (
originalSkip = []string{
"created",
"container",
"docker_version",
"hostname",
"config:image",
"container_config:cmd",
"container_config:image",
"history",
"rootfs:diff_ids",
}
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()
level, err := logrus.ParseLevel(logLevel)
if err != nil {
logrus.Fatalf("error parsing log level %q: %v", logLevel, err)
}
logrus.SetLevel(level)
os.Exit(m.Run())
}
func TestConformance(t *testing.T) {
var tempdir string
var err error
if buildahDir == "" {
if tempdir == "" {
tempdir, err = ioutil.TempDir("", "buildah-conformance-")
require.Nil(t, err, "error creating temporary directory")
defer os.RemoveAll(tempdir)
}
buildahDir = filepath.Join(tempdir, "buildah")
}
if dockerDir == "" {
if tempdir == "" {
tempdir, err = ioutil.TempDir("", "buildah-conformance-")
require.Nil(t, err, "error creating temporary directory")
defer os.RemoveAll(tempdir)
}
dockerDir = filepath.Join(tempdir, "docker")
}
if imagebuilderDir == "" {
if tempdir == "" {
tempdir, err = ioutil.TempDir("", "buildah-conformance-")
require.Nil(t, err, "error creating temporary directory")
defer os.RemoveAll(tempdir)
}
imagebuilderDir = filepath.Join(tempdir, "imagebuilder")
}
dateStamp := fmt.Sprintf("%d", time.Now().UnixNano())
for i := range internalTestCases {
t.Run(internalTestCases[i].name, func(t *testing.T) {
testConformanceInternal(t, dateStamp, i)
})
}
}
func testConformanceInternal(t *testing.T, dateStamp string, testIndex int) {
test := internalTestCases[testIndex]
cwd, err := os.Getwd()
require.Nil(t, err, "error finding current directory")
// create a temporary directory to hold our build context
tempdir, err := ioutil.TempDir("", "buildah-conformance-")
require.Nil(t, err, "error creating temporary directory")
defer os.RemoveAll(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, 0700); err != nil {
require.Nil(t, err, "error creating test directory to check if xattrs are testable: %v", err)
}
testFile := filepath.Join(testDir, "testfile")
if err := ioutil.WriteFile(testFile, []byte("whatever"), 0600); err != nil {
require.Nil(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, 0755)
}
pipeReader.Close()
wg.Done()
}()
wg.Wait()
assert.Nil(t, getErr, "error reading build info from %q", filepath.Join("testdata", test.dockerfile))
assert.Nil(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)
// 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 := ioutil.ReadFile(dockerfileName)
require.Nil(t, err, "error reading Dockerfile %q", filepath.Join(tempdir, dockerfileName))
dockerfileContents = contents
}
// initialize storage for buildah
options := storage.StoreOptions{
GraphRoot: rootDir,
RunRoot: runrootDir,
RootlessStoragePath: rootDir,
}
store, err := storage.GetStore(options)
require.Nil(t, err, "error creating buildah storage at %q", rootDir)
defer func() {
if store != nil {
_, err := store.Shutdown(true)
require.Nil(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.Nil(t, err, "error creating test layer to check if xattrs are testable: %v", err)
}
mountPoint, err := store.Mount(layer.ID, "")
if err != nil {
require.Nil(t, err, "error mounting test layer to check if xattrs are testable: %v", err)
}
testFile := filepath.Join(mountPoint, "testfile")
if err := ioutil.WriteFile(testFile, []byte("whatever"), 0600); err != nil {
require.Nil(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.Nil(t, err, "error removing test layer after checking if xattrs are testable: %v", err)
}
}
// connect to dockerd
client, err := docker.NewClientFromEnv()
require.Nil(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.Nil(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.Nil(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
ctx := context.TODO()
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, 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, 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, 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 := ioutil.WriteFile(dockerfileName, dockerfileContents, 0644)
require.Nil(t, err, "error writing Dockerfile at %q", dockerfileName)
err = os.Chtimes(dockerfileName, testDate, testDate)
require.Nil(t, err, "error resetting timestamp on Dockerfile at %q", dockerfileName)
err = os.Chtimes(contextDir, testDate, testDate)
require.Nil(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 := ioutil.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, 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()
}
deleteLabel := func(config map[string]interface{}, label string) {
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, label)
}
}
}
}
}
}
deleteLabel(originalBuildahConfig, buildah.BuilderIdentityAnnotation)
deleteLabel(ociBuildahConfig, buildah.BuilderIdentityAnnotation)
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 {
originalDockerConfig, ociDockerConfig, fsDocker = readReport(t, filepath.Join(dockerDir, t.Name()))
if t.Failed() {
t.FailNow()
}
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 {
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{}
options := imagebuildah.BuildOptions{
ContextDirectory: contextDir,
CommonBuildOpts: &buildah.CommonBuildOptions{},
NamespaceOptions: []buildah.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,
}
// 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 buildUsingDocker(ctx context.Context, t *testing.T, client *docker.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.Nil(t, err, "unable to compute path of dockerfile %q relative to context directory %q", dockerfileName, contextDir)
// set up build options
output := &bytes.Buffer{}
options := docker.BuildImageOptions{
Context: ctx,
ContextDir: contextDir,
Dockerfile: dockerfileRelativePath,
OutputStream: output,
Name: dockerImage,
NoCache: true,
RmTmpContainer: true,
ForceRmTmpContainer: true,
}
// 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())
}
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.Nil(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(nil)
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,
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, 0755)
require.Nil(t, err, "error ensuring directory %q exists for storing a report")
// save the Dockerfile that was used to generate the image
err = ioutil.WriteFile(filepath.Join(directory, "Dockerfile"), dockerfileContents, 0644)
require.Nil(t, err, "error saving Dockerfile for image %q", imageName)
// save the log generated while building the image
err = ioutil.WriteFile(filepath.Join(directory, "build.log"), buildLog, 0644)
require.Nil(t, err, "error saving build log for image %q", imageName)
// save the version information
if len(version) > 0 {
err = ioutil.WriteFile(filepath.Join(directory, "version"), []byte(strings.Join(version, "\n")+"\n"), 0644)
require.Nil(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.Nil(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.Nil(t, err, "error opening image %q to read its configuration", imageName)
closer = img
// read the config blob in its original form
rawConfig, err := img.ConfigBlob(ctx)
require.Nil(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.Nil(t, err, "error reading OCI-format configuration from image %q", imageName)
encodedConfig, err := json.Marshal(ociConfig)
require.Nil(t, err, "error encoding OCI-format configuration from image %q for saving", imageName)
// save the config blob in the OCI format
err = ioutil.WriteFile(filepath.Join(directory, "oci.json"), encodedConfig, 0644)
require.Nil(t, err, "error saving OCI-format configuration from image %q", imageName)
// save the config blob in its original format
err = ioutil.WriteFile(filepath.Join(directory, "config.json"), rawConfig, 0644)
require.Nil(t, err, "error saving original configuration from image %q", imageName)
// start pulling layer information
layerBlobInfos, err := img.LayerInfosForCopy(ctx)
require.Nil(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.Nil(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.Nil(t, err, "error encoding filesystem tree from image %q for saving", imageName)
err = ioutil.WriteFile(filepath.Join(directory, "fs.json"), encodedFSTree, 0644)
require.Nil(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()
uncompressedBlob, _, err := compression.AutoDecompress(io.TeeReader(reader, compressedDigest.Hash()))
require.Nil(t, err, "error decompressing blob %+v for image %q", blobInfo, imageName)
defer uncompressedBlob.Close()
uncompressedDigest := digest.Canonical.Digester()
tr := tar.NewReader(io.TeeReader(uncompressedBlob, uncompressedDigest.Hash()))
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.Nil(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)
layer.CompressedDigest = compressedDigest.Digest()
require.Equal(t, blobInfo.Digest, layer.CompressedDigest, "calculated digest of compressed blob didn't match expected digest")
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) (original, oci, fs map[string]interface{}) {
// read the config in the as-committed (docker) format
originalConfig, err := ioutil.ReadFile(filepath.Join(directory, "config.json"))
require.Nil(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.Nil(t, err, "error decoding configuration from file %q", filepath.Join(directory, "config.json"))
// read the config in converted-to-OCI format
ociConfig, err := ioutil.ReadFile(filepath.Join(directory, "oci.json"))
require.Nil(t, err, "error reading OCI configuration file %q", filepath.Join(directory, "oci.json"))
// dump it into a map
oci = make(map[string]interface{})
err = json.Unmarshal(ociConfig, &oci)
require.Nil(t, err, "error decoding OCI configuration from file %q", filepath.Join(directory, "oci.json"))
// read the filesystem
fsInfo, err := ioutil.ReadFile(filepath.Join(directory, "fs.json"))
require.Nil(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.Nil(t, err, "error decoding filesystem summary from file %q", filepath.Join(directory, "fs.json"))
// return both
return original, oci, fs
}
// contains is used to check if item is exist in []string or not
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
nextSkip := skip
for _, s := range skip {
if strings.Contains(s, ":") {
tmp := strings.Split(s, ":")
if tmp[0] == k {
nextSkip = append(nextSkip, strings.Join(tmp[1:], ":"))
}
}
}
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)
}
}
}
replace := func(slice []string) []string {
return append([]string{}, slice...)
}
return replace(missKeys), replace(leftKeys), replace(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
type 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
withoutDocker bool // don't build this with docker, because it depends on a buildah-specific feature
withoutImagebuilder bool // don't build this with imagebuilder, because it depends on a buildah-specific feature
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
}
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 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",
fsSkip: []string{},
},
{
name: "copy from subdir to new directory",
contextDir: "copydir",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY dir/file /subdir/",
}, "\n"),
fsSkip: []string{"(dir):subdir"},
},
{
name: "copy to renamed file",
contextDir: "copyrename",
fsSkip: []string{"(dir):usr:(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):test2:mtime", "(dir):test3:mtime", "(dir):test3:(dir):copy:mtime",
"(dir):tmp:mtime", "(dir):tmp:passwd:mtime",
},
},
{
name: "exposed default",
dockerfile: "Dockerfile.exposedefault",
},
{
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"},
},
{
name: "volumerun",
contextDir: "volumerun",
fsSkip: []string{"(dir):var:mtime", "(dir):var:(dir):www:mtime"},
},
{
name: "mount",
contextDir: "mount",
buildahRegex: "/tmp/test/file.*?regular file.*?/tmp/test/file2.*?regular file",
withoutDocker: true,
transientMounts: []string{"@@TEMPDIR@@:/tmp/test"},
},
{
name: "transient-mount",
contextDir: "transientmount",
buildahRegex: "file2.*?FROM busybox ENV name value",
withoutDocker: true,
transientMounts: []string{"@@TEMPDIR@@:/mountdir", "@@TEMPDIR@@/Dockerfile.env:/mountfile"},
},
{
// from internal team chat
name: "ci-pipeline-modified",
dockerfileContents: strings.Join([]string{
"FROM 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",
"env-contents.txt:mtime",
},
},
{
name: "add-permissions",
dockerfileContents: strings.Join([]string{
"FROM scratch",
fmt.Sprintf("# Does ADD preserve permissions differently for archives and files?"),
"ADD archive.tar subdir1/",
"ADD archive/ subdir2/",
}, "\n"),
tweakContextDir: func(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
content := []byte("test content")
if err := os.Mkdir(filepath.Join(contextDir, "archive"), 0755); err != nil {
return errors.Wrapf(err, "error creating subdirectory of temporary context directory")
}
filename := filepath.Join(contextDir, "archive", "should-be-owned-by-root")
if err = ioutil.WriteFile(filename, content, 0640); err != nil {
return errors.Wrapf(err, "error creating file owned by root in temporary context directory")
}
if err = os.Chown(filename, 0, 0); err != nil {
return errors.Wrapf(err, "error setting ownership on file owned by root in temporary context directory")
}
if err = os.Chtimes(filename, testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on file owned by root file in temporary context directory")
}
filename = filepath.Join(contextDir, "archive", "should-be-owned-by-99")
if err = ioutil.WriteFile(filename, content, 0640); err != nil {
return errors.Wrapf(err, "error creating file owned by 99 in temporary context directory")
}
if err = os.Chown(filename, 99, 99); err != nil {
return errors.Wrapf(err, "error setting ownership on file owned by 99 in temporary context directory")
}
if err = os.Chtimes(filename, testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on file owned by 99 in temporary context directory")
}
filename = filepath.Join(contextDir, "archive.tar")
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return errors.Wrapf(err, "error creating archive file")
}
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: 0640,
Uid: 0,
Gid: 0,
})
if err != nil {
return errors.Wrapf(err, "error writing archive file header")
}
n, err := tw.Write(content)
if err != nil {
return errors.Wrapf(err, "error writing archive file contents")
}
if n != len(content) {
return errors.Errorf("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: 0640,
Uid: 99,
Gid: 99,
})
if err != nil {
return errors.Wrapf(err, "error writing archive file header")
}
n, err = tw.Write(content)
if err != nil {
return errors.Wrapf(err, "error writing archive file contents")
}
if n != len(content) {
return errors.Errorf("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",
fmt.Sprintf("# Does COPY --chown change permissions on already-present directories?"),
"COPY subdir/ subdir/",
"COPY --chown=99:99 subdir/ subdir/",
}, "\n"),
tweakContextDir: func(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
content := []byte("test content")
if err := os.Mkdir(filepath.Join(contextDir, "subdir"), 0755); err != nil {
return errors.Wrapf(err, "error creating subdirectory of temporary context directory")
}
filename := filepath.Join(contextDir, "subdir", "would-be-owned-by-root")
if err = ioutil.WriteFile(filename, content, 0640); err != nil {
return errors.Wrapf(err, "error creating file owned by root in temporary context directory")
}
if err = os.Chown(filename, 0, 0); err != nil {
return errors.Wrapf(err, "error setting ownership on file owned by root in temporary context directory")
}
if err = os.Chtimes(filename, testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on file owned by root file in temporary context directory")
}
filename = filepath.Join(contextDir, "subdir", "would-be-owned-by-99")
if err = ioutil.WriteFile(filename, content, 0640); err != nil {
return errors.Wrapf(err, "error creating file owned by 99 in temporary context directory")
}
if err = os.Chown(filename, 99, 99); err != nil {
return errors.Wrapf(err, "error setting ownership on file owned by 99 in temporary context directory")
}
if err = os.Chtimes(filename, testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on file owned by 99 in temporary context directory")
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
},
{
name: "copy-permissions-implicit",
dockerfileContents: strings.Join([]string{
"FROM scratch",
fmt.Sprintf("# Does COPY --chown change permissions on already-present directories?"),
"COPY --chown=99:99 subdir/ subdir/",
"COPY subdir/ subdir/",
}, "\n"),
tweakContextDir: func(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
content := []byte("test content")
if err := os.Mkdir(filepath.Join(contextDir, "subdir"), 0755); err != nil {
return errors.Wrapf(err, "error creating subdirectory of temporary context directory")
}
filename := filepath.Join(contextDir, "subdir", "would-be-owned-by-root")
if err = ioutil.WriteFile(filename, content, 0640); err != nil {
return errors.Wrapf(err, "error creating file owned by root in temporary context directory")
}
if err = os.Chown(filename, 0, 0); err != nil {
return errors.Wrapf(err, "error setting ownership on file owned by root in temporary context directory")
}
if err = os.Chtimes(filename, testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on file owned by root file in temporary context directory")
}
filename = filepath.Join(contextDir, "subdir", "would-be-owned-by-99")
if err = ioutil.WriteFile(filename, content, 0640); err != nil {
return errors.Wrapf(err, "error creating file owned by 99 in temporary context directory")
}
if err = os.Chown(filename, 99, 99); err != nil {
return errors.Wrapf(err, "error setting ownership on file owned by 99 in temporary context directory")
}
if err = os.Chtimes(filename, testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on file owned by 99 in temporary context directory")
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
},
{
// 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 busybox@sha256:9ddee63a712cea977267342e8750ecbc60d3aab25f04ceacfa795e6fce341793 AS build",
"RUN mkdir -p /target/subdir",
"RUN cp /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"},
},
{
name: "dockerfile-in-subdirectory",
dockerfile: "subdir/Dockerfile",
contextDir: "subdir",
},
{
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(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
filename := filepath.Join(contextDir, "should-be-setuid-file")
if err = ioutil.WriteFile(filename, []byte("test content"), 0644); err != nil {
return errors.Wrapf(err, "error creating setuid test file in temporary context directory")
}
if err = syscall.Chmod(filename, syscall.S_ISUID|0755); err != nil {
return errors.Wrapf(err, "error setting setuid bit on test file in temporary context directory")
}
if err = os.Chtimes(filename, testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on setuid test file in temporary context directory")
}
filename = filepath.Join(contextDir, "should-be-setgid-file")
if err = ioutil.WriteFile(filename, []byte("test content"), 0644); err != nil {
return errors.Wrapf(err, "error creating setgid test file in temporary context directory")
}
if err = syscall.Chmod(filename, syscall.S_ISGID|0755); err != nil {
return errors.Wrapf(err, "error setting setgid bit on test file in temporary context directory")
}
if err = os.Chtimes(filename, testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on setgid test file in temporary context directory")
}
filename = filepath.Join(contextDir, "should-be-sticky-file")
if err = ioutil.WriteFile(filename, []byte("test content"), 0644); err != nil {
return errors.Wrapf(err, "error creating sticky test file in temporary context directory")
}
if err = syscall.Chmod(filename, syscall.S_ISVTX|0755); err != nil {
return errors.Wrapf(err, "error setting permissions on sticky test file in temporary context directory")
}
if err = os.Chtimes(filename, testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on sticky test file in temporary context directory")
}
filename = filepath.Join(contextDir, "should-not-be-setuid-setgid-sticky-file")
if err = ioutil.WriteFile(filename, []byte("test content"), 0644); err != nil {
return errors.Wrapf(err, "error creating non-suid non-sgid non-sticky test file in temporary context directory")
}
if err = syscall.Chmod(filename, 0640); err != nil {
return errors.Wrapf(err, "error setting permissions on plain test file in temporary context directory")
}
if err = os.Chtimes(filename, testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on plain test file in temporary context directory")
}
return nil
},
fsSkip: []string{"(dir):subdir1:mtime", "(dir):subdir2:mtime"},
},
{
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 = ioutil.WriteFile(filename, []byte("test content"), 0644); err != nil {
return errors.Wrapf(err, "error creating test file with xattrs in temporary context directory")
}
if err = copier.Lsetxattrs(filename, map[string]string{"user.a": "test"}); err != nil {
return errors.Wrapf(err, "error setting xattrs on test file in temporary context directory")
}
if err = syscall.Chmod(filename, 0640); err != nil {
return errors.Wrapf(err, "error setting permissions on test file in temporary context directory")
}
if err = os.Chtimes(filename, testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on test file in temporary context directory")
}
return nil
},
fsSkip: []string{"(dir):subdir1:mtime", "(dir):subdir2:mtime"},
},
{
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(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
filename := filepath.Join(contextDir, "archive.tar")
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return errors.Wrapf(err, "error creating new archive file in temporary context directory")
}
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 | 0755,
ModTime: testDate,
}
if err = tw.WriteHeader(&hdr); err != nil {
return errors.Wrapf(err, "error writing tar archive header")
}
if _, err = io.Copy(tw, bytes.NewReader([]byte("whatever"))); err != nil {
return errors.Wrapf(err, "error writing tar archive content")
}
hdr = tar.Header{
Name: "setgid-file",
Uid: 0,
Gid: 0,
Typeflag: tar.TypeReg,
Size: 8,
Mode: cISGID | 0755,
ModTime: testDate,
}
if err = tw.WriteHeader(&hdr); err != nil {
return errors.Wrapf(err, "error writing tar archive header")
}
if _, err = io.Copy(tw, bytes.NewReader([]byte("whatever"))); err != nil {
return errors.Wrapf(err, "error writing tar archive content")
}
hdr = tar.Header{
Name: "sticky-file",
Uid: 0,
Gid: 0,
Typeflag: tar.TypeReg,
Size: 8,
Mode: cISVTX | 0755,
ModTime: testDate,
}
if err = tw.WriteHeader(&hdr); err != nil {
return errors.Wrapf(err, "error writing tar archive header")
}
if _, err = io.Copy(tw, bytes.NewReader([]byte("whatever"))); err != nil {
return errors.Wrapf(err, "error writing tar archive content")
}
return nil
},
},
{
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, 0644)
if err != nil {
return errors.Wrapf(err, "error creating new archive file in temporary context directory")
}
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: 0640,
ModTime: testDate,
Xattrs: map[string]string{"user.a": "test"},
}
if err = tw.WriteHeader(&hdr); err != nil {
return errors.Wrapf(err, "error writing tar archive header")
}
if _, err = io.Copy(tw, bytes.NewReader([]byte("whatever"))); err != nil {
return errors.Wrapf(err, "error writing tar archive content")
}
return nil
},
fsSkip: []string{"(dir):subdir1:mtime", "(dir):subdir2:mtime"},
},
{
// 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 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"),
},
{
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 = ioutil.WriteFile(filename, []byte("test content"), 0644); err != nil {
return errors.Wrapf(err, "error creating test file with xattrs in temporary context directory")
}
if err = copier.Lsetxattrs(filename, map[string]string{"user.a": "test"}); err != nil {
return errors.Wrapf(err, "error setting xattrs on test file in temporary context directory")
}
if err = syscall.Chmod(filename, 0640); err != nil {
return errors.Wrapf(err, "error setting permissions on test file in temporary context directory")
}
if err = os.Chtimes(filename, testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on test file in temporary context directory")
}
return nil
},
},
{
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: "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"},
},
{
name: "copy-integration1",
contextDir: "dockerignore/integration1",
shouldFailAt: 3,
failureRegex: "no such file or directory",
},
{
name: "copy-integration2",
contextDir: "dockerignore/integration2",
},
{
name: "copy-integration3",
contextDir: "dockerignore/integration3",
shouldFailAt: 4,
failureRegex: "no such file or directory",
},
{
name: "multi-stage-through-base",
dockerfileContents: strings.Join([]string{
"FROM alpine AS base",
"RUN touch /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 busybox as layer",
"RUN touch /root/layer",
"FROM layer as derived",
"RUN touch /root/derived ; rm /root/layer",
"FROM 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",
fsSkip: []string{"(dir):tmp:mtime", "(dir):tmp:(dir):stuff:mtime"},
},
{
name: "dockerignore-is-even-there",
contextDir: "dockerignore/empty",
fsSkip: []string{"(dir):subdir:mtime"},
},
{
name: "dockerignore-irrelevant",
contextDir: "dockerignore/empty",
tweakContextDir: func(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
dockerignore := []byte(strings.Join([]string{"**/*-a", "!**/*-c"}, "\n"))
if err := ioutil.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0600); err != nil {
return errors.Wrapf(err, "error writing .dockerignore file")
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on .dockerignore file in temporary context directory")
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
},
{
name: "dockerignore-exceptions-dot",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY . subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
dockerignore := []byte(strings.Join([]string{"**/*-a", "!**/*-c"}, "\n"))
if err := ioutil.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0644); err != nil {
return errors.Wrapf(err, "error writing .dockerignore file")
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on .dockerignore file in temporary context directory")
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
},
{
name: "dockerignore-extensions-star",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY * subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
dockerignore := []byte(strings.Join([]string{"**/*-a", "!**/*-c"}, "\n"))
if err := ioutil.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0600); err != nil {
return errors.Wrapf(err, "error writing .dockerignore file")
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on .dockerignore file in temporary context directory")
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
},
{
name: "dockerignore-includes-dot",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY . subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
dockerignore := []byte(strings.Join([]string{"!**/*-c"}, "\n"))
if err := ioutil.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0640); err != nil {
return errors.Wrapf(err, "error writing .dockerignore file")
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on .dockerignore file in temporary context directory")
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
},
{
name: "dockerignore-includes-star",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY * subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
dockerignore := []byte("!**/*-c\n")
if err := ioutil.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0100); err != nil {
return errors.Wrapf(err, "error writing .dockerignore file")
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on .dockerignore file in temporary context directory")
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
},
{
name: "dockerignore-exclude-plain-dot",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY . subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
dockerignore := []byte("subdir-c")
if err := ioutil.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0200); err != nil {
return errors.Wrapf(err, "error writing .dockerignore file")
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on .dockerignore file in temporary context directory")
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
},
{
name: "dockerignore-exclude-plain-star",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY * subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
dockerignore := []byte("subdir-c")
if err := ioutil.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0400); err != nil {
return errors.Wrapf(err, "error writing .dockerignore file")
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on .dockerignore file in temporary context directory")
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
},
{
name: "dockerignore-exclude-plain-dot",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY . subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
dockerignore := []byte("**/subdir-c")
if err := ioutil.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0200); err != nil {
return errors.Wrapf(err, "error writing .dockerignore file")
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on .dockerignore file in temporary context directory")
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
},
{
name: "dockerignore-exclude-plain-star",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY * subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
dockerignore := []byte("**/subdir-c")
if err := ioutil.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0400); err != nil {
return errors.Wrapf(err, "error writing .dockerignore file")
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on .dockerignore file in temporary context directory")
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
},
{
name: "dockerignore-exclude-wildcard-dot",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY . subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
dockerignore := []byte("subdir-*")
if err := ioutil.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0000); err != nil {
return errors.Wrapf(err, "error writing .dockerignore file")
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on .dockerignore file in temporary context directory")
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
},
{
name: "dockerignore-exclude-wildcard-star",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY * subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
dockerignore := []byte("subdir-*")
if err := ioutil.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0660); err != nil {
return errors.Wrapf(err, "error writing .dockerignore file")
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on .dockerignore file in temporary context directory")
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
},
{
name: "dockerignore-exclude-deep-wildcard-dot",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY . subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
dockerignore := []byte("**/subdir-*")
if err := ioutil.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0000); err != nil {
return errors.Wrapf(err, "error writing .dockerignore file")
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on .dockerignore file in temporary context directory")
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
},
{
name: "dockerignore-exclude-deep-wildcard-star",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY * subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
dockerignore := []byte("**/subdir-*")
if err := ioutil.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0660); err != nil {
return errors.Wrapf(err, "error writing .dockerignore file")
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on .dockerignore file in temporary context directory")
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
},
{
name: "dockerignore-exclude-deep-subdir-dot",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY . subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
dockerignore := []byte("**/subdir-f")
if err := ioutil.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0666); err != nil {
return errors.Wrapf(err, "error writing .dockerignore file")
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on .dockerignore file in temporary context directory")
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
},
{
name: "dockerignore-exclude-deep-subdir-star",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY * subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
dockerignore := []byte("**/subdir-f")
if err := ioutil.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0640); err != nil {
return errors.Wrapf(err, "error writing .dockerignore file")
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on .dockerignore file in temporary context directory")
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
},
{
name: "dockerignore-exclude-not-so-deep-subdir-dot",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY . subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
dockerignore := []byte("**/subdir-b")
if err := ioutil.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0705); err != nil {
return errors.Wrapf(err, "error writing .dockerignore file")
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on .dockerignore file in temporary context directory")
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
},
{
name: "dockerignore-exclude-not-so-deep-subdir-star",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY * subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
dockerignore := []byte("**/subdir-b")
if err := ioutil.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0750); err != nil {
return errors.Wrapf(err, "error writing .dockerignore file")
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on .dockerignore file in temporary context directory")
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
},
{
name: "dockerignore-exclude-kind-of-deep-subdir-dot",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY . subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
dockerignore := []byte(strings.Join([]string{"**/subdir-e", "!**/subdir-f"}, "\n"))
if err := ioutil.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0750); err != nil {
return errors.Wrapf(err, "error writing .dockerignore file")
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on .dockerignore file in temporary context directory")
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
},
{
name: "dockerignore-exclude-kind-of-deep-subdir-star",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY * subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
dockerignore := []byte(strings.Join([]string{"**/subdir-e", "!**/subdir-f"}, "\n"))
if err := ioutil.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0750); err != nil {
return errors.Wrapf(err, "error writing .dockerignore file")
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on .dockerignore file in temporary context directory")
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
},
{
name: "dockerignore-exclude-deep-subdir-dot",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY . subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
dockerignore := []byte(strings.Join([]string{"**/subdir-f", "!**/subdir-g"}, "\n"))
if err := ioutil.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0750); err != nil {
return errors.Wrapf(err, "error writing .dockerignore file")
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on .dockerignore file in temporary context directory")
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
},
{
name: "dockerignore-exclude-deep-subdir-star",
dockerfileContents: strings.Join([]string{
"FROM scratch",
"COPY * subdir/",
}, "\n"),
contextDir: "dockerignore/populated",
tweakContextDir: func(t *testing.T, contextDir, storageDriver, storageRoot string) (err error) {
dockerignore := []byte(strings.Join([]string{"**/subdir-f", "!**/subdir-g"}, "\n"))
if err := ioutil.WriteFile(filepath.Join(contextDir, ".dockerignore"), dockerignore, 0750); err != nil {
return errors.Wrapf(err, "error writing .dockerignore file")
}
if err = os.Chtimes(filepath.Join(contextDir, ".dockerignore"), testDate, testDate); err != nil {
return errors.Wrapf(err, "error setting date on .dockerignore file in temporary context directory")
}
return nil
},
fsSkip: []string{"(dir):subdir:mtime"},
},
{
name: "env-whitespace",
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM scratch`,
`COPY script .`,
`ENV name value`,
}, "\n"),
},
{
name: "env-simple",
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM scratch`,
`COPY script .`,
`ENV name=value`,
}, "\n"),
},
{
name: "env-unquoted-list",
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM scratch`,
`COPY script .`,
`ENV name=value name2=value2`,
}, "\n"),
},
{
name: "env-dquoted-list",
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM scratch`,
`COPY script .`,
`ENV name="value value1"`,
}, "\n"),
},
{
name: "env-escaped-value",
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM scratch`,
`COPY script .`,
`ENV name=value\ value2`,
}, "\n"),
},
{
name: "env-squote-in-dquote",
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM scratch`,
`COPY script .`,
`ENV name="value'quote space'value2"`,
}, "\n"),
},
{
name: "env-dquote-in-squote",
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM scratch`,
`COPY script .`,
`ENV name='value"double quote"value2'`,
}, "\n"),
},
{
name: "env-escaped-list",
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM scratch`,
`COPY script .`,
`ENV name=value\ value2 name2=value2\ value3`,
}, "\n"),
},
{
name: "env-eddquote",
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM scratch`,
`COPY script .`,
`ENV name="a\"b"`,
}, "\n"),
},
{
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"),
},
{
name: "env-essquote",
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM scratch`,
`COPY script .`,
`ENV name='a\'b''`,
}, "\n"),
},
{
name: "env-edsquote",
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM scratch`,
`COPY script .`,
`ENV name='a\"b'`,
}, "\n"),
},
{
name: "env-empty-squote-in-empty-dquote",
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM scratch`,
`COPY script .`,
`ENV name="''"`,
}, "\n"),
},
{
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"),
},
{
name: "copy-from-owner", // from issue #2518
dockerfileContents: strings.Join([]string{
`FROM alpine`,
`RUN set -ex; touch /test; chown 65:65 /test`,
`FROM scratch`,
`USER 66:66`,
`COPY --from=0 /test /test`,
}, "\n"),
fsSkip: []string{"test:mtime"},
},
{
name: "copy-from-owner-with-chown", // issue #2518, but with chown to override
dockerfileContents: strings.Join([]string{
`FROM alpine`,
`RUN set -ex; touch /test; chown 65:65 /test`,
`FROM scratch`,
`USER 66:66`,
`COPY --from=0 --chown=1:1 /test /test`,
}, "\n"),
fsSkip: []string{"test:mtime"},
},
{
name: "copy-for-user", // flip side of issue #2518
contextDir: "copy",
dockerfileContents: strings.Join([]string{
`FROM 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 alpine`,
`USER 66:66`,
`COPY --chown=1:1 /script /script`,
}, "\n"),
},
{
name: "add-archive-1",
contextDir: "add/archive",
dockerfile: "Dockerfile.1",
},
{
name: "add-archive-2",
contextDir: "add/archive",
dockerfile: "Dockerfile.2",
},
{
name: "add-archive-3",
contextDir: "add/archive",
dockerfile: "Dockerfile.3",
},
{
name: "add-archive-4",
contextDir: "add/archive",
dockerfile: "Dockerfile.4",
fsSkip: []string{"(dir):sub:mtime"},
},
{
name: "add-archive-5",
contextDir: "add/archive",
dockerfile: "Dockerfile.5",
fsSkip: []string{"(dir):sub:mtime"},
},
{
name: "add-archive-6",
contextDir: "add/archive",
dockerfile: "Dockerfile.6",
fsSkip: []string{"(dir):sub:mtime"},
},
{
name: "add-archive-7",
contextDir: "add/archive",
dockerfile: "Dockerfile.7",
fsSkip: []string{"(dir):sub:mtime"},
},
{
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",
},
{
name: "dockerignore-allowlist-subdir-nofile-file",
contextDir: "dockerignore/allowlist/subdir-nofile",
shouldFailAt: 2,
failureRegex: "no such file or directory",
},
{
name: "dockerignore-allowlist-subdir-file-dir",
contextDir: "dockerignore/allowlist/subdir-file",
fsSkip: []string{"(dir):f1:mtime"},
},
{
name: "dockerignore-allowlist-subdir-file-file",
contextDir: "dockerignore/allowlist/subdir-file",
fsSkip: []string{"(dir):f1:mtime"},
},
{
name: "dockerignore-allowlist-nothing-dot",
contextDir: "dockerignore/allowlist/nothing-dot",
fsSkip: []string{"file:mtime"},
},
{
name: "dockerignore-allowlist-nothing-slash",
contextDir: "dockerignore/allowlist/nothing-slash",
fsSkip: []string{"file:mtime"},
},
{
// 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",
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"},
},
{
name: "dockerignore-allowlist-subsubdir-nosubdir",
contextDir: "dockerignore/allowlist/subsubdir-nosubdir",
fsSkip: []string{"file:mtime"},
},
{
name: "dockerignore-allowlist-alternating",
contextDir: "dockerignore/allowlist/alternating",
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",
},
{
name: "dockerignore-allowlist-alternating-other",
contextDir: "dockerignore/allowlist/alternating-other",
shouldFailAt: 7,
failureRegex: "no such file or directory",
},
{
name: "tar-g",
contextDir: "tar-g",
fsSkip: []string{"(dir):tmp:mtime"},
},
}
|