docker_cli_build_test.go 134 KB

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