docker_cli_build_test.go 132 KB

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