docker_cli_build_test.go 124 KB

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