docker_cli_build_test.go 143 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599
  1. package main
  2. import (
  3. "archive/tar"
  4. "bufio"
  5. "bytes"
  6. "encoding/json"
  7. "fmt"
  8. "io/ioutil"
  9. "os"
  10. "os/exec"
  11. "path/filepath"
  12. "reflect"
  13. "regexp"
  14. "runtime"
  15. "strconv"
  16. "strings"
  17. "sync"
  18. "testing"
  19. "text/template"
  20. "time"
  21. "github.com/docker/docker/builder/command"
  22. "github.com/docker/docker/pkg/archive"
  23. "github.com/docker/docker/pkg/stringutils"
  24. )
  25. func TestBuildJSONEmptyRun(t *testing.T) {
  26. name := "testbuildjsonemptyrun"
  27. defer deleteImages(name)
  28. _, err := buildImage(
  29. name,
  30. `
  31. FROM busybox
  32. RUN []
  33. `,
  34. true)
  35. if err != nil {
  36. t.Fatal("error when dealing with a RUN statement with empty JSON array")
  37. }
  38. logDone("build - RUN with an empty array should not panic")
  39. }
  40. func TestBuildEmptyWhitespace(t *testing.T) {
  41. name := "testbuildemptywhitespace"
  42. defer deleteImages(name)
  43. _, err := buildImage(
  44. name,
  45. `
  46. FROM busybox
  47. COPY
  48. quux \
  49. bar
  50. `,
  51. true)
  52. if err == nil {
  53. t.Fatal("no error when dealing with a COPY statement with no content on the same line")
  54. }
  55. logDone("build - statements with whitespace and no content should generate a parse error")
  56. }
  57. func TestBuildShCmdJSONEntrypoint(t *testing.T) {
  58. name := "testbuildshcmdjsonentrypoint"
  59. defer deleteImages(name)
  60. _, err := buildImage(
  61. name,
  62. `
  63. FROM busybox
  64. ENTRYPOINT ["/bin/echo"]
  65. CMD echo test
  66. `,
  67. true)
  68. if err != nil {
  69. t.Fatal(err)
  70. }
  71. out, _, err := runCommandWithOutput(
  72. exec.Command(
  73. dockerBinary,
  74. "run",
  75. "--rm",
  76. name))
  77. if err != nil {
  78. t.Fatal(err)
  79. }
  80. if strings.TrimSpace(out) != "/bin/sh -c echo test" {
  81. t.Fatal("CMD did not contain /bin/sh -c")
  82. }
  83. logDone("build - CMD should always contain /bin/sh -c when specified without JSON")
  84. }
  85. func TestBuildEnvironmentReplacementUser(t *testing.T) {
  86. name := "testbuildenvironmentreplacement"
  87. defer deleteImages(name)
  88. _, err := buildImage(name, `
  89. FROM scratch
  90. ENV user foo
  91. USER ${user}
  92. `, true)
  93. if err != nil {
  94. t.Fatal(err)
  95. }
  96. res, err := inspectFieldJSON(name, "Config.User")
  97. if err != nil {
  98. t.Fatal(err)
  99. }
  100. if res != `"foo"` {
  101. t.Fatal("User foo from environment not in Config.User on image")
  102. }
  103. logDone("build - user environment replacement")
  104. }
  105. func TestBuildEnvironmentReplacementVolume(t *testing.T) {
  106. name := "testbuildenvironmentreplacement"
  107. defer deleteImages(name)
  108. _, err := buildImage(name, `
  109. FROM scratch
  110. ENV volume /quux
  111. VOLUME ${volume}
  112. `, true)
  113. if err != nil {
  114. t.Fatal(err)
  115. }
  116. res, err := inspectFieldJSON(name, "Config.Volumes")
  117. if err != nil {
  118. t.Fatal(err)
  119. }
  120. var volumes map[string]interface{}
  121. if err := json.Unmarshal([]byte(res), &volumes); err != nil {
  122. t.Fatal(err)
  123. }
  124. if _, ok := volumes["/quux"]; !ok {
  125. t.Fatal("Volume /quux from environment not in Config.Volumes on image")
  126. }
  127. logDone("build - volume environment replacement")
  128. }
  129. func TestBuildEnvironmentReplacementExpose(t *testing.T) {
  130. name := "testbuildenvironmentreplacement"
  131. defer deleteImages(name)
  132. _, err := buildImage(name, `
  133. FROM scratch
  134. ENV port 80
  135. EXPOSE ${port}
  136. `, true)
  137. if err != nil {
  138. t.Fatal(err)
  139. }
  140. res, err := inspectFieldJSON(name, "Config.ExposedPorts")
  141. if err != nil {
  142. t.Fatal(err)
  143. }
  144. var exposedPorts map[string]interface{}
  145. if err := json.Unmarshal([]byte(res), &exposedPorts); err != nil {
  146. t.Fatal(err)
  147. }
  148. if _, ok := exposedPorts["80/tcp"]; !ok {
  149. t.Fatal("Exposed port 80 from environment not in Config.ExposedPorts on image")
  150. }
  151. logDone("build - expose environment replacement")
  152. }
  153. func TestBuildEnvironmentReplacementWorkdir(t *testing.T) {
  154. name := "testbuildenvironmentreplacement"
  155. defer deleteImages(name)
  156. _, err := buildImage(name, `
  157. FROM busybox
  158. ENV MYWORKDIR /work
  159. RUN mkdir ${MYWORKDIR}
  160. WORKDIR ${MYWORKDIR}
  161. `, true)
  162. if err != nil {
  163. t.Fatal(err)
  164. }
  165. logDone("build - workdir environment replacement")
  166. }
  167. func TestBuildEnvironmentReplacementAddCopy(t *testing.T) {
  168. name := "testbuildenvironmentreplacement"
  169. defer deleteImages(name)
  170. ctx, err := fakeContext(`
  171. FROM scratch
  172. ENV baz foo
  173. ENV quux bar
  174. ENV dot .
  175. ADD ${baz} ${dot}
  176. COPY ${quux} ${dot}
  177. `,
  178. map[string]string{
  179. "foo": "test1",
  180. "bar": "test2",
  181. })
  182. if err != nil {
  183. t.Fatal(err)
  184. }
  185. defer ctx.Close()
  186. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  187. t.Fatal(err)
  188. }
  189. logDone("build - add/copy environment replacement")
  190. }
  191. func TestBuildEnvironmentReplacementEnv(t *testing.T) {
  192. name := "testbuildenvironmentreplacement"
  193. defer deleteImages(name)
  194. _, err := buildImage(name,
  195. `
  196. FROM busybox
  197. ENV foo zzz
  198. ENV bar ${foo}
  199. ENV abc1='$foo'
  200. ENV env1=$foo env2=${foo} env3="$foo" env4="${foo}"
  201. RUN [ "$abc1" = '$foo' ] && (echo "$abc1" | grep -q foo)
  202. ENV abc2="\$foo"
  203. RUN [ "$abc2" = '$foo' ] && (echo "$abc2" | grep -q foo)
  204. ENV abc3 '$foo'
  205. RUN [ "$abc3" = '$foo' ] && (echo "$abc3" | grep -q foo)
  206. ENV abc4 "\$foo"
  207. RUN [ "$abc4" = '$foo' ] && (echo "$abc4" | grep -q foo)
  208. `, true)
  209. if err != nil {
  210. t.Fatal(err)
  211. }
  212. res, err := inspectFieldJSON(name, "Config.Env")
  213. if err != nil {
  214. t.Fatal(err)
  215. }
  216. envResult := []string{}
  217. if err = unmarshalJSON([]byte(res), &envResult); err != nil {
  218. t.Fatal(err)
  219. }
  220. found := false
  221. envCount := 0
  222. for _, env := range envResult {
  223. parts := strings.SplitN(env, "=", 2)
  224. if parts[0] == "bar" {
  225. found = true
  226. if parts[1] != "zzz" {
  227. t.Fatalf("Could not find replaced var for env `bar`: got %q instead of `zzz`", parts[1])
  228. }
  229. } else if strings.HasPrefix(parts[0], "env") {
  230. envCount++
  231. if parts[1] != "zzz" {
  232. t.Fatalf("%s should be 'foo' but instead its %q", parts[0], parts[1])
  233. }
  234. }
  235. }
  236. if !found {
  237. t.Fatal("Never found the `bar` env variable")
  238. }
  239. if envCount != 4 {
  240. t.Fatalf("Didn't find all env vars - only saw %d\n%s", envCount, envResult)
  241. }
  242. logDone("build - env environment replacement")
  243. }
  244. func TestBuildHandleEscapes(t *testing.T) {
  245. name := "testbuildhandleescapes"
  246. defer deleteImages(name)
  247. _, err := buildImage(name,
  248. `
  249. FROM scratch
  250. ENV FOO bar
  251. VOLUME ${FOO}
  252. `, true)
  253. if err != nil {
  254. t.Fatal(err)
  255. }
  256. var result map[string]map[string]struct{}
  257. res, err := inspectFieldJSON(name, "Config.Volumes")
  258. if err != nil {
  259. t.Fatal(err)
  260. }
  261. if err = unmarshalJSON([]byte(res), &result); err != nil {
  262. t.Fatal(err)
  263. }
  264. if _, ok := result["bar"]; !ok {
  265. t.Fatal("Could not find volume bar set from env foo in volumes table")
  266. }
  267. deleteImages(name)
  268. _, err = buildImage(name,
  269. `
  270. FROM scratch
  271. ENV FOO bar
  272. VOLUME \${FOO}
  273. `, true)
  274. if err != nil {
  275. t.Fatal(err)
  276. }
  277. res, err = inspectFieldJSON(name, "Config.Volumes")
  278. if err != nil {
  279. t.Fatal(err)
  280. }
  281. if err = unmarshalJSON([]byte(res), &result); err != nil {
  282. t.Fatal(err)
  283. }
  284. if _, ok := result["${FOO}"]; !ok {
  285. t.Fatal("Could not find volume ${FOO} set from env foo in volumes table")
  286. }
  287. deleteImages(name)
  288. // this test in particular provides *7* backslashes and expects 6 to come back.
  289. // Like above, the first escape is swallowed and the rest are treated as
  290. // literals, this one is just less obvious because of all the character noise.
  291. _, err = buildImage(name,
  292. `
  293. FROM scratch
  294. ENV FOO bar
  295. VOLUME \\\\\\\${FOO}
  296. `, true)
  297. if err != nil {
  298. t.Fatal(err)
  299. }
  300. res, err = inspectFieldJSON(name, "Config.Volumes")
  301. if err != nil {
  302. t.Fatal(err)
  303. }
  304. if err = unmarshalJSON([]byte(res), &result); err != nil {
  305. t.Fatal(err)
  306. }
  307. if _, ok := result[`\\\${FOO}`]; !ok {
  308. t.Fatal(`Could not find volume \\\${FOO} set from env foo in volumes table`, result)
  309. }
  310. logDone("build - handle escapes")
  311. }
  312. func TestBuildOnBuildLowercase(t *testing.T) {
  313. name := "testbuildonbuildlowercase"
  314. name2 := "testbuildonbuildlowercase2"
  315. defer deleteImages(name, name2)
  316. _, err := buildImage(name,
  317. `
  318. FROM busybox
  319. onbuild run echo quux
  320. `, true)
  321. if err != nil {
  322. t.Fatal(err)
  323. }
  324. _, out, err := buildImageWithOut(name2, fmt.Sprintf(`
  325. FROM %s
  326. `, name), true)
  327. if err != nil {
  328. t.Fatal(err)
  329. }
  330. if !strings.Contains(out, "quux") {
  331. t.Fatalf("Did not receive the expected echo text, got %s", out)
  332. }
  333. if strings.Contains(out, "ONBUILD ONBUILD") {
  334. t.Fatalf("Got an ONBUILD ONBUILD error with no error: got %s", out)
  335. }
  336. logDone("build - handle case-insensitive onbuild statement")
  337. }
  338. func TestBuildEnvEscapes(t *testing.T) {
  339. name := "testbuildenvescapes"
  340. defer deleteImages(name)
  341. defer deleteAllContainers()
  342. _, err := buildImage(name,
  343. `
  344. FROM busybox
  345. ENV TEST foo
  346. CMD echo \$
  347. `,
  348. true)
  349. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-t", name))
  350. if err != nil {
  351. t.Fatal(err)
  352. }
  353. if strings.TrimSpace(out) != "$" {
  354. t.Fatalf("Env TEST was not overwritten with bar when foo was supplied to dockerfile: was %q", strings.TrimSpace(out))
  355. }
  356. logDone("build - env should handle \\$ properly")
  357. }
  358. func TestBuildEnvOverwrite(t *testing.T) {
  359. name := "testbuildenvoverwrite"
  360. defer deleteImages(name)
  361. defer deleteAllContainers()
  362. _, err := buildImage(name,
  363. `
  364. FROM busybox
  365. ENV TEST foo
  366. CMD echo ${TEST}
  367. `,
  368. true)
  369. if err != nil {
  370. t.Fatal(err)
  371. }
  372. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-e", "TEST=bar", "-t", name))
  373. if err != nil {
  374. t.Fatal(err)
  375. }
  376. if strings.TrimSpace(out) != "bar" {
  377. t.Fatalf("Env TEST was not overwritten with bar when foo was supplied to dockerfile: was %q", strings.TrimSpace(out))
  378. }
  379. logDone("build - env should overwrite builder ENV during run")
  380. }
  381. func TestBuildOnBuildForbiddenMaintainerInSourceImage(t *testing.T) {
  382. name := "testbuildonbuildforbiddenmaintainerinsourceimage"
  383. defer deleteImages("onbuild")
  384. defer deleteImages(name)
  385. defer deleteAllContainers()
  386. createCmd := exec.Command(dockerBinary, "create", "busybox", "true")
  387. out, _, _, err := runCommandWithStdoutStderr(createCmd)
  388. if err != nil {
  389. t.Fatal(out, err)
  390. }
  391. cleanedContainerID := stripTrailingCharacters(out)
  392. commitCmd := exec.Command(dockerBinary, "commit", "--run", "{\"OnBuild\":[\"MAINTAINER docker.io\"]}", cleanedContainerID, "onbuild")
  393. if _, err := runCommand(commitCmd); err != nil {
  394. t.Fatal(err)
  395. }
  396. _, err = buildImage(name,
  397. `FROM onbuild`,
  398. true)
  399. if err != nil {
  400. if !strings.Contains(err.Error(), "maintainer isn't allowed as an ONBUILD trigger") {
  401. t.Fatalf("Wrong error %v, must be about MAINTAINER and ONBUILD in source image", err)
  402. }
  403. } else {
  404. t.Fatal("Error must not be nil")
  405. }
  406. logDone("build - onbuild forbidden maintainer in source image")
  407. }
  408. func TestBuildOnBuildForbiddenFromInSourceImage(t *testing.T) {
  409. name := "testbuildonbuildforbiddenfrominsourceimage"
  410. defer deleteImages("onbuild")
  411. defer deleteImages(name)
  412. defer deleteAllContainers()
  413. createCmd := exec.Command(dockerBinary, "create", "busybox", "true")
  414. out, _, _, err := runCommandWithStdoutStderr(createCmd)
  415. if err != nil {
  416. t.Fatal(out, err)
  417. }
  418. cleanedContainerID := stripTrailingCharacters(out)
  419. commitCmd := exec.Command(dockerBinary, "commit", "--run", "{\"OnBuild\":[\"FROM busybox\"]}", cleanedContainerID, "onbuild")
  420. if _, err := runCommand(commitCmd); err != nil {
  421. t.Fatal(err)
  422. }
  423. _, err = buildImage(name,
  424. `FROM onbuild`,
  425. true)
  426. if err != nil {
  427. if !strings.Contains(err.Error(), "from isn't allowed as an ONBUILD trigger") {
  428. t.Fatalf("Wrong error %v, must be about FROM and ONBUILD in source image", err)
  429. }
  430. } else {
  431. t.Fatal("Error must not be nil")
  432. }
  433. logDone("build - onbuild forbidden from in source image")
  434. }
  435. func TestBuildOnBuildForbiddenChainedInSourceImage(t *testing.T) {
  436. name := "testbuildonbuildforbiddenchainedinsourceimage"
  437. defer deleteImages("onbuild")
  438. defer deleteImages(name)
  439. defer deleteAllContainers()
  440. createCmd := exec.Command(dockerBinary, "create", "busybox", "true")
  441. out, _, _, err := runCommandWithStdoutStderr(createCmd)
  442. if err != nil {
  443. t.Fatal(out, err)
  444. }
  445. cleanedContainerID := stripTrailingCharacters(out)
  446. commitCmd := exec.Command(dockerBinary, "commit", "--run", "{\"OnBuild\":[\"ONBUILD RUN ls\"]}", cleanedContainerID, "onbuild")
  447. if _, err := runCommand(commitCmd); err != nil {
  448. t.Fatal(err)
  449. }
  450. _, err = buildImage(name,
  451. `FROM onbuild`,
  452. true)
  453. if err != nil {
  454. if !strings.Contains(err.Error(), "Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed") {
  455. t.Fatalf("Wrong error %v, must be about chaining ONBUILD in source image", err)
  456. }
  457. } else {
  458. t.Fatal("Error must not be nil")
  459. }
  460. logDone("build - onbuild forbidden chained in source image")
  461. }
  462. func TestBuildOnBuildCmdEntrypointJSON(t *testing.T) {
  463. name1 := "onbuildcmd"
  464. name2 := "onbuildgenerated"
  465. defer deleteImages(name2)
  466. defer deleteImages(name1)
  467. defer deleteAllContainers()
  468. _, err := buildImage(name1, `
  469. FROM busybox
  470. ONBUILD CMD ["hello world"]
  471. ONBUILD ENTRYPOINT ["echo"]
  472. ONBUILD RUN ["true"]`,
  473. false)
  474. if err != nil {
  475. t.Fatal(err)
  476. }
  477. _, err = buildImage(name2, fmt.Sprintf(`FROM %s`, name1), false)
  478. if err != nil {
  479. t.Fatal(err)
  480. }
  481. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-t", name2))
  482. if err != nil {
  483. t.Fatal(err)
  484. }
  485. if !regexp.MustCompile(`(?m)^hello world`).MatchString(out) {
  486. t.Fatal("did not get echo output from onbuild", out)
  487. }
  488. logDone("build - onbuild with json entrypoint/cmd")
  489. }
  490. func TestBuildOnBuildEntrypointJSON(t *testing.T) {
  491. name1 := "onbuildcmd"
  492. name2 := "onbuildgenerated"
  493. defer deleteImages(name2)
  494. defer deleteImages(name1)
  495. defer deleteAllContainers()
  496. _, err := buildImage(name1, `
  497. FROM busybox
  498. ONBUILD ENTRYPOINT ["echo"]`,
  499. false)
  500. if err != nil {
  501. t.Fatal(err)
  502. }
  503. _, err = buildImage(name2, fmt.Sprintf("FROM %s\nCMD [\"hello world\"]\n", name1), false)
  504. if err != nil {
  505. t.Fatal(err)
  506. }
  507. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-t", name2))
  508. if err != nil {
  509. t.Fatal(err)
  510. }
  511. if !regexp.MustCompile(`(?m)^hello world`).MatchString(out) {
  512. t.Fatal("got malformed output from onbuild", out)
  513. }
  514. logDone("build - onbuild with json entrypoint")
  515. }
  516. func TestBuildCacheADD(t *testing.T) {
  517. name := "testbuildtwoimageswithadd"
  518. defer deleteImages(name)
  519. server, err := fakeStorage(map[string]string{
  520. "robots.txt": "hello",
  521. "index.html": "world",
  522. })
  523. if err != nil {
  524. t.Fatal(err)
  525. }
  526. defer server.Close()
  527. if _, err := buildImage(name,
  528. fmt.Sprintf(`FROM scratch
  529. ADD %s/robots.txt /`, server.URL()),
  530. true); err != nil {
  531. t.Fatal(err)
  532. }
  533. if err != nil {
  534. t.Fatal(err)
  535. }
  536. deleteImages(name)
  537. _, out, err := buildImageWithOut(name,
  538. fmt.Sprintf(`FROM scratch
  539. ADD %s/index.html /`, server.URL()),
  540. true)
  541. if err != nil {
  542. t.Fatal(err)
  543. }
  544. if strings.Contains(out, "Using cache") {
  545. t.Fatal("2nd build used cache on ADD, it shouldn't")
  546. }
  547. logDone("build - build two images with remote ADD")
  548. }
  549. func TestBuildLastModified(t *testing.T) {
  550. name := "testbuildlastmodified"
  551. defer deleteImages(name)
  552. server, err := fakeStorage(map[string]string{
  553. "file": "hello",
  554. })
  555. if err != nil {
  556. t.Fatal(err)
  557. }
  558. defer server.Close()
  559. var out, out2 string
  560. dFmt := `FROM busybox
  561. ADD %s/file /
  562. RUN ls -le /file`
  563. dockerfile := fmt.Sprintf(dFmt, server.URL())
  564. if _, out, err = buildImageWithOut(name, dockerfile, false); err != nil {
  565. t.Fatal(err)
  566. }
  567. originMTime := regexp.MustCompile(`root.*/file.*\n`).FindString(out)
  568. // Make sure our regexp is correct
  569. if strings.Index(originMTime, "/file") < 0 {
  570. t.Fatalf("Missing ls info on 'file':\n%s", out)
  571. }
  572. // Build it again and make sure the mtime of the file didn't change.
  573. // Wait a few seconds to make sure the time changed enough to notice
  574. time.Sleep(2 * time.Second)
  575. if _, out2, err = buildImageWithOut(name, dockerfile, false); err != nil {
  576. t.Fatal(err)
  577. }
  578. newMTime := regexp.MustCompile(`root.*/file.*\n`).FindString(out2)
  579. if newMTime != originMTime {
  580. t.Fatalf("MTime changed:\nOrigin:%s\nNew:%s", originMTime, newMTime)
  581. }
  582. // Now 'touch' the file and make sure the timestamp DID change this time
  583. // Create a new fakeStorage instead of just using Add() to help windows
  584. server, err = fakeStorage(map[string]string{
  585. "file": "hello",
  586. })
  587. if err != nil {
  588. t.Fatal(err)
  589. }
  590. defer server.Close()
  591. dockerfile = fmt.Sprintf(dFmt, server.URL())
  592. if _, out2, err = buildImageWithOut(name, dockerfile, false); err != nil {
  593. t.Fatal(err)
  594. }
  595. newMTime = regexp.MustCompile(`root.*/file.*\n`).FindString(out2)
  596. if newMTime == originMTime {
  597. t.Fatalf("MTime didn't change:\nOrigin:%s\nNew:%s", originMTime, newMTime)
  598. }
  599. logDone("build - use Last-Modified header")
  600. }
  601. func TestBuildSixtySteps(t *testing.T) {
  602. name := "foobuildsixtysteps"
  603. defer deleteImages(name)
  604. ctx, err := fakeContext("FROM scratch\n"+strings.Repeat("ADD foo /\n", 60),
  605. map[string]string{
  606. "foo": "test1",
  607. })
  608. if err != nil {
  609. t.Fatal(err)
  610. }
  611. defer ctx.Close()
  612. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  613. t.Fatal(err)
  614. }
  615. logDone("build - build an image with sixty build steps")
  616. }
  617. func TestBuildAddSingleFileToRoot(t *testing.T) {
  618. name := "testaddimg"
  619. defer deleteImages(name)
  620. ctx, err := fakeContext(fmt.Sprintf(`FROM busybox
  621. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  622. RUN echo 'dockerio:x:1001:' >> /etc/group
  623. RUN touch /exists
  624. RUN chown dockerio.dockerio /exists
  625. ADD test_file /
  626. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  627. RUN [ $(ls -l /test_file | awk '{print $1}') = '%s' ]
  628. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod),
  629. map[string]string{
  630. "test_file": "test1",
  631. })
  632. if err != nil {
  633. t.Fatal(err)
  634. }
  635. defer ctx.Close()
  636. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  637. t.Fatal(err)
  638. }
  639. logDone("build - add single file to root")
  640. }
  641. // Issue #3960: "ADD src ." hangs
  642. func TestBuildAddSingleFileToWorkdir(t *testing.T) {
  643. name := "testaddsinglefiletoworkdir"
  644. defer deleteImages(name)
  645. ctx, err := fakeContext(`FROM busybox
  646. ADD test_file .`,
  647. map[string]string{
  648. "test_file": "test1",
  649. })
  650. if err != nil {
  651. t.Fatal(err)
  652. }
  653. defer ctx.Close()
  654. done := make(chan struct{})
  655. go func() {
  656. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  657. t.Fatal(err)
  658. }
  659. close(done)
  660. }()
  661. select {
  662. case <-time.After(5 * time.Second):
  663. t.Fatal("Build with adding to workdir timed out")
  664. case <-done:
  665. }
  666. logDone("build - add single file to workdir")
  667. }
  668. func TestBuildAddSingleFileToExistDir(t *testing.T) {
  669. name := "testaddsinglefiletoexistdir"
  670. defer deleteImages(name)
  671. ctx, err := fakeContext(`FROM busybox
  672. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  673. RUN echo 'dockerio:x:1001:' >> /etc/group
  674. RUN mkdir /exists
  675. RUN touch /exists/exists_file
  676. RUN chown -R dockerio.dockerio /exists
  677. ADD test_file /exists/
  678. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  679. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]
  680. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
  681. map[string]string{
  682. "test_file": "test1",
  683. })
  684. if err != nil {
  685. t.Fatal(err)
  686. }
  687. defer ctx.Close()
  688. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  689. t.Fatal(err)
  690. }
  691. logDone("build - add single file to existing dir")
  692. }
  693. func TestBuildCopyAddMultipleFiles(t *testing.T) {
  694. server, err := fakeStorage(map[string]string{
  695. "robots.txt": "hello",
  696. })
  697. if err != nil {
  698. t.Fatal(err)
  699. }
  700. defer server.Close()
  701. name := "testcopymultiplefilestofile"
  702. defer deleteImages(name)
  703. ctx, err := fakeContext(fmt.Sprintf(`FROM busybox
  704. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  705. RUN echo 'dockerio:x:1001:' >> /etc/group
  706. RUN mkdir /exists
  707. RUN touch /exists/exists_file
  708. RUN chown -R dockerio.dockerio /exists
  709. COPY test_file1 test_file2 /exists/
  710. ADD test_file3 test_file4 %s/robots.txt /exists/
  711. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  712. RUN [ $(ls -l /exists/test_file1 | awk '{print $3":"$4}') = 'root:root' ]
  713. RUN [ $(ls -l /exists/test_file2 | awk '{print $3":"$4}') = 'root:root' ]
  714. RUN [ $(ls -l /exists/test_file3 | awk '{print $3":"$4}') = 'root:root' ]
  715. RUN [ $(ls -l /exists/test_file4 | awk '{print $3":"$4}') = 'root:root' ]
  716. RUN [ $(ls -l /exists/robots.txt | awk '{print $3":"$4}') = 'root:root' ]
  717. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  718. `, server.URL()),
  719. map[string]string{
  720. "test_file1": "test1",
  721. "test_file2": "test2",
  722. "test_file3": "test3",
  723. "test_file4": "test4",
  724. })
  725. defer ctx.Close()
  726. if err != nil {
  727. t.Fatal(err)
  728. }
  729. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  730. t.Fatal(err)
  731. }
  732. logDone("build - multiple file copy/add tests")
  733. }
  734. func TestBuildAddMultipleFilesToFile(t *testing.T) {
  735. name := "testaddmultiplefilestofile"
  736. defer deleteImages(name)
  737. ctx, err := fakeContext(`FROM scratch
  738. ADD file1.txt file2.txt test
  739. `,
  740. map[string]string{
  741. "file1.txt": "test1",
  742. "file2.txt": "test1",
  743. })
  744. defer ctx.Close()
  745. if err != nil {
  746. t.Fatal(err)
  747. }
  748. expected := "When using ADD with more than one source file, the destination must be a directory and end with a /"
  749. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  750. t.Fatalf("Wrong error: (should contain %q) got:\n%v", expected, err)
  751. }
  752. logDone("build - multiple add files to file")
  753. }
  754. func TestBuildJSONAddMultipleFilesToFile(t *testing.T) {
  755. name := "testjsonaddmultiplefilestofile"
  756. defer deleteImages(name)
  757. ctx, err := fakeContext(`FROM scratch
  758. ADD ["file1.txt", "file2.txt", "test"]
  759. `,
  760. map[string]string{
  761. "file1.txt": "test1",
  762. "file2.txt": "test1",
  763. })
  764. defer ctx.Close()
  765. if err != nil {
  766. t.Fatal(err)
  767. }
  768. expected := "When using ADD with more than one source file, the destination must be a directory and end with a /"
  769. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  770. t.Fatalf("Wrong error: (should contain %q) got:\n%v", expected, err)
  771. }
  772. logDone("build - multiple add files to file json syntax")
  773. }
  774. func TestBuildAddMultipleFilesToFileWild(t *testing.T) {
  775. name := "testaddmultiplefilestofilewild"
  776. defer deleteImages(name)
  777. ctx, err := fakeContext(`FROM scratch
  778. ADD file*.txt test
  779. `,
  780. map[string]string{
  781. "file1.txt": "test1",
  782. "file2.txt": "test1",
  783. })
  784. defer ctx.Close()
  785. if err != nil {
  786. t.Fatal(err)
  787. }
  788. expected := "When using ADD with more than one source file, the destination must be a directory and end with a /"
  789. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  790. t.Fatalf("Wrong error: (should contain %q) got:\n%v", expected, err)
  791. }
  792. logDone("build - multiple add files to file wild")
  793. }
  794. func TestBuildJSONAddMultipleFilesToFileWild(t *testing.T) {
  795. name := "testjsonaddmultiplefilestofilewild"
  796. defer deleteImages(name)
  797. ctx, err := fakeContext(`FROM scratch
  798. ADD ["file*.txt", "test"]
  799. `,
  800. map[string]string{
  801. "file1.txt": "test1",
  802. "file2.txt": "test1",
  803. })
  804. defer ctx.Close()
  805. if err != nil {
  806. t.Fatal(err)
  807. }
  808. expected := "When using ADD with more than one source file, the destination must be a directory and end with a /"
  809. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  810. t.Fatalf("Wrong error: (should contain %q) got:\n%v", expected, err)
  811. }
  812. logDone("build - multiple add files to file wild json syntax")
  813. }
  814. func TestBuildCopyMultipleFilesToFile(t *testing.T) {
  815. name := "testcopymultiplefilestofile"
  816. defer deleteImages(name)
  817. ctx, err := fakeContext(`FROM scratch
  818. COPY file1.txt file2.txt test
  819. `,
  820. map[string]string{
  821. "file1.txt": "test1",
  822. "file2.txt": "test1",
  823. })
  824. defer ctx.Close()
  825. if err != nil {
  826. t.Fatal(err)
  827. }
  828. expected := "When using COPY with more than one source file, the destination must be a directory and end with a /"
  829. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  830. t.Fatalf("Wrong error: (should contain %q) got:\n%v", expected, err)
  831. }
  832. logDone("build - multiple copy files to file")
  833. }
  834. func TestBuildJSONCopyMultipleFilesToFile(t *testing.T) {
  835. name := "testjsoncopymultiplefilestofile"
  836. defer deleteImages(name)
  837. ctx, err := fakeContext(`FROM scratch
  838. COPY ["file1.txt", "file2.txt", "test"]
  839. `,
  840. map[string]string{
  841. "file1.txt": "test1",
  842. "file2.txt": "test1",
  843. })
  844. defer ctx.Close()
  845. if err != nil {
  846. t.Fatal(err)
  847. }
  848. expected := "When using COPY with more than one source file, the destination must be a directory and end with a /"
  849. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  850. t.Fatalf("Wrong error: (should contain %q) got:\n%v", expected, err)
  851. }
  852. logDone("build - multiple copy files to file json syntax")
  853. }
  854. func TestBuildAddFileWithWhitespace(t *testing.T) {
  855. name := "testaddfilewithwhitespace"
  856. defer deleteImages(name)
  857. ctx, err := fakeContext(`FROM busybox
  858. RUN mkdir "/test dir"
  859. RUN mkdir "/test_dir"
  860. ADD [ "test file1", "/test_file1" ]
  861. ADD [ "test_file2", "/test file2" ]
  862. ADD [ "test file3", "/test file3" ]
  863. ADD [ "test dir/test_file4", "/test_dir/test_file4" ]
  864. ADD [ "test_dir/test_file5", "/test dir/test_file5" ]
  865. ADD [ "test dir/test_file6", "/test dir/test_file6" ]
  866. RUN [ $(cat "/test_file1") = 'test1' ]
  867. RUN [ $(cat "/test file2") = 'test2' ]
  868. RUN [ $(cat "/test file3") = 'test3' ]
  869. RUN [ $(cat "/test_dir/test_file4") = 'test4' ]
  870. RUN [ $(cat "/test dir/test_file5") = 'test5' ]
  871. RUN [ $(cat "/test dir/test_file6") = 'test6' ]`,
  872. map[string]string{
  873. "test file1": "test1",
  874. "test_file2": "test2",
  875. "test file3": "test3",
  876. "test dir/test_file4": "test4",
  877. "test_dir/test_file5": "test5",
  878. "test dir/test_file6": "test6",
  879. })
  880. defer ctx.Close()
  881. if err != nil {
  882. t.Fatal(err)
  883. }
  884. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  885. t.Fatal(err)
  886. }
  887. logDone("build - add file with whitespace")
  888. }
  889. func TestBuildCopyFileWithWhitespace(t *testing.T) {
  890. name := "testcopyfilewithwhitespace"
  891. defer deleteImages(name)
  892. ctx, err := fakeContext(`FROM busybox
  893. RUN mkdir "/test dir"
  894. RUN mkdir "/test_dir"
  895. COPY [ "test file1", "/test_file1" ]
  896. COPY [ "test_file2", "/test file2" ]
  897. COPY [ "test file3", "/test file3" ]
  898. COPY [ "test dir/test_file4", "/test_dir/test_file4" ]
  899. COPY [ "test_dir/test_file5", "/test dir/test_file5" ]
  900. COPY [ "test dir/test_file6", "/test dir/test_file6" ]
  901. RUN [ $(cat "/test_file1") = 'test1' ]
  902. RUN [ $(cat "/test file2") = 'test2' ]
  903. RUN [ $(cat "/test file3") = 'test3' ]
  904. RUN [ $(cat "/test_dir/test_file4") = 'test4' ]
  905. RUN [ $(cat "/test dir/test_file5") = 'test5' ]
  906. RUN [ $(cat "/test dir/test_file6") = 'test6' ]`,
  907. map[string]string{
  908. "test file1": "test1",
  909. "test_file2": "test2",
  910. "test file3": "test3",
  911. "test dir/test_file4": "test4",
  912. "test_dir/test_file5": "test5",
  913. "test dir/test_file6": "test6",
  914. })
  915. defer ctx.Close()
  916. if err != nil {
  917. t.Fatal(err)
  918. }
  919. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  920. t.Fatal(err)
  921. }
  922. logDone("build - copy file with whitespace")
  923. }
  924. func TestBuildAddMultipleFilesToFileWithWhitespace(t *testing.T) {
  925. name := "testaddmultiplefilestofilewithwhitespace"
  926. defer deleteImages(name)
  927. ctx, err := fakeContext(`FROM busybox
  928. ADD [ "test file1", "test file2", "test" ]
  929. `,
  930. map[string]string{
  931. "test file1": "test1",
  932. "test file2": "test2",
  933. })
  934. defer ctx.Close()
  935. if err != nil {
  936. t.Fatal(err)
  937. }
  938. expected := "When using ADD with more than one source file, the destination must be a directory and end with a /"
  939. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  940. t.Fatalf("Wrong error: (should contain %q) got:\n%v", expected, err)
  941. }
  942. logDone("build - multiple add files to file with whitespace")
  943. }
  944. func TestBuildCopyMultipleFilesToFileWithWhitespace(t *testing.T) {
  945. name := "testcopymultiplefilestofilewithwhitespace"
  946. defer deleteImages(name)
  947. ctx, err := fakeContext(`FROM busybox
  948. COPY [ "test file1", "test file2", "test" ]
  949. `,
  950. map[string]string{
  951. "test file1": "test1",
  952. "test file2": "test2",
  953. })
  954. defer ctx.Close()
  955. if err != nil {
  956. t.Fatal(err)
  957. }
  958. expected := "When using COPY with more than one source file, the destination must be a directory and end with a /"
  959. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  960. t.Fatalf("Wrong error: (should contain %q) got:\n%v", expected, err)
  961. }
  962. logDone("build - multiple copy files to file with whitespace")
  963. }
  964. func TestBuildCopyWildcard(t *testing.T) {
  965. name := "testcopywildcard"
  966. defer deleteImages(name)
  967. server, err := fakeStorage(map[string]string{
  968. "robots.txt": "hello",
  969. "index.html": "world",
  970. })
  971. if err != nil {
  972. t.Fatal(err)
  973. }
  974. defer server.Close()
  975. ctx, err := fakeContext(fmt.Sprintf(`FROM busybox
  976. COPY file*.txt /tmp/
  977. RUN ls /tmp/file1.txt /tmp/file2.txt
  978. RUN mkdir /tmp1
  979. COPY dir* /tmp1/
  980. RUN ls /tmp1/dirt /tmp1/nested_file /tmp1/nested_dir/nest_nest_file
  981. RUN mkdir /tmp2
  982. ADD dir/*dir %s/robots.txt /tmp2/
  983. RUN ls /tmp2/nest_nest_file /tmp2/robots.txt
  984. `, server.URL()),
  985. map[string]string{
  986. "file1.txt": "test1",
  987. "file2.txt": "test2",
  988. "dir/nested_file": "nested file",
  989. "dir/nested_dir/nest_nest_file": "2 times nested",
  990. "dirt": "dirty",
  991. })
  992. defer ctx.Close()
  993. if err != nil {
  994. t.Fatal(err)
  995. }
  996. id1, err := buildImageFromContext(name, ctx, true)
  997. if err != nil {
  998. t.Fatal(err)
  999. }
  1000. // Now make sure we use a cache the 2nd time
  1001. id2, err := buildImageFromContext(name, ctx, true)
  1002. if err != nil {
  1003. t.Fatal(err)
  1004. }
  1005. if id1 != id2 {
  1006. t.Fatal("didn't use the cache")
  1007. }
  1008. logDone("build - copy wild card")
  1009. }
  1010. func TestBuildCopyWildcardNoFind(t *testing.T) {
  1011. name := "testcopywildcardnofind"
  1012. defer deleteImages(name)
  1013. ctx, err := fakeContext(`FROM busybox
  1014. COPY file*.txt /tmp/
  1015. `, nil)
  1016. defer ctx.Close()
  1017. if err != nil {
  1018. t.Fatal(err)
  1019. }
  1020. _, err = buildImageFromContext(name, ctx, true)
  1021. if err == nil {
  1022. t.Fatal("should have failed to find a file")
  1023. }
  1024. if !strings.Contains(err.Error(), "No source files were specified") {
  1025. t.Fatalf("Wrong error %v, must be about no source files", err)
  1026. }
  1027. logDone("build - copy wild card no find")
  1028. }
  1029. func TestBuildCopyWildcardCache(t *testing.T) {
  1030. name := "testcopywildcardcache"
  1031. defer deleteImages(name)
  1032. ctx, err := fakeContext(`FROM busybox
  1033. COPY file1.txt /tmp/`,
  1034. map[string]string{
  1035. "file1.txt": "test1",
  1036. })
  1037. defer ctx.Close()
  1038. if err != nil {
  1039. t.Fatal(err)
  1040. }
  1041. id1, err := buildImageFromContext(name, ctx, true)
  1042. if err != nil {
  1043. t.Fatal(err)
  1044. }
  1045. // Now make sure we use a cache the 2nd time even with wild cards.
  1046. // Use the same context so the file is the same and the checksum will match
  1047. ctx.Add("Dockerfile", `FROM busybox
  1048. COPY file*.txt /tmp/`)
  1049. id2, err := buildImageFromContext(name, ctx, true)
  1050. if err != nil {
  1051. t.Fatal(err)
  1052. }
  1053. if id1 != id2 {
  1054. t.Fatal("didn't use the cache")
  1055. }
  1056. logDone("build - copy wild card cache")
  1057. }
  1058. func TestBuildAddSingleFileToNonExistingDir(t *testing.T) {
  1059. name := "testaddsinglefiletononexistingdir"
  1060. defer deleteImages(name)
  1061. ctx, err := fakeContext(`FROM busybox
  1062. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1063. RUN echo 'dockerio:x:1001:' >> /etc/group
  1064. RUN touch /exists
  1065. RUN chown dockerio.dockerio /exists
  1066. ADD test_file /test_dir/
  1067. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  1068. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  1069. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
  1070. map[string]string{
  1071. "test_file": "test1",
  1072. })
  1073. if err != nil {
  1074. t.Fatal(err)
  1075. }
  1076. defer ctx.Close()
  1077. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1078. t.Fatal(err)
  1079. }
  1080. logDone("build - add single file to non-existing dir")
  1081. }
  1082. func TestBuildAddDirContentToRoot(t *testing.T) {
  1083. name := "testadddircontenttoroot"
  1084. defer deleteImages(name)
  1085. ctx, err := fakeContext(`FROM busybox
  1086. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1087. RUN echo 'dockerio:x:1001:' >> /etc/group
  1088. RUN touch /exists
  1089. RUN chown dockerio.dockerio exists
  1090. ADD test_dir /
  1091. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  1092. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
  1093. map[string]string{
  1094. "test_dir/test_file": "test1",
  1095. })
  1096. if err != nil {
  1097. t.Fatal(err)
  1098. }
  1099. defer ctx.Close()
  1100. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1101. t.Fatal(err)
  1102. }
  1103. logDone("build - add directory contents to root")
  1104. }
  1105. func TestBuildAddDirContentToExistingDir(t *testing.T) {
  1106. name := "testadddircontenttoexistingdir"
  1107. defer deleteImages(name)
  1108. ctx, err := fakeContext(`FROM busybox
  1109. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1110. RUN echo 'dockerio:x:1001:' >> /etc/group
  1111. RUN mkdir /exists
  1112. RUN touch /exists/exists_file
  1113. RUN chown -R dockerio.dockerio /exists
  1114. ADD test_dir/ /exists/
  1115. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  1116. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  1117. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]`,
  1118. map[string]string{
  1119. "test_dir/test_file": "test1",
  1120. })
  1121. if err != nil {
  1122. t.Fatal(err)
  1123. }
  1124. defer ctx.Close()
  1125. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1126. t.Fatal(err)
  1127. }
  1128. logDone("build - add directory contents to existing dir")
  1129. }
  1130. func TestBuildAddWholeDirToRoot(t *testing.T) {
  1131. name := "testaddwholedirtoroot"
  1132. defer deleteImages(name)
  1133. ctx, err := fakeContext(fmt.Sprintf(`FROM busybox
  1134. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1135. RUN echo 'dockerio:x:1001:' >> /etc/group
  1136. RUN touch /exists
  1137. RUN chown dockerio.dockerio exists
  1138. ADD test_dir /test_dir
  1139. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  1140. RUN [ $(ls -l / | grep test_dir | awk '{print $1}') = 'drwxr-xr-x' ]
  1141. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  1142. RUN [ $(ls -l /test_dir/test_file | awk '{print $1}') = '%s' ]
  1143. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod),
  1144. map[string]string{
  1145. "test_dir/test_file": "test1",
  1146. })
  1147. if err != nil {
  1148. t.Fatal(err)
  1149. }
  1150. defer ctx.Close()
  1151. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1152. t.Fatal(err)
  1153. }
  1154. logDone("build - add whole directory to root")
  1155. }
  1156. // Testing #5941
  1157. func TestBuildAddEtcToRoot(t *testing.T) {
  1158. name := "testaddetctoroot"
  1159. defer deleteImages(name)
  1160. ctx, err := fakeContext(`FROM scratch
  1161. ADD . /`,
  1162. map[string]string{
  1163. "etc/test_file": "test1",
  1164. })
  1165. if err != nil {
  1166. t.Fatal(err)
  1167. }
  1168. defer ctx.Close()
  1169. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1170. t.Fatal(err)
  1171. }
  1172. logDone("build - add etc directory to root")
  1173. }
  1174. // Testing #9401
  1175. func TestBuildAddPreservesFilesSpecialBits(t *testing.T) {
  1176. name := "testaddpreservesfilesspecialbits"
  1177. defer deleteImages(name)
  1178. ctx, err := fakeContext(`FROM busybox
  1179. ADD suidbin /usr/bin/suidbin
  1180. RUN chmod 4755 /usr/bin/suidbin
  1181. RUN [ $(ls -l /usr/bin/suidbin | awk '{print $1}') = '-rwsr-xr-x' ]
  1182. ADD ./data/ /
  1183. RUN [ $(ls -l /usr/bin/suidbin | awk '{print $1}') = '-rwsr-xr-x' ]`,
  1184. map[string]string{
  1185. "suidbin": "suidbin",
  1186. "/data/usr/test_file": "test1",
  1187. })
  1188. if err != nil {
  1189. t.Fatal(err)
  1190. }
  1191. defer ctx.Close()
  1192. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1193. t.Fatal(err)
  1194. }
  1195. logDone("build - add preserves files special bits")
  1196. }
  1197. func TestBuildCopySingleFileToRoot(t *testing.T) {
  1198. name := "testcopysinglefiletoroot"
  1199. defer deleteImages(name)
  1200. ctx, err := fakeContext(fmt.Sprintf(`FROM busybox
  1201. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1202. RUN echo 'dockerio:x:1001:' >> /etc/group
  1203. RUN touch /exists
  1204. RUN chown dockerio.dockerio /exists
  1205. COPY test_file /
  1206. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  1207. RUN [ $(ls -l /test_file | awk '{print $1}') = '%s' ]
  1208. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod),
  1209. map[string]string{
  1210. "test_file": "test1",
  1211. })
  1212. if err != nil {
  1213. t.Fatal(err)
  1214. }
  1215. defer ctx.Close()
  1216. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1217. t.Fatal(err)
  1218. }
  1219. logDone("build - copy single file to root")
  1220. }
  1221. // Issue #3960: "ADD src ." hangs - adapted for COPY
  1222. func TestBuildCopySingleFileToWorkdir(t *testing.T) {
  1223. name := "testcopysinglefiletoworkdir"
  1224. defer deleteImages(name)
  1225. ctx, err := fakeContext(`FROM busybox
  1226. COPY test_file .`,
  1227. map[string]string{
  1228. "test_file": "test1",
  1229. })
  1230. if err != nil {
  1231. t.Fatal(err)
  1232. }
  1233. defer ctx.Close()
  1234. done := make(chan struct{})
  1235. go func() {
  1236. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1237. t.Fatal(err)
  1238. }
  1239. close(done)
  1240. }()
  1241. select {
  1242. case <-time.After(5 * time.Second):
  1243. t.Fatal("Build with adding to workdir timed out")
  1244. case <-done:
  1245. }
  1246. logDone("build - copy single file to workdir")
  1247. }
  1248. func TestBuildCopySingleFileToExistDir(t *testing.T) {
  1249. name := "testcopysinglefiletoexistdir"
  1250. defer deleteImages(name)
  1251. ctx, err := fakeContext(`FROM busybox
  1252. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1253. RUN echo 'dockerio:x:1001:' >> /etc/group
  1254. RUN mkdir /exists
  1255. RUN touch /exists/exists_file
  1256. RUN chown -R dockerio.dockerio /exists
  1257. COPY test_file /exists/
  1258. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  1259. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]
  1260. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
  1261. map[string]string{
  1262. "test_file": "test1",
  1263. })
  1264. if err != nil {
  1265. t.Fatal(err)
  1266. }
  1267. defer ctx.Close()
  1268. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1269. t.Fatal(err)
  1270. }
  1271. logDone("build - copy single file to existing dir")
  1272. }
  1273. func TestBuildCopySingleFileToNonExistDir(t *testing.T) {
  1274. name := "testcopysinglefiletononexistdir"
  1275. defer deleteImages(name)
  1276. ctx, err := fakeContext(`FROM busybox
  1277. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1278. RUN echo 'dockerio:x:1001:' >> /etc/group
  1279. RUN touch /exists
  1280. RUN chown dockerio.dockerio /exists
  1281. COPY test_file /test_dir/
  1282. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  1283. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  1284. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
  1285. map[string]string{
  1286. "test_file": "test1",
  1287. })
  1288. if err != nil {
  1289. t.Fatal(err)
  1290. }
  1291. defer ctx.Close()
  1292. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1293. t.Fatal(err)
  1294. }
  1295. logDone("build - copy single file to non-existing dir")
  1296. }
  1297. func TestBuildCopyDirContentToRoot(t *testing.T) {
  1298. name := "testcopydircontenttoroot"
  1299. defer deleteImages(name)
  1300. ctx, err := fakeContext(`FROM busybox
  1301. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1302. RUN echo 'dockerio:x:1001:' >> /etc/group
  1303. RUN touch /exists
  1304. RUN chown dockerio.dockerio exists
  1305. COPY test_dir /
  1306. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  1307. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
  1308. map[string]string{
  1309. "test_dir/test_file": "test1",
  1310. })
  1311. if err != nil {
  1312. t.Fatal(err)
  1313. }
  1314. defer ctx.Close()
  1315. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1316. t.Fatal(err)
  1317. }
  1318. logDone("build - copy directory contents to root")
  1319. }
  1320. func TestBuildCopyDirContentToExistDir(t *testing.T) {
  1321. name := "testcopydircontenttoexistdir"
  1322. defer deleteImages(name)
  1323. ctx, err := fakeContext(`FROM busybox
  1324. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1325. RUN echo 'dockerio:x:1001:' >> /etc/group
  1326. RUN mkdir /exists
  1327. RUN touch /exists/exists_file
  1328. RUN chown -R dockerio.dockerio /exists
  1329. COPY test_dir/ /exists/
  1330. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  1331. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  1332. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]`,
  1333. map[string]string{
  1334. "test_dir/test_file": "test1",
  1335. })
  1336. if err != nil {
  1337. t.Fatal(err)
  1338. }
  1339. defer ctx.Close()
  1340. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1341. t.Fatal(err)
  1342. }
  1343. logDone("build - copy directory contents to existing dir")
  1344. }
  1345. func TestBuildCopyWholeDirToRoot(t *testing.T) {
  1346. name := "testcopywholedirtoroot"
  1347. defer deleteImages(name)
  1348. ctx, err := fakeContext(fmt.Sprintf(`FROM busybox
  1349. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1350. RUN echo 'dockerio:x:1001:' >> /etc/group
  1351. RUN touch /exists
  1352. RUN chown dockerio.dockerio exists
  1353. COPY test_dir /test_dir
  1354. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  1355. RUN [ $(ls -l / | grep test_dir | awk '{print $1}') = 'drwxr-xr-x' ]
  1356. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  1357. RUN [ $(ls -l /test_dir/test_file | awk '{print $1}') = '%s' ]
  1358. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod),
  1359. map[string]string{
  1360. "test_dir/test_file": "test1",
  1361. })
  1362. if err != nil {
  1363. t.Fatal(err)
  1364. }
  1365. defer ctx.Close()
  1366. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1367. t.Fatal(err)
  1368. }
  1369. logDone("build - copy whole directory to root")
  1370. }
  1371. func TestBuildCopyEtcToRoot(t *testing.T) {
  1372. name := "testcopyetctoroot"
  1373. defer deleteImages(name)
  1374. ctx, err := fakeContext(`FROM scratch
  1375. COPY . /`,
  1376. map[string]string{
  1377. "etc/test_file": "test1",
  1378. })
  1379. if err != nil {
  1380. t.Fatal(err)
  1381. }
  1382. defer ctx.Close()
  1383. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1384. t.Fatal(err)
  1385. }
  1386. logDone("build - copy etc directory to root")
  1387. }
  1388. func TestBuildCopyDisallowRemote(t *testing.T) {
  1389. name := "testcopydisallowremote"
  1390. defer deleteImages(name)
  1391. _, out, err := buildImageWithOut(name, `FROM scratch
  1392. COPY https://index.docker.io/robots.txt /`,
  1393. true)
  1394. if err == nil || !strings.Contains(out, "Source can't be a URL for COPY") {
  1395. t.Fatalf("Error should be about disallowed remote source, got err: %s, out: %q", err, out)
  1396. }
  1397. logDone("build - copy - disallow copy from remote")
  1398. }
  1399. func TestBuildAddBadLinks(t *testing.T) {
  1400. const (
  1401. dockerfile = `
  1402. FROM scratch
  1403. ADD links.tar /
  1404. ADD foo.txt /symlink/
  1405. `
  1406. targetFile = "foo.txt"
  1407. )
  1408. var (
  1409. name = "test-link-absolute"
  1410. )
  1411. defer deleteImages(name)
  1412. ctx, err := fakeContext(dockerfile, nil)
  1413. if err != nil {
  1414. t.Fatal(err)
  1415. }
  1416. defer ctx.Close()
  1417. tempDir, err := ioutil.TempDir("", "test-link-absolute-temp-")
  1418. if err != nil {
  1419. t.Fatalf("failed to create temporary directory: %s", tempDir)
  1420. }
  1421. defer os.RemoveAll(tempDir)
  1422. var symlinkTarget string
  1423. if runtime.GOOS == "windows" {
  1424. var driveLetter string
  1425. if abs, err := filepath.Abs(tempDir); err != nil {
  1426. t.Fatal(err)
  1427. } else {
  1428. driveLetter = abs[:1]
  1429. }
  1430. tempDirWithoutDrive := tempDir[2:]
  1431. symlinkTarget = fmt.Sprintf(`%s:\..\..\..\..\..\..\..\..\..\..\..\..%s`, driveLetter, tempDirWithoutDrive)
  1432. } else {
  1433. symlinkTarget = fmt.Sprintf("/../../../../../../../../../../../..%s", tempDir)
  1434. }
  1435. tarPath := filepath.Join(ctx.Dir, "links.tar")
  1436. nonExistingFile := filepath.Join(tempDir, targetFile)
  1437. fooPath := filepath.Join(ctx.Dir, targetFile)
  1438. tarOut, err := os.Create(tarPath)
  1439. if err != nil {
  1440. t.Fatal(err)
  1441. }
  1442. tarWriter := tar.NewWriter(tarOut)
  1443. header := &tar.Header{
  1444. Name: "symlink",
  1445. Typeflag: tar.TypeSymlink,
  1446. Linkname: symlinkTarget,
  1447. Mode: 0755,
  1448. Uid: 0,
  1449. Gid: 0,
  1450. }
  1451. err = tarWriter.WriteHeader(header)
  1452. if err != nil {
  1453. t.Fatal(err)
  1454. }
  1455. tarWriter.Close()
  1456. tarOut.Close()
  1457. foo, err := os.Create(fooPath)
  1458. if err != nil {
  1459. t.Fatal(err)
  1460. }
  1461. defer foo.Close()
  1462. if _, err := foo.WriteString("test"); err != nil {
  1463. t.Fatal(err)
  1464. }
  1465. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1466. t.Fatal(err)
  1467. }
  1468. if _, err := os.Stat(nonExistingFile); err == nil || err != nil && !os.IsNotExist(err) {
  1469. t.Fatalf("%s shouldn't have been written and it shouldn't exist", nonExistingFile)
  1470. }
  1471. logDone("build - ADD must add files in container")
  1472. }
  1473. func TestBuildAddBadLinksVolume(t *testing.T) {
  1474. const (
  1475. dockerfileTemplate = `
  1476. FROM busybox
  1477. RUN ln -s /../../../../../../../../%s /x
  1478. VOLUME /x
  1479. ADD foo.txt /x/`
  1480. targetFile = "foo.txt"
  1481. )
  1482. var (
  1483. name = "test-link-absolute-volume"
  1484. dockerfile = ""
  1485. )
  1486. defer deleteImages(name)
  1487. tempDir, err := ioutil.TempDir("", "test-link-absolute-volume-temp-")
  1488. if err != nil {
  1489. t.Fatalf("failed to create temporary directory: %s", tempDir)
  1490. }
  1491. defer os.RemoveAll(tempDir)
  1492. dockerfile = fmt.Sprintf(dockerfileTemplate, tempDir)
  1493. nonExistingFile := filepath.Join(tempDir, targetFile)
  1494. ctx, err := fakeContext(dockerfile, nil)
  1495. if err != nil {
  1496. t.Fatal(err)
  1497. }
  1498. defer ctx.Close()
  1499. fooPath := filepath.Join(ctx.Dir, targetFile)
  1500. foo, err := os.Create(fooPath)
  1501. if err != nil {
  1502. t.Fatal(err)
  1503. }
  1504. defer foo.Close()
  1505. if _, err := foo.WriteString("test"); err != nil {
  1506. t.Fatal(err)
  1507. }
  1508. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1509. t.Fatal(err)
  1510. }
  1511. if _, err := os.Stat(nonExistingFile); err == nil || err != nil && !os.IsNotExist(err) {
  1512. t.Fatalf("%s shouldn't have been written and it shouldn't exist", nonExistingFile)
  1513. }
  1514. logDone("build - ADD should add files in volume")
  1515. }
  1516. // Issue #5270 - ensure we throw a better error than "unexpected EOF"
  1517. // when we can't access files in the context.
  1518. func TestBuildWithInaccessibleFilesInContext(t *testing.T) {
  1519. testRequires(t, UnixCli) // test uses chown/chmod: not available on windows
  1520. {
  1521. name := "testbuildinaccessiblefiles"
  1522. defer deleteImages(name)
  1523. ctx, err := fakeContext("FROM scratch\nADD . /foo/", map[string]string{"fileWithoutReadAccess": "foo"})
  1524. if err != nil {
  1525. t.Fatal(err)
  1526. }
  1527. defer ctx.Close()
  1528. // This is used to ensure we detect inaccessible files early during build in the cli client
  1529. pathToFileWithoutReadAccess := filepath.Join(ctx.Dir, "fileWithoutReadAccess")
  1530. if err = os.Chown(pathToFileWithoutReadAccess, 0, 0); err != nil {
  1531. t.Fatalf("failed to chown file to root: %s", err)
  1532. }
  1533. if err = os.Chmod(pathToFileWithoutReadAccess, 0700); err != nil {
  1534. t.Fatalf("failed to chmod file to 700: %s", err)
  1535. }
  1536. buildCmd := exec.Command("su", "unprivilegeduser", "-c", fmt.Sprintf("%s build -t %s .", dockerBinary, name))
  1537. buildCmd.Dir = ctx.Dir
  1538. out, _, err := runCommandWithOutput(buildCmd)
  1539. if err == nil {
  1540. t.Fatalf("build should have failed: %s %s", err, out)
  1541. }
  1542. // check if we've detected the failure before we started building
  1543. if !strings.Contains(out, "no permission to read from ") {
  1544. t.Fatalf("output should've contained the string: no permission to read from but contained: %s", out)
  1545. }
  1546. if !strings.Contains(out, "Error checking context is accessible") {
  1547. t.Fatalf("output should've contained the string: Error checking context is accessible")
  1548. }
  1549. }
  1550. {
  1551. name := "testbuildinaccessibledirectory"
  1552. defer deleteImages(name)
  1553. ctx, err := fakeContext("FROM scratch\nADD . /foo/", map[string]string{"directoryWeCantStat/bar": "foo"})
  1554. if err != nil {
  1555. t.Fatal(err)
  1556. }
  1557. defer ctx.Close()
  1558. // This is used to ensure we detect inaccessible directories early during build in the cli client
  1559. pathToDirectoryWithoutReadAccess := filepath.Join(ctx.Dir, "directoryWeCantStat")
  1560. pathToFileInDirectoryWithoutReadAccess := filepath.Join(pathToDirectoryWithoutReadAccess, "bar")
  1561. if err = os.Chown(pathToDirectoryWithoutReadAccess, 0, 0); err != nil {
  1562. t.Fatalf("failed to chown directory to root: %s", err)
  1563. }
  1564. if err = os.Chmod(pathToDirectoryWithoutReadAccess, 0444); err != nil {
  1565. t.Fatalf("failed to chmod directory to 444: %s", err)
  1566. }
  1567. if err = os.Chmod(pathToFileInDirectoryWithoutReadAccess, 0700); err != nil {
  1568. t.Fatalf("failed to chmod file to 700: %s", err)
  1569. }
  1570. buildCmd := exec.Command("su", "unprivilegeduser", "-c", fmt.Sprintf("%s build -t %s .", dockerBinary, name))
  1571. buildCmd.Dir = ctx.Dir
  1572. out, _, err := runCommandWithOutput(buildCmd)
  1573. if err == nil {
  1574. t.Fatalf("build should have failed: %s %s", err, out)
  1575. }
  1576. // check if we've detected the failure before we started building
  1577. if !strings.Contains(out, "can't stat") {
  1578. t.Fatalf("output should've contained the string: can't access %s", out)
  1579. }
  1580. if !strings.Contains(out, "Error checking context is accessible") {
  1581. t.Fatalf("output should've contained the string: Error checking context is accessible")
  1582. }
  1583. }
  1584. {
  1585. name := "testlinksok"
  1586. defer deleteImages(name)
  1587. ctx, err := fakeContext("FROM scratch\nADD . /foo/", nil)
  1588. if err != nil {
  1589. t.Fatal(err)
  1590. }
  1591. defer ctx.Close()
  1592. target := "../../../../../../../../../../../../../../../../../../../azA"
  1593. if err := os.Symlink(filepath.Join(ctx.Dir, "g"), target); err != nil {
  1594. t.Fatal(err)
  1595. }
  1596. defer os.Remove(target)
  1597. // This is used to ensure we don't follow links when checking if everything in the context is accessible
  1598. // This test doesn't require that we run commands as an unprivileged user
  1599. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1600. t.Fatal(err)
  1601. }
  1602. }
  1603. {
  1604. name := "testbuildignoredinaccessible"
  1605. defer deleteImages(name)
  1606. ctx, err := fakeContext("FROM scratch\nADD . /foo/",
  1607. map[string]string{
  1608. "directoryWeCantStat/bar": "foo",
  1609. ".dockerignore": "directoryWeCantStat",
  1610. })
  1611. if err != nil {
  1612. t.Fatal(err)
  1613. }
  1614. defer ctx.Close()
  1615. // This is used to ensure we don't try to add inaccessible files when they are ignored by a .dockerignore pattern
  1616. pathToDirectoryWithoutReadAccess := filepath.Join(ctx.Dir, "directoryWeCantStat")
  1617. pathToFileInDirectoryWithoutReadAccess := filepath.Join(pathToDirectoryWithoutReadAccess, "bar")
  1618. if err = os.Chown(pathToDirectoryWithoutReadAccess, 0, 0); err != nil {
  1619. t.Fatalf("failed to chown directory to root: %s", err)
  1620. }
  1621. if err = os.Chmod(pathToDirectoryWithoutReadAccess, 0444); err != nil {
  1622. t.Fatalf("failed to chmod directory to 755: %s", err)
  1623. }
  1624. if err = os.Chmod(pathToFileInDirectoryWithoutReadAccess, 0700); err != nil {
  1625. t.Fatalf("failed to chmod file to 444: %s", err)
  1626. }
  1627. buildCmd := exec.Command("su", "unprivilegeduser", "-c", fmt.Sprintf("%s build -t %s .", dockerBinary, name))
  1628. buildCmd.Dir = ctx.Dir
  1629. if out, _, err := runCommandWithOutput(buildCmd); err != nil {
  1630. t.Fatalf("build should have worked: %s %s", err, out)
  1631. }
  1632. }
  1633. logDone("build - ADD from context with inaccessible files must not pass")
  1634. logDone("build - ADD from context with accessible links must work")
  1635. logDone("build - ADD from context with ignored inaccessible files must work")
  1636. }
  1637. func TestBuildForceRm(t *testing.T) {
  1638. containerCountBefore, err := getContainerCount()
  1639. if err != nil {
  1640. t.Fatalf("failed to get the container count: %s", err)
  1641. }
  1642. name := "testbuildforcerm"
  1643. defer deleteImages(name)
  1644. ctx, err := fakeContext("FROM scratch\nRUN true\nRUN thiswillfail", nil)
  1645. if err != nil {
  1646. t.Fatal(err)
  1647. }
  1648. defer ctx.Close()
  1649. buildCmd := exec.Command(dockerBinary, "build", "-t", name, "--force-rm", ".")
  1650. buildCmd.Dir = ctx.Dir
  1651. if out, _, err := runCommandWithOutput(buildCmd); err == nil {
  1652. t.Fatalf("failed to build the image: %s, %v", out, err)
  1653. }
  1654. containerCountAfter, err := getContainerCount()
  1655. if err != nil {
  1656. t.Fatalf("failed to get the container count: %s", err)
  1657. }
  1658. if containerCountBefore != containerCountAfter {
  1659. t.Fatalf("--force-rm shouldn't have left containers behind")
  1660. }
  1661. logDone("build - ensure --force-rm doesn't leave containers behind")
  1662. }
  1663. // Test that an infinite sleep during a build is killed if the client disconnects.
  1664. // This test is fairly hairy because there are lots of ways to race.
  1665. // Strategy:
  1666. // * Monitor the output of docker events starting from before
  1667. // * Run a 1-year-long sleep from a docker build.
  1668. // * When docker events sees container start, close the "docker build" command
  1669. // * Wait for docker events to emit a dying event.
  1670. func TestBuildCancelationKillsSleep(t *testing.T) {
  1671. // TODO(jfrazelle): Make this work on Windows.
  1672. testRequires(t, SameHostDaemon)
  1673. name := "testbuildcancelation"
  1674. defer deleteImages(name)
  1675. // (Note: one year, will never finish)
  1676. ctx, err := fakeContext("FROM busybox\nRUN sleep 31536000", nil)
  1677. if err != nil {
  1678. t.Fatal(err)
  1679. }
  1680. defer ctx.Close()
  1681. var wg sync.WaitGroup
  1682. defer wg.Wait()
  1683. finish := make(chan struct{})
  1684. defer close(finish)
  1685. eventStart := make(chan struct{})
  1686. eventDie := make(chan struct{})
  1687. // Start one second ago, to avoid rounding problems
  1688. startEpoch := time.Now().Add(-1 * time.Second)
  1689. // Goroutine responsible for watching start/die events from `docker events`
  1690. wg.Add(1)
  1691. go func() {
  1692. defer wg.Done()
  1693. // Watch for events since epoch.
  1694. eventsCmd := exec.Command(dockerBinary, "events",
  1695. "-since", fmt.Sprint(startEpoch.Unix()))
  1696. stdout, err := eventsCmd.StdoutPipe()
  1697. err = eventsCmd.Start()
  1698. if err != nil {
  1699. t.Fatalf("failed to start 'docker events': %s", err)
  1700. }
  1701. go func() {
  1702. <-finish
  1703. eventsCmd.Process.Kill()
  1704. }()
  1705. var started, died bool
  1706. matchStart := regexp.MustCompile(" \\(from busybox\\:latest\\) start$")
  1707. matchDie := regexp.MustCompile(" \\(from busybox\\:latest\\) die$")
  1708. //
  1709. // Read lines of `docker events` looking for container start and stop.
  1710. //
  1711. scanner := bufio.NewScanner(stdout)
  1712. for scanner.Scan() {
  1713. if ok := matchStart.MatchString(scanner.Text()); ok {
  1714. if started {
  1715. t.Fatal("assertion fail: more than one container started")
  1716. }
  1717. close(eventStart)
  1718. started = true
  1719. }
  1720. if ok := matchDie.MatchString(scanner.Text()); ok {
  1721. if died {
  1722. t.Fatal("assertion fail: more than one container died")
  1723. }
  1724. close(eventDie)
  1725. died = true
  1726. }
  1727. }
  1728. err = eventsCmd.Wait()
  1729. if err != nil && !IsKilled(err) {
  1730. t.Fatalf("docker events had bad exit status: %s", err)
  1731. }
  1732. }()
  1733. buildCmd := exec.Command(dockerBinary, "build", "-t", name, ".")
  1734. buildCmd.Dir = ctx.Dir
  1735. buildCmd.Stdout = os.Stdout
  1736. err = buildCmd.Start()
  1737. if err != nil {
  1738. t.Fatalf("failed to run build: %s", err)
  1739. }
  1740. select {
  1741. case <-time.After(30 * time.Second):
  1742. t.Fatal("failed to observe build container start in timely fashion")
  1743. case <-eventStart:
  1744. // Proceeds from here when we see the container fly past in the
  1745. // output of "docker events".
  1746. // Now we know the container is running.
  1747. }
  1748. // Send a kill to the `docker build` command.
  1749. // Causes the underlying build to be cancelled due to socket close.
  1750. err = buildCmd.Process.Kill()
  1751. if err != nil {
  1752. t.Fatalf("error killing build command: %s", err)
  1753. }
  1754. // Get the exit status of `docker build`, check it exited because killed.
  1755. err = buildCmd.Wait()
  1756. if err != nil && !IsKilled(err) {
  1757. t.Fatalf("wait failed during build run: %T %s", err, err)
  1758. }
  1759. select {
  1760. case <-time.After(30 * time.Second):
  1761. // If we don't get here in a timely fashion, it wasn't killed.
  1762. t.Fatal("container cancel did not succeed")
  1763. case <-eventDie:
  1764. // We saw the container shut down in the `docker events` stream,
  1765. // as expected.
  1766. }
  1767. logDone("build - ensure canceled job finishes immediately")
  1768. }
  1769. func TestBuildRm(t *testing.T) {
  1770. name := "testbuildrm"
  1771. defer deleteImages(name)
  1772. ctx, err := fakeContext("FROM scratch\nADD foo /\nADD foo /", map[string]string{"foo": "bar"})
  1773. if err != nil {
  1774. t.Fatal(err)
  1775. }
  1776. defer ctx.Close()
  1777. {
  1778. containerCountBefore, err := getContainerCount()
  1779. if err != nil {
  1780. t.Fatalf("failed to get the container count: %s", err)
  1781. }
  1782. out, _, err := dockerCmdInDir(t, ctx.Dir, "build", "--rm", "-t", name, ".")
  1783. if err != nil {
  1784. t.Fatal("failed to build the image", out)
  1785. }
  1786. containerCountAfter, err := getContainerCount()
  1787. if err != nil {
  1788. t.Fatalf("failed to get the container count: %s", err)
  1789. }
  1790. if containerCountBefore != containerCountAfter {
  1791. t.Fatalf("-rm shouldn't have left containers behind")
  1792. }
  1793. deleteImages(name)
  1794. }
  1795. {
  1796. containerCountBefore, err := getContainerCount()
  1797. if err != nil {
  1798. t.Fatalf("failed to get the container count: %s", err)
  1799. }
  1800. out, _, err := dockerCmdInDir(t, ctx.Dir, "build", "-t", name, ".")
  1801. if err != nil {
  1802. t.Fatal("failed to build the image", out)
  1803. }
  1804. containerCountAfter, err := getContainerCount()
  1805. if err != nil {
  1806. t.Fatalf("failed to get the container count: %s", err)
  1807. }
  1808. if containerCountBefore != containerCountAfter {
  1809. t.Fatalf("--rm shouldn't have left containers behind")
  1810. }
  1811. deleteImages(name)
  1812. }
  1813. {
  1814. containerCountBefore, err := getContainerCount()
  1815. if err != nil {
  1816. t.Fatalf("failed to get the container count: %s", err)
  1817. }
  1818. out, _, err := dockerCmdInDir(t, ctx.Dir, "build", "--rm=false", "-t", name, ".")
  1819. if err != nil {
  1820. t.Fatal("failed to build the image", out)
  1821. }
  1822. containerCountAfter, err := getContainerCount()
  1823. if err != nil {
  1824. t.Fatalf("failed to get the container count: %s", err)
  1825. }
  1826. if containerCountBefore == containerCountAfter {
  1827. t.Fatalf("--rm=false should have left containers behind")
  1828. }
  1829. deleteAllContainers()
  1830. deleteImages(name)
  1831. }
  1832. logDone("build - ensure --rm doesn't leave containers behind and that --rm=true is the default")
  1833. logDone("build - ensure --rm=false overrides the default")
  1834. }
  1835. func TestBuildWithVolumes(t *testing.T) {
  1836. var (
  1837. result map[string]map[string]struct{}
  1838. name = "testbuildvolumes"
  1839. emptyMap = make(map[string]struct{})
  1840. expected = map[string]map[string]struct{}{
  1841. "/test1": emptyMap,
  1842. "/test2": emptyMap,
  1843. "/test3": emptyMap,
  1844. "/test4": emptyMap,
  1845. "/test5": emptyMap,
  1846. "/test6": emptyMap,
  1847. "[/test7": emptyMap,
  1848. "/test8]": emptyMap,
  1849. }
  1850. )
  1851. defer deleteImages(name)
  1852. _, err := buildImage(name,
  1853. `FROM scratch
  1854. VOLUME /test1
  1855. VOLUME /test2
  1856. VOLUME /test3 /test4
  1857. VOLUME ["/test5", "/test6"]
  1858. VOLUME [/test7 /test8]
  1859. `,
  1860. true)
  1861. if err != nil {
  1862. t.Fatal(err)
  1863. }
  1864. res, err := inspectFieldJSON(name, "Config.Volumes")
  1865. if err != nil {
  1866. t.Fatal(err)
  1867. }
  1868. err = unmarshalJSON([]byte(res), &result)
  1869. if err != nil {
  1870. t.Fatal(err)
  1871. }
  1872. equal := reflect.DeepEqual(&result, &expected)
  1873. if !equal {
  1874. t.Fatalf("Volumes %s, expected %s", result, expected)
  1875. }
  1876. logDone("build - with volumes")
  1877. }
  1878. func TestBuildMaintainer(t *testing.T) {
  1879. name := "testbuildmaintainer"
  1880. expected := "dockerio"
  1881. defer deleteImages(name)
  1882. _, err := buildImage(name,
  1883. `FROM scratch
  1884. MAINTAINER dockerio`,
  1885. true)
  1886. if err != nil {
  1887. t.Fatal(err)
  1888. }
  1889. res, err := inspectField(name, "Author")
  1890. if err != nil {
  1891. t.Fatal(err)
  1892. }
  1893. if res != expected {
  1894. t.Fatalf("Maintainer %s, expected %s", res, expected)
  1895. }
  1896. logDone("build - maintainer")
  1897. }
  1898. func TestBuildUser(t *testing.T) {
  1899. name := "testbuilduser"
  1900. expected := "dockerio"
  1901. defer deleteImages(name)
  1902. _, err := buildImage(name,
  1903. `FROM busybox
  1904. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1905. USER dockerio
  1906. RUN [ $(whoami) = 'dockerio' ]`,
  1907. true)
  1908. if err != nil {
  1909. t.Fatal(err)
  1910. }
  1911. res, err := inspectField(name, "Config.User")
  1912. if err != nil {
  1913. t.Fatal(err)
  1914. }
  1915. if res != expected {
  1916. t.Fatalf("User %s, expected %s", res, expected)
  1917. }
  1918. logDone("build - user")
  1919. }
  1920. func TestBuildRelativeWorkdir(t *testing.T) {
  1921. name := "testbuildrelativeworkdir"
  1922. expected := "/test2/test3"
  1923. defer deleteImages(name)
  1924. _, err := buildImage(name,
  1925. `FROM busybox
  1926. RUN [ "$PWD" = '/' ]
  1927. WORKDIR test1
  1928. RUN [ "$PWD" = '/test1' ]
  1929. WORKDIR /test2
  1930. RUN [ "$PWD" = '/test2' ]
  1931. WORKDIR test3
  1932. RUN [ "$PWD" = '/test2/test3' ]`,
  1933. true)
  1934. if err != nil {
  1935. t.Fatal(err)
  1936. }
  1937. res, err := inspectField(name, "Config.WorkingDir")
  1938. if err != nil {
  1939. t.Fatal(err)
  1940. }
  1941. if res != expected {
  1942. t.Fatalf("Workdir %s, expected %s", res, expected)
  1943. }
  1944. logDone("build - relative workdir")
  1945. }
  1946. func TestBuildWorkdirWithEnvVariables(t *testing.T) {
  1947. name := "testbuildworkdirwithenvvariables"
  1948. expected := "/test1/test2"
  1949. defer deleteImages(name)
  1950. _, err := buildImage(name,
  1951. `FROM busybox
  1952. ENV DIRPATH /test1
  1953. ENV SUBDIRNAME test2
  1954. WORKDIR $DIRPATH
  1955. WORKDIR $SUBDIRNAME/$MISSING_VAR`,
  1956. true)
  1957. if err != nil {
  1958. t.Fatal(err)
  1959. }
  1960. res, err := inspectField(name, "Config.WorkingDir")
  1961. if err != nil {
  1962. t.Fatal(err)
  1963. }
  1964. if res != expected {
  1965. t.Fatalf("Workdir %s, expected %s", res, expected)
  1966. }
  1967. logDone("build - workdir with env variables")
  1968. }
  1969. func TestBuildRelativeCopy(t *testing.T) {
  1970. name := "testbuildrelativecopy"
  1971. defer deleteImages(name)
  1972. dockerfile := `
  1973. FROM busybox
  1974. WORKDIR /test1
  1975. WORKDIR test2
  1976. RUN [ "$PWD" = '/test1/test2' ]
  1977. COPY foo ./
  1978. RUN [ "$(cat /test1/test2/foo)" = 'hello' ]
  1979. ADD foo ./bar/baz
  1980. RUN [ "$(cat /test1/test2/bar/baz)" = 'hello' ]
  1981. COPY foo ./bar/baz2
  1982. RUN [ "$(cat /test1/test2/bar/baz2)" = 'hello' ]
  1983. WORKDIR ..
  1984. COPY foo ./
  1985. RUN [ "$(cat /test1/foo)" = 'hello' ]
  1986. COPY foo /test3/
  1987. RUN [ "$(cat /test3/foo)" = 'hello' ]
  1988. WORKDIR /test4
  1989. COPY . .
  1990. RUN [ "$(cat /test4/foo)" = 'hello' ]
  1991. WORKDIR /test5/test6
  1992. COPY foo ../
  1993. RUN [ "$(cat /test5/foo)" = 'hello' ]
  1994. `
  1995. ctx, err := fakeContext(dockerfile, map[string]string{
  1996. "foo": "hello",
  1997. })
  1998. defer ctx.Close()
  1999. if err != nil {
  2000. t.Fatal(err)
  2001. }
  2002. _, err = buildImageFromContext(name, ctx, false)
  2003. if err != nil {
  2004. t.Fatal(err)
  2005. }
  2006. logDone("build - relative copy/add")
  2007. }
  2008. func TestBuildEnv(t *testing.T) {
  2009. name := "testbuildenv"
  2010. expected := "[PATH=/test:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin PORT=2375]"
  2011. defer deleteImages(name)
  2012. _, err := buildImage(name,
  2013. `FROM busybox
  2014. ENV PATH /test:$PATH
  2015. ENV PORT 2375
  2016. RUN [ $(env | grep PORT) = 'PORT=2375' ]`,
  2017. true)
  2018. if err != nil {
  2019. t.Fatal(err)
  2020. }
  2021. res, err := inspectField(name, "Config.Env")
  2022. if err != nil {
  2023. t.Fatal(err)
  2024. }
  2025. if res != expected {
  2026. t.Fatalf("Env %s, expected %s", res, expected)
  2027. }
  2028. logDone("build - env")
  2029. }
  2030. func TestBuildContextCleanup(t *testing.T) {
  2031. testRequires(t, SameHostDaemon)
  2032. name := "testbuildcontextcleanup"
  2033. defer deleteImages(name)
  2034. entries, err := ioutil.ReadDir("/var/lib/docker/tmp")
  2035. if err != nil {
  2036. t.Fatalf("failed to list contents of tmp dir: %s", err)
  2037. }
  2038. _, err = buildImage(name,
  2039. `FROM scratch
  2040. ENTRYPOINT ["/bin/echo"]`,
  2041. true)
  2042. if err != nil {
  2043. t.Fatal(err)
  2044. }
  2045. entriesFinal, err := ioutil.ReadDir("/var/lib/docker/tmp")
  2046. if err != nil {
  2047. t.Fatalf("failed to list contents of tmp dir: %s", err)
  2048. }
  2049. if err = compareDirectoryEntries(entries, entriesFinal); err != nil {
  2050. t.Fatalf("context should have been deleted, but wasn't")
  2051. }
  2052. logDone("build - verify context cleanup works properly")
  2053. }
  2054. func TestBuildContextCleanupFailedBuild(t *testing.T) {
  2055. testRequires(t, SameHostDaemon)
  2056. name := "testbuildcontextcleanup"
  2057. defer deleteImages(name)
  2058. defer deleteAllContainers()
  2059. entries, err := ioutil.ReadDir("/var/lib/docker/tmp")
  2060. if err != nil {
  2061. t.Fatalf("failed to list contents of tmp dir: %s", err)
  2062. }
  2063. _, err = buildImage(name,
  2064. `FROM scratch
  2065. RUN /non/existing/command`,
  2066. true)
  2067. if err == nil {
  2068. t.Fatalf("expected build to fail, but it didn't")
  2069. }
  2070. entriesFinal, err := ioutil.ReadDir("/var/lib/docker/tmp")
  2071. if err != nil {
  2072. t.Fatalf("failed to list contents of tmp dir: %s", err)
  2073. }
  2074. if err = compareDirectoryEntries(entries, entriesFinal); err != nil {
  2075. t.Fatalf("context should have been deleted, but wasn't")
  2076. }
  2077. logDone("build - verify context cleanup works properly after an unsuccessful build")
  2078. }
  2079. func TestBuildCmd(t *testing.T) {
  2080. name := "testbuildcmd"
  2081. expected := "[/bin/echo Hello World]"
  2082. defer deleteImages(name)
  2083. _, err := buildImage(name,
  2084. `FROM scratch
  2085. CMD ["/bin/echo", "Hello World"]`,
  2086. true)
  2087. if err != nil {
  2088. t.Fatal(err)
  2089. }
  2090. res, err := inspectField(name, "Config.Cmd")
  2091. if err != nil {
  2092. t.Fatal(err)
  2093. }
  2094. if res != expected {
  2095. t.Fatalf("Cmd %s, expected %s", res, expected)
  2096. }
  2097. logDone("build - cmd")
  2098. }
  2099. func TestBuildExpose(t *testing.T) {
  2100. name := "testbuildexpose"
  2101. expected := "map[2375/tcp:map[]]"
  2102. defer deleteImages(name)
  2103. _, err := buildImage(name,
  2104. `FROM scratch
  2105. EXPOSE 2375`,
  2106. true)
  2107. if err != nil {
  2108. t.Fatal(err)
  2109. }
  2110. res, err := inspectField(name, "Config.ExposedPorts")
  2111. if err != nil {
  2112. t.Fatal(err)
  2113. }
  2114. if res != expected {
  2115. t.Fatalf("Exposed ports %s, expected %s", res, expected)
  2116. }
  2117. logDone("build - expose")
  2118. }
  2119. func TestBuildExposeMorePorts(t *testing.T) {
  2120. // start building docker file with a large number of ports
  2121. portList := make([]string, 50)
  2122. line := make([]string, 100)
  2123. expectedPorts := make([]int, len(portList)*len(line))
  2124. for i := 0; i < len(portList); i++ {
  2125. for j := 0; j < len(line); j++ {
  2126. p := i*len(line) + j + 1
  2127. line[j] = strconv.Itoa(p)
  2128. expectedPorts[p-1] = p
  2129. }
  2130. if i == len(portList)-1 {
  2131. portList[i] = strings.Join(line, " ")
  2132. } else {
  2133. portList[i] = strings.Join(line, " ") + ` \`
  2134. }
  2135. }
  2136. dockerfile := `FROM scratch
  2137. EXPOSE {{range .}} {{.}}
  2138. {{end}}`
  2139. tmpl := template.Must(template.New("dockerfile").Parse(dockerfile))
  2140. buf := bytes.NewBuffer(nil)
  2141. tmpl.Execute(buf, portList)
  2142. name := "testbuildexpose"
  2143. defer deleteImages(name)
  2144. _, err := buildImage(name, buf.String(), true)
  2145. if err != nil {
  2146. t.Fatal(err)
  2147. }
  2148. // check if all the ports are saved inside Config.ExposedPorts
  2149. res, err := inspectFieldJSON(name, "Config.ExposedPorts")
  2150. if err != nil {
  2151. t.Fatal(err)
  2152. }
  2153. var exposedPorts map[string]interface{}
  2154. if err := json.Unmarshal([]byte(res), &exposedPorts); err != nil {
  2155. t.Fatal(err)
  2156. }
  2157. for _, p := range expectedPorts {
  2158. ep := fmt.Sprintf("%d/tcp", p)
  2159. if _, ok := exposedPorts[ep]; !ok {
  2160. t.Errorf("Port(%s) is not exposed", ep)
  2161. } else {
  2162. delete(exposedPorts, ep)
  2163. }
  2164. }
  2165. if len(exposedPorts) != 0 {
  2166. t.Errorf("Unexpected extra exposed ports %v", exposedPorts)
  2167. }
  2168. logDone("build - expose large number of ports")
  2169. }
  2170. func TestBuildExposeOrder(t *testing.T) {
  2171. buildID := func(name, exposed string) string {
  2172. _, err := buildImage(name, fmt.Sprintf(`FROM scratch
  2173. EXPOSE %s`, exposed), true)
  2174. if err != nil {
  2175. t.Fatal(err)
  2176. }
  2177. id, err := inspectField(name, "Id")
  2178. if err != nil {
  2179. t.Fatal(err)
  2180. }
  2181. return id
  2182. }
  2183. id1 := buildID("testbuildexpose1", "80 2375")
  2184. id2 := buildID("testbuildexpose2", "2375 80")
  2185. defer deleteImages("testbuildexpose1", "testbuildexpose2")
  2186. if id1 != id2 {
  2187. t.Errorf("EXPOSE should invalidate the cache only when ports actually changed")
  2188. }
  2189. logDone("build - expose order")
  2190. }
  2191. func TestBuildExposeUpperCaseProto(t *testing.T) {
  2192. name := "testbuildexposeuppercaseproto"
  2193. expected := "map[5678/udp:map[]]"
  2194. defer deleteImages(name)
  2195. _, err := buildImage(name,
  2196. `FROM scratch
  2197. EXPOSE 5678/UDP`,
  2198. true)
  2199. if err != nil {
  2200. t.Fatal(err)
  2201. }
  2202. res, err := inspectField(name, "Config.ExposedPorts")
  2203. if err != nil {
  2204. t.Fatal(err)
  2205. }
  2206. if res != expected {
  2207. t.Fatalf("Exposed ports %s, expected %s", res, expected)
  2208. }
  2209. logDone("build - expose port with upper case proto")
  2210. }
  2211. func TestBuildExposeHostPort(t *testing.T) {
  2212. // start building docker file with ip:hostPort:containerPort
  2213. name := "testbuildexpose"
  2214. expected := "map[5678/tcp:map[]]"
  2215. defer deleteImages(name)
  2216. _, out, err := buildImageWithOut(name,
  2217. `FROM scratch
  2218. EXPOSE 192.168.1.2:2375:5678`,
  2219. true)
  2220. if err != nil {
  2221. t.Fatal(err)
  2222. }
  2223. if !strings.Contains(out, "to map host ports to container ports (ip:hostPort:containerPort) is deprecated.") {
  2224. t.Fatal("Missing warning message")
  2225. }
  2226. res, err := inspectField(name, "Config.ExposedPorts")
  2227. if err != nil {
  2228. t.Fatal(err)
  2229. }
  2230. if res != expected {
  2231. t.Fatalf("Exposed ports %s, expected %s", res, expected)
  2232. }
  2233. logDone("build - ignore exposing host's port")
  2234. }
  2235. func TestBuildEmptyEntrypointInheritance(t *testing.T) {
  2236. name := "testbuildentrypointinheritance"
  2237. name2 := "testbuildentrypointinheritance2"
  2238. defer deleteImages(name, name2)
  2239. _, err := buildImage(name,
  2240. `FROM busybox
  2241. ENTRYPOINT ["/bin/echo"]`,
  2242. true)
  2243. if err != nil {
  2244. t.Fatal(err)
  2245. }
  2246. res, err := inspectField(name, "Config.Entrypoint")
  2247. if err != nil {
  2248. t.Fatal(err)
  2249. }
  2250. expected := "[/bin/echo]"
  2251. if res != expected {
  2252. t.Fatalf("Entrypoint %s, expected %s", res, expected)
  2253. }
  2254. _, err = buildImage(name2,
  2255. fmt.Sprintf(`FROM %s
  2256. ENTRYPOINT []`, name),
  2257. true)
  2258. if err != nil {
  2259. t.Fatal(err)
  2260. }
  2261. res, err = inspectField(name2, "Config.Entrypoint")
  2262. if err != nil {
  2263. t.Fatal(err)
  2264. }
  2265. expected = "[]"
  2266. if res != expected {
  2267. t.Fatalf("Entrypoint %s, expected %s", res, expected)
  2268. }
  2269. logDone("build - empty entrypoint inheritance")
  2270. }
  2271. func TestBuildEmptyEntrypoint(t *testing.T) {
  2272. name := "testbuildentrypoint"
  2273. defer deleteImages(name)
  2274. expected := "[]"
  2275. _, err := buildImage(name,
  2276. `FROM busybox
  2277. ENTRYPOINT []`,
  2278. true)
  2279. if err != nil {
  2280. t.Fatal(err)
  2281. }
  2282. res, err := inspectField(name, "Config.Entrypoint")
  2283. if err != nil {
  2284. t.Fatal(err)
  2285. }
  2286. if res != expected {
  2287. t.Fatalf("Entrypoint %s, expected %s", res, expected)
  2288. }
  2289. logDone("build - empty entrypoint")
  2290. }
  2291. func TestBuildEntrypoint(t *testing.T) {
  2292. name := "testbuildentrypoint"
  2293. expected := "[/bin/echo]"
  2294. defer deleteImages(name)
  2295. _, err := buildImage(name,
  2296. `FROM scratch
  2297. ENTRYPOINT ["/bin/echo"]`,
  2298. true)
  2299. if err != nil {
  2300. t.Fatal(err)
  2301. }
  2302. res, err := inspectField(name, "Config.Entrypoint")
  2303. if err != nil {
  2304. t.Fatal(err)
  2305. }
  2306. if res != expected {
  2307. t.Fatalf("Entrypoint %s, expected %s", res, expected)
  2308. }
  2309. logDone("build - entrypoint")
  2310. }
  2311. // #6445 ensure ONBUILD triggers aren't committed to grandchildren
  2312. func TestBuildOnBuildLimitedInheritence(t *testing.T) {
  2313. var (
  2314. out2, out3 string
  2315. )
  2316. {
  2317. name1 := "testonbuildtrigger1"
  2318. dockerfile1 := `
  2319. FROM busybox
  2320. RUN echo "GRANDPARENT"
  2321. ONBUILD RUN echo "ONBUILD PARENT"
  2322. `
  2323. ctx, err := fakeContext(dockerfile1, nil)
  2324. if err != nil {
  2325. t.Fatal(err)
  2326. }
  2327. defer ctx.Close()
  2328. out1, _, err := dockerCmdInDir(t, ctx.Dir, "build", "-t", name1, ".")
  2329. if err != nil {
  2330. t.Fatalf("build failed to complete: %s, %v", out1, err)
  2331. }
  2332. defer deleteImages(name1)
  2333. }
  2334. {
  2335. name2 := "testonbuildtrigger2"
  2336. dockerfile2 := `
  2337. FROM testonbuildtrigger1
  2338. `
  2339. ctx, err := fakeContext(dockerfile2, nil)
  2340. if err != nil {
  2341. t.Fatal(err)
  2342. }
  2343. defer ctx.Close()
  2344. out2, _, err = dockerCmdInDir(t, ctx.Dir, "build", "-t", name2, ".")
  2345. if err != nil {
  2346. t.Fatalf("build failed to complete: %s, %v", out2, err)
  2347. }
  2348. defer deleteImages(name2)
  2349. }
  2350. {
  2351. name3 := "testonbuildtrigger3"
  2352. dockerfile3 := `
  2353. FROM testonbuildtrigger2
  2354. `
  2355. ctx, err := fakeContext(dockerfile3, nil)
  2356. if err != nil {
  2357. t.Fatal(err)
  2358. }
  2359. defer ctx.Close()
  2360. out3, _, err = dockerCmdInDir(t, ctx.Dir, "build", "-t", name3, ".")
  2361. if err != nil {
  2362. t.Fatalf("build failed to complete: %s, %v", out3, err)
  2363. }
  2364. defer deleteImages(name3)
  2365. }
  2366. // ONBUILD should be run in second build.
  2367. if !strings.Contains(out2, "ONBUILD PARENT") {
  2368. t.Fatalf("ONBUILD instruction did not run in child of ONBUILD parent")
  2369. }
  2370. // ONBUILD should *not* be run in third build.
  2371. if strings.Contains(out3, "ONBUILD PARENT") {
  2372. t.Fatalf("ONBUILD instruction ran in grandchild of ONBUILD parent")
  2373. }
  2374. logDone("build - onbuild")
  2375. }
  2376. func TestBuildWithCache(t *testing.T) {
  2377. name := "testbuildwithcache"
  2378. defer deleteImages(name)
  2379. id1, err := buildImage(name,
  2380. `FROM scratch
  2381. MAINTAINER dockerio
  2382. EXPOSE 5432
  2383. ENTRYPOINT ["/bin/echo"]`,
  2384. true)
  2385. if err != nil {
  2386. t.Fatal(err)
  2387. }
  2388. id2, err := buildImage(name,
  2389. `FROM scratch
  2390. MAINTAINER dockerio
  2391. EXPOSE 5432
  2392. ENTRYPOINT ["/bin/echo"]`,
  2393. true)
  2394. if err != nil {
  2395. t.Fatal(err)
  2396. }
  2397. if id1 != id2 {
  2398. t.Fatal("The cache should have been used but hasn't.")
  2399. }
  2400. logDone("build - with cache")
  2401. }
  2402. func TestBuildWithoutCache(t *testing.T) {
  2403. name := "testbuildwithoutcache"
  2404. name2 := "testbuildwithoutcache2"
  2405. defer deleteImages(name, name2)
  2406. id1, err := buildImage(name,
  2407. `FROM scratch
  2408. MAINTAINER dockerio
  2409. EXPOSE 5432
  2410. ENTRYPOINT ["/bin/echo"]`,
  2411. true)
  2412. if err != nil {
  2413. t.Fatal(err)
  2414. }
  2415. id2, err := buildImage(name2,
  2416. `FROM scratch
  2417. MAINTAINER dockerio
  2418. EXPOSE 5432
  2419. ENTRYPOINT ["/bin/echo"]`,
  2420. false)
  2421. if err != nil {
  2422. t.Fatal(err)
  2423. }
  2424. if id1 == id2 {
  2425. t.Fatal("The cache should have been invalided but hasn't.")
  2426. }
  2427. logDone("build - without cache")
  2428. }
  2429. func TestBuildConditionalCache(t *testing.T) {
  2430. name := "testbuildconditionalcache"
  2431. name2 := "testbuildconditionalcache2"
  2432. defer deleteImages(name, name2)
  2433. dockerfile := `
  2434. FROM busybox
  2435. ADD foo /tmp/`
  2436. ctx, err := fakeContext(dockerfile, map[string]string{
  2437. "foo": "hello",
  2438. })
  2439. if err != nil {
  2440. t.Fatal(err)
  2441. }
  2442. defer ctx.Close()
  2443. id1, err := buildImageFromContext(name, ctx, true)
  2444. if err != nil {
  2445. t.Fatalf("Error building #1: %s", err)
  2446. }
  2447. if err := ctx.Add("foo", "bye"); err != nil {
  2448. t.Fatalf("Error modifying foo: %s", err)
  2449. }
  2450. id2, err := buildImageFromContext(name, ctx, false)
  2451. if err != nil {
  2452. t.Fatalf("Error building #2: %s", err)
  2453. }
  2454. if id2 == id1 {
  2455. t.Fatal("Should not have used the cache")
  2456. }
  2457. id3, err := buildImageFromContext(name, ctx, true)
  2458. if err != nil {
  2459. t.Fatalf("Error building #3: %s", err)
  2460. }
  2461. if id3 != id2 {
  2462. t.Fatal("Should have used the cache")
  2463. }
  2464. logDone("build - conditional cache")
  2465. }
  2466. func TestBuildADDLocalFileWithCache(t *testing.T) {
  2467. name := "testbuildaddlocalfilewithcache"
  2468. name2 := "testbuildaddlocalfilewithcache2"
  2469. defer deleteImages(name, name2)
  2470. dockerfile := `
  2471. FROM busybox
  2472. MAINTAINER dockerio
  2473. ADD foo /usr/lib/bla/bar
  2474. RUN [ "$(cat /usr/lib/bla/bar)" = "hello" ]`
  2475. ctx, err := fakeContext(dockerfile, map[string]string{
  2476. "foo": "hello",
  2477. })
  2478. defer ctx.Close()
  2479. if err != nil {
  2480. t.Fatal(err)
  2481. }
  2482. id1, err := buildImageFromContext(name, ctx, true)
  2483. if err != nil {
  2484. t.Fatal(err)
  2485. }
  2486. id2, err := buildImageFromContext(name2, ctx, true)
  2487. if err != nil {
  2488. t.Fatal(err)
  2489. }
  2490. if id1 != id2 {
  2491. t.Fatal("The cache should have been used but hasn't.")
  2492. }
  2493. logDone("build - add local file with cache")
  2494. }
  2495. func TestBuildADDMultipleLocalFileWithCache(t *testing.T) {
  2496. name := "testbuildaddmultiplelocalfilewithcache"
  2497. name2 := "testbuildaddmultiplelocalfilewithcache2"
  2498. defer deleteImages(name, name2)
  2499. dockerfile := `
  2500. FROM busybox
  2501. MAINTAINER dockerio
  2502. ADD foo Dockerfile /usr/lib/bla/
  2503. RUN [ "$(cat /usr/lib/bla/foo)" = "hello" ]`
  2504. ctx, err := fakeContext(dockerfile, map[string]string{
  2505. "foo": "hello",
  2506. })
  2507. defer ctx.Close()
  2508. if err != nil {
  2509. t.Fatal(err)
  2510. }
  2511. id1, err := buildImageFromContext(name, ctx, true)
  2512. if err != nil {
  2513. t.Fatal(err)
  2514. }
  2515. id2, err := buildImageFromContext(name2, ctx, true)
  2516. if err != nil {
  2517. t.Fatal(err)
  2518. }
  2519. if id1 != id2 {
  2520. t.Fatal("The cache should have been used but hasn't.")
  2521. }
  2522. logDone("build - add multiple local files with cache")
  2523. }
  2524. func TestBuildADDLocalFileWithoutCache(t *testing.T) {
  2525. name := "testbuildaddlocalfilewithoutcache"
  2526. name2 := "testbuildaddlocalfilewithoutcache2"
  2527. defer deleteImages(name, name2)
  2528. dockerfile := `
  2529. FROM busybox
  2530. MAINTAINER dockerio
  2531. ADD foo /usr/lib/bla/bar
  2532. RUN [ "$(cat /usr/lib/bla/bar)" = "hello" ]`
  2533. ctx, err := fakeContext(dockerfile, map[string]string{
  2534. "foo": "hello",
  2535. })
  2536. defer ctx.Close()
  2537. if err != nil {
  2538. t.Fatal(err)
  2539. }
  2540. id1, err := buildImageFromContext(name, ctx, true)
  2541. if err != nil {
  2542. t.Fatal(err)
  2543. }
  2544. id2, err := buildImageFromContext(name2, ctx, false)
  2545. if err != nil {
  2546. t.Fatal(err)
  2547. }
  2548. if id1 == id2 {
  2549. t.Fatal("The cache should have been invalided but hasn't.")
  2550. }
  2551. logDone("build - add local file without cache")
  2552. }
  2553. func TestBuildCopyDirButNotFile(t *testing.T) {
  2554. name := "testbuildcopydirbutnotfile"
  2555. name2 := "testbuildcopydirbutnotfile2"
  2556. defer deleteImages(name, name2)
  2557. dockerfile := `
  2558. FROM scratch
  2559. COPY dir /tmp/`
  2560. ctx, err := fakeContext(dockerfile, map[string]string{
  2561. "dir/foo": "hello",
  2562. })
  2563. defer ctx.Close()
  2564. if err != nil {
  2565. t.Fatal(err)
  2566. }
  2567. id1, err := buildImageFromContext(name, ctx, true)
  2568. if err != nil {
  2569. t.Fatal(err)
  2570. }
  2571. // Check that adding file with similar name doesn't mess with cache
  2572. if err := ctx.Add("dir_file", "hello2"); err != nil {
  2573. t.Fatal(err)
  2574. }
  2575. id2, err := buildImageFromContext(name2, ctx, true)
  2576. if err != nil {
  2577. t.Fatal(err)
  2578. }
  2579. if id1 != id2 {
  2580. t.Fatal("The cache should have been used but wasn't")
  2581. }
  2582. logDone("build - add current directory but not file")
  2583. }
  2584. func TestBuildADDCurrentDirWithCache(t *testing.T) {
  2585. name := "testbuildaddcurrentdirwithcache"
  2586. name2 := name + "2"
  2587. name3 := name + "3"
  2588. name4 := name + "4"
  2589. name5 := name + "5"
  2590. defer deleteImages(name, name2, name3, name4, name5)
  2591. dockerfile := `
  2592. FROM scratch
  2593. MAINTAINER dockerio
  2594. ADD . /usr/lib/bla`
  2595. ctx, err := fakeContext(dockerfile, map[string]string{
  2596. "foo": "hello",
  2597. })
  2598. defer ctx.Close()
  2599. if err != nil {
  2600. t.Fatal(err)
  2601. }
  2602. id1, err := buildImageFromContext(name, ctx, true)
  2603. if err != nil {
  2604. t.Fatal(err)
  2605. }
  2606. // Check that adding file invalidate cache of "ADD ."
  2607. if err := ctx.Add("bar", "hello2"); err != nil {
  2608. t.Fatal(err)
  2609. }
  2610. id2, err := buildImageFromContext(name2, ctx, true)
  2611. if err != nil {
  2612. t.Fatal(err)
  2613. }
  2614. if id1 == id2 {
  2615. t.Fatal("The cache should have been invalided but hasn't.")
  2616. }
  2617. // Check that changing file invalidate cache of "ADD ."
  2618. if err := ctx.Add("foo", "hello1"); err != nil {
  2619. t.Fatal(err)
  2620. }
  2621. id3, err := buildImageFromContext(name3, ctx, true)
  2622. if err != nil {
  2623. t.Fatal(err)
  2624. }
  2625. if id2 == id3 {
  2626. t.Fatal("The cache should have been invalided but hasn't.")
  2627. }
  2628. // Check that changing file to same content invalidate cache of "ADD ."
  2629. time.Sleep(1 * time.Second) // wait second because of mtime precision
  2630. if err := ctx.Add("foo", "hello1"); err != nil {
  2631. t.Fatal(err)
  2632. }
  2633. id4, err := buildImageFromContext(name4, ctx, true)
  2634. if err != nil {
  2635. t.Fatal(err)
  2636. }
  2637. if id3 == id4 {
  2638. t.Fatal("The cache should have been invalided but hasn't.")
  2639. }
  2640. id5, err := buildImageFromContext(name5, ctx, true)
  2641. if err != nil {
  2642. t.Fatal(err)
  2643. }
  2644. if id4 != id5 {
  2645. t.Fatal("The cache should have been used but hasn't.")
  2646. }
  2647. logDone("build - add current directory with cache")
  2648. }
  2649. func TestBuildADDCurrentDirWithoutCache(t *testing.T) {
  2650. name := "testbuildaddcurrentdirwithoutcache"
  2651. name2 := "testbuildaddcurrentdirwithoutcache2"
  2652. defer deleteImages(name, name2)
  2653. dockerfile := `
  2654. FROM scratch
  2655. MAINTAINER dockerio
  2656. ADD . /usr/lib/bla`
  2657. ctx, err := fakeContext(dockerfile, map[string]string{
  2658. "foo": "hello",
  2659. })
  2660. defer ctx.Close()
  2661. if err != nil {
  2662. t.Fatal(err)
  2663. }
  2664. id1, err := buildImageFromContext(name, ctx, true)
  2665. if err != nil {
  2666. t.Fatal(err)
  2667. }
  2668. id2, err := buildImageFromContext(name2, ctx, false)
  2669. if err != nil {
  2670. t.Fatal(err)
  2671. }
  2672. if id1 == id2 {
  2673. t.Fatal("The cache should have been invalided but hasn't.")
  2674. }
  2675. logDone("build - add current directory without cache")
  2676. }
  2677. func TestBuildADDRemoteFileWithCache(t *testing.T) {
  2678. name := "testbuildaddremotefilewithcache"
  2679. defer deleteImages(name)
  2680. server, err := fakeStorage(map[string]string{
  2681. "baz": "hello",
  2682. })
  2683. if err != nil {
  2684. t.Fatal(err)
  2685. }
  2686. defer server.Close()
  2687. id1, err := buildImage(name,
  2688. fmt.Sprintf(`FROM scratch
  2689. MAINTAINER dockerio
  2690. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2691. true)
  2692. if err != nil {
  2693. t.Fatal(err)
  2694. }
  2695. id2, err := buildImage(name,
  2696. fmt.Sprintf(`FROM scratch
  2697. MAINTAINER dockerio
  2698. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2699. true)
  2700. if err != nil {
  2701. t.Fatal(err)
  2702. }
  2703. if id1 != id2 {
  2704. t.Fatal("The cache should have been used but hasn't.")
  2705. }
  2706. logDone("build - add remote file with cache")
  2707. }
  2708. func TestBuildADDRemoteFileWithoutCache(t *testing.T) {
  2709. name := "testbuildaddremotefilewithoutcache"
  2710. name2 := "testbuildaddremotefilewithoutcache2"
  2711. defer deleteImages(name, name2)
  2712. server, err := fakeStorage(map[string]string{
  2713. "baz": "hello",
  2714. })
  2715. if err != nil {
  2716. t.Fatal(err)
  2717. }
  2718. defer server.Close()
  2719. id1, err := buildImage(name,
  2720. fmt.Sprintf(`FROM scratch
  2721. MAINTAINER dockerio
  2722. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2723. true)
  2724. if err != nil {
  2725. t.Fatal(err)
  2726. }
  2727. id2, err := buildImage(name2,
  2728. fmt.Sprintf(`FROM scratch
  2729. MAINTAINER dockerio
  2730. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2731. false)
  2732. if err != nil {
  2733. t.Fatal(err)
  2734. }
  2735. if id1 == id2 {
  2736. t.Fatal("The cache should have been invalided but hasn't.")
  2737. }
  2738. logDone("build - add remote file without cache")
  2739. }
  2740. func TestBuildADDRemoteFileMTime(t *testing.T) {
  2741. name := "testbuildaddremotefilemtime"
  2742. name2 := name + "2"
  2743. name3 := name + "3"
  2744. name4 := name + "4"
  2745. defer deleteImages(name, name2, name3, name4)
  2746. files := map[string]string{"baz": "hello"}
  2747. server, err := fakeStorage(files)
  2748. if err != nil {
  2749. t.Fatal(err)
  2750. }
  2751. defer server.Close()
  2752. ctx, err := fakeContext(fmt.Sprintf(`FROM scratch
  2753. MAINTAINER dockerio
  2754. ADD %s/baz /usr/lib/baz/quux`, server.URL()), nil)
  2755. if err != nil {
  2756. t.Fatal(err)
  2757. }
  2758. defer ctx.Close()
  2759. id1, err := buildImageFromContext(name, ctx, true)
  2760. if err != nil {
  2761. t.Fatal(err)
  2762. }
  2763. id2, err := buildImageFromContext(name2, ctx, true)
  2764. if err != nil {
  2765. t.Fatal(err)
  2766. }
  2767. if id1 != id2 {
  2768. t.Fatal("The cache should have been used but wasn't - #1")
  2769. }
  2770. // Now create a different server withsame contents (causes different mtim)
  2771. // This time the cache should not be used
  2772. // allow some time for clock to pass as mtime precision is only 1s
  2773. time.Sleep(2 * time.Second)
  2774. server2, err := fakeStorage(files)
  2775. if err != nil {
  2776. t.Fatal(err)
  2777. }
  2778. defer server2.Close()
  2779. ctx2, err := fakeContext(fmt.Sprintf(`FROM scratch
  2780. MAINTAINER dockerio
  2781. ADD %s/baz /usr/lib/baz/quux`, server2.URL()), nil)
  2782. if err != nil {
  2783. t.Fatal(err)
  2784. }
  2785. defer ctx2.Close()
  2786. id3, err := buildImageFromContext(name3, ctx2, true)
  2787. if err != nil {
  2788. t.Fatal(err)
  2789. }
  2790. if id1 == id3 {
  2791. t.Fatal("The cache should not have been used but was")
  2792. }
  2793. // And for good measure do it again and make sure cache is used this time
  2794. id4, err := buildImageFromContext(name4, ctx2, true)
  2795. if err != nil {
  2796. t.Fatal(err)
  2797. }
  2798. if id3 != id4 {
  2799. t.Fatal("The cache should have been used but wasn't - #2")
  2800. }
  2801. logDone("build - add remote file testing mtime")
  2802. }
  2803. func TestBuildADDLocalAndRemoteFilesWithCache(t *testing.T) {
  2804. name := "testbuildaddlocalandremotefilewithcache"
  2805. defer deleteImages(name)
  2806. server, err := fakeStorage(map[string]string{
  2807. "baz": "hello",
  2808. })
  2809. if err != nil {
  2810. t.Fatal(err)
  2811. }
  2812. defer server.Close()
  2813. ctx, err := fakeContext(fmt.Sprintf(`FROM scratch
  2814. MAINTAINER dockerio
  2815. ADD foo /usr/lib/bla/bar
  2816. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2817. map[string]string{
  2818. "foo": "hello world",
  2819. })
  2820. if err != nil {
  2821. t.Fatal(err)
  2822. }
  2823. defer ctx.Close()
  2824. id1, err := buildImageFromContext(name, ctx, true)
  2825. if err != nil {
  2826. t.Fatal(err)
  2827. }
  2828. id2, err := buildImageFromContext(name, ctx, true)
  2829. if err != nil {
  2830. t.Fatal(err)
  2831. }
  2832. if id1 != id2 {
  2833. t.Fatal("The cache should have been used but hasn't.")
  2834. }
  2835. logDone("build - add local and remote file with cache")
  2836. }
  2837. func testContextTar(t *testing.T, compression archive.Compression) {
  2838. ctx, err := fakeContext(
  2839. `FROM busybox
  2840. ADD foo /foo
  2841. CMD ["cat", "/foo"]`,
  2842. map[string]string{
  2843. "foo": "bar",
  2844. },
  2845. )
  2846. defer ctx.Close()
  2847. if err != nil {
  2848. t.Fatal(err)
  2849. }
  2850. context, err := archive.Tar(ctx.Dir, compression)
  2851. if err != nil {
  2852. t.Fatalf("failed to build context tar: %v", err)
  2853. }
  2854. name := "contexttar"
  2855. buildCmd := exec.Command(dockerBinary, "build", "-t", name, "-")
  2856. defer deleteImages(name)
  2857. buildCmd.Stdin = context
  2858. if out, _, err := runCommandWithOutput(buildCmd); err != nil {
  2859. t.Fatalf("build failed to complete: %v %v", out, err)
  2860. }
  2861. logDone(fmt.Sprintf("build - build an image with a context tar, compression: %v", compression))
  2862. }
  2863. func TestBuildContextTarGzip(t *testing.T) {
  2864. testContextTar(t, archive.Gzip)
  2865. }
  2866. func TestBuildContextTarNoCompression(t *testing.T) {
  2867. testContextTar(t, archive.Uncompressed)
  2868. }
  2869. func TestBuildNoContext(t *testing.T) {
  2870. buildCmd := exec.Command(dockerBinary, "build", "-t", "nocontext", "-")
  2871. buildCmd.Stdin = strings.NewReader("FROM busybox\nCMD echo ok\n")
  2872. if out, _, err := runCommandWithOutput(buildCmd); err != nil {
  2873. t.Fatalf("build failed to complete: %v %v", out, err)
  2874. }
  2875. if out, _, err := dockerCmd(t, "run", "--rm", "nocontext"); out != "ok\n" || err != nil {
  2876. t.Fatalf("run produced invalid output: %q, expected %q", out, "ok")
  2877. }
  2878. deleteImages("nocontext")
  2879. logDone("build - build an image with no context")
  2880. }
  2881. // TODO: TestCaching
  2882. func TestBuildADDLocalAndRemoteFilesWithoutCache(t *testing.T) {
  2883. name := "testbuildaddlocalandremotefilewithoutcache"
  2884. name2 := "testbuildaddlocalandremotefilewithoutcache2"
  2885. defer deleteImages(name, name2)
  2886. server, err := fakeStorage(map[string]string{
  2887. "baz": "hello",
  2888. })
  2889. if err != nil {
  2890. t.Fatal(err)
  2891. }
  2892. defer server.Close()
  2893. ctx, err := fakeContext(fmt.Sprintf(`FROM scratch
  2894. MAINTAINER dockerio
  2895. ADD foo /usr/lib/bla/bar
  2896. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2897. map[string]string{
  2898. "foo": "hello world",
  2899. })
  2900. if err != nil {
  2901. t.Fatal(err)
  2902. }
  2903. defer ctx.Close()
  2904. id1, err := buildImageFromContext(name, ctx, true)
  2905. if err != nil {
  2906. t.Fatal(err)
  2907. }
  2908. id2, err := buildImageFromContext(name2, ctx, false)
  2909. if err != nil {
  2910. t.Fatal(err)
  2911. }
  2912. if id1 == id2 {
  2913. t.Fatal("The cache should have been invalided but hasn't.")
  2914. }
  2915. logDone("build - add local and remote file without cache")
  2916. }
  2917. func TestBuildWithVolumeOwnership(t *testing.T) {
  2918. name := "testbuildimg"
  2919. defer deleteImages(name)
  2920. _, err := buildImage(name,
  2921. `FROM busybox:latest
  2922. RUN mkdir /test && chown daemon:daemon /test && chmod 0600 /test
  2923. VOLUME /test`,
  2924. true)
  2925. if err != nil {
  2926. t.Fatal(err)
  2927. }
  2928. cmd := exec.Command(dockerBinary, "run", "--rm", "testbuildimg", "ls", "-la", "/test")
  2929. out, _, err := runCommandWithOutput(cmd)
  2930. if err != nil {
  2931. t.Fatal(out, err)
  2932. }
  2933. if expected := "drw-------"; !strings.Contains(out, expected) {
  2934. t.Fatalf("expected %s received %s", expected, out)
  2935. }
  2936. if expected := "daemon daemon"; !strings.Contains(out, expected) {
  2937. t.Fatalf("expected %s received %s", expected, out)
  2938. }
  2939. logDone("build - volume ownership")
  2940. }
  2941. // testing #1405 - config.Cmd does not get cleaned up if
  2942. // utilizing cache
  2943. func TestBuildEntrypointRunCleanup(t *testing.T) {
  2944. name := "testbuildcmdcleanup"
  2945. defer deleteImages(name)
  2946. if _, err := buildImage(name,
  2947. `FROM busybox
  2948. RUN echo "hello"`,
  2949. true); err != nil {
  2950. t.Fatal(err)
  2951. }
  2952. ctx, err := fakeContext(`FROM busybox
  2953. RUN echo "hello"
  2954. ADD foo /foo
  2955. ENTRYPOINT ["/bin/echo"]`,
  2956. map[string]string{
  2957. "foo": "hello",
  2958. })
  2959. defer ctx.Close()
  2960. if err != nil {
  2961. t.Fatal(err)
  2962. }
  2963. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2964. t.Fatal(err)
  2965. }
  2966. res, err := inspectField(name, "Config.Cmd")
  2967. if err != nil {
  2968. t.Fatal(err)
  2969. }
  2970. // Cmd must be cleaned up
  2971. if expected := "<no value>"; res != expected {
  2972. t.Fatalf("Cmd %s, expected %s", res, expected)
  2973. }
  2974. logDone("build - cleanup cmd after RUN")
  2975. }
  2976. func TestBuildForbiddenContextPath(t *testing.T) {
  2977. name := "testbuildforbidpath"
  2978. defer deleteImages(name)
  2979. ctx, err := fakeContext(`FROM scratch
  2980. ADD ../../ test/
  2981. `,
  2982. map[string]string{
  2983. "test.txt": "test1",
  2984. "other.txt": "other",
  2985. })
  2986. defer ctx.Close()
  2987. if err != nil {
  2988. t.Fatal(err)
  2989. }
  2990. expected := "Forbidden path outside the build context: ../../ "
  2991. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  2992. t.Fatalf("Wrong error: (should contain \"%s\") got:\n%v", expected, err)
  2993. }
  2994. logDone("build - forbidden context path")
  2995. }
  2996. func TestBuildADDFileNotFound(t *testing.T) {
  2997. name := "testbuildaddnotfound"
  2998. defer deleteImages(name)
  2999. ctx, err := fakeContext(`FROM scratch
  3000. ADD foo /usr/local/bar`,
  3001. map[string]string{"bar": "hello"})
  3002. defer ctx.Close()
  3003. if err != nil {
  3004. t.Fatal(err)
  3005. }
  3006. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3007. if !strings.Contains(err.Error(), "foo: no such file or directory") {
  3008. t.Fatalf("Wrong error %v, must be about missing foo file or directory", err)
  3009. }
  3010. } else {
  3011. t.Fatal("Error must not be nil")
  3012. }
  3013. logDone("build - add file not found")
  3014. }
  3015. func TestBuildInheritance(t *testing.T) {
  3016. name := "testbuildinheritance"
  3017. defer deleteImages(name)
  3018. _, err := buildImage(name,
  3019. `FROM scratch
  3020. EXPOSE 2375`,
  3021. true)
  3022. if err != nil {
  3023. t.Fatal(err)
  3024. }
  3025. ports1, err := inspectField(name, "Config.ExposedPorts")
  3026. if err != nil {
  3027. t.Fatal(err)
  3028. }
  3029. _, err = buildImage(name,
  3030. fmt.Sprintf(`FROM %s
  3031. ENTRYPOINT ["/bin/echo"]`, name),
  3032. true)
  3033. if err != nil {
  3034. t.Fatal(err)
  3035. }
  3036. res, err := inspectField(name, "Config.Entrypoint")
  3037. if err != nil {
  3038. t.Fatal(err)
  3039. }
  3040. if expected := "[/bin/echo]"; res != expected {
  3041. t.Fatalf("Entrypoint %s, expected %s", res, expected)
  3042. }
  3043. ports2, err := inspectField(name, "Config.ExposedPorts")
  3044. if err != nil {
  3045. t.Fatal(err)
  3046. }
  3047. if ports1 != ports2 {
  3048. t.Fatalf("Ports must be same: %s != %s", ports1, ports2)
  3049. }
  3050. logDone("build - inheritance")
  3051. }
  3052. func TestBuildFails(t *testing.T) {
  3053. name := "testbuildfails"
  3054. defer deleteImages(name)
  3055. defer deleteAllContainers()
  3056. _, err := buildImage(name,
  3057. `FROM busybox
  3058. RUN sh -c "exit 23"`,
  3059. true)
  3060. if err != nil {
  3061. if !strings.Contains(err.Error(), "returned a non-zero code: 23") {
  3062. t.Fatalf("Wrong error %v, must be about non-zero code 23", err)
  3063. }
  3064. } else {
  3065. t.Fatal("Error must not be nil")
  3066. }
  3067. logDone("build - unsuccessful")
  3068. }
  3069. func TestBuildFailsDockerfileEmpty(t *testing.T) {
  3070. name := "testbuildfails"
  3071. defer deleteImages(name)
  3072. _, err := buildImage(name, ``, true)
  3073. if err != nil {
  3074. if !strings.Contains(err.Error(), "The Dockerfile (Dockerfile) cannot be empty") {
  3075. t.Fatalf("Wrong error %v, must be about empty Dockerfile", err)
  3076. }
  3077. } else {
  3078. t.Fatal("Error must not be nil")
  3079. }
  3080. logDone("build - unsuccessful with empty dockerfile")
  3081. }
  3082. func TestBuildOnBuild(t *testing.T) {
  3083. name := "testbuildonbuild"
  3084. defer deleteImages(name)
  3085. _, err := buildImage(name,
  3086. `FROM busybox
  3087. ONBUILD RUN touch foobar`,
  3088. true)
  3089. if err != nil {
  3090. t.Fatal(err)
  3091. }
  3092. _, err = buildImage(name,
  3093. fmt.Sprintf(`FROM %s
  3094. RUN [ -f foobar ]`, name),
  3095. true)
  3096. if err != nil {
  3097. t.Fatal(err)
  3098. }
  3099. logDone("build - onbuild")
  3100. }
  3101. func TestBuildOnBuildForbiddenChained(t *testing.T) {
  3102. name := "testbuildonbuildforbiddenchained"
  3103. defer deleteImages(name)
  3104. _, err := buildImage(name,
  3105. `FROM busybox
  3106. ONBUILD ONBUILD RUN touch foobar`,
  3107. true)
  3108. if err != nil {
  3109. if !strings.Contains(err.Error(), "Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed") {
  3110. t.Fatalf("Wrong error %v, must be about chaining ONBUILD", err)
  3111. }
  3112. } else {
  3113. t.Fatal("Error must not be nil")
  3114. }
  3115. logDone("build - onbuild forbidden chained")
  3116. }
  3117. func TestBuildOnBuildForbiddenFrom(t *testing.T) {
  3118. name := "testbuildonbuildforbiddenfrom"
  3119. defer deleteImages(name)
  3120. _, err := buildImage(name,
  3121. `FROM busybox
  3122. ONBUILD FROM scratch`,
  3123. true)
  3124. if err != nil {
  3125. if !strings.Contains(err.Error(), "FROM isn't allowed as an ONBUILD trigger") {
  3126. t.Fatalf("Wrong error %v, must be about FROM forbidden", err)
  3127. }
  3128. } else {
  3129. t.Fatal("Error must not be nil")
  3130. }
  3131. logDone("build - onbuild forbidden from")
  3132. }
  3133. func TestBuildOnBuildForbiddenMaintainer(t *testing.T) {
  3134. name := "testbuildonbuildforbiddenmaintainer"
  3135. defer deleteImages(name)
  3136. _, err := buildImage(name,
  3137. `FROM busybox
  3138. ONBUILD MAINTAINER docker.io`,
  3139. true)
  3140. if err != nil {
  3141. if !strings.Contains(err.Error(), "MAINTAINER isn't allowed as an ONBUILD trigger") {
  3142. t.Fatalf("Wrong error %v, must be about MAINTAINER forbidden", err)
  3143. }
  3144. } else {
  3145. t.Fatal("Error must not be nil")
  3146. }
  3147. logDone("build - onbuild forbidden maintainer")
  3148. }
  3149. // gh #2446
  3150. func TestBuildAddToSymlinkDest(t *testing.T) {
  3151. name := "testbuildaddtosymlinkdest"
  3152. defer deleteImages(name)
  3153. ctx, err := fakeContext(`FROM busybox
  3154. RUN mkdir /foo
  3155. RUN ln -s /foo /bar
  3156. ADD foo /bar/
  3157. RUN [ -f /bar/foo ]
  3158. RUN [ -f /foo/foo ]`,
  3159. map[string]string{
  3160. "foo": "hello",
  3161. })
  3162. if err != nil {
  3163. t.Fatal(err)
  3164. }
  3165. defer ctx.Close()
  3166. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3167. t.Fatal(err)
  3168. }
  3169. logDone("build - add to symlink destination")
  3170. }
  3171. func TestBuildEscapeWhitespace(t *testing.T) {
  3172. name := "testbuildescaping"
  3173. defer deleteImages(name)
  3174. _, err := buildImage(name, `
  3175. FROM busybox
  3176. MAINTAINER "Docker \
  3177. IO <io@\
  3178. docker.com>"
  3179. `, true)
  3180. res, err := inspectField(name, "Author")
  3181. if err != nil {
  3182. t.Fatal(err)
  3183. }
  3184. if res != "\"Docker IO <io@docker.com>\"" {
  3185. t.Fatalf("Parsed string did not match the escaped string. Got: %q", res)
  3186. }
  3187. logDone("build - validate escaping whitespace")
  3188. }
  3189. func TestBuildVerifyIntString(t *testing.T) {
  3190. // Verify that strings that look like ints are still passed as strings
  3191. name := "testbuildstringing"
  3192. defer deleteImages(name)
  3193. _, err := buildImage(name, `
  3194. FROM busybox
  3195. MAINTAINER 123
  3196. `, true)
  3197. out, rc, err := runCommandWithOutput(exec.Command(dockerBinary, "inspect", name))
  3198. if rc != 0 || err != nil {
  3199. t.Fatalf("Unexcepted error from inspect: rc: %v err: %v", rc, err)
  3200. }
  3201. if !strings.Contains(out, "\"123\"") {
  3202. t.Fatalf("Output does not contain the int as a string:\n%s", out)
  3203. }
  3204. logDone("build - verify int/strings as strings")
  3205. }
  3206. func TestBuildDockerignore(t *testing.T) {
  3207. name := "testbuilddockerignore"
  3208. defer deleteImages(name)
  3209. dockerfile := `
  3210. FROM busybox
  3211. ADD . /bla
  3212. RUN [[ -f /bla/src/x.go ]]
  3213. RUN [[ -f /bla/Makefile ]]
  3214. RUN [[ ! -e /bla/src/_vendor ]]
  3215. RUN [[ ! -e /bla/.gitignore ]]
  3216. RUN [[ ! -e /bla/README.md ]]
  3217. RUN [[ ! -e /bla/.git ]]`
  3218. ctx, err := fakeContext(dockerfile, map[string]string{
  3219. "Makefile": "all:",
  3220. ".git/HEAD": "ref: foo",
  3221. "src/x.go": "package main",
  3222. "src/_vendor/v.go": "package main",
  3223. ".gitignore": "",
  3224. "README.md": "readme",
  3225. ".dockerignore": ".git\npkg\n.gitignore\nsrc/_vendor\n*.md",
  3226. })
  3227. defer ctx.Close()
  3228. if err != nil {
  3229. t.Fatal(err)
  3230. }
  3231. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3232. t.Fatal(err)
  3233. }
  3234. logDone("build - test .dockerignore")
  3235. }
  3236. func TestBuildDockerignoreCleanPaths(t *testing.T) {
  3237. name := "testbuilddockerignorecleanpaths"
  3238. defer deleteImages(name)
  3239. dockerfile := `
  3240. FROM busybox
  3241. ADD . /tmp/
  3242. RUN (! ls /tmp/foo) && (! ls /tmp/foo2) && (! ls /tmp/dir1/foo)`
  3243. ctx, err := fakeContext(dockerfile, map[string]string{
  3244. "foo": "foo",
  3245. "foo2": "foo2",
  3246. "dir1/foo": "foo in dir1",
  3247. ".dockerignore": "./foo\ndir1//foo\n./dir1/../foo2",
  3248. })
  3249. if err != nil {
  3250. t.Fatal(err)
  3251. }
  3252. defer ctx.Close()
  3253. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3254. t.Fatal(err)
  3255. }
  3256. logDone("build - test .dockerignore with clean paths")
  3257. }
  3258. func TestBuildDockerignoringDockerfile(t *testing.T) {
  3259. name := "testbuilddockerignoredockerfile"
  3260. defer deleteImages(name)
  3261. dockerfile := `
  3262. FROM busybox
  3263. ADD . /tmp/
  3264. RUN ! ls /tmp/Dockerfile
  3265. RUN ls /tmp/.dockerignore`
  3266. ctx, err := fakeContext(dockerfile, map[string]string{
  3267. "Dockerfile": dockerfile,
  3268. ".dockerignore": "Dockerfile\n",
  3269. })
  3270. if err != nil {
  3271. t.Fatal(err)
  3272. }
  3273. defer ctx.Close()
  3274. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3275. t.Fatalf("Didn't ignore Dockerfile correctly:%s", err)
  3276. }
  3277. // now try it with ./Dockerfile
  3278. ctx.Add(".dockerignore", "./Dockerfile\n")
  3279. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3280. t.Fatalf("Didn't ignore ./Dockerfile correctly:%s", err)
  3281. }
  3282. logDone("build - test .dockerignore of Dockerfile")
  3283. }
  3284. func TestBuildDockerignoringRenamedDockerfile(t *testing.T) {
  3285. name := "testbuilddockerignoredockerfile"
  3286. defer deleteImages(name)
  3287. dockerfile := `
  3288. FROM busybox
  3289. ADD . /tmp/
  3290. RUN ls /tmp/Dockerfile
  3291. RUN ! ls /tmp/MyDockerfile
  3292. RUN ls /tmp/.dockerignore`
  3293. ctx, err := fakeContext(dockerfile, map[string]string{
  3294. "Dockerfile": "Should not use me",
  3295. "MyDockerfile": dockerfile,
  3296. ".dockerignore": "MyDockerfile\n",
  3297. })
  3298. if err != nil {
  3299. t.Fatal(err)
  3300. }
  3301. defer ctx.Close()
  3302. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3303. t.Fatalf("Didn't ignore MyDockerfile correctly:%s", err)
  3304. }
  3305. // now try it with ./MyDockerfile
  3306. ctx.Add(".dockerignore", "./MyDockerfile\n")
  3307. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3308. t.Fatalf("Didn't ignore ./MyDockerfile correctly:%s", err)
  3309. }
  3310. logDone("build - test .dockerignore of renamed Dockerfile")
  3311. }
  3312. func TestBuildDockerignoringDockerignore(t *testing.T) {
  3313. name := "testbuilddockerignoredockerignore"
  3314. defer deleteImages(name)
  3315. dockerfile := `
  3316. FROM busybox
  3317. ADD . /tmp/
  3318. RUN ! ls /tmp/.dockerignore
  3319. RUN ls /tmp/Dockerfile`
  3320. ctx, err := fakeContext(dockerfile, map[string]string{
  3321. "Dockerfile": dockerfile,
  3322. ".dockerignore": ".dockerignore\n",
  3323. })
  3324. defer ctx.Close()
  3325. if err != nil {
  3326. t.Fatal(err)
  3327. }
  3328. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3329. t.Fatalf("Didn't ignore .dockerignore correctly:%s", err)
  3330. }
  3331. logDone("build - test .dockerignore of .dockerignore")
  3332. }
  3333. func TestBuildDockerignoreTouchDockerfile(t *testing.T) {
  3334. var id1 string
  3335. var id2 string
  3336. name := "testbuilddockerignoretouchdockerfile"
  3337. defer deleteImages(name)
  3338. dockerfile := `
  3339. FROM busybox
  3340. ADD . /tmp/`
  3341. ctx, err := fakeContext(dockerfile, map[string]string{
  3342. "Dockerfile": dockerfile,
  3343. ".dockerignore": "Dockerfile\n",
  3344. })
  3345. defer ctx.Close()
  3346. if err != nil {
  3347. t.Fatal(err)
  3348. }
  3349. if id1, err = buildImageFromContext(name, ctx, true); err != nil {
  3350. t.Fatalf("Didn't build it correctly:%s", err)
  3351. }
  3352. if id2, err = buildImageFromContext(name, ctx, true); err != nil {
  3353. t.Fatalf("Didn't build it correctly:%s", err)
  3354. }
  3355. if id1 != id2 {
  3356. t.Fatalf("Didn't use the cache - 1")
  3357. }
  3358. // Now make sure touching Dockerfile doesn't invalidate the cache
  3359. if err = ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil {
  3360. t.Fatalf("Didn't add Dockerfile: %s", err)
  3361. }
  3362. if id2, err = buildImageFromContext(name, ctx, true); err != nil {
  3363. t.Fatalf("Didn't build it correctly:%s", err)
  3364. }
  3365. if id1 != id2 {
  3366. t.Fatalf("Didn't use the cache - 2")
  3367. }
  3368. // One more time but just 'touch' it instead of changing the content
  3369. if err = ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil {
  3370. t.Fatalf("Didn't add Dockerfile: %s", err)
  3371. }
  3372. if id2, err = buildImageFromContext(name, ctx, true); err != nil {
  3373. t.Fatalf("Didn't build it correctly:%s", err)
  3374. }
  3375. if id1 != id2 {
  3376. t.Fatalf("Didn't use the cache - 3")
  3377. }
  3378. logDone("build - test .dockerignore touch dockerfile")
  3379. }
  3380. func TestBuildDockerignoringWholeDir(t *testing.T) {
  3381. name := "testbuilddockerignorewholedir"
  3382. defer deleteImages(name)
  3383. dockerfile := `
  3384. FROM busybox
  3385. COPY . /
  3386. RUN [[ ! -e /.gitignore ]]
  3387. RUN [[ -f /Makefile ]]`
  3388. ctx, err := fakeContext(dockerfile, map[string]string{
  3389. "Dockerfile": "FROM scratch",
  3390. "Makefile": "all:",
  3391. ".dockerignore": ".*\n",
  3392. })
  3393. defer ctx.Close()
  3394. if err != nil {
  3395. t.Fatal(err)
  3396. }
  3397. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3398. t.Fatal(err)
  3399. }
  3400. logDone("build - test .dockerignore whole dir with .*")
  3401. }
  3402. func TestBuildLineBreak(t *testing.T) {
  3403. name := "testbuildlinebreak"
  3404. defer deleteImages(name)
  3405. _, err := buildImage(name,
  3406. `FROM busybox
  3407. RUN sh -c 'echo root:testpass \
  3408. > /tmp/passwd'
  3409. RUN mkdir -p /var/run/sshd
  3410. RUN [ "$(cat /tmp/passwd)" = "root:testpass" ]
  3411. RUN [ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]`,
  3412. true)
  3413. if err != nil {
  3414. t.Fatal(err)
  3415. }
  3416. logDone("build - line break with \\")
  3417. }
  3418. func TestBuildEOLInLine(t *testing.T) {
  3419. name := "testbuildeolinline"
  3420. defer deleteImages(name)
  3421. _, err := buildImage(name,
  3422. `FROM busybox
  3423. RUN sh -c 'echo root:testpass > /tmp/passwd'
  3424. RUN echo "foo \n bar"; echo "baz"
  3425. RUN mkdir -p /var/run/sshd
  3426. RUN [ "$(cat /tmp/passwd)" = "root:testpass" ]
  3427. RUN [ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]`,
  3428. true)
  3429. if err != nil {
  3430. t.Fatal(err)
  3431. }
  3432. logDone("build - end of line in dockerfile instruction")
  3433. }
  3434. func TestBuildCommentsShebangs(t *testing.T) {
  3435. name := "testbuildcomments"
  3436. defer deleteImages(name)
  3437. _, err := buildImage(name,
  3438. `FROM busybox
  3439. # This is an ordinary comment.
  3440. RUN { echo '#!/bin/sh'; echo 'echo hello world'; } > /hello.sh
  3441. RUN [ ! -x /hello.sh ]
  3442. # comment with line break \
  3443. RUN chmod +x /hello.sh
  3444. RUN [ -x /hello.sh ]
  3445. RUN [ "$(cat /hello.sh)" = $'#!/bin/sh\necho hello world' ]
  3446. RUN [ "$(/hello.sh)" = "hello world" ]`,
  3447. true)
  3448. if err != nil {
  3449. t.Fatal(err)
  3450. }
  3451. logDone("build - comments and shebangs")
  3452. }
  3453. func TestBuildUsersAndGroups(t *testing.T) {
  3454. name := "testbuildusers"
  3455. defer deleteImages(name)
  3456. _, err := buildImage(name,
  3457. `FROM busybox
  3458. # Make sure our defaults work
  3459. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)" = '0:0/root:root' ]
  3460. # TODO decide if "args.user = strconv.Itoa(syscall.Getuid())" is acceptable behavior for changeUser in sysvinit instead of "return nil" when "USER" isn't specified (so that we get the proper group list even if that is the empty list, even in the default case of not supplying an explicit USER to run as, which implies USER 0)
  3461. USER root
  3462. RUN [ "$(id -G):$(id -Gn)" = '0 10:root wheel' ]
  3463. # Setup dockerio user and group
  3464. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  3465. RUN echo 'dockerio:x:1001:' >> /etc/group
  3466. # Make sure we can switch to our user and all the information is exactly as we expect it to be
  3467. USER dockerio
  3468. RUN id -G
  3469. RUN id -Gn
  3470. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3471. # Switch back to root and double check that worked exactly as we might expect it to
  3472. USER root
  3473. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '0:0/root:root/0 10:root wheel' ]
  3474. # Add a "supplementary" group for our dockerio user
  3475. RUN echo 'supplementary:x:1002:dockerio' >> /etc/group
  3476. # ... and then go verify that we get it like we expect
  3477. USER dockerio
  3478. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  3479. USER 1001
  3480. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  3481. # super test the new "user:group" syntax
  3482. USER dockerio:dockerio
  3483. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3484. USER 1001:dockerio
  3485. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3486. USER dockerio:1001
  3487. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3488. USER 1001:1001
  3489. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3490. USER dockerio:supplementary
  3491. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3492. USER dockerio:1002
  3493. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3494. USER 1001:supplementary
  3495. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3496. USER 1001:1002
  3497. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3498. # make sure unknown uid/gid still works properly
  3499. USER 1042:1043
  3500. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1042:1043/1042:1043/1043:1043' ]`,
  3501. true)
  3502. if err != nil {
  3503. t.Fatal(err)
  3504. }
  3505. logDone("build - users and groups")
  3506. }
  3507. func TestBuildEnvUsage(t *testing.T) {
  3508. name := "testbuildenvusage"
  3509. defer deleteImages(name)
  3510. dockerfile := `FROM busybox
  3511. ENV HOME /root
  3512. ENV PATH $HOME/bin:$PATH
  3513. ENV PATH /tmp:$PATH
  3514. RUN [ "$PATH" = "/tmp:$HOME/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ]
  3515. ENV FOO /foo/baz
  3516. ENV BAR /bar
  3517. ENV BAZ $BAR
  3518. ENV FOOPATH $PATH:$FOO
  3519. RUN [ "$BAR" = "$BAZ" ]
  3520. RUN [ "$FOOPATH" = "$PATH:/foo/baz" ]
  3521. ENV FROM hello/docker/world
  3522. ENV TO /docker/world/hello
  3523. ADD $FROM $TO
  3524. RUN [ "$(cat $TO)" = "hello" ]
  3525. ENV abc=def
  3526. ENV ghi=$abc
  3527. RUN [ "$ghi" = "def" ]
  3528. `
  3529. ctx, err := fakeContext(dockerfile, map[string]string{
  3530. "hello/docker/world": "hello",
  3531. })
  3532. if err != nil {
  3533. t.Fatal(err)
  3534. }
  3535. defer ctx.Close()
  3536. _, err = buildImageFromContext(name, ctx, true)
  3537. if err != nil {
  3538. t.Fatal(err)
  3539. }
  3540. logDone("build - environment variables usage")
  3541. }
  3542. func TestBuildEnvUsage2(t *testing.T) {
  3543. name := "testbuildenvusage2"
  3544. defer deleteImages(name)
  3545. dockerfile := `FROM busybox
  3546. ENV abc=def
  3547. RUN [ "$abc" = "def" ]
  3548. ENV def="hello world"
  3549. RUN [ "$def" = "hello world" ]
  3550. ENV def=hello\ world
  3551. RUN [ "$def" = "hello world" ]
  3552. ENV v1=abc v2="hi there"
  3553. RUN [ "$v1" = "abc" ]
  3554. RUN [ "$v2" = "hi there" ]
  3555. ENV v3='boogie nights' v4="with'quotes too"
  3556. RUN [ "$v3" = "boogie nights" ]
  3557. RUN [ "$v4" = "with'quotes too" ]
  3558. ENV abc=zzz FROM=hello/docker/world
  3559. ENV abc=zzz TO=/docker/world/hello
  3560. ADD $FROM $TO
  3561. RUN [ "$(cat $TO)" = "hello" ]
  3562. ENV abc "zzz"
  3563. RUN [ $abc = "zzz" ]
  3564. ENV abc 'yyy'
  3565. RUN [ $abc = 'yyy' ]
  3566. ENV abc=
  3567. RUN [ "$abc" = "" ]
  3568. # use grep to make sure if the builder substitutes \$foo by mistake
  3569. # we don't get a false positive
  3570. ENV abc=\$foo
  3571. RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep foo)
  3572. ENV abc \$foo
  3573. RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep foo)
  3574. ENV abc=\'foo\'
  3575. RUN [ "$abc" = "'foo'" ]
  3576. ENV abc=\"foo\"
  3577. RUN [ "$abc" = "\"foo\"" ]
  3578. ENV abc "foo"
  3579. RUN [ "$abc" = "foo" ]
  3580. ENV abc 'foo'
  3581. RUN [ "$abc" = 'foo' ]
  3582. ENV abc \'foo\'
  3583. RUN [ "$abc" = "'foo'" ]
  3584. ENV abc \"foo\"
  3585. RUN [ "$abc" = '"foo"' ]
  3586. ENV e1=bar
  3587. ENV e2=$e1
  3588. ENV e3=$e11
  3589. ENV e4=\$e1
  3590. ENV e5=\$e11
  3591. RUN [ "$e0,$e1,$e2,$e3,$e4,$e5" = ',bar,bar,,$e1,$e11' ]
  3592. ENV ee1 bar
  3593. ENV ee2 $ee1
  3594. ENV ee3 $ee11
  3595. ENV ee4 \$ee1
  3596. ENV ee5 \$ee11
  3597. RUN [ "$ee1,$ee2,$ee3,$ee4,$ee5" = 'bar,bar,,$ee1,$ee11' ]
  3598. ENV eee1="foo"
  3599. ENV eee2='foo'
  3600. ENV eee3 "foo"
  3601. ENV eee4 'foo'
  3602. RUN [ "$eee1,$eee2,$eee3,$eee4" = 'foo,foo,foo,foo' ]
  3603. `
  3604. ctx, err := fakeContext(dockerfile, map[string]string{
  3605. "hello/docker/world": "hello",
  3606. })
  3607. if err != nil {
  3608. t.Fatal(err)
  3609. }
  3610. defer ctx.Close()
  3611. _, err = buildImageFromContext(name, ctx, true)
  3612. if err != nil {
  3613. t.Fatal(err)
  3614. }
  3615. logDone("build - environment variables usage2")
  3616. }
  3617. func TestBuildAddScript(t *testing.T) {
  3618. name := "testbuildaddscript"
  3619. defer deleteImages(name)
  3620. dockerfile := `
  3621. FROM busybox
  3622. ADD test /test
  3623. RUN ["chmod","+x","/test"]
  3624. RUN ["/test"]
  3625. RUN [ "$(cat /testfile)" = 'test!' ]`
  3626. ctx, err := fakeContext(dockerfile, map[string]string{
  3627. "test": "#!/bin/sh\necho 'test!' > /testfile",
  3628. })
  3629. if err != nil {
  3630. t.Fatal(err)
  3631. }
  3632. defer ctx.Close()
  3633. _, err = buildImageFromContext(name, ctx, true)
  3634. if err != nil {
  3635. t.Fatal(err)
  3636. }
  3637. logDone("build - add and run script")
  3638. }
  3639. func TestBuildAddTar(t *testing.T) {
  3640. name := "testbuildaddtar"
  3641. defer deleteImages(name)
  3642. ctx := func() *FakeContext {
  3643. dockerfile := `
  3644. FROM busybox
  3645. ADD test.tar /
  3646. RUN cat /test/foo | grep Hi
  3647. ADD test.tar /test.tar
  3648. RUN cat /test.tar/test/foo | grep Hi
  3649. ADD test.tar /unlikely-to-exist
  3650. RUN cat /unlikely-to-exist/test/foo | grep Hi
  3651. ADD test.tar /unlikely-to-exist-trailing-slash/
  3652. RUN cat /unlikely-to-exist-trailing-slash/test/foo | grep Hi
  3653. RUN mkdir /existing-directory
  3654. ADD test.tar /existing-directory
  3655. RUN cat /existing-directory/test/foo | grep Hi
  3656. ADD test.tar /existing-directory-trailing-slash/
  3657. RUN cat /existing-directory-trailing-slash/test/foo | grep Hi`
  3658. tmpDir, err := ioutil.TempDir("", "fake-context")
  3659. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3660. if err != nil {
  3661. t.Fatalf("failed to create test.tar archive: %v", err)
  3662. }
  3663. defer testTar.Close()
  3664. tw := tar.NewWriter(testTar)
  3665. if err := tw.WriteHeader(&tar.Header{
  3666. Name: "test/foo",
  3667. Size: 2,
  3668. }); err != nil {
  3669. t.Fatalf("failed to write tar file header: %v", err)
  3670. }
  3671. if _, err := tw.Write([]byte("Hi")); err != nil {
  3672. t.Fatalf("failed to write tar file content: %v", err)
  3673. }
  3674. if err := tw.Close(); err != nil {
  3675. t.Fatalf("failed to close tar archive: %v", err)
  3676. }
  3677. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3678. t.Fatalf("failed to open destination dockerfile: %v", err)
  3679. }
  3680. return fakeContextFromDir(tmpDir)
  3681. }()
  3682. defer ctx.Close()
  3683. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3684. t.Fatalf("build failed to complete for TestBuildAddTar: %v", err)
  3685. }
  3686. logDone("build - ADD tar")
  3687. }
  3688. func TestBuildAddTarXz(t *testing.T) {
  3689. name := "testbuildaddtarxz"
  3690. defer deleteImages(name)
  3691. ctx := func() *FakeContext {
  3692. dockerfile := `
  3693. FROM busybox
  3694. ADD test.tar.xz /
  3695. RUN cat /test/foo | grep Hi`
  3696. tmpDir, err := ioutil.TempDir("", "fake-context")
  3697. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3698. if err != nil {
  3699. t.Fatalf("failed to create test.tar archive: %v", err)
  3700. }
  3701. defer testTar.Close()
  3702. tw := tar.NewWriter(testTar)
  3703. if err := tw.WriteHeader(&tar.Header{
  3704. Name: "test/foo",
  3705. Size: 2,
  3706. }); err != nil {
  3707. t.Fatalf("failed to write tar file header: %v", err)
  3708. }
  3709. if _, err := tw.Write([]byte("Hi")); err != nil {
  3710. t.Fatalf("failed to write tar file content: %v", err)
  3711. }
  3712. if err := tw.Close(); err != nil {
  3713. t.Fatalf("failed to close tar archive: %v", err)
  3714. }
  3715. xzCompressCmd := exec.Command("xz", "-k", "test.tar")
  3716. xzCompressCmd.Dir = tmpDir
  3717. out, _, err := runCommandWithOutput(xzCompressCmd)
  3718. if err != nil {
  3719. t.Fatal(err, out)
  3720. }
  3721. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3722. t.Fatalf("failed to open destination dockerfile: %v", err)
  3723. }
  3724. return fakeContextFromDir(tmpDir)
  3725. }()
  3726. defer ctx.Close()
  3727. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3728. t.Fatalf("build failed to complete for TestBuildAddTarXz: %v", err)
  3729. }
  3730. logDone("build - ADD tar.xz")
  3731. }
  3732. func TestBuildAddTarXzGz(t *testing.T) {
  3733. name := "testbuildaddtarxzgz"
  3734. defer deleteImages(name)
  3735. ctx := func() *FakeContext {
  3736. dockerfile := `
  3737. FROM busybox
  3738. ADD test.tar.xz.gz /
  3739. RUN ls /test.tar.xz.gz`
  3740. tmpDir, err := ioutil.TempDir("", "fake-context")
  3741. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3742. if err != nil {
  3743. t.Fatalf("failed to create test.tar archive: %v", err)
  3744. }
  3745. defer testTar.Close()
  3746. tw := tar.NewWriter(testTar)
  3747. if err := tw.WriteHeader(&tar.Header{
  3748. Name: "test/foo",
  3749. Size: 2,
  3750. }); err != nil {
  3751. t.Fatalf("failed to write tar file header: %v", err)
  3752. }
  3753. if _, err := tw.Write([]byte("Hi")); err != nil {
  3754. t.Fatalf("failed to write tar file content: %v", err)
  3755. }
  3756. if err := tw.Close(); err != nil {
  3757. t.Fatalf("failed to close tar archive: %v", err)
  3758. }
  3759. xzCompressCmd := exec.Command("xz", "-k", "test.tar")
  3760. xzCompressCmd.Dir = tmpDir
  3761. out, _, err := runCommandWithOutput(xzCompressCmd)
  3762. if err != nil {
  3763. t.Fatal(err, out)
  3764. }
  3765. gzipCompressCmd := exec.Command("gzip", "test.tar.xz")
  3766. gzipCompressCmd.Dir = tmpDir
  3767. out, _, err = runCommandWithOutput(gzipCompressCmd)
  3768. if err != nil {
  3769. t.Fatal(err, out)
  3770. }
  3771. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3772. t.Fatalf("failed to open destination dockerfile: %v", err)
  3773. }
  3774. return fakeContextFromDir(tmpDir)
  3775. }()
  3776. defer ctx.Close()
  3777. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3778. t.Fatalf("build failed to complete for TestBuildAddTarXz: %v", err)
  3779. }
  3780. logDone("build - ADD tar.xz.gz")
  3781. }
  3782. func TestBuildFromGIT(t *testing.T) {
  3783. name := "testbuildfromgit"
  3784. defer deleteImages(name)
  3785. git, err := fakeGIT("repo", map[string]string{
  3786. "Dockerfile": `FROM busybox
  3787. ADD first /first
  3788. RUN [ -f /first ]
  3789. MAINTAINER docker`,
  3790. "first": "test git data",
  3791. }, true)
  3792. if err != nil {
  3793. t.Fatal(err)
  3794. }
  3795. defer git.Close()
  3796. _, err = buildImageFromPath(name, git.RepoURL, true)
  3797. if err != nil {
  3798. t.Fatal(err)
  3799. }
  3800. res, err := inspectField(name, "Author")
  3801. if err != nil {
  3802. t.Fatal(err)
  3803. }
  3804. if res != "docker" {
  3805. t.Fatalf("Maintainer should be docker, got %s", res)
  3806. }
  3807. logDone("build - build from GIT")
  3808. }
  3809. func TestBuildCleanupCmdOnEntrypoint(t *testing.T) {
  3810. name := "testbuildcmdcleanuponentrypoint"
  3811. defer deleteImages(name)
  3812. if _, err := buildImage(name,
  3813. `FROM scratch
  3814. CMD ["test"]
  3815. ENTRYPOINT ["echo"]`,
  3816. true); err != nil {
  3817. t.Fatal(err)
  3818. }
  3819. if _, err := buildImage(name,
  3820. fmt.Sprintf(`FROM %s
  3821. ENTRYPOINT ["cat"]`, name),
  3822. true); err != nil {
  3823. t.Fatal(err)
  3824. }
  3825. res, err := inspectField(name, "Config.Cmd")
  3826. if err != nil {
  3827. t.Fatal(err)
  3828. }
  3829. if expected := "<no value>"; res != expected {
  3830. t.Fatalf("Cmd %s, expected %s", res, expected)
  3831. }
  3832. res, err = inspectField(name, "Config.Entrypoint")
  3833. if err != nil {
  3834. t.Fatal(err)
  3835. }
  3836. if expected := "[cat]"; res != expected {
  3837. t.Fatalf("Entrypoint %s, expected %s", res, expected)
  3838. }
  3839. logDone("build - cleanup cmd on ENTRYPOINT")
  3840. }
  3841. func TestBuildClearCmd(t *testing.T) {
  3842. name := "testbuildclearcmd"
  3843. defer deleteImages(name)
  3844. _, err := buildImage(name,
  3845. `From scratch
  3846. ENTRYPOINT ["/bin/bash"]
  3847. CMD []`,
  3848. true)
  3849. if err != nil {
  3850. t.Fatal(err)
  3851. }
  3852. res, err := inspectFieldJSON(name, "Config.Cmd")
  3853. if err != nil {
  3854. t.Fatal(err)
  3855. }
  3856. if res != "[]" {
  3857. t.Fatalf("Cmd %s, expected %s", res, "[]")
  3858. }
  3859. logDone("build - clearcmd")
  3860. }
  3861. func TestBuildEmptyCmd(t *testing.T) {
  3862. name := "testbuildemptycmd"
  3863. defer deleteImages(name)
  3864. if _, err := buildImage(name, "FROM scratch\nMAINTAINER quux\n", true); err != nil {
  3865. t.Fatal(err)
  3866. }
  3867. res, err := inspectFieldJSON(name, "Config.Cmd")
  3868. if err != nil {
  3869. t.Fatal(err)
  3870. }
  3871. if res != "null" {
  3872. t.Fatalf("Cmd %s, expected %s", res, "null")
  3873. }
  3874. logDone("build - empty cmd")
  3875. }
  3876. func TestBuildOnBuildOutput(t *testing.T) {
  3877. name := "testbuildonbuildparent"
  3878. defer deleteImages(name)
  3879. if _, err := buildImage(name, "FROM busybox\nONBUILD RUN echo foo\n", true); err != nil {
  3880. t.Fatal(err)
  3881. }
  3882. childname := "testbuildonbuildchild"
  3883. defer deleteImages(childname)
  3884. _, out, err := buildImageWithOut(name, "FROM "+name+"\nMAINTAINER quux\n", true)
  3885. if err != nil {
  3886. t.Fatal(err)
  3887. }
  3888. if !strings.Contains(out, "Trigger 0, RUN echo foo") {
  3889. t.Fatal("failed to find the ONBUILD output", out)
  3890. }
  3891. logDone("build - onbuild output")
  3892. }
  3893. func TestBuildInvalidTag(t *testing.T) {
  3894. name := "abcd:" + stringutils.GenerateRandomAlphaOnlyString(200)
  3895. defer deleteImages(name)
  3896. _, out, err := buildImageWithOut(name, "FROM scratch\nMAINTAINER quux\n", true)
  3897. // if the error doesnt check for illegal tag name, or the image is built
  3898. // then this should fail
  3899. if !strings.Contains(out, "Illegal tag name") || strings.Contains(out, "Sending build context to Docker daemon") {
  3900. t.Fatalf("failed to stop before building. Error: %s, Output: %s", err, out)
  3901. }
  3902. logDone("build - invalid tag")
  3903. }
  3904. func TestBuildCmdShDashC(t *testing.T) {
  3905. name := "testbuildcmdshc"
  3906. defer deleteImages(name)
  3907. if _, err := buildImage(name, "FROM busybox\nCMD echo cmd\n", true); err != nil {
  3908. t.Fatal(err)
  3909. }
  3910. res, err := inspectFieldJSON(name, "Config.Cmd")
  3911. if err != nil {
  3912. t.Fatal(err, res)
  3913. }
  3914. expected := `["/bin/sh","-c","echo cmd"]`
  3915. if res != expected {
  3916. t.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  3917. }
  3918. logDone("build - cmd should have sh -c for non-json")
  3919. }
  3920. func TestBuildCmdSpaces(t *testing.T) {
  3921. // Test to make sure that when we strcat arrays we take into account
  3922. // the arg separator to make sure ["echo","hi"] and ["echo hi"] don't
  3923. // look the same
  3924. name := "testbuildcmdspaces"
  3925. defer deleteImages(name)
  3926. var id1 string
  3927. var id2 string
  3928. var err error
  3929. if id1, err = buildImage(name, "FROM busybox\nCMD [\"echo hi\"]\n", true); err != nil {
  3930. t.Fatal(err)
  3931. }
  3932. if id2, err = buildImage(name, "FROM busybox\nCMD [\"echo\", \"hi\"]\n", true); err != nil {
  3933. t.Fatal(err)
  3934. }
  3935. if id1 == id2 {
  3936. t.Fatal("Should not have resulted in the same CMD")
  3937. }
  3938. // Now do the same with ENTRYPOINT
  3939. if id1, err = buildImage(name, "FROM busybox\nENTRYPOINT [\"echo hi\"]\n", true); err != nil {
  3940. t.Fatal(err)
  3941. }
  3942. if id2, err = buildImage(name, "FROM busybox\nENTRYPOINT [\"echo\", \"hi\"]\n", true); err != nil {
  3943. t.Fatal(err)
  3944. }
  3945. if id1 == id2 {
  3946. t.Fatal("Should not have resulted in the same ENTRYPOINT")
  3947. }
  3948. logDone("build - cmd with spaces")
  3949. }
  3950. func TestBuildCmdJSONNoShDashC(t *testing.T) {
  3951. name := "testbuildcmdjson"
  3952. defer deleteImages(name)
  3953. if _, err := buildImage(name, "FROM busybox\nCMD [\"echo\", \"cmd\"]", true); err != nil {
  3954. t.Fatal(err)
  3955. }
  3956. res, err := inspectFieldJSON(name, "Config.Cmd")
  3957. if err != nil {
  3958. t.Fatal(err, res)
  3959. }
  3960. expected := `["echo","cmd"]`
  3961. if res != expected {
  3962. t.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  3963. }
  3964. logDone("build - cmd should not have /bin/sh -c for json")
  3965. }
  3966. func TestBuildErrorInvalidInstruction(t *testing.T) {
  3967. name := "testbuildignoreinvalidinstruction"
  3968. defer deleteImages(name)
  3969. out, _, err := buildImageWithOut(name, "FROM busybox\nfoo bar", true)
  3970. if err == nil {
  3971. t.Fatalf("Should have failed: %s", out)
  3972. }
  3973. logDone("build - error invalid Dockerfile instruction")
  3974. }
  3975. func TestBuildEntrypointInheritance(t *testing.T) {
  3976. defer deleteImages("parent", "child")
  3977. defer deleteAllContainers()
  3978. if _, err := buildImage("parent", `
  3979. FROM busybox
  3980. ENTRYPOINT exit 130
  3981. `, true); err != nil {
  3982. t.Fatal(err)
  3983. }
  3984. status, _ := runCommand(exec.Command(dockerBinary, "run", "parent"))
  3985. if status != 130 {
  3986. t.Fatalf("expected exit code 130 but received %d", status)
  3987. }
  3988. if _, err := buildImage("child", `
  3989. FROM parent
  3990. ENTRYPOINT exit 5
  3991. `, true); err != nil {
  3992. t.Fatal(err)
  3993. }
  3994. status, _ = runCommand(exec.Command(dockerBinary, "run", "child"))
  3995. if status != 5 {
  3996. t.Fatalf("expected exit code 5 but received %d", status)
  3997. }
  3998. logDone("build - clear entrypoint")
  3999. }
  4000. func TestBuildEntrypointInheritanceInspect(t *testing.T) {
  4001. var (
  4002. name = "testbuildepinherit"
  4003. name2 = "testbuildepinherit2"
  4004. expected = `["/bin/sh","-c","echo quux"]`
  4005. )
  4006. defer deleteImages(name, name2)
  4007. defer deleteAllContainers()
  4008. if _, err := buildImage(name, "FROM busybox\nENTRYPOINT /foo/bar", true); err != nil {
  4009. t.Fatal(err)
  4010. }
  4011. if _, err := buildImage(name2, fmt.Sprintf("FROM %s\nENTRYPOINT echo quux", name), true); err != nil {
  4012. t.Fatal(err)
  4013. }
  4014. res, err := inspectFieldJSON(name2, "Config.Entrypoint")
  4015. if err != nil {
  4016. t.Fatal(err, res)
  4017. }
  4018. if res != expected {
  4019. t.Fatalf("Expected value %s not in Config.Entrypoint: %s", expected, res)
  4020. }
  4021. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-t", name2))
  4022. if err != nil {
  4023. t.Fatal(err, out)
  4024. }
  4025. expected = "quux"
  4026. if strings.TrimSpace(out) != expected {
  4027. t.Fatalf("Expected output is %s, got %s", expected, out)
  4028. }
  4029. logDone("build - entrypoint override inheritance properly")
  4030. }
  4031. func TestBuildRunShEntrypoint(t *testing.T) {
  4032. name := "testbuildentrypoint"
  4033. defer deleteImages(name)
  4034. _, err := buildImage(name,
  4035. `FROM busybox
  4036. ENTRYPOINT /bin/echo`,
  4037. true)
  4038. if err != nil {
  4039. t.Fatal(err)
  4040. }
  4041. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--rm", name))
  4042. if err != nil {
  4043. t.Fatal(err, out)
  4044. }
  4045. logDone("build - entrypoint with /bin/echo running successfully")
  4046. }
  4047. func TestBuildExoticShellInterpolation(t *testing.T) {
  4048. name := "testbuildexoticshellinterpolation"
  4049. defer deleteImages(name)
  4050. _, err := buildImage(name, `
  4051. FROM busybox
  4052. ENV SOME_VAR a.b.c
  4053. RUN [ "$SOME_VAR" = 'a.b.c' ]
  4054. RUN [ "${SOME_VAR}" = 'a.b.c' ]
  4055. RUN [ "${SOME_VAR%.*}" = 'a.b' ]
  4056. RUN [ "${SOME_VAR%%.*}" = 'a' ]
  4057. RUN [ "${SOME_VAR#*.}" = 'b.c' ]
  4058. RUN [ "${SOME_VAR##*.}" = 'c' ]
  4059. RUN [ "${SOME_VAR/c/d}" = 'a.b.d' ]
  4060. RUN [ "${#SOME_VAR}" = '5' ]
  4061. RUN [ "${SOME_UNSET_VAR:-$SOME_VAR}" = 'a.b.c' ]
  4062. RUN [ "${SOME_VAR:+Version: ${SOME_VAR}}" = 'Version: a.b.c' ]
  4063. RUN [ "${SOME_UNSET_VAR:+${SOME_VAR}}" = '' ]
  4064. RUN [ "${SOME_UNSET_VAR:-${SOME_VAR:-d.e.f}}" = 'a.b.c' ]
  4065. `, false)
  4066. if err != nil {
  4067. t.Fatal(err)
  4068. }
  4069. logDone("build - exotic shell interpolation")
  4070. }
  4071. func TestBuildVerifySingleQuoteFails(t *testing.T) {
  4072. // This testcase is supposed to generate an error because the
  4073. // JSON array we're passing in on the CMD uses single quotes instead
  4074. // of double quotes (per the JSON spec). This means we interpret it
  4075. // as a "string" insead of "JSON array" and pass it on to "sh -c" and
  4076. // it should barf on it.
  4077. name := "testbuildsinglequotefails"
  4078. defer deleteImages(name)
  4079. defer deleteAllContainers()
  4080. _, err := buildImage(name,
  4081. `FROM busybox
  4082. CMD [ '/bin/sh', '-c', 'echo hi' ]`,
  4083. true)
  4084. _, _, err = runCommandWithOutput(exec.Command(dockerBinary, "run", "--rm", name))
  4085. if err == nil {
  4086. t.Fatal("The image was not supposed to be able to run")
  4087. }
  4088. logDone("build - verify single quotes break the build")
  4089. }
  4090. func TestBuildVerboseOut(t *testing.T) {
  4091. name := "testbuildverboseout"
  4092. defer deleteImages(name)
  4093. _, out, err := buildImageWithOut(name,
  4094. `FROM busybox
  4095. RUN echo 123`,
  4096. false)
  4097. if err != nil {
  4098. t.Fatal(err)
  4099. }
  4100. if !strings.Contains(out, "\n123\n") {
  4101. t.Fatalf("Output should contain %q: %q", "123", out)
  4102. }
  4103. logDone("build - verbose output from commands")
  4104. }
  4105. func TestBuildWithTabs(t *testing.T) {
  4106. name := "testbuildwithtabs"
  4107. defer deleteImages(name)
  4108. _, err := buildImage(name,
  4109. "FROM busybox\nRUN echo\tone\t\ttwo", true)
  4110. if err != nil {
  4111. t.Fatal(err)
  4112. }
  4113. res, err := inspectFieldJSON(name, "ContainerConfig.Cmd")
  4114. if err != nil {
  4115. t.Fatal(err)
  4116. }
  4117. expected1 := `["/bin/sh","-c","echo\tone\t\ttwo"]`
  4118. expected2 := `["/bin/sh","-c","echo\u0009one\u0009\u0009two"]` // syntactically equivalent, and what Go 1.3 generates
  4119. if res != expected1 && res != expected2 {
  4120. t.Fatalf("Missing tabs.\nGot: %s\nExp: %s or %s", res, expected1, expected2)
  4121. }
  4122. logDone("build - with tabs")
  4123. }
  4124. func TestBuildLabels(t *testing.T) {
  4125. name := "testbuildlabel"
  4126. expected := `{"License":"GPL","Vendor":"Acme"}`
  4127. defer deleteImages(name)
  4128. _, err := buildImage(name,
  4129. `FROM busybox
  4130. LABEL Vendor=Acme
  4131. LABEL License GPL`,
  4132. true)
  4133. if err != nil {
  4134. t.Fatal(err)
  4135. }
  4136. res, err := inspectFieldJSON(name, "Config.Labels")
  4137. if err != nil {
  4138. t.Fatal(err)
  4139. }
  4140. if res != expected {
  4141. t.Fatalf("Labels %s, expected %s", res, expected)
  4142. }
  4143. logDone("build - label")
  4144. }
  4145. func TestBuildLabelsCache(t *testing.T) {
  4146. name := "testbuildlabelcache"
  4147. defer deleteImages(name)
  4148. id1, err := buildImage(name,
  4149. `FROM busybox
  4150. LABEL Vendor=Acme`, false)
  4151. if err != nil {
  4152. t.Fatalf("Build 1 should have worked: %v", err)
  4153. }
  4154. id2, err := buildImage(name,
  4155. `FROM busybox
  4156. LABEL Vendor=Acme`, true)
  4157. if err != nil || id1 != id2 {
  4158. t.Fatalf("Build 2 should have worked & used cache(%s,%s): %v", id1, id2, err)
  4159. }
  4160. id2, err = buildImage(name,
  4161. `FROM busybox
  4162. LABEL Vendor=Acme1`, true)
  4163. if err != nil || id1 == id2 {
  4164. t.Fatalf("Build 3 should have worked & NOT used cache(%s,%s): %v", id1, id2, err)
  4165. }
  4166. id2, err = buildImage(name,
  4167. `FROM busybox
  4168. LABEL Vendor Acme`, true) // Note: " " and "=" should be same
  4169. if err != nil || id1 != id2 {
  4170. t.Fatalf("Build 4 should have worked & used cache(%s,%s): %v", id1, id2, err)
  4171. }
  4172. // Now make sure the cache isn't used by mistake
  4173. id1, err = buildImage(name,
  4174. `FROM busybox
  4175. LABEL f1=b1 f2=b2`, false)
  4176. if err != nil {
  4177. t.Fatalf("Build 5 should have worked: %q", err)
  4178. }
  4179. id2, err = buildImage(name,
  4180. `FROM busybox
  4181. LABEL f1="b1 f2=b2"`, true)
  4182. if err != nil || id1 == id2 {
  4183. t.Fatalf("Build 6 should have worked & NOT used the cache(%s,%s): %q", id1, id2, err)
  4184. }
  4185. logDone("build - label cache")
  4186. }
  4187. func TestBuildStderr(t *testing.T) {
  4188. // This test just makes sure that no non-error output goes
  4189. // to stderr
  4190. name := "testbuildstderr"
  4191. defer deleteImages(name)
  4192. _, _, stderr, err := buildImageWithStdoutStderr(name,
  4193. "FROM busybox\nRUN echo one", true)
  4194. if err != nil {
  4195. t.Fatal(err)
  4196. }
  4197. if runtime.GOOS == "windows" {
  4198. // stderr might contain a security warning on windows
  4199. lines := strings.Split(stderr, "\n")
  4200. for _, v := range lines {
  4201. if v != "" && !strings.Contains(v, "SECURITY WARNING:") {
  4202. t.Fatalf("Stderr contains unexpected output line: %q", v)
  4203. }
  4204. }
  4205. } else {
  4206. if stderr != "" {
  4207. t.Fatalf("Stderr should have been empty, instead its: %q", stderr)
  4208. }
  4209. }
  4210. logDone("build - testing stderr")
  4211. }
  4212. func TestBuildChownSingleFile(t *testing.T) {
  4213. testRequires(t, UnixCli) // test uses chown: not available on windows
  4214. name := "testbuildchownsinglefile"
  4215. defer deleteImages(name)
  4216. ctx, err := fakeContext(`
  4217. FROM busybox
  4218. COPY test /
  4219. RUN ls -l /test
  4220. RUN [ $(ls -l /test | awk '{print $3":"$4}') = 'root:root' ]
  4221. `, map[string]string{
  4222. "test": "test",
  4223. })
  4224. if err != nil {
  4225. t.Fatal(err)
  4226. }
  4227. defer ctx.Close()
  4228. if err := os.Chown(filepath.Join(ctx.Dir, "test"), 4242, 4242); err != nil {
  4229. t.Fatal(err)
  4230. }
  4231. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  4232. t.Fatal(err)
  4233. }
  4234. logDone("build - change permission on single file")
  4235. }
  4236. func TestBuildSymlinkBreakout(t *testing.T) {
  4237. name := "testbuildsymlinkbreakout"
  4238. tmpdir, err := ioutil.TempDir("", name)
  4239. if err != nil {
  4240. t.Fatal(err)
  4241. }
  4242. defer os.RemoveAll(tmpdir)
  4243. ctx := filepath.Join(tmpdir, "context")
  4244. if err := os.MkdirAll(ctx, 0755); err != nil {
  4245. t.Fatal(err)
  4246. }
  4247. if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte(`
  4248. from busybox
  4249. add symlink.tar /
  4250. add inject /symlink/
  4251. `), 0644); err != nil {
  4252. t.Fatal(err)
  4253. }
  4254. inject := filepath.Join(ctx, "inject")
  4255. if err := ioutil.WriteFile(inject, nil, 0644); err != nil {
  4256. t.Fatal(err)
  4257. }
  4258. f, err := os.Create(filepath.Join(ctx, "symlink.tar"))
  4259. if err != nil {
  4260. t.Fatal(err)
  4261. }
  4262. w := tar.NewWriter(f)
  4263. w.WriteHeader(&tar.Header{
  4264. Name: "symlink2",
  4265. Typeflag: tar.TypeSymlink,
  4266. Linkname: "/../../../../../../../../../../../../../../",
  4267. Uid: os.Getuid(),
  4268. Gid: os.Getgid(),
  4269. })
  4270. w.WriteHeader(&tar.Header{
  4271. Name: "symlink",
  4272. Typeflag: tar.TypeSymlink,
  4273. Linkname: filepath.Join("symlink2", tmpdir),
  4274. Uid: os.Getuid(),
  4275. Gid: os.Getgid(),
  4276. })
  4277. w.Close()
  4278. f.Close()
  4279. if _, err := buildImageFromContext(name, fakeContextFromDir(ctx), false); err != nil {
  4280. t.Fatal(err)
  4281. }
  4282. if _, err := os.Lstat(filepath.Join(tmpdir, "inject")); err == nil {
  4283. t.Fatal("symlink breakout - inject")
  4284. } else if !os.IsNotExist(err) {
  4285. t.Fatalf("unexpected error: %v", err)
  4286. }
  4287. logDone("build - symlink breakout")
  4288. }
  4289. func TestBuildXZHost(t *testing.T) {
  4290. name := "testbuildxzhost"
  4291. defer deleteImages(name)
  4292. ctx, err := fakeContext(`
  4293. FROM busybox
  4294. ADD xz /usr/local/sbin/
  4295. RUN chmod 755 /usr/local/sbin/xz
  4296. ADD test.xz /
  4297. RUN [ ! -e /injected ]`,
  4298. map[string]string{
  4299. "test.xz": "\xfd\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00" +
  4300. "\x21\x01\x16\x00\x00\x00\x74\x2f\xe5\xa3\x01\x00\x3f\xfd" +
  4301. "\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00\x21",
  4302. "xz": "#!/bin/sh\ntouch /injected",
  4303. })
  4304. if err != nil {
  4305. t.Fatal(err)
  4306. }
  4307. defer ctx.Close()
  4308. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  4309. t.Fatal(err)
  4310. }
  4311. logDone("build - xz host is being used")
  4312. }
  4313. func TestBuildVolumesRetainContents(t *testing.T) {
  4314. var (
  4315. name = "testbuildvolumescontent"
  4316. expected = "some text"
  4317. )
  4318. defer deleteImages(name)
  4319. ctx, err := fakeContext(`
  4320. FROM busybox
  4321. COPY content /foo/file
  4322. VOLUME /foo
  4323. CMD cat /foo/file`,
  4324. map[string]string{
  4325. "content": expected,
  4326. })
  4327. if err != nil {
  4328. t.Fatal(err)
  4329. }
  4330. defer ctx.Close()
  4331. if _, err := buildImageFromContext(name, ctx, false); err != nil {
  4332. t.Fatal(err)
  4333. }
  4334. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--rm", name))
  4335. if err != nil {
  4336. t.Fatal(err)
  4337. }
  4338. if out != expected {
  4339. t.Fatalf("expected file contents for /foo/file to be %q but received %q", expected, out)
  4340. }
  4341. logDone("build - volumes retain contents in build")
  4342. }
  4343. func TestBuildRenamedDockerfile(t *testing.T) {
  4344. defer deleteAllContainers()
  4345. ctx, err := fakeContext(`FROM busybox
  4346. RUN echo from Dockerfile`,
  4347. map[string]string{
  4348. "Dockerfile": "FROM busybox\nRUN echo from Dockerfile",
  4349. "files/Dockerfile": "FROM busybox\nRUN echo from files/Dockerfile",
  4350. "files/dFile": "FROM busybox\nRUN echo from files/dFile",
  4351. "dFile": "FROM busybox\nRUN echo from dFile",
  4352. "files/dFile2": "FROM busybox\nRUN echo from files/dFile2",
  4353. })
  4354. defer ctx.Close()
  4355. if err != nil {
  4356. t.Fatal(err)
  4357. }
  4358. out, _, err := dockerCmdInDir(t, ctx.Dir, "build", "-t", "test1", ".")
  4359. if err != nil {
  4360. t.Fatalf("Failed to build: %s\n%s", out, err)
  4361. }
  4362. if !strings.Contains(out, "from Dockerfile") {
  4363. t.Fatalf("test1 should have used Dockerfile, output:%s", out)
  4364. }
  4365. out, _, err = dockerCmdInDir(t, ctx.Dir, "build", "-f", filepath.Join("files", "Dockerfile"), "-t", "test2", ".")
  4366. if err != nil {
  4367. t.Fatal(err)
  4368. }
  4369. if !strings.Contains(out, "from files/Dockerfile") {
  4370. t.Fatalf("test2 should have used files/Dockerfile, output:%s", out)
  4371. }
  4372. out, _, err = dockerCmdInDir(t, ctx.Dir, "build", fmt.Sprintf("--file=%s", filepath.Join("files", "dFile")), "-t", "test3", ".")
  4373. if err != nil {
  4374. t.Fatal(err)
  4375. }
  4376. if !strings.Contains(out, "from files/dFile") {
  4377. t.Fatalf("test3 should have used files/dFile, output:%s", out)
  4378. }
  4379. out, _, err = dockerCmdInDir(t, ctx.Dir, "build", "--file=dFile", "-t", "test4", ".")
  4380. if err != nil {
  4381. t.Fatal(err)
  4382. }
  4383. if !strings.Contains(out, "from dFile") {
  4384. t.Fatalf("test4 should have used dFile, output:%s", out)
  4385. }
  4386. dirWithNoDockerfile, _ := ioutil.TempDir(os.TempDir(), "test5")
  4387. nonDockerfileFile := filepath.Join(dirWithNoDockerfile, "notDockerfile")
  4388. if _, err = os.Create(nonDockerfileFile); err != nil {
  4389. t.Fatal(err)
  4390. }
  4391. out, _, err = dockerCmdInDir(t, ctx.Dir, "build", fmt.Sprintf("--file=%s", nonDockerfileFile), "-t", "test5", ".")
  4392. if err == nil {
  4393. t.Fatalf("test5 was supposed to fail to find passwd")
  4394. }
  4395. if expected := fmt.Sprintf("The Dockerfile (%s) must be within the build context (.)", strings.Replace(nonDockerfileFile, `\`, `\\`, -1)); !strings.Contains(out, expected) {
  4396. t.Fatalf("wrong error messsage:%v\nexpected to contain=%v", out, expected)
  4397. }
  4398. out, _, err = dockerCmdInDir(t, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join("..", "Dockerfile"), "-t", "test6", "..")
  4399. if err != nil {
  4400. t.Fatalf("test6 failed: %s", err)
  4401. }
  4402. if !strings.Contains(out, "from Dockerfile") {
  4403. t.Fatalf("test6 should have used root Dockerfile, output:%s", out)
  4404. }
  4405. out, _, err = dockerCmdInDir(t, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join(ctx.Dir, "files", "Dockerfile"), "-t", "test7", "..")
  4406. if err != nil {
  4407. t.Fatalf("test7 failed: %s", err)
  4408. }
  4409. if !strings.Contains(out, "from files/Dockerfile") {
  4410. t.Fatalf("test7 should have used files Dockerfile, output:%s", out)
  4411. }
  4412. out, _, err = dockerCmdInDir(t, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join("..", "Dockerfile"), "-t", "test8", ".")
  4413. if err == nil || !strings.Contains(out, "must be within the build context") {
  4414. t.Fatalf("test8 should have failed with Dockerfile out of context: %s", err)
  4415. }
  4416. tmpDir := os.TempDir()
  4417. out, _, err = dockerCmdInDir(t, tmpDir, "build", "-t", "test9", ctx.Dir)
  4418. if err != nil {
  4419. t.Fatalf("test9 - failed: %s", err)
  4420. }
  4421. if !strings.Contains(out, "from Dockerfile") {
  4422. t.Fatalf("test9 should have used root Dockerfile, output:%s", out)
  4423. }
  4424. out, _, err = dockerCmdInDir(t, filepath.Join(ctx.Dir, "files"), "build", "-f", "dFile2", "-t", "test10", ".")
  4425. if err != nil {
  4426. t.Fatalf("test10 should have worked: %s", err)
  4427. }
  4428. if !strings.Contains(out, "from files/dFile2") {
  4429. t.Fatalf("test10 should have used files/dFile2, output:%s", out)
  4430. }
  4431. logDone("build - rename dockerfile")
  4432. }
  4433. func TestBuildFromMixedcaseDockerfile(t *testing.T) {
  4434. testRequires(t, UnixCli) // Dockerfile overwrites dockerfile on windows
  4435. defer deleteImages("test1")
  4436. ctx, err := fakeContext(`FROM busybox
  4437. RUN echo from dockerfile`,
  4438. map[string]string{
  4439. "dockerfile": "FROM busybox\nRUN echo from dockerfile",
  4440. })
  4441. defer ctx.Close()
  4442. if err != nil {
  4443. t.Fatal(err)
  4444. }
  4445. out, _, err := dockerCmdInDir(t, ctx.Dir, "build", "-t", "test1", ".")
  4446. if err != nil {
  4447. t.Fatalf("Failed to build: %s\n%s", out, err)
  4448. }
  4449. if !strings.Contains(out, "from dockerfile") {
  4450. t.Fatalf("Missing proper output: %s", out)
  4451. }
  4452. logDone("build - mixedcase Dockerfile")
  4453. }
  4454. func TestBuildWithTwoDockerfiles(t *testing.T) {
  4455. testRequires(t, UnixCli) // Dockerfile overwrites dockerfile on windows
  4456. defer deleteImages("test1")
  4457. ctx, err := fakeContext(`FROM busybox
  4458. RUN echo from Dockerfile`,
  4459. map[string]string{
  4460. "dockerfile": "FROM busybox\nRUN echo from dockerfile",
  4461. })
  4462. defer ctx.Close()
  4463. if err != nil {
  4464. t.Fatal(err)
  4465. }
  4466. out, _, err := dockerCmdInDir(t, ctx.Dir, "build", "-t", "test1", ".")
  4467. if err != nil {
  4468. t.Fatalf("Failed to build: %s\n%s", out, err)
  4469. }
  4470. if !strings.Contains(out, "from Dockerfile") {
  4471. t.Fatalf("Missing proper output: %s", out)
  4472. }
  4473. logDone("build - two Dockerfiles")
  4474. }
  4475. func TestBuildFromURLWithF(t *testing.T) {
  4476. defer deleteImages("test1")
  4477. server, err := fakeStorage(map[string]string{"baz": `FROM busybox
  4478. RUN echo from baz
  4479. COPY * /tmp/
  4480. RUN find /tmp/`})
  4481. if err != nil {
  4482. t.Fatal(err)
  4483. }
  4484. defer server.Close()
  4485. ctx, err := fakeContext(`FROM busybox
  4486. RUN echo from Dockerfile`,
  4487. map[string]string{})
  4488. defer ctx.Close()
  4489. if err != nil {
  4490. t.Fatal(err)
  4491. }
  4492. // Make sure that -f is ignored and that we don't use the Dockerfile
  4493. // that's in the current dir
  4494. out, _, err := dockerCmdInDir(t, ctx.Dir, "build", "-f", "baz", "-t", "test1", server.URL()+"/baz")
  4495. if err != nil {
  4496. t.Fatalf("Failed to build: %s\n%s", out, err)
  4497. }
  4498. if !strings.Contains(out, "from baz") ||
  4499. strings.Contains(out, "/tmp/baz") ||
  4500. !strings.Contains(out, "/tmp/Dockerfile") {
  4501. t.Fatalf("Missing proper output: %s", out)
  4502. }
  4503. logDone("build - from URL with -f")
  4504. }
  4505. func TestBuildFromStdinWithF(t *testing.T) {
  4506. defer deleteImages("test1")
  4507. ctx, err := fakeContext(`FROM busybox
  4508. RUN echo from Dockerfile`,
  4509. map[string]string{})
  4510. defer ctx.Close()
  4511. if err != nil {
  4512. t.Fatal(err)
  4513. }
  4514. // Make sure that -f is ignored and that we don't use the Dockerfile
  4515. // that's in the current dir
  4516. dockerCommand := exec.Command(dockerBinary, "build", "-f", "baz", "-t", "test1", "-")
  4517. dockerCommand.Dir = ctx.Dir
  4518. dockerCommand.Stdin = strings.NewReader(`FROM busybox
  4519. RUN echo from baz
  4520. COPY * /tmp/
  4521. RUN find /tmp/`)
  4522. out, status, err := runCommandWithOutput(dockerCommand)
  4523. if err != nil || status != 0 {
  4524. t.Fatalf("Error building: %s", err)
  4525. }
  4526. if !strings.Contains(out, "from baz") ||
  4527. strings.Contains(out, "/tmp/baz") ||
  4528. !strings.Contains(out, "/tmp/Dockerfile") {
  4529. t.Fatalf("Missing proper output: %s", out)
  4530. }
  4531. logDone("build - from stdin with -f")
  4532. }
  4533. func TestBuildFromOfficialNames(t *testing.T) {
  4534. name := "testbuildfromofficial"
  4535. fromNames := []string{
  4536. "busybox",
  4537. "docker.io/busybox",
  4538. "index.docker.io/busybox",
  4539. "library/busybox",
  4540. "docker.io/library/busybox",
  4541. "index.docker.io/library/busybox",
  4542. }
  4543. for idx, fromName := range fromNames {
  4544. imgName := fmt.Sprintf("%s%d", name, idx)
  4545. _, err := buildImage(imgName, "FROM "+fromName, true)
  4546. if err != nil {
  4547. t.Errorf("Build failed using FROM %s: %s", fromName, err)
  4548. }
  4549. deleteImages(imgName)
  4550. }
  4551. logDone("build - from official names")
  4552. }
  4553. func TestBuildDockerfileOutsideContext(t *testing.T) {
  4554. testRequires(t, UnixCli) // uses os.Symlink: not implemented in windows at the time of writing (go-1.4.2)
  4555. name := "testbuilddockerfileoutsidecontext"
  4556. tmpdir, err := ioutil.TempDir("", name)
  4557. if err != nil {
  4558. t.Fatal(err)
  4559. }
  4560. defer os.RemoveAll(tmpdir)
  4561. ctx := filepath.Join(tmpdir, "context")
  4562. if err := os.MkdirAll(ctx, 0755); err != nil {
  4563. t.Fatal(err)
  4564. }
  4565. if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte("FROM scratch\nENV X Y"), 0644); err != nil {
  4566. t.Fatal(err)
  4567. }
  4568. wd, err := os.Getwd()
  4569. if err != nil {
  4570. t.Fatal(err)
  4571. }
  4572. defer os.Chdir(wd)
  4573. if err := os.Chdir(ctx); err != nil {
  4574. t.Fatal(err)
  4575. }
  4576. if err := ioutil.WriteFile(filepath.Join(tmpdir, "outsideDockerfile"), []byte("FROM scratch\nENV x y"), 0644); err != nil {
  4577. t.Fatal(err)
  4578. }
  4579. if err := os.Symlink(filepath.Join("..", "outsideDockerfile"), filepath.Join(ctx, "dockerfile1")); err != nil {
  4580. t.Fatal(err)
  4581. }
  4582. if err := os.Symlink(filepath.Join(tmpdir, "outsideDockerfile"), filepath.Join(ctx, "dockerfile2")); err != nil {
  4583. t.Fatal(err)
  4584. }
  4585. for _, dockerfilePath := range []string{
  4586. filepath.Join("..", "outsideDockerfile"),
  4587. filepath.Join(ctx, "dockerfile1"),
  4588. filepath.Join(ctx, "dockerfile2"),
  4589. } {
  4590. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "build", "-t", name, "--no-cache", "-f", dockerfilePath, "."))
  4591. if err == nil {
  4592. t.Fatalf("Expected error with %s. Out: %s", dockerfilePath, out)
  4593. }
  4594. if !strings.Contains(out, "must be within the build context") && !strings.Contains(out, "Cannot locate Dockerfile") {
  4595. t.Fatalf("Unexpected error with %s. Out: %s", dockerfilePath, out)
  4596. }
  4597. deleteImages(name)
  4598. }
  4599. os.Chdir(tmpdir)
  4600. // Path to Dockerfile should be resolved relative to working directory, not relative to context.
  4601. // There is a Dockerfile in the context, but since there is no Dockerfile in the current directory, the following should fail
  4602. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "build", "-t", name, "--no-cache", "-f", "Dockerfile", ctx))
  4603. if err == nil {
  4604. t.Fatalf("Expected error. Out: %s", out)
  4605. }
  4606. deleteImages(name)
  4607. logDone("build - Dockerfile outside context")
  4608. }
  4609. func TestBuildSpaces(t *testing.T) {
  4610. // Test to make sure that leading/trailing spaces on a command
  4611. // doesn't change the error msg we get
  4612. var (
  4613. err1 error
  4614. err2 error
  4615. )
  4616. name := "testspaces"
  4617. defer deleteImages(name)
  4618. ctx, err := fakeContext("FROM busybox\nCOPY\n",
  4619. map[string]string{
  4620. "Dockerfile": "FROM busybox\nCOPY\n",
  4621. })
  4622. if err != nil {
  4623. t.Fatal(err)
  4624. }
  4625. defer ctx.Close()
  4626. if _, err1 = buildImageFromContext(name, ctx, false); err1 == nil {
  4627. t.Fatal("Build 1 was supposed to fail, but didn't")
  4628. }
  4629. ctx.Add("Dockerfile", "FROM busybox\nCOPY ")
  4630. if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil {
  4631. t.Fatal("Build 2 was supposed to fail, but didn't")
  4632. }
  4633. removeLogTimestamps := func(s string) string {
  4634. return regexp.MustCompile(`time="(.*?)"`).ReplaceAllString(s, `time=[TIMESTAMP]`)
  4635. }
  4636. // Skip over the times
  4637. e1 := removeLogTimestamps(err1.Error())
  4638. e2 := removeLogTimestamps(err2.Error())
  4639. // Ignore whitespace since that's what were verifying doesn't change stuff
  4640. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  4641. t.Fatalf("Build 2's error wasn't the same as build 1's\n1:%s\n2:%s", err1, err2)
  4642. }
  4643. ctx.Add("Dockerfile", "FROM busybox\n COPY")
  4644. if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil {
  4645. t.Fatal("Build 3 was supposed to fail, but didn't")
  4646. }
  4647. // Skip over the times
  4648. e1 = removeLogTimestamps(err1.Error())
  4649. e2 = removeLogTimestamps(err2.Error())
  4650. // Ignore whitespace since that's what were verifying doesn't change stuff
  4651. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  4652. t.Fatalf("Build 3's error wasn't the same as build 1's\n1:%s\n3:%s", err1, err2)
  4653. }
  4654. ctx.Add("Dockerfile", "FROM busybox\n COPY ")
  4655. if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil {
  4656. t.Fatal("Build 4 was supposed to fail, but didn't")
  4657. }
  4658. // Skip over the times
  4659. e1 = removeLogTimestamps(err1.Error())
  4660. e2 = removeLogTimestamps(err2.Error())
  4661. // Ignore whitespace since that's what were verifying doesn't change stuff
  4662. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  4663. t.Fatalf("Build 4's error wasn't the same as build 1's\n1:%s\n4:%s", err1, err2)
  4664. }
  4665. logDone("build - test spaces")
  4666. }
  4667. func TestBuildSpacesWithQuotes(t *testing.T) {
  4668. // Test to make sure that spaces in quotes aren't lost
  4669. name := "testspacesquotes"
  4670. defer deleteImages(name)
  4671. dockerfile := `FROM busybox
  4672. RUN echo " \
  4673. foo "`
  4674. _, out, err := buildImageWithOut(name, dockerfile, false)
  4675. if err != nil {
  4676. t.Fatal("Build failed:", err)
  4677. }
  4678. expecting := "\n foo \n"
  4679. if !strings.Contains(out, expecting) {
  4680. t.Fatalf("Bad output: %q expecting to contian %q", out, expecting)
  4681. }
  4682. logDone("build - test spaces with quotes")
  4683. }
  4684. // #4393
  4685. func TestBuildVolumeFileExistsinContainer(t *testing.T) {
  4686. buildCmd := exec.Command(dockerBinary, "build", "-t", "docker-test-errcreatevolumewithfile", "-")
  4687. buildCmd.Stdin = strings.NewReader(`
  4688. FROM busybox
  4689. RUN touch /foo
  4690. VOLUME /foo
  4691. `)
  4692. out, _, err := runCommandWithOutput(buildCmd)
  4693. if err == nil || !strings.Contains(out, "file exists") {
  4694. t.Fatalf("expected build to fail when file exists in container at requested volume path")
  4695. }
  4696. logDone("build - errors when volume is specified where a file exists")
  4697. }
  4698. func TestBuildMissingArgs(t *testing.T) {
  4699. // Test to make sure that all Dockerfile commands (except the ones listed
  4700. // in skipCmds) will generate an error if no args are provided.
  4701. // Note: INSERT is deprecated so we exclude it because of that.
  4702. skipCmds := map[string]struct{}{
  4703. "CMD": {},
  4704. "RUN": {},
  4705. "ENTRYPOINT": {},
  4706. "INSERT": {},
  4707. }
  4708. defer deleteAllContainers()
  4709. for cmd := range command.Commands {
  4710. cmd = strings.ToUpper(cmd)
  4711. if _, ok := skipCmds[cmd]; ok {
  4712. continue
  4713. }
  4714. var dockerfile string
  4715. if cmd == "FROM" {
  4716. dockerfile = cmd
  4717. } else {
  4718. // Add FROM to make sure we don't complain about it missing
  4719. dockerfile = "FROM busybox\n" + cmd
  4720. }
  4721. ctx, err := fakeContext(dockerfile, map[string]string{})
  4722. if err != nil {
  4723. t.Fatal(err)
  4724. }
  4725. defer ctx.Close()
  4726. var out string
  4727. if out, err = buildImageFromContext("args", ctx, true); err == nil {
  4728. t.Fatalf("%s was supposed to fail. Out:%s", cmd, out)
  4729. }
  4730. if !strings.Contains(err.Error(), cmd+" requires") {
  4731. t.Fatalf("%s returned the wrong type of error:%s", cmd, err)
  4732. }
  4733. }
  4734. logDone("build - verify missing args")
  4735. }
  4736. func TestBuildEmptyScratch(t *testing.T) {
  4737. defer deleteImages("sc")
  4738. _, out, err := buildImageWithOut("sc", "FROM scratch", true)
  4739. if err == nil {
  4740. t.Fatalf("Build was supposed to fail")
  4741. }
  4742. if !strings.Contains(out, "No image was generated") {
  4743. t.Fatalf("Wrong error message: %v", out)
  4744. }
  4745. logDone("build - empty scratch Dockerfile")
  4746. }
  4747. func TestBuildDotDotFile(t *testing.T) {
  4748. defer deleteImages("sc")
  4749. ctx, err := fakeContext("FROM busybox\n",
  4750. map[string]string{
  4751. "..gitme": "",
  4752. })
  4753. if err != nil {
  4754. t.Fatal(err)
  4755. }
  4756. defer ctx.Close()
  4757. if _, err = buildImageFromContext("sc", ctx, false); err != nil {
  4758. t.Fatalf("Build was supposed to work: %s", err)
  4759. }
  4760. logDone("build - ..file")
  4761. }
  4762. func TestBuildNotVerbose(t *testing.T) {
  4763. defer deleteAllContainers()
  4764. defer deleteImages("verbose")
  4765. ctx, err := fakeContext("FROM busybox\nENV abc=hi\nRUN echo $abc there", map[string]string{})
  4766. if err != nil {
  4767. t.Fatal(err)
  4768. }
  4769. defer ctx.Close()
  4770. // First do it w/verbose - baseline
  4771. buildCmd := exec.Command(dockerBinary, "build", "--no-cache", "-t", "verbose", ".")
  4772. buildCmd.Dir = ctx.Dir
  4773. out, _, err := runCommandWithOutput(buildCmd)
  4774. if err != nil {
  4775. t.Fatalf("failed to build the image w/o -q: %s, %v", out, err)
  4776. }
  4777. if !strings.Contains(out, "hi there") {
  4778. t.Fatalf("missing output:%s\n", out)
  4779. }
  4780. // Now do it w/o verbose
  4781. buildCmd = exec.Command(dockerBinary, "build", "--no-cache", "-q", "-t", "verbose", ".")
  4782. buildCmd.Dir = ctx.Dir
  4783. out, _, err = runCommandWithOutput(buildCmd)
  4784. if err != nil {
  4785. t.Fatalf("failed to build the image w/ -q: %s, %v", out, err)
  4786. }
  4787. if strings.Contains(out, "hi there") {
  4788. t.Fatalf("Bad output, should not contain 'hi there':%s", out)
  4789. }
  4790. logDone("build - not verbose")
  4791. }
  4792. func TestBuildRUNoneJSON(t *testing.T) {
  4793. name := "testbuildrunonejson"
  4794. defer deleteAllContainers()
  4795. defer deleteImages(name, "hello-world")
  4796. ctx, err := fakeContext(`FROM hello-world:frozen
  4797. RUN [ "/hello" ]`, map[string]string{})
  4798. if err != nil {
  4799. t.Fatal(err)
  4800. }
  4801. defer ctx.Close()
  4802. buildCmd := exec.Command(dockerBinary, "build", "--no-cache", "-t", name, ".")
  4803. buildCmd.Dir = ctx.Dir
  4804. out, _, err := runCommandWithOutput(buildCmd)
  4805. if err != nil {
  4806. t.Fatalf("failed to build the image: %s, %v", out, err)
  4807. }
  4808. if !strings.Contains(out, "Hello from Docker") {
  4809. t.Fatalf("bad output: %s", out)
  4810. }
  4811. logDone("build - RUN with one JSON arg")
  4812. }
  4813. func TestBuildResourceConstraintsAreUsed(t *testing.T) {
  4814. name := "testbuildresourceconstraints"
  4815. defer deleteAllContainers()
  4816. defer deleteImages(name, "hello-world")
  4817. ctx, err := fakeContext(`
  4818. FROM hello-world:frozen
  4819. RUN ["/hello"]
  4820. `, map[string]string{})
  4821. if err != nil {
  4822. t.Fatal(err)
  4823. }
  4824. cmd := exec.Command(dockerBinary, "build", "--rm=false", "--memory=64m", "--memory-swap=-1", "--cpuset-cpus=1", "--cpu-shares=100", "-t", name, ".")
  4825. cmd.Dir = ctx.Dir
  4826. out, _, err := runCommandWithOutput(cmd)
  4827. if err != nil {
  4828. t.Fatal(err, out)
  4829. }
  4830. out, _, err = dockerCmd(t, "ps", "-lq")
  4831. if err != nil {
  4832. t.Fatal(err, out)
  4833. }
  4834. cID := stripTrailingCharacters(out)
  4835. type hostConfig struct {
  4836. Memory float64 // Use float64 here since the json decoder sees it that way
  4837. MemorySwap int
  4838. CpusetCpus string
  4839. CpuShares int
  4840. }
  4841. cfg, err := inspectFieldJSON(cID, "HostConfig")
  4842. if err != nil {
  4843. t.Fatal(err)
  4844. }
  4845. var c1 hostConfig
  4846. if err := json.Unmarshal([]byte(cfg), &c1); err != nil {
  4847. t.Fatal(err, cfg)
  4848. }
  4849. mem := int64(c1.Memory)
  4850. if mem != 67108864 || c1.MemorySwap != -1 || c1.CpusetCpus != "1" || c1.CpuShares != 100 {
  4851. t.Fatalf("resource constraints not set properly:\nMemory: %d, MemSwap: %d, CpusetCpus: %s, CpuShares: %d",
  4852. mem, c1.MemorySwap, c1.CpusetCpus, c1.CpuShares)
  4853. }
  4854. // Make sure constraints aren't saved to image
  4855. _, _, err = dockerCmd(t, "run", "--name=test", name)
  4856. if err != nil {
  4857. t.Fatal(err)
  4858. }
  4859. cfg, err = inspectFieldJSON("test", "HostConfig")
  4860. if err != nil {
  4861. t.Fatal(err)
  4862. }
  4863. var c2 hostConfig
  4864. if err := json.Unmarshal([]byte(cfg), &c2); err != nil {
  4865. t.Fatal(err, cfg)
  4866. }
  4867. mem = int64(c2.Memory)
  4868. if mem == 67108864 || c2.MemorySwap == -1 || c2.CpusetCpus == "1" || c2.CpuShares == 100 {
  4869. t.Fatalf("resource constraints leaked from build:\nMemory: %d, MemSwap: %d, CpusetCpus: %s, CpuShares: %d",
  4870. mem, c2.MemorySwap, c2.CpusetCpus, c2.CpuShares)
  4871. }
  4872. logDone("build - resource constraints applied")
  4873. }
  4874. func TestBuildEmptyStringVolume(t *testing.T) {
  4875. name := "testbuildemptystringvolume"
  4876. defer deleteImages(name)
  4877. _, err := buildImage(name, `
  4878. FROM busybox
  4879. ENV foo=""
  4880. VOLUME $foo
  4881. `, false)
  4882. if err == nil {
  4883. t.Fatal("Should have failed to build")
  4884. }
  4885. logDone("build - empty string volume")
  4886. }