docker_cli_build_test.go 122 KB

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