docker_cli_build_test.go 127 KB

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