docker_cli_build_test.go 136 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400
  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. if err != nil {
  920. c.Fatal(err)
  921. }
  922. defer ctx.Close()
  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) TestBuildCopyWildcardInName(c *check.C) {
  954. name := "testcopywildcardinname"
  955. defer deleteImages(name)
  956. ctx, err := fakeContext(`FROM busybox
  957. COPY *.txt /tmp/
  958. RUN [ "$(cat /tmp/\*.txt)" = 'hi there' ]
  959. `, map[string]string{"*.txt": "hi there"})
  960. if err != nil {
  961. // Normally we would do c.Fatal(err) here but given that
  962. // the odds of this failing are so rare, it must be because
  963. // the OS we're running the client on doesn't support * in
  964. // filenames (like windows). So, instead of failing the test
  965. // just let it pass. Then we don't need to explicitly
  966. // say which OSs this works on or not.
  967. return
  968. }
  969. defer ctx.Close()
  970. _, err = buildImageFromContext(name, ctx, true)
  971. if err != nil {
  972. c.Fatalf("should have built: %q", err)
  973. }
  974. }
  975. func (s *DockerSuite) TestBuildCopyWildcardCache(c *check.C) {
  976. name := "testcopywildcardcache"
  977. ctx, err := fakeContext(`FROM busybox
  978. COPY file1.txt /tmp/`,
  979. map[string]string{
  980. "file1.txt": "test1",
  981. })
  982. defer ctx.Close()
  983. if err != nil {
  984. c.Fatal(err)
  985. }
  986. id1, err := buildImageFromContext(name, ctx, true)
  987. if err != nil {
  988. c.Fatal(err)
  989. }
  990. // Now make sure we use a cache the 2nd time even with wild cards.
  991. // Use the same context so the file is the same and the checksum will match
  992. ctx.Add("Dockerfile", `FROM busybox
  993. COPY file*.txt /tmp/`)
  994. id2, err := buildImageFromContext(name, ctx, true)
  995. if err != nil {
  996. c.Fatal(err)
  997. }
  998. if id1 != id2 {
  999. c.Fatal("didn't use the cache")
  1000. }
  1001. }
  1002. func (s *DockerSuite) TestBuildAddSingleFileToNonExistingDir(c *check.C) {
  1003. name := "testaddsinglefiletononexistingdir"
  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_file /test_dir/
  1010. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  1011. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  1012. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
  1013. map[string]string{
  1014. "test_file": "test1",
  1015. })
  1016. if err != nil {
  1017. c.Fatal(err)
  1018. }
  1019. defer ctx.Close()
  1020. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1021. c.Fatal(err)
  1022. }
  1023. }
  1024. func (s *DockerSuite) TestBuildAddDirContentToRoot(c *check.C) {
  1025. name := "testadddircontenttoroot"
  1026. ctx, err := fakeContext(`FROM busybox
  1027. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1028. RUN echo 'dockerio:x:1001:' >> /etc/group
  1029. RUN touch /exists
  1030. RUN chown dockerio.dockerio exists
  1031. ADD test_dir /
  1032. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  1033. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
  1034. map[string]string{
  1035. "test_dir/test_file": "test1",
  1036. })
  1037. if err != nil {
  1038. c.Fatal(err)
  1039. }
  1040. defer ctx.Close()
  1041. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1042. c.Fatal(err)
  1043. }
  1044. }
  1045. func (s *DockerSuite) TestBuildAddDirContentToExistingDir(c *check.C) {
  1046. name := "testadddircontenttoexistingdir"
  1047. ctx, err := fakeContext(`FROM busybox
  1048. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1049. RUN echo 'dockerio:x:1001:' >> /etc/group
  1050. RUN mkdir /exists
  1051. RUN touch /exists/exists_file
  1052. RUN chown -R dockerio.dockerio /exists
  1053. ADD test_dir/ /exists/
  1054. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  1055. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  1056. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]`,
  1057. map[string]string{
  1058. "test_dir/test_file": "test1",
  1059. })
  1060. if err != nil {
  1061. c.Fatal(err)
  1062. }
  1063. defer ctx.Close()
  1064. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1065. c.Fatal(err)
  1066. }
  1067. }
  1068. func (s *DockerSuite) TestBuildAddWholeDirToRoot(c *check.C) {
  1069. name := "testaddwholedirtoroot"
  1070. ctx, err := fakeContext(fmt.Sprintf(`FROM busybox
  1071. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1072. RUN echo 'dockerio:x:1001:' >> /etc/group
  1073. RUN touch /exists
  1074. RUN chown dockerio.dockerio exists
  1075. ADD test_dir /test_dir
  1076. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  1077. RUN [ $(ls -l / | grep test_dir | awk '{print $1}') = 'drwxr-xr-x' ]
  1078. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  1079. RUN [ $(ls -l /test_dir/test_file | awk '{print $1}') = '%s' ]
  1080. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod),
  1081. map[string]string{
  1082. "test_dir/test_file": "test1",
  1083. })
  1084. if err != nil {
  1085. c.Fatal(err)
  1086. }
  1087. defer ctx.Close()
  1088. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1089. c.Fatal(err)
  1090. }
  1091. }
  1092. // Testing #5941
  1093. func (s *DockerSuite) TestBuildAddEtcToRoot(c *check.C) {
  1094. name := "testaddetctoroot"
  1095. ctx, err := fakeContext(`FROM scratch
  1096. ADD . /`,
  1097. map[string]string{
  1098. "etc/test_file": "test1",
  1099. })
  1100. if err != nil {
  1101. c.Fatal(err)
  1102. }
  1103. defer ctx.Close()
  1104. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1105. c.Fatal(err)
  1106. }
  1107. }
  1108. // Testing #9401
  1109. func (s *DockerSuite) TestBuildAddPreservesFilesSpecialBits(c *check.C) {
  1110. name := "testaddpreservesfilesspecialbits"
  1111. ctx, err := fakeContext(`FROM busybox
  1112. ADD suidbin /usr/bin/suidbin
  1113. RUN chmod 4755 /usr/bin/suidbin
  1114. RUN [ $(ls -l /usr/bin/suidbin | awk '{print $1}') = '-rwsr-xr-x' ]
  1115. ADD ./data/ /
  1116. RUN [ $(ls -l /usr/bin/suidbin | awk '{print $1}') = '-rwsr-xr-x' ]`,
  1117. map[string]string{
  1118. "suidbin": "suidbin",
  1119. "/data/usr/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. func (s *DockerSuite) TestBuildCopySingleFileToRoot(c *check.C) {
  1130. name := "testcopysinglefiletoroot"
  1131. ctx, err := fakeContext(fmt.Sprintf(`FROM busybox
  1132. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1133. RUN echo 'dockerio:x:1001:' >> /etc/group
  1134. RUN touch /exists
  1135. RUN chown dockerio.dockerio /exists
  1136. COPY test_file /
  1137. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  1138. RUN [ $(ls -l /test_file | awk '{print $1}') = '%s' ]
  1139. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod),
  1140. map[string]string{
  1141. "test_file": "test1",
  1142. })
  1143. if err != nil {
  1144. c.Fatal(err)
  1145. }
  1146. defer ctx.Close()
  1147. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1148. c.Fatal(err)
  1149. }
  1150. }
  1151. // Issue #3960: "ADD src ." hangs - adapted for COPY
  1152. func (s *DockerSuite) TestBuildCopySingleFileToWorkdir(c *check.C) {
  1153. name := "testcopysinglefiletoworkdir"
  1154. ctx, err := fakeContext(`FROM busybox
  1155. COPY test_file .`,
  1156. map[string]string{
  1157. "test_file": "test1",
  1158. })
  1159. if err != nil {
  1160. c.Fatal(err)
  1161. }
  1162. defer ctx.Close()
  1163. errChan := make(chan error)
  1164. go func() {
  1165. _, err := buildImageFromContext(name, ctx, true)
  1166. errChan <- err
  1167. close(errChan)
  1168. }()
  1169. select {
  1170. case <-time.After(5 * time.Second):
  1171. c.Fatal("Build with adding to workdir timed out")
  1172. case err := <-errChan:
  1173. c.Assert(err, check.IsNil)
  1174. }
  1175. }
  1176. func (s *DockerSuite) TestBuildCopySingleFileToExistDir(c *check.C) {
  1177. name := "testcopysinglefiletoexistdir"
  1178. ctx, err := fakeContext(`FROM busybox
  1179. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1180. RUN echo 'dockerio:x:1001:' >> /etc/group
  1181. RUN mkdir /exists
  1182. RUN touch /exists/exists_file
  1183. RUN chown -R dockerio.dockerio /exists
  1184. COPY test_file /exists/
  1185. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  1186. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]
  1187. RUN [ $(ls -l /exists/exists_file | 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) TestBuildCopySingleFileToNonExistDir(c *check.C) {
  1200. name := "testcopysinglefiletononexistdir"
  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_file /test_dir/
  1207. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  1208. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  1209. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
  1210. map[string]string{
  1211. "test_file": "test1",
  1212. })
  1213. if err != nil {
  1214. c.Fatal(err)
  1215. }
  1216. defer ctx.Close()
  1217. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1218. c.Fatal(err)
  1219. }
  1220. }
  1221. func (s *DockerSuite) TestBuildCopyDirContentToRoot(c *check.C) {
  1222. name := "testcopydircontenttoroot"
  1223. ctx, err := fakeContext(`FROM busybox
  1224. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1225. RUN echo 'dockerio:x:1001:' >> /etc/group
  1226. RUN touch /exists
  1227. RUN chown dockerio.dockerio exists
  1228. COPY test_dir /
  1229. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  1230. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
  1231. map[string]string{
  1232. "test_dir/test_file": "test1",
  1233. })
  1234. if err != nil {
  1235. c.Fatal(err)
  1236. }
  1237. defer ctx.Close()
  1238. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1239. c.Fatal(err)
  1240. }
  1241. }
  1242. func (s *DockerSuite) TestBuildCopyDirContentToExistDir(c *check.C) {
  1243. name := "testcopydircontenttoexistdir"
  1244. ctx, err := fakeContext(`FROM busybox
  1245. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1246. RUN echo 'dockerio:x:1001:' >> /etc/group
  1247. RUN mkdir /exists
  1248. RUN touch /exists/exists_file
  1249. RUN chown -R dockerio.dockerio /exists
  1250. COPY test_dir/ /exists/
  1251. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  1252. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  1253. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]`,
  1254. map[string]string{
  1255. "test_dir/test_file": "test1",
  1256. })
  1257. if err != nil {
  1258. c.Fatal(err)
  1259. }
  1260. defer ctx.Close()
  1261. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1262. c.Fatal(err)
  1263. }
  1264. }
  1265. func (s *DockerSuite) TestBuildCopyWholeDirToRoot(c *check.C) {
  1266. name := "testcopywholedirtoroot"
  1267. ctx, err := fakeContext(fmt.Sprintf(`FROM busybox
  1268. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1269. RUN echo 'dockerio:x:1001:' >> /etc/group
  1270. RUN touch /exists
  1271. RUN chown dockerio.dockerio exists
  1272. COPY test_dir /test_dir
  1273. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  1274. RUN [ $(ls -l / | grep test_dir | awk '{print $1}') = 'drwxr-xr-x' ]
  1275. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  1276. RUN [ $(ls -l /test_dir/test_file | awk '{print $1}') = '%s' ]
  1277. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod),
  1278. map[string]string{
  1279. "test_dir/test_file": "test1",
  1280. })
  1281. if err != nil {
  1282. c.Fatal(err)
  1283. }
  1284. defer ctx.Close()
  1285. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1286. c.Fatal(err)
  1287. }
  1288. }
  1289. func (s *DockerSuite) TestBuildCopyEtcToRoot(c *check.C) {
  1290. name := "testcopyetctoroot"
  1291. ctx, err := fakeContext(`FROM scratch
  1292. COPY . /`,
  1293. map[string]string{
  1294. "etc/test_file": "test1",
  1295. })
  1296. if err != nil {
  1297. c.Fatal(err)
  1298. }
  1299. defer ctx.Close()
  1300. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1301. c.Fatal(err)
  1302. }
  1303. }
  1304. func (s *DockerSuite) TestBuildCopyDisallowRemote(c *check.C) {
  1305. name := "testcopydisallowremote"
  1306. _, out, err := buildImageWithOut(name, `FROM scratch
  1307. COPY https://index.docker.io/robots.txt /`,
  1308. true)
  1309. if err == nil || !strings.Contains(out, "Source can't be a URL for COPY") {
  1310. c.Fatalf("Error should be about disallowed remote source, got err: %s, out: %q", err, out)
  1311. }
  1312. }
  1313. func (s *DockerSuite) TestBuildAddBadLinks(c *check.C) {
  1314. const (
  1315. dockerfile = `
  1316. FROM scratch
  1317. ADD links.tar /
  1318. ADD foo.txt /symlink/
  1319. `
  1320. targetFile = "foo.txt"
  1321. )
  1322. var (
  1323. name = "test-link-absolute"
  1324. )
  1325. ctx, err := fakeContext(dockerfile, nil)
  1326. if err != nil {
  1327. c.Fatal(err)
  1328. }
  1329. defer ctx.Close()
  1330. tempDir, err := ioutil.TempDir("", "test-link-absolute-temp-")
  1331. if err != nil {
  1332. c.Fatalf("failed to create temporary directory: %s", tempDir)
  1333. }
  1334. defer os.RemoveAll(tempDir)
  1335. var symlinkTarget string
  1336. if runtime.GOOS == "windows" {
  1337. var driveLetter string
  1338. if abs, err := filepath.Abs(tempDir); err != nil {
  1339. c.Fatal(err)
  1340. } else {
  1341. driveLetter = abs[:1]
  1342. }
  1343. tempDirWithoutDrive := tempDir[2:]
  1344. symlinkTarget = fmt.Sprintf(`%s:\..\..\..\..\..\..\..\..\..\..\..\..%s`, driveLetter, tempDirWithoutDrive)
  1345. } else {
  1346. symlinkTarget = fmt.Sprintf("/../../../../../../../../../../../..%s", tempDir)
  1347. }
  1348. tarPath := filepath.Join(ctx.Dir, "links.tar")
  1349. nonExistingFile := filepath.Join(tempDir, targetFile)
  1350. fooPath := filepath.Join(ctx.Dir, targetFile)
  1351. tarOut, err := os.Create(tarPath)
  1352. if err != nil {
  1353. c.Fatal(err)
  1354. }
  1355. tarWriter := tar.NewWriter(tarOut)
  1356. header := &tar.Header{
  1357. Name: "symlink",
  1358. Typeflag: tar.TypeSymlink,
  1359. Linkname: symlinkTarget,
  1360. Mode: 0755,
  1361. Uid: 0,
  1362. Gid: 0,
  1363. }
  1364. err = tarWriter.WriteHeader(header)
  1365. if err != nil {
  1366. c.Fatal(err)
  1367. }
  1368. tarWriter.Close()
  1369. tarOut.Close()
  1370. foo, err := os.Create(fooPath)
  1371. if err != nil {
  1372. c.Fatal(err)
  1373. }
  1374. defer foo.Close()
  1375. if _, err := foo.WriteString("test"); err != nil {
  1376. c.Fatal(err)
  1377. }
  1378. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1379. c.Fatal(err)
  1380. }
  1381. if _, err := os.Stat(nonExistingFile); err == nil || err != nil && !os.IsNotExist(err) {
  1382. c.Fatalf("%s shouldn't have been written and it shouldn't exist", nonExistingFile)
  1383. }
  1384. }
  1385. func (s *DockerSuite) TestBuildAddBadLinksVolume(c *check.C) {
  1386. const (
  1387. dockerfileTemplate = `
  1388. FROM busybox
  1389. RUN ln -s /../../../../../../../../%s /x
  1390. VOLUME /x
  1391. ADD foo.txt /x/`
  1392. targetFile = "foo.txt"
  1393. )
  1394. var (
  1395. name = "test-link-absolute-volume"
  1396. dockerfile = ""
  1397. )
  1398. tempDir, err := ioutil.TempDir("", "test-link-absolute-volume-temp-")
  1399. if err != nil {
  1400. c.Fatalf("failed to create temporary directory: %s", tempDir)
  1401. }
  1402. defer os.RemoveAll(tempDir)
  1403. dockerfile = fmt.Sprintf(dockerfileTemplate, tempDir)
  1404. nonExistingFile := filepath.Join(tempDir, targetFile)
  1405. ctx, err := fakeContext(dockerfile, nil)
  1406. if err != nil {
  1407. c.Fatal(err)
  1408. }
  1409. defer ctx.Close()
  1410. fooPath := filepath.Join(ctx.Dir, targetFile)
  1411. foo, err := os.Create(fooPath)
  1412. if err != nil {
  1413. c.Fatal(err)
  1414. }
  1415. defer foo.Close()
  1416. if _, err := foo.WriteString("test"); err != nil {
  1417. c.Fatal(err)
  1418. }
  1419. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1420. c.Fatal(err)
  1421. }
  1422. if _, err := os.Stat(nonExistingFile); err == nil || err != nil && !os.IsNotExist(err) {
  1423. c.Fatalf("%s shouldn't have been written and it shouldn't exist", nonExistingFile)
  1424. }
  1425. }
  1426. // Issue #5270 - ensure we throw a better error than "unexpected EOF"
  1427. // when we can't access files in the context.
  1428. func (s *DockerSuite) TestBuildWithInaccessibleFilesInContext(c *check.C) {
  1429. testRequires(c, UnixCli) // test uses chown/chmod: not available on windows
  1430. {
  1431. name := "testbuildinaccessiblefiles"
  1432. ctx, err := fakeContext("FROM scratch\nADD . /foo/", map[string]string{"fileWithoutReadAccess": "foo"})
  1433. if err != nil {
  1434. c.Fatal(err)
  1435. }
  1436. defer ctx.Close()
  1437. // This is used to ensure we detect inaccessible files early during build in the cli client
  1438. pathToFileWithoutReadAccess := filepath.Join(ctx.Dir, "fileWithoutReadAccess")
  1439. if err = os.Chown(pathToFileWithoutReadAccess, 0, 0); err != nil {
  1440. c.Fatalf("failed to chown file to root: %s", err)
  1441. }
  1442. if err = os.Chmod(pathToFileWithoutReadAccess, 0700); err != nil {
  1443. c.Fatalf("failed to chmod file to 700: %s", err)
  1444. }
  1445. buildCmd := exec.Command("su", "unprivilegeduser", "-c", fmt.Sprintf("%s build -t %s .", dockerBinary, name))
  1446. buildCmd.Dir = ctx.Dir
  1447. out, _, err := runCommandWithOutput(buildCmd)
  1448. if err == nil {
  1449. c.Fatalf("build should have failed: %s %s", err, out)
  1450. }
  1451. // check if we've detected the failure before we started building
  1452. if !strings.Contains(out, "no permission to read from ") {
  1453. c.Fatalf("output should've contained the string: no permission to read from but contained: %s", out)
  1454. }
  1455. if !strings.Contains(out, "Error checking context") {
  1456. c.Fatalf("output should've contained the string: Error checking context")
  1457. }
  1458. }
  1459. {
  1460. name := "testbuildinaccessibledirectory"
  1461. ctx, err := fakeContext("FROM scratch\nADD . /foo/", map[string]string{"directoryWeCantStat/bar": "foo"})
  1462. if err != nil {
  1463. c.Fatal(err)
  1464. }
  1465. defer ctx.Close()
  1466. // This is used to ensure we detect inaccessible directories early during build in the cli client
  1467. pathToDirectoryWithoutReadAccess := filepath.Join(ctx.Dir, "directoryWeCantStat")
  1468. pathToFileInDirectoryWithoutReadAccess := filepath.Join(pathToDirectoryWithoutReadAccess, "bar")
  1469. if err = os.Chown(pathToDirectoryWithoutReadAccess, 0, 0); err != nil {
  1470. c.Fatalf("failed to chown directory to root: %s", err)
  1471. }
  1472. if err = os.Chmod(pathToDirectoryWithoutReadAccess, 0444); err != nil {
  1473. c.Fatalf("failed to chmod directory to 444: %s", err)
  1474. }
  1475. if err = os.Chmod(pathToFileInDirectoryWithoutReadAccess, 0700); err != nil {
  1476. c.Fatalf("failed to chmod file to 700: %s", err)
  1477. }
  1478. buildCmd := exec.Command("su", "unprivilegeduser", "-c", fmt.Sprintf("%s build -t %s .", dockerBinary, name))
  1479. buildCmd.Dir = ctx.Dir
  1480. out, _, err := runCommandWithOutput(buildCmd)
  1481. if err == nil {
  1482. c.Fatalf("build should have failed: %s %s", err, out)
  1483. }
  1484. // check if we've detected the failure before we started building
  1485. if !strings.Contains(out, "can't stat") {
  1486. c.Fatalf("output should've contained the string: can't access %s", out)
  1487. }
  1488. if !strings.Contains(out, "Error checking context") {
  1489. c.Fatalf("output should've contained the string: Error checking context\ngot:%s", out)
  1490. }
  1491. }
  1492. {
  1493. name := "testlinksok"
  1494. ctx, err := fakeContext("FROM scratch\nADD . /foo/", nil)
  1495. if err != nil {
  1496. c.Fatal(err)
  1497. }
  1498. defer ctx.Close()
  1499. target := "../../../../../../../../../../../../../../../../../../../azA"
  1500. if err := os.Symlink(filepath.Join(ctx.Dir, "g"), target); err != nil {
  1501. c.Fatal(err)
  1502. }
  1503. defer os.Remove(target)
  1504. // This is used to ensure we don't follow links when checking if everything in the context is accessible
  1505. // This test doesn't require that we run commands as an unprivileged user
  1506. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1507. c.Fatal(err)
  1508. }
  1509. }
  1510. {
  1511. name := "testbuildignoredinaccessible"
  1512. ctx, err := fakeContext("FROM scratch\nADD . /foo/",
  1513. map[string]string{
  1514. "directoryWeCantStat/bar": "foo",
  1515. ".dockerignore": "directoryWeCantStat",
  1516. })
  1517. if err != nil {
  1518. c.Fatal(err)
  1519. }
  1520. defer ctx.Close()
  1521. // This is used to ensure we don't try to add inaccessible files when they are ignored by a .dockerignore pattern
  1522. pathToDirectoryWithoutReadAccess := filepath.Join(ctx.Dir, "directoryWeCantStat")
  1523. pathToFileInDirectoryWithoutReadAccess := filepath.Join(pathToDirectoryWithoutReadAccess, "bar")
  1524. if err = os.Chown(pathToDirectoryWithoutReadAccess, 0, 0); err != nil {
  1525. c.Fatalf("failed to chown directory to root: %s", err)
  1526. }
  1527. if err = os.Chmod(pathToDirectoryWithoutReadAccess, 0444); err != nil {
  1528. c.Fatalf("failed to chmod directory to 755: %s", err)
  1529. }
  1530. if err = os.Chmod(pathToFileInDirectoryWithoutReadAccess, 0700); err != nil {
  1531. c.Fatalf("failed to chmod file to 444: %s", err)
  1532. }
  1533. buildCmd := exec.Command("su", "unprivilegeduser", "-c", fmt.Sprintf("%s build -t %s .", dockerBinary, name))
  1534. buildCmd.Dir = ctx.Dir
  1535. if out, _, err := runCommandWithOutput(buildCmd); err != nil {
  1536. c.Fatalf("build should have worked: %s %s", err, out)
  1537. }
  1538. }
  1539. }
  1540. func (s *DockerSuite) TestBuildForceRm(c *check.C) {
  1541. containerCountBefore, err := getContainerCount()
  1542. if err != nil {
  1543. c.Fatalf("failed to get the container count: %s", err)
  1544. }
  1545. name := "testbuildforcerm"
  1546. ctx, err := fakeContext("FROM scratch\nRUN true\nRUN thiswillfail", nil)
  1547. if err != nil {
  1548. c.Fatal(err)
  1549. }
  1550. defer ctx.Close()
  1551. buildCmd := exec.Command(dockerBinary, "build", "-t", name, "--force-rm", ".")
  1552. buildCmd.Dir = ctx.Dir
  1553. if out, _, err := runCommandWithOutput(buildCmd); err == nil {
  1554. c.Fatalf("failed to build the image: %s, %v", out, err)
  1555. }
  1556. containerCountAfter, err := getContainerCount()
  1557. if err != nil {
  1558. c.Fatalf("failed to get the container count: %s", err)
  1559. }
  1560. if containerCountBefore != containerCountAfter {
  1561. c.Fatalf("--force-rm shouldn't have left containers behind")
  1562. }
  1563. }
  1564. // Test that an infinite sleep during a build is killed if the client disconnects.
  1565. // This test is fairly hairy because there are lots of ways to race.
  1566. // Strategy:
  1567. // * Monitor the output of docker events starting from before
  1568. // * Run a 1-year-long sleep from a docker build.
  1569. // * When docker events sees container start, close the "docker build" command
  1570. // * Wait for docker events to emit a dying event.
  1571. func (s *DockerSuite) TestBuildCancelationKillsSleep(c *check.C) {
  1572. name := "testbuildcancelation"
  1573. // (Note: one year, will never finish)
  1574. ctx, err := fakeContext("FROM busybox\nRUN sleep 31536000", nil)
  1575. if err != nil {
  1576. c.Fatal(err)
  1577. }
  1578. defer ctx.Close()
  1579. finish := make(chan struct{})
  1580. defer close(finish)
  1581. eventStart := make(chan struct{})
  1582. eventDie := make(chan struct{})
  1583. containerID := make(chan string)
  1584. startEpoch := daemonTime(c).Unix()
  1585. // Watch for events since epoch.
  1586. eventsCmd := exec.Command(
  1587. dockerBinary, "events",
  1588. "--since", strconv.FormatInt(startEpoch, 10))
  1589. stdout, err := eventsCmd.StdoutPipe()
  1590. if err != nil {
  1591. c.Fatal(err)
  1592. }
  1593. if err := eventsCmd.Start(); err != nil {
  1594. c.Fatal(err)
  1595. }
  1596. defer eventsCmd.Process.Kill()
  1597. // Goroutine responsible for watching start/die events from `docker events`
  1598. go func() {
  1599. cid := <-containerID
  1600. matchStart := regexp.MustCompile(cid + `(.*) start$`)
  1601. matchDie := regexp.MustCompile(cid + `(.*) die$`)
  1602. //
  1603. // Read lines of `docker events` looking for container start and stop.
  1604. //
  1605. scanner := bufio.NewScanner(stdout)
  1606. for scanner.Scan() {
  1607. switch {
  1608. case matchStart.MatchString(scanner.Text()):
  1609. close(eventStart)
  1610. case matchDie.MatchString(scanner.Text()):
  1611. close(eventDie)
  1612. }
  1613. }
  1614. }()
  1615. buildCmd := exec.Command(dockerBinary, "build", "-t", name, ".")
  1616. buildCmd.Dir = ctx.Dir
  1617. stdoutBuild, err := buildCmd.StdoutPipe()
  1618. if err := buildCmd.Start(); err != nil {
  1619. c.Fatalf("failed to run build: %s", err)
  1620. }
  1621. matchCID := regexp.MustCompile("Running in ")
  1622. scanner := bufio.NewScanner(stdoutBuild)
  1623. for scanner.Scan() {
  1624. line := scanner.Text()
  1625. if ok := matchCID.MatchString(line); ok {
  1626. containerID <- line[len(line)-12:]
  1627. break
  1628. }
  1629. }
  1630. select {
  1631. case <-time.After(5 * time.Second):
  1632. c.Fatal("failed to observe build container start in timely fashion")
  1633. case <-eventStart:
  1634. // Proceeds from here when we see the container fly past in the
  1635. // output of "docker events".
  1636. // Now we know the container is running.
  1637. }
  1638. // Send a kill to the `docker build` command.
  1639. // Causes the underlying build to be cancelled due to socket close.
  1640. if err := buildCmd.Process.Kill(); err != nil {
  1641. c.Fatalf("error killing build command: %s", err)
  1642. }
  1643. // Get the exit status of `docker build`, check it exited because killed.
  1644. if err := buildCmd.Wait(); err != nil && !IsKilled(err) {
  1645. c.Fatalf("wait failed during build run: %T %s", err, err)
  1646. }
  1647. select {
  1648. case <-time.After(5 * time.Second):
  1649. // If we don't get here in a timely fashion, it wasn't killed.
  1650. c.Fatal("container cancel did not succeed")
  1651. case <-eventDie:
  1652. // We saw the container shut down in the `docker events` stream,
  1653. // as expected.
  1654. }
  1655. }
  1656. func (s *DockerSuite) TestBuildRm(c *check.C) {
  1657. name := "testbuildrm"
  1658. ctx, err := fakeContext("FROM scratch\nADD foo /\nADD foo /", map[string]string{"foo": "bar"})
  1659. if err != nil {
  1660. c.Fatal(err)
  1661. }
  1662. defer ctx.Close()
  1663. {
  1664. containerCountBefore, err := getContainerCount()
  1665. if err != nil {
  1666. c.Fatalf("failed to get the container count: %s", err)
  1667. }
  1668. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "--rm", "-t", name, ".")
  1669. if err != nil {
  1670. c.Fatal("failed to build the image", out)
  1671. }
  1672. containerCountAfter, err := getContainerCount()
  1673. if err != nil {
  1674. c.Fatalf("failed to get the container count: %s", err)
  1675. }
  1676. if containerCountBefore != containerCountAfter {
  1677. c.Fatalf("-rm shouldn't have left containers behind")
  1678. }
  1679. deleteImages(name)
  1680. }
  1681. {
  1682. containerCountBefore, err := getContainerCount()
  1683. if err != nil {
  1684. c.Fatalf("failed to get the container count: %s", err)
  1685. }
  1686. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", name, ".")
  1687. if err != nil {
  1688. c.Fatal("failed to build the image", out)
  1689. }
  1690. containerCountAfter, err := getContainerCount()
  1691. if err != nil {
  1692. c.Fatalf("failed to get the container count: %s", err)
  1693. }
  1694. if containerCountBefore != containerCountAfter {
  1695. c.Fatalf("--rm shouldn't have left containers behind")
  1696. }
  1697. deleteImages(name)
  1698. }
  1699. {
  1700. containerCountBefore, err := getContainerCount()
  1701. if err != nil {
  1702. c.Fatalf("failed to get the container count: %s", err)
  1703. }
  1704. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "--rm=false", "-t", name, ".")
  1705. if err != nil {
  1706. c.Fatal("failed to build the image", out)
  1707. }
  1708. containerCountAfter, err := getContainerCount()
  1709. if err != nil {
  1710. c.Fatalf("failed to get the container count: %s", err)
  1711. }
  1712. if containerCountBefore == containerCountAfter {
  1713. c.Fatalf("--rm=false should have left containers behind")
  1714. }
  1715. deleteImages(name)
  1716. }
  1717. }
  1718. func (s *DockerSuite) TestBuildWithVolumes(c *check.C) {
  1719. var (
  1720. result map[string]map[string]struct{}
  1721. name = "testbuildvolumes"
  1722. emptyMap = make(map[string]struct{})
  1723. expected = map[string]map[string]struct{}{
  1724. "/test1": emptyMap,
  1725. "/test2": emptyMap,
  1726. "/test3": emptyMap,
  1727. "/test4": emptyMap,
  1728. "/test5": emptyMap,
  1729. "/test6": emptyMap,
  1730. "[/test7": emptyMap,
  1731. "/test8]": emptyMap,
  1732. }
  1733. )
  1734. _, err := buildImage(name,
  1735. `FROM scratch
  1736. VOLUME /test1
  1737. VOLUME /test2
  1738. VOLUME /test3 /test4
  1739. VOLUME ["/test5", "/test6"]
  1740. VOLUME [/test7 /test8]
  1741. `,
  1742. true)
  1743. if err != nil {
  1744. c.Fatal(err)
  1745. }
  1746. res, err := inspectFieldJSON(name, "Config.Volumes")
  1747. if err != nil {
  1748. c.Fatal(err)
  1749. }
  1750. err = unmarshalJSON([]byte(res), &result)
  1751. if err != nil {
  1752. c.Fatal(err)
  1753. }
  1754. equal := reflect.DeepEqual(&result, &expected)
  1755. if !equal {
  1756. c.Fatalf("Volumes %s, expected %s", result, expected)
  1757. }
  1758. }
  1759. func (s *DockerSuite) TestBuildMaintainer(c *check.C) {
  1760. name := "testbuildmaintainer"
  1761. expected := "dockerio"
  1762. _, err := buildImage(name,
  1763. `FROM scratch
  1764. MAINTAINER dockerio`,
  1765. true)
  1766. if err != nil {
  1767. c.Fatal(err)
  1768. }
  1769. res, err := inspectField(name, "Author")
  1770. if err != nil {
  1771. c.Fatal(err)
  1772. }
  1773. if res != expected {
  1774. c.Fatalf("Maintainer %s, expected %s", res, expected)
  1775. }
  1776. }
  1777. func (s *DockerSuite) TestBuildUser(c *check.C) {
  1778. name := "testbuilduser"
  1779. expected := "dockerio"
  1780. _, err := buildImage(name,
  1781. `FROM busybox
  1782. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1783. USER dockerio
  1784. RUN [ $(whoami) = 'dockerio' ]`,
  1785. true)
  1786. if err != nil {
  1787. c.Fatal(err)
  1788. }
  1789. res, err := inspectField(name, "Config.User")
  1790. if err != nil {
  1791. c.Fatal(err)
  1792. }
  1793. if res != expected {
  1794. c.Fatalf("User %s, expected %s", res, expected)
  1795. }
  1796. }
  1797. func (s *DockerSuite) TestBuildRelativeWorkdir(c *check.C) {
  1798. name := "testbuildrelativeworkdir"
  1799. expected := "/test2/test3"
  1800. _, err := buildImage(name,
  1801. `FROM busybox
  1802. RUN [ "$PWD" = '/' ]
  1803. WORKDIR test1
  1804. RUN [ "$PWD" = '/test1' ]
  1805. WORKDIR /test2
  1806. RUN [ "$PWD" = '/test2' ]
  1807. WORKDIR test3
  1808. RUN [ "$PWD" = '/test2/test3' ]`,
  1809. true)
  1810. if err != nil {
  1811. c.Fatal(err)
  1812. }
  1813. res, err := inspectField(name, "Config.WorkingDir")
  1814. if err != nil {
  1815. c.Fatal(err)
  1816. }
  1817. if res != expected {
  1818. c.Fatalf("Workdir %s, expected %s", res, expected)
  1819. }
  1820. }
  1821. func (s *DockerSuite) TestBuildWorkdirWithEnvVariables(c *check.C) {
  1822. name := "testbuildworkdirwithenvvariables"
  1823. expected := "/test1/test2"
  1824. _, err := buildImage(name,
  1825. `FROM busybox
  1826. ENV DIRPATH /test1
  1827. ENV SUBDIRNAME test2
  1828. WORKDIR $DIRPATH
  1829. WORKDIR $SUBDIRNAME/$MISSING_VAR`,
  1830. true)
  1831. if err != nil {
  1832. c.Fatal(err)
  1833. }
  1834. res, err := inspectField(name, "Config.WorkingDir")
  1835. if err != nil {
  1836. c.Fatal(err)
  1837. }
  1838. if res != expected {
  1839. c.Fatalf("Workdir %s, expected %s", res, expected)
  1840. }
  1841. }
  1842. func (s *DockerSuite) TestBuildRelativeCopy(c *check.C) {
  1843. name := "testbuildrelativecopy"
  1844. dockerfile := `
  1845. FROM busybox
  1846. WORKDIR /test1
  1847. WORKDIR test2
  1848. RUN [ "$PWD" = '/test1/test2' ]
  1849. COPY foo ./
  1850. RUN [ "$(cat /test1/test2/foo)" = 'hello' ]
  1851. ADD foo ./bar/baz
  1852. RUN [ "$(cat /test1/test2/bar/baz)" = 'hello' ]
  1853. COPY foo ./bar/baz2
  1854. RUN [ "$(cat /test1/test2/bar/baz2)" = 'hello' ]
  1855. WORKDIR ..
  1856. COPY foo ./
  1857. RUN [ "$(cat /test1/foo)" = 'hello' ]
  1858. COPY foo /test3/
  1859. RUN [ "$(cat /test3/foo)" = 'hello' ]
  1860. WORKDIR /test4
  1861. COPY . .
  1862. RUN [ "$(cat /test4/foo)" = 'hello' ]
  1863. WORKDIR /test5/test6
  1864. COPY foo ../
  1865. RUN [ "$(cat /test5/foo)" = 'hello' ]
  1866. `
  1867. ctx, err := fakeContext(dockerfile, map[string]string{
  1868. "foo": "hello",
  1869. })
  1870. defer ctx.Close()
  1871. if err != nil {
  1872. c.Fatal(err)
  1873. }
  1874. _, err = buildImageFromContext(name, ctx, false)
  1875. if err != nil {
  1876. c.Fatal(err)
  1877. }
  1878. }
  1879. func (s *DockerSuite) TestBuildEnv(c *check.C) {
  1880. name := "testbuildenv"
  1881. expected := "[PATH=/test:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin PORT=2375]"
  1882. _, err := buildImage(name,
  1883. `FROM busybox
  1884. ENV PATH /test:$PATH
  1885. ENV PORT 2375
  1886. RUN [ $(env | grep PORT) = 'PORT=2375' ]`,
  1887. true)
  1888. if err != nil {
  1889. c.Fatal(err)
  1890. }
  1891. res, err := inspectField(name, "Config.Env")
  1892. if err != nil {
  1893. c.Fatal(err)
  1894. }
  1895. if res != expected {
  1896. c.Fatalf("Env %s, expected %s", res, expected)
  1897. }
  1898. }
  1899. func (s *DockerSuite) TestBuildContextCleanup(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. ENTRYPOINT ["/bin/echo"]`,
  1909. true)
  1910. if err != nil {
  1911. c.Fatal(err)
  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) TestBuildContextCleanupFailedBuild(c *check.C) {
  1922. testRequires(c, SameHostDaemon)
  1923. name := "testbuildcontextcleanup"
  1924. entries, err := ioutil.ReadDir("/var/lib/docker/tmp")
  1925. if err != nil {
  1926. c.Fatalf("failed to list contents of tmp dir: %s", err)
  1927. }
  1928. _, err = buildImage(name,
  1929. `FROM scratch
  1930. RUN /non/existing/command`,
  1931. true)
  1932. if err == nil {
  1933. c.Fatalf("expected build to fail, but it didn't")
  1934. }
  1935. entriesFinal, err := ioutil.ReadDir("/var/lib/docker/tmp")
  1936. if err != nil {
  1937. c.Fatalf("failed to list contents of tmp dir: %s", err)
  1938. }
  1939. if err = compareDirectoryEntries(entries, entriesFinal); err != nil {
  1940. c.Fatalf("context should have been deleted, but wasn't")
  1941. }
  1942. }
  1943. func (s *DockerSuite) TestBuildCmd(c *check.C) {
  1944. name := "testbuildcmd"
  1945. expected := "{[/bin/echo Hello World]}"
  1946. _, err := buildImage(name,
  1947. `FROM scratch
  1948. CMD ["/bin/echo", "Hello World"]`,
  1949. true)
  1950. if err != nil {
  1951. c.Fatal(err)
  1952. }
  1953. res, err := inspectField(name, "Config.Cmd")
  1954. if err != nil {
  1955. c.Fatal(err)
  1956. }
  1957. if res != expected {
  1958. c.Fatalf("Cmd %s, expected %s", res, expected)
  1959. }
  1960. }
  1961. func (s *DockerSuite) TestBuildExpose(c *check.C) {
  1962. name := "testbuildexpose"
  1963. expected := "map[2375/tcp:{}]"
  1964. _, err := buildImage(name,
  1965. `FROM scratch
  1966. EXPOSE 2375`,
  1967. true)
  1968. if err != nil {
  1969. c.Fatal(err)
  1970. }
  1971. res, err := inspectField(name, "Config.ExposedPorts")
  1972. if err != nil {
  1973. c.Fatal(err)
  1974. }
  1975. if res != expected {
  1976. c.Fatalf("Exposed ports %s, expected %s", res, expected)
  1977. }
  1978. }
  1979. func (s *DockerSuite) TestBuildExposeMorePorts(c *check.C) {
  1980. // start building docker file with a large number of ports
  1981. portList := make([]string, 50)
  1982. line := make([]string, 100)
  1983. expectedPorts := make([]int, len(portList)*len(line))
  1984. for i := 0; i < len(portList); i++ {
  1985. for j := 0; j < len(line); j++ {
  1986. p := i*len(line) + j + 1
  1987. line[j] = strconv.Itoa(p)
  1988. expectedPorts[p-1] = p
  1989. }
  1990. if i == len(portList)-1 {
  1991. portList[i] = strings.Join(line, " ")
  1992. } else {
  1993. portList[i] = strings.Join(line, " ") + ` \`
  1994. }
  1995. }
  1996. dockerfile := `FROM scratch
  1997. EXPOSE {{range .}} {{.}}
  1998. {{end}}`
  1999. tmpl := template.Must(template.New("dockerfile").Parse(dockerfile))
  2000. buf := bytes.NewBuffer(nil)
  2001. tmpl.Execute(buf, portList)
  2002. name := "testbuildexpose"
  2003. _, err := buildImage(name, buf.String(), true)
  2004. if err != nil {
  2005. c.Fatal(err)
  2006. }
  2007. // check if all the ports are saved inside Config.ExposedPorts
  2008. res, err := inspectFieldJSON(name, "Config.ExposedPorts")
  2009. if err != nil {
  2010. c.Fatal(err)
  2011. }
  2012. var exposedPorts map[string]interface{}
  2013. if err := json.Unmarshal([]byte(res), &exposedPorts); err != nil {
  2014. c.Fatal(err)
  2015. }
  2016. for _, p := range expectedPorts {
  2017. ep := fmt.Sprintf("%d/tcp", p)
  2018. if _, ok := exposedPorts[ep]; !ok {
  2019. c.Errorf("Port(%s) is not exposed", ep)
  2020. } else {
  2021. delete(exposedPorts, ep)
  2022. }
  2023. }
  2024. if len(exposedPorts) != 0 {
  2025. c.Errorf("Unexpected extra exposed ports %v", exposedPorts)
  2026. }
  2027. }
  2028. func (s *DockerSuite) TestBuildExposeOrder(c *check.C) {
  2029. buildID := func(name, exposed string) string {
  2030. _, err := buildImage(name, fmt.Sprintf(`FROM scratch
  2031. EXPOSE %s`, exposed), true)
  2032. if err != nil {
  2033. c.Fatal(err)
  2034. }
  2035. id, err := inspectField(name, "Id")
  2036. if err != nil {
  2037. c.Fatal(err)
  2038. }
  2039. return id
  2040. }
  2041. id1 := buildID("testbuildexpose1", "80 2375")
  2042. id2 := buildID("testbuildexpose2", "2375 80")
  2043. if id1 != id2 {
  2044. c.Errorf("EXPOSE should invalidate the cache only when ports actually changed")
  2045. }
  2046. }
  2047. func (s *DockerSuite) TestBuildExposeUpperCaseProto(c *check.C) {
  2048. name := "testbuildexposeuppercaseproto"
  2049. expected := "map[5678/udp:{}]"
  2050. _, err := buildImage(name,
  2051. `FROM scratch
  2052. EXPOSE 5678/UDP`,
  2053. true)
  2054. if err != nil {
  2055. c.Fatal(err)
  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. dockerfile := `
  2395. FROM scratch
  2396. MAINTAINER dockerio
  2397. ADD . /usr/lib/bla`
  2398. ctx, err := fakeContext(dockerfile, map[string]string{
  2399. "foo": "hello",
  2400. })
  2401. defer ctx.Close()
  2402. if err != nil {
  2403. c.Fatal(err)
  2404. }
  2405. id1, err := buildImageFromContext(name, ctx, true)
  2406. if err != nil {
  2407. c.Fatal(err)
  2408. }
  2409. // Check that adding file invalidate cache of "ADD ."
  2410. if err := ctx.Add("bar", "hello2"); err != nil {
  2411. c.Fatal(err)
  2412. }
  2413. id2, err := buildImageFromContext(name2, ctx, true)
  2414. if err != nil {
  2415. c.Fatal(err)
  2416. }
  2417. if id1 == id2 {
  2418. c.Fatal("The cache should have been invalided but hasn't.")
  2419. }
  2420. // Check that changing file invalidate cache of "ADD ."
  2421. if err := ctx.Add("foo", "hello1"); err != nil {
  2422. c.Fatal(err)
  2423. }
  2424. id3, err := buildImageFromContext(name3, ctx, true)
  2425. if err != nil {
  2426. c.Fatal(err)
  2427. }
  2428. if id2 == id3 {
  2429. c.Fatal("The cache should have been invalided but hasn't.")
  2430. }
  2431. // Check that changing file to same content with different mtime does not
  2432. // 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 used but hasn't.")
  2443. }
  2444. }
  2445. func (s *DockerSuite) TestBuildAddCurrentDirWithoutCache(c *check.C) {
  2446. name := "testbuildaddcurrentdirwithoutcache"
  2447. name2 := "testbuildaddcurrentdirwithoutcache2"
  2448. dockerfile := `
  2449. FROM scratch
  2450. MAINTAINER dockerio
  2451. ADD . /usr/lib/bla`
  2452. ctx, err := fakeContext(dockerfile, map[string]string{
  2453. "foo": "hello",
  2454. })
  2455. defer ctx.Close()
  2456. if err != nil {
  2457. c.Fatal(err)
  2458. }
  2459. id1, err := buildImageFromContext(name, ctx, true)
  2460. if err != nil {
  2461. c.Fatal(err)
  2462. }
  2463. id2, err := buildImageFromContext(name2, ctx, false)
  2464. if err != nil {
  2465. c.Fatal(err)
  2466. }
  2467. if id1 == id2 {
  2468. c.Fatal("The cache should have been invalided but hasn't.")
  2469. }
  2470. }
  2471. func (s *DockerSuite) TestBuildAddRemoteFileWithCache(c *check.C) {
  2472. name := "testbuildaddremotefilewithcache"
  2473. server, err := fakeStorage(map[string]string{
  2474. "baz": "hello",
  2475. })
  2476. if err != nil {
  2477. c.Fatal(err)
  2478. }
  2479. defer server.Close()
  2480. id1, err := buildImage(name,
  2481. fmt.Sprintf(`FROM scratch
  2482. MAINTAINER dockerio
  2483. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2484. true)
  2485. if err != nil {
  2486. c.Fatal(err)
  2487. }
  2488. id2, err := buildImage(name,
  2489. fmt.Sprintf(`FROM scratch
  2490. MAINTAINER dockerio
  2491. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2492. true)
  2493. if err != nil {
  2494. c.Fatal(err)
  2495. }
  2496. if id1 != id2 {
  2497. c.Fatal("The cache should have been used but hasn't.")
  2498. }
  2499. }
  2500. func (s *DockerSuite) TestBuildAddRemoteFileWithoutCache(c *check.C) {
  2501. name := "testbuildaddremotefilewithoutcache"
  2502. name2 := "testbuildaddremotefilewithoutcache2"
  2503. server, err := fakeStorage(map[string]string{
  2504. "baz": "hello",
  2505. })
  2506. if err != nil {
  2507. c.Fatal(err)
  2508. }
  2509. defer server.Close()
  2510. id1, err := buildImage(name,
  2511. fmt.Sprintf(`FROM scratch
  2512. MAINTAINER dockerio
  2513. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2514. true)
  2515. if err != nil {
  2516. c.Fatal(err)
  2517. }
  2518. id2, err := buildImage(name2,
  2519. fmt.Sprintf(`FROM scratch
  2520. MAINTAINER dockerio
  2521. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2522. false)
  2523. if err != nil {
  2524. c.Fatal(err)
  2525. }
  2526. if id1 == id2 {
  2527. c.Fatal("The cache should have been invalided but hasn't.")
  2528. }
  2529. }
  2530. func (s *DockerSuite) TestBuildAddRemoteFileMTime(c *check.C) {
  2531. name := "testbuildaddremotefilemtime"
  2532. name2 := name + "2"
  2533. name3 := name + "3"
  2534. files := map[string]string{"baz": "hello"}
  2535. server, err := fakeStorage(files)
  2536. if err != nil {
  2537. c.Fatal(err)
  2538. }
  2539. defer server.Close()
  2540. ctx, err := fakeContext(fmt.Sprintf(`FROM scratch
  2541. MAINTAINER dockerio
  2542. ADD %s/baz /usr/lib/baz/quux`, server.URL()), nil)
  2543. if err != nil {
  2544. c.Fatal(err)
  2545. }
  2546. defer ctx.Close()
  2547. id1, err := buildImageFromContext(name, ctx, true)
  2548. if err != nil {
  2549. c.Fatal(err)
  2550. }
  2551. id2, err := buildImageFromContext(name2, ctx, true)
  2552. if err != nil {
  2553. c.Fatal(err)
  2554. }
  2555. if id1 != id2 {
  2556. c.Fatal("The cache should have been used but wasn't - #1")
  2557. }
  2558. // Now create a different server with same contents (causes different mtime)
  2559. // The cache should still be used
  2560. // allow some time for clock to pass as mtime precision is only 1s
  2561. time.Sleep(2 * time.Second)
  2562. server2, err := fakeStorage(files)
  2563. if err != nil {
  2564. c.Fatal(err)
  2565. }
  2566. defer server2.Close()
  2567. ctx2, err := fakeContext(fmt.Sprintf(`FROM scratch
  2568. MAINTAINER dockerio
  2569. ADD %s/baz /usr/lib/baz/quux`, server2.URL()), nil)
  2570. if err != nil {
  2571. c.Fatal(err)
  2572. }
  2573. defer ctx2.Close()
  2574. id3, err := buildImageFromContext(name3, ctx2, true)
  2575. if err != nil {
  2576. c.Fatal(err)
  2577. }
  2578. if id1 != id3 {
  2579. c.Fatal("The cache should have been used but wasn't")
  2580. }
  2581. }
  2582. func (s *DockerSuite) TestBuildAddLocalAndRemoteFilesWithCache(c *check.C) {
  2583. name := "testbuildaddlocalandremotefilewithcache"
  2584. server, err := fakeStorage(map[string]string{
  2585. "baz": "hello",
  2586. })
  2587. if err != nil {
  2588. c.Fatal(err)
  2589. }
  2590. defer server.Close()
  2591. ctx, err := fakeContext(fmt.Sprintf(`FROM scratch
  2592. MAINTAINER dockerio
  2593. ADD foo /usr/lib/bla/bar
  2594. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2595. map[string]string{
  2596. "foo": "hello world",
  2597. })
  2598. if err != nil {
  2599. c.Fatal(err)
  2600. }
  2601. defer ctx.Close()
  2602. id1, err := buildImageFromContext(name, ctx, true)
  2603. if err != nil {
  2604. c.Fatal(err)
  2605. }
  2606. id2, err := buildImageFromContext(name, ctx, true)
  2607. if err != nil {
  2608. c.Fatal(err)
  2609. }
  2610. if id1 != id2 {
  2611. c.Fatal("The cache should have been used but hasn't.")
  2612. }
  2613. }
  2614. func testContextTar(c *check.C, compression archive.Compression) {
  2615. ctx, err := fakeContext(
  2616. `FROM busybox
  2617. ADD foo /foo
  2618. CMD ["cat", "/foo"]`,
  2619. map[string]string{
  2620. "foo": "bar",
  2621. },
  2622. )
  2623. defer ctx.Close()
  2624. if err != nil {
  2625. c.Fatal(err)
  2626. }
  2627. context, err := archive.Tar(ctx.Dir, compression)
  2628. if err != nil {
  2629. c.Fatalf("failed to build context tar: %v", err)
  2630. }
  2631. name := "contexttar"
  2632. buildCmd := exec.Command(dockerBinary, "build", "-t", name, "-")
  2633. buildCmd.Stdin = context
  2634. if out, _, err := runCommandWithOutput(buildCmd); err != nil {
  2635. c.Fatalf("build failed to complete: %v %v", out, err)
  2636. }
  2637. }
  2638. func (s *DockerSuite) TestBuildContextTarGzip(c *check.C) {
  2639. testContextTar(c, archive.Gzip)
  2640. }
  2641. func (s *DockerSuite) TestBuildContextTarNoCompression(c *check.C) {
  2642. testContextTar(c, archive.Uncompressed)
  2643. }
  2644. func (s *DockerSuite) TestBuildNoContext(c *check.C) {
  2645. buildCmd := exec.Command(dockerBinary, "build", "-t", "nocontext", "-")
  2646. buildCmd.Stdin = strings.NewReader("FROM busybox\nCMD echo ok\n")
  2647. if out, _, err := runCommandWithOutput(buildCmd); err != nil {
  2648. c.Fatalf("build failed to complete: %v %v", out, err)
  2649. }
  2650. if out, _ := dockerCmd(c, "run", "--rm", "nocontext"); out != "ok\n" {
  2651. c.Fatalf("run produced invalid output: %q, expected %q", out, "ok")
  2652. }
  2653. }
  2654. // TODO: TestCaching
  2655. func (s *DockerSuite) TestBuildAddLocalAndRemoteFilesWithoutCache(c *check.C) {
  2656. name := "testbuildaddlocalandremotefilewithoutcache"
  2657. name2 := "testbuildaddlocalandremotefilewithoutcache2"
  2658. server, err := fakeStorage(map[string]string{
  2659. "baz": "hello",
  2660. })
  2661. if err != nil {
  2662. c.Fatal(err)
  2663. }
  2664. defer server.Close()
  2665. ctx, err := fakeContext(fmt.Sprintf(`FROM scratch
  2666. MAINTAINER dockerio
  2667. ADD foo /usr/lib/bla/bar
  2668. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2669. map[string]string{
  2670. "foo": "hello world",
  2671. })
  2672. if err != nil {
  2673. c.Fatal(err)
  2674. }
  2675. defer ctx.Close()
  2676. id1, err := buildImageFromContext(name, ctx, true)
  2677. if err != nil {
  2678. c.Fatal(err)
  2679. }
  2680. id2, err := buildImageFromContext(name2, ctx, false)
  2681. if err != nil {
  2682. c.Fatal(err)
  2683. }
  2684. if id1 == id2 {
  2685. c.Fatal("The cache should have been invalided but hasn't.")
  2686. }
  2687. }
  2688. func (s *DockerSuite) TestBuildWithVolumeOwnership(c *check.C) {
  2689. name := "testbuildimg"
  2690. _, err := buildImage(name,
  2691. `FROM busybox:latest
  2692. RUN mkdir /test && chown daemon:daemon /test && chmod 0600 /test
  2693. VOLUME /test`,
  2694. true)
  2695. if err != nil {
  2696. c.Fatal(err)
  2697. }
  2698. cmd := exec.Command(dockerBinary, "run", "--rm", "testbuildimg", "ls", "-la", "/test")
  2699. out, _, err := runCommandWithOutput(cmd)
  2700. if err != nil {
  2701. c.Fatal(out, err)
  2702. }
  2703. if expected := "drw-------"; !strings.Contains(out, expected) {
  2704. c.Fatalf("expected %s received %s", expected, out)
  2705. }
  2706. if expected := "daemon daemon"; !strings.Contains(out, expected) {
  2707. c.Fatalf("expected %s received %s", expected, out)
  2708. }
  2709. }
  2710. // testing #1405 - config.Cmd does not get cleaned up if
  2711. // utilizing cache
  2712. func (s *DockerSuite) TestBuildEntrypointRunCleanup(c *check.C) {
  2713. name := "testbuildcmdcleanup"
  2714. if _, err := buildImage(name,
  2715. `FROM busybox
  2716. RUN echo "hello"`,
  2717. true); err != nil {
  2718. c.Fatal(err)
  2719. }
  2720. ctx, err := fakeContext(`FROM busybox
  2721. RUN echo "hello"
  2722. ADD foo /foo
  2723. ENTRYPOINT ["/bin/echo"]`,
  2724. map[string]string{
  2725. "foo": "hello",
  2726. })
  2727. defer ctx.Close()
  2728. if err != nil {
  2729. c.Fatal(err)
  2730. }
  2731. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2732. c.Fatal(err)
  2733. }
  2734. res, err := inspectField(name, "Config.Cmd")
  2735. if err != nil {
  2736. c.Fatal(err)
  2737. }
  2738. // Cmd must be cleaned up
  2739. if res != "<nil>" {
  2740. c.Fatalf("Cmd %s, expected nil", res)
  2741. }
  2742. }
  2743. func (s *DockerSuite) TestBuildForbiddenContextPath(c *check.C) {
  2744. name := "testbuildforbidpath"
  2745. ctx, err := fakeContext(`FROM scratch
  2746. ADD ../../ test/
  2747. `,
  2748. map[string]string{
  2749. "test.txt": "test1",
  2750. "other.txt": "other",
  2751. })
  2752. defer ctx.Close()
  2753. if err != nil {
  2754. c.Fatal(err)
  2755. }
  2756. expected := "Forbidden path outside the build context: ../../ "
  2757. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  2758. c.Fatalf("Wrong error: (should contain \"%s\") got:\n%v", expected, err)
  2759. }
  2760. }
  2761. func (s *DockerSuite) TestBuildAddFileNotFound(c *check.C) {
  2762. name := "testbuildaddnotfound"
  2763. ctx, err := fakeContext(`FROM scratch
  2764. ADD foo /usr/local/bar`,
  2765. map[string]string{"bar": "hello"})
  2766. defer ctx.Close()
  2767. if err != nil {
  2768. c.Fatal(err)
  2769. }
  2770. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2771. if !strings.Contains(err.Error(), "foo: no such file or directory") {
  2772. c.Fatalf("Wrong error %v, must be about missing foo file or directory", err)
  2773. }
  2774. } else {
  2775. c.Fatal("Error must not be nil")
  2776. }
  2777. }
  2778. func (s *DockerSuite) TestBuildInheritance(c *check.C) {
  2779. name := "testbuildinheritance"
  2780. _, err := buildImage(name,
  2781. `FROM scratch
  2782. EXPOSE 2375`,
  2783. true)
  2784. if err != nil {
  2785. c.Fatal(err)
  2786. }
  2787. ports1, err := inspectField(name, "Config.ExposedPorts")
  2788. if err != nil {
  2789. c.Fatal(err)
  2790. }
  2791. _, err = buildImage(name,
  2792. fmt.Sprintf(`FROM %s
  2793. ENTRYPOINT ["/bin/echo"]`, name),
  2794. true)
  2795. if err != nil {
  2796. c.Fatal(err)
  2797. }
  2798. res, err := inspectField(name, "Config.Entrypoint")
  2799. if err != nil {
  2800. c.Fatal(err)
  2801. }
  2802. if expected := "{[/bin/echo]}"; res != expected {
  2803. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  2804. }
  2805. ports2, err := inspectField(name, "Config.ExposedPorts")
  2806. if err != nil {
  2807. c.Fatal(err)
  2808. }
  2809. if ports1 != ports2 {
  2810. c.Fatalf("Ports must be same: %s != %s", ports1, ports2)
  2811. }
  2812. }
  2813. func (s *DockerSuite) TestBuildFails(c *check.C) {
  2814. name := "testbuildfails"
  2815. _, err := buildImage(name,
  2816. `FROM busybox
  2817. RUN sh -c "exit 23"`,
  2818. true)
  2819. if err != nil {
  2820. if !strings.Contains(err.Error(), "returned a non-zero code: 23") {
  2821. c.Fatalf("Wrong error %v, must be about non-zero code 23", err)
  2822. }
  2823. } else {
  2824. c.Fatal("Error must not be nil")
  2825. }
  2826. }
  2827. func (s *DockerSuite) TestBuildFailsDockerfileEmpty(c *check.C) {
  2828. name := "testbuildfails"
  2829. _, err := buildImage(name, ``, true)
  2830. if err != nil {
  2831. if !strings.Contains(err.Error(), "The Dockerfile (Dockerfile) cannot be empty") {
  2832. c.Fatalf("Wrong error %v, must be about empty Dockerfile", err)
  2833. }
  2834. } else {
  2835. c.Fatal("Error must not be nil")
  2836. }
  2837. }
  2838. func (s *DockerSuite) TestBuildOnBuild(c *check.C) {
  2839. name := "testbuildonbuild"
  2840. _, err := buildImage(name,
  2841. `FROM busybox
  2842. ONBUILD RUN touch foobar`,
  2843. true)
  2844. if err != nil {
  2845. c.Fatal(err)
  2846. }
  2847. _, err = buildImage(name,
  2848. fmt.Sprintf(`FROM %s
  2849. RUN [ -f foobar ]`, name),
  2850. true)
  2851. if err != nil {
  2852. c.Fatal(err)
  2853. }
  2854. }
  2855. func (s *DockerSuite) TestBuildOnBuildForbiddenChained(c *check.C) {
  2856. name := "testbuildonbuildforbiddenchained"
  2857. _, err := buildImage(name,
  2858. `FROM busybox
  2859. ONBUILD ONBUILD RUN touch foobar`,
  2860. true)
  2861. if err != nil {
  2862. if !strings.Contains(err.Error(), "Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed") {
  2863. c.Fatalf("Wrong error %v, must be about chaining ONBUILD", err)
  2864. }
  2865. } else {
  2866. c.Fatal("Error must not be nil")
  2867. }
  2868. }
  2869. func (s *DockerSuite) TestBuildOnBuildForbiddenFrom(c *check.C) {
  2870. name := "testbuildonbuildforbiddenfrom"
  2871. _, err := buildImage(name,
  2872. `FROM busybox
  2873. ONBUILD FROM scratch`,
  2874. true)
  2875. if err != nil {
  2876. if !strings.Contains(err.Error(), "FROM isn't allowed as an ONBUILD trigger") {
  2877. c.Fatalf("Wrong error %v, must be about FROM forbidden", err)
  2878. }
  2879. } else {
  2880. c.Fatal("Error must not be nil")
  2881. }
  2882. }
  2883. func (s *DockerSuite) TestBuildOnBuildForbiddenMaintainer(c *check.C) {
  2884. name := "testbuildonbuildforbiddenmaintainer"
  2885. _, err := buildImage(name,
  2886. `FROM busybox
  2887. ONBUILD MAINTAINER docker.io`,
  2888. true)
  2889. if err != nil {
  2890. if !strings.Contains(err.Error(), "MAINTAINER isn't allowed as an ONBUILD trigger") {
  2891. c.Fatalf("Wrong error %v, must be about MAINTAINER forbidden", err)
  2892. }
  2893. } else {
  2894. c.Fatal("Error must not be nil")
  2895. }
  2896. }
  2897. // gh #2446
  2898. func (s *DockerSuite) TestBuildAddToSymlinkDest(c *check.C) {
  2899. name := "testbuildaddtosymlinkdest"
  2900. ctx, err := fakeContext(`FROM busybox
  2901. RUN mkdir /foo
  2902. RUN ln -s /foo /bar
  2903. ADD foo /bar/
  2904. RUN [ -f /bar/foo ]
  2905. RUN [ -f /foo/foo ]`,
  2906. map[string]string{
  2907. "foo": "hello",
  2908. })
  2909. if err != nil {
  2910. c.Fatal(err)
  2911. }
  2912. defer ctx.Close()
  2913. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2914. c.Fatal(err)
  2915. }
  2916. }
  2917. func (s *DockerSuite) TestBuildEscapeWhitespace(c *check.C) {
  2918. name := "testbuildescaping"
  2919. _, err := buildImage(name, `
  2920. FROM busybox
  2921. MAINTAINER "Docker \
  2922. IO <io@\
  2923. docker.com>"
  2924. `, true)
  2925. res, err := inspectField(name, "Author")
  2926. if err != nil {
  2927. c.Fatal(err)
  2928. }
  2929. if res != "\"Docker IO <io@docker.com>\"" {
  2930. c.Fatalf("Parsed string did not match the escaped string. Got: %q", res)
  2931. }
  2932. }
  2933. func (s *DockerSuite) TestBuildVerifyIntString(c *check.C) {
  2934. // Verify that strings that look like ints are still passed as strings
  2935. name := "testbuildstringing"
  2936. _, err := buildImage(name, `
  2937. FROM busybox
  2938. MAINTAINER 123
  2939. `, true)
  2940. out, rc, err := runCommandWithOutput(exec.Command(dockerBinary, "inspect", name))
  2941. if rc != 0 || err != nil {
  2942. c.Fatalf("Unexpected error from inspect: rc: %v err: %v", rc, err)
  2943. }
  2944. if !strings.Contains(out, "\"123\"") {
  2945. c.Fatalf("Output does not contain the int as a string:\n%s", out)
  2946. }
  2947. }
  2948. func (s *DockerSuite) TestBuildDockerignore(c *check.C) {
  2949. name := "testbuilddockerignore"
  2950. dockerfile := `
  2951. FROM busybox
  2952. ADD . /bla
  2953. RUN [[ -f /bla/src/x.go ]]
  2954. RUN [[ -f /bla/Makefile ]]
  2955. RUN [[ ! -e /bla/src/_vendor ]]
  2956. RUN [[ ! -e /bla/.gitignore ]]
  2957. RUN [[ ! -e /bla/README.md ]]
  2958. RUN [[ ! -e /bla/dir/foo ]]
  2959. RUN [[ ! -e /bla/foo ]]
  2960. RUN [[ ! -e /bla/.git ]]`
  2961. ctx, err := fakeContext(dockerfile, map[string]string{
  2962. "Makefile": "all:",
  2963. ".git/HEAD": "ref: foo",
  2964. "src/x.go": "package main",
  2965. "src/_vendor/v.go": "package main",
  2966. "dir/foo": "",
  2967. ".gitignore": "",
  2968. "README.md": "readme",
  2969. ".dockerignore": `
  2970. .git
  2971. pkg
  2972. .gitignore
  2973. src/_vendor
  2974. *.md
  2975. dir`,
  2976. })
  2977. if err != nil {
  2978. c.Fatal(err)
  2979. }
  2980. defer ctx.Close()
  2981. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2982. c.Fatal(err)
  2983. }
  2984. }
  2985. func (s *DockerSuite) TestBuildDockerignoreCleanPaths(c *check.C) {
  2986. name := "testbuilddockerignorecleanpaths"
  2987. dockerfile := `
  2988. FROM busybox
  2989. ADD . /tmp/
  2990. RUN (! ls /tmp/foo) && (! ls /tmp/foo2) && (! ls /tmp/dir1/foo)`
  2991. ctx, err := fakeContext(dockerfile, map[string]string{
  2992. "foo": "foo",
  2993. "foo2": "foo2",
  2994. "dir1/foo": "foo in dir1",
  2995. ".dockerignore": "./foo\ndir1//foo\n./dir1/../foo2",
  2996. })
  2997. if err != nil {
  2998. c.Fatal(err)
  2999. }
  3000. defer ctx.Close()
  3001. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3002. c.Fatal(err)
  3003. }
  3004. }
  3005. func (s *DockerSuite) TestBuildDockerignoreExceptions(c *check.C) {
  3006. name := "testbuilddockerignoreexceptions"
  3007. defer deleteImages(name)
  3008. dockerfile := `
  3009. FROM busybox
  3010. ADD . /bla
  3011. RUN [[ -f /bla/src/x.go ]]
  3012. RUN [[ -f /bla/Makefile ]]
  3013. RUN [[ ! -e /bla/src/_vendor ]]
  3014. RUN [[ ! -e /bla/.gitignore ]]
  3015. RUN [[ ! -e /bla/README.md ]]
  3016. RUN [[ -e /bla/dir/dir/foo ]]
  3017. RUN [[ ! -e /bla/dir/foo1 ]]
  3018. RUN [[ -f /bla/dir/e ]]
  3019. RUN [[ -f /bla/dir/e-dir/foo ]]
  3020. RUN [[ ! -e /bla/foo ]]
  3021. RUN [[ ! -e /bla/.git ]]`
  3022. ctx, err := fakeContext(dockerfile, map[string]string{
  3023. "Makefile": "all:",
  3024. ".git/HEAD": "ref: foo",
  3025. "src/x.go": "package main",
  3026. "src/_vendor/v.go": "package main",
  3027. "dir/foo": "",
  3028. "dir/foo1": "",
  3029. "dir/dir/f1": "",
  3030. "dir/dir/foo": "",
  3031. "dir/e": "",
  3032. "dir/e-dir/foo": "",
  3033. ".gitignore": "",
  3034. "README.md": "readme",
  3035. ".dockerignore": `
  3036. .git
  3037. pkg
  3038. .gitignore
  3039. src/_vendor
  3040. *.md
  3041. dir
  3042. !dir/e*
  3043. !dir/dir/foo`,
  3044. })
  3045. if err != nil {
  3046. c.Fatal(err)
  3047. }
  3048. defer ctx.Close()
  3049. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3050. c.Fatal(err)
  3051. }
  3052. }
  3053. func (s *DockerSuite) TestBuildDockerignoringDockerfile(c *check.C) {
  3054. name := "testbuilddockerignoredockerfile"
  3055. dockerfile := `
  3056. FROM busybox
  3057. ADD . /tmp/
  3058. RUN ! ls /tmp/Dockerfile
  3059. RUN ls /tmp/.dockerignore`
  3060. ctx, err := fakeContext(dockerfile, map[string]string{
  3061. "Dockerfile": dockerfile,
  3062. ".dockerignore": "Dockerfile\n",
  3063. })
  3064. if err != nil {
  3065. c.Fatal(err)
  3066. }
  3067. defer ctx.Close()
  3068. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3069. c.Fatalf("Didn't ignore Dockerfile correctly:%s", err)
  3070. }
  3071. // now try it with ./Dockerfile
  3072. ctx.Add(".dockerignore", "./Dockerfile\n")
  3073. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3074. c.Fatalf("Didn't ignore ./Dockerfile correctly:%s", err)
  3075. }
  3076. }
  3077. func (s *DockerSuite) TestBuildDockerignoringRenamedDockerfile(c *check.C) {
  3078. name := "testbuilddockerignoredockerfile"
  3079. dockerfile := `
  3080. FROM busybox
  3081. ADD . /tmp/
  3082. RUN ls /tmp/Dockerfile
  3083. RUN ! ls /tmp/MyDockerfile
  3084. RUN ls /tmp/.dockerignore`
  3085. ctx, err := fakeContext(dockerfile, map[string]string{
  3086. "Dockerfile": "Should not use me",
  3087. "MyDockerfile": dockerfile,
  3088. ".dockerignore": "MyDockerfile\n",
  3089. })
  3090. if err != nil {
  3091. c.Fatal(err)
  3092. }
  3093. defer ctx.Close()
  3094. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3095. c.Fatalf("Didn't ignore MyDockerfile correctly:%s", err)
  3096. }
  3097. // now try it with ./MyDockerfile
  3098. ctx.Add(".dockerignore", "./MyDockerfile\n")
  3099. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3100. c.Fatalf("Didn't ignore ./MyDockerfile correctly:%s", err)
  3101. }
  3102. }
  3103. func (s *DockerSuite) TestBuildDockerignoringDockerignore(c *check.C) {
  3104. name := "testbuilddockerignoredockerignore"
  3105. dockerfile := `
  3106. FROM busybox
  3107. ADD . /tmp/
  3108. RUN ! ls /tmp/.dockerignore
  3109. RUN ls /tmp/Dockerfile`
  3110. ctx, err := fakeContext(dockerfile, map[string]string{
  3111. "Dockerfile": dockerfile,
  3112. ".dockerignore": ".dockerignore\n",
  3113. })
  3114. defer ctx.Close()
  3115. if err != nil {
  3116. c.Fatal(err)
  3117. }
  3118. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3119. c.Fatalf("Didn't ignore .dockerignore correctly:%s", err)
  3120. }
  3121. }
  3122. func (s *DockerSuite) TestBuildDockerignoreTouchDockerfile(c *check.C) {
  3123. var id1 string
  3124. var id2 string
  3125. name := "testbuilddockerignoretouchdockerfile"
  3126. dockerfile := `
  3127. FROM busybox
  3128. ADD . /tmp/`
  3129. ctx, err := fakeContext(dockerfile, map[string]string{
  3130. "Dockerfile": dockerfile,
  3131. ".dockerignore": "Dockerfile\n",
  3132. })
  3133. defer ctx.Close()
  3134. if err != nil {
  3135. c.Fatal(err)
  3136. }
  3137. if id1, err = buildImageFromContext(name, ctx, true); err != nil {
  3138. c.Fatalf("Didn't build it correctly:%s", err)
  3139. }
  3140. if id2, err = buildImageFromContext(name, ctx, true); err != nil {
  3141. c.Fatalf("Didn't build it correctly:%s", err)
  3142. }
  3143. if id1 != id2 {
  3144. c.Fatalf("Didn't use the cache - 1")
  3145. }
  3146. // Now make sure touching Dockerfile doesn't invalidate the cache
  3147. if err = ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil {
  3148. c.Fatalf("Didn't add Dockerfile: %s", err)
  3149. }
  3150. if id2, err = buildImageFromContext(name, ctx, true); err != nil {
  3151. c.Fatalf("Didn't build it correctly:%s", err)
  3152. }
  3153. if id1 != id2 {
  3154. c.Fatalf("Didn't use the cache - 2")
  3155. }
  3156. // One more time but just 'touch' it instead of changing the content
  3157. if err = ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil {
  3158. c.Fatalf("Didn't add Dockerfile: %s", err)
  3159. }
  3160. if id2, err = buildImageFromContext(name, ctx, true); err != nil {
  3161. c.Fatalf("Didn't build it correctly:%s", err)
  3162. }
  3163. if id1 != id2 {
  3164. c.Fatalf("Didn't use the cache - 3")
  3165. }
  3166. }
  3167. func (s *DockerSuite) TestBuildDockerignoringWholeDir(c *check.C) {
  3168. name := "testbuilddockerignorewholedir"
  3169. dockerfile := `
  3170. FROM busybox
  3171. COPY . /
  3172. RUN [[ ! -e /.gitignore ]]
  3173. RUN [[ -f /Makefile ]]`
  3174. ctx, err := fakeContext(dockerfile, map[string]string{
  3175. "Dockerfile": "FROM scratch",
  3176. "Makefile": "all:",
  3177. ".gitignore": "",
  3178. ".dockerignore": ".*\n",
  3179. })
  3180. c.Assert(err, check.IsNil)
  3181. defer ctx.Close()
  3182. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3183. c.Fatal(err)
  3184. }
  3185. c.Assert(ctx.Add(".dockerfile", "*"), check.IsNil)
  3186. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3187. c.Fatal(err)
  3188. }
  3189. c.Assert(ctx.Add(".dockerfile", "."), check.IsNil)
  3190. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3191. c.Fatal(err)
  3192. }
  3193. c.Assert(ctx.Add(".dockerfile", "?"), check.IsNil)
  3194. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3195. c.Fatal(err)
  3196. }
  3197. }
  3198. func (s *DockerSuite) TestBuildDockerignoringBadExclusion(c *check.C) {
  3199. name := "testbuilddockerignorewholedir"
  3200. dockerfile := `
  3201. FROM busybox
  3202. COPY . /
  3203. RUN [[ ! -e /.gitignore ]]
  3204. RUN [[ -f /Makefile ]]`
  3205. ctx, err := fakeContext(dockerfile, map[string]string{
  3206. "Dockerfile": "FROM scratch",
  3207. "Makefile": "all:",
  3208. ".gitignore": "",
  3209. ".dockerignore": "!\n",
  3210. })
  3211. c.Assert(err, check.IsNil)
  3212. defer ctx.Close()
  3213. if _, err = buildImageFromContext(name, ctx, true); err == nil {
  3214. c.Fatalf("Build was supposed to fail but didn't")
  3215. }
  3216. if err.Error() != "failed to build the image: Error checking context: 'Illegal exclusion pattern: !'.\n" {
  3217. c.Fatalf("Incorrect output, got:%q", err.Error())
  3218. }
  3219. }
  3220. func (s *DockerSuite) TestBuildLineBreak(c *check.C) {
  3221. name := "testbuildlinebreak"
  3222. _, err := buildImage(name,
  3223. `FROM busybox
  3224. RUN sh -c 'echo root:testpass \
  3225. > /tmp/passwd'
  3226. RUN mkdir -p /var/run/sshd
  3227. RUN [ "$(cat /tmp/passwd)" = "root:testpass" ]
  3228. RUN [ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]`,
  3229. true)
  3230. if err != nil {
  3231. c.Fatal(err)
  3232. }
  3233. }
  3234. func (s *DockerSuite) TestBuildEOLInLine(c *check.C) {
  3235. name := "testbuildeolinline"
  3236. _, err := buildImage(name,
  3237. `FROM busybox
  3238. RUN sh -c 'echo root:testpass > /tmp/passwd'
  3239. RUN echo "foo \n bar"; echo "baz"
  3240. RUN mkdir -p /var/run/sshd
  3241. RUN [ "$(cat /tmp/passwd)" = "root:testpass" ]
  3242. RUN [ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]`,
  3243. true)
  3244. if err != nil {
  3245. c.Fatal(err)
  3246. }
  3247. }
  3248. func (s *DockerSuite) TestBuildCommentsShebangs(c *check.C) {
  3249. name := "testbuildcomments"
  3250. _, err := buildImage(name,
  3251. `FROM busybox
  3252. # This is an ordinary comment.
  3253. RUN { echo '#!/bin/sh'; echo 'echo hello world'; } > /hello.sh
  3254. RUN [ ! -x /hello.sh ]
  3255. # comment with line break \
  3256. RUN chmod +x /hello.sh
  3257. RUN [ -x /hello.sh ]
  3258. RUN [ "$(cat /hello.sh)" = $'#!/bin/sh\necho hello world' ]
  3259. RUN [ "$(/hello.sh)" = "hello world" ]`,
  3260. true)
  3261. if err != nil {
  3262. c.Fatal(err)
  3263. }
  3264. }
  3265. func (s *DockerSuite) TestBuildUsersAndGroups(c *check.C) {
  3266. name := "testbuildusers"
  3267. _, err := buildImage(name,
  3268. `FROM busybox
  3269. # Make sure our defaults work
  3270. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)" = '0:0/root:root' ]
  3271. # 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)
  3272. USER root
  3273. RUN [ "$(id -G):$(id -Gn)" = '0 10:root wheel' ]
  3274. # Setup dockerio user and group
  3275. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  3276. RUN echo 'dockerio:x:1001:' >> /etc/group
  3277. # Make sure we can switch to our user and all the information is exactly as we expect it to be
  3278. USER dockerio
  3279. RUN id -G
  3280. RUN id -Gn
  3281. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3282. # Switch back to root and double check that worked exactly as we might expect it to
  3283. USER root
  3284. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '0:0/root:root/0 10:root wheel' ]
  3285. # Add a "supplementary" group for our dockerio user
  3286. RUN echo 'supplementary:x:1002:dockerio' >> /etc/group
  3287. # ... and then go verify that we get it like we expect
  3288. USER dockerio
  3289. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  3290. USER 1001
  3291. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  3292. # super test the new "user:group" syntax
  3293. USER dockerio:dockerio
  3294. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3295. USER 1001:dockerio
  3296. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3297. USER dockerio:1001
  3298. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3299. USER 1001:1001
  3300. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3301. USER dockerio:supplementary
  3302. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3303. USER dockerio:1002
  3304. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3305. USER 1001:supplementary
  3306. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3307. USER 1001:1002
  3308. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3309. # make sure unknown uid/gid still works properly
  3310. USER 1042:1043
  3311. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1042:1043/1042:1043/1043:1043' ]`,
  3312. true)
  3313. if err != nil {
  3314. c.Fatal(err)
  3315. }
  3316. }
  3317. func (s *DockerSuite) TestBuildEnvUsage(c *check.C) {
  3318. name := "testbuildenvusage"
  3319. dockerfile := `FROM busybox
  3320. ENV HOME /root
  3321. ENV PATH $HOME/bin:$PATH
  3322. ENV PATH /tmp:$PATH
  3323. RUN [ "$PATH" = "/tmp:$HOME/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ]
  3324. ENV FOO /foo/baz
  3325. ENV BAR /bar
  3326. ENV BAZ $BAR
  3327. ENV FOOPATH $PATH:$FOO
  3328. RUN [ "$BAR" = "$BAZ" ]
  3329. RUN [ "$FOOPATH" = "$PATH:/foo/baz" ]
  3330. ENV FROM hello/docker/world
  3331. ENV TO /docker/world/hello
  3332. ADD $FROM $TO
  3333. RUN [ "$(cat $TO)" = "hello" ]
  3334. ENV abc=def
  3335. ENV ghi=$abc
  3336. RUN [ "$ghi" = "def" ]
  3337. `
  3338. ctx, err := fakeContext(dockerfile, map[string]string{
  3339. "hello/docker/world": "hello",
  3340. })
  3341. if err != nil {
  3342. c.Fatal(err)
  3343. }
  3344. defer ctx.Close()
  3345. _, err = buildImageFromContext(name, ctx, true)
  3346. if err != nil {
  3347. c.Fatal(err)
  3348. }
  3349. }
  3350. func (s *DockerSuite) TestBuildEnvUsage2(c *check.C) {
  3351. name := "testbuildenvusage2"
  3352. dockerfile := `FROM busybox
  3353. ENV abc=def
  3354. RUN [ "$abc" = "def" ]
  3355. ENV def="hello world"
  3356. RUN [ "$def" = "hello world" ]
  3357. ENV def=hello\ world
  3358. RUN [ "$def" = "hello world" ]
  3359. ENV v1=abc v2="hi there"
  3360. RUN [ "$v1" = "abc" ]
  3361. RUN [ "$v2" = "hi there" ]
  3362. ENV v3='boogie nights' v4="with'quotes too"
  3363. RUN [ "$v3" = "boogie nights" ]
  3364. RUN [ "$v4" = "with'quotes too" ]
  3365. ENV abc=zzz FROM=hello/docker/world
  3366. ENV abc=zzz TO=/docker/world/hello
  3367. ADD $FROM $TO
  3368. RUN [ "$(cat $TO)" = "hello" ]
  3369. ENV abc "zzz"
  3370. RUN [ $abc = "zzz" ]
  3371. ENV abc 'yyy'
  3372. RUN [ $abc = 'yyy' ]
  3373. ENV abc=
  3374. RUN [ "$abc" = "" ]
  3375. # use grep to make sure if the builder substitutes \$foo by mistake
  3376. # we don't get a false positive
  3377. ENV abc=\$foo
  3378. RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep foo)
  3379. ENV abc \$foo
  3380. RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep foo)
  3381. ENV abc=\'foo\'
  3382. RUN [ "$abc" = "'foo'" ]
  3383. ENV abc=\"foo\"
  3384. RUN [ "$abc" = "\"foo\"" ]
  3385. ENV abc "foo"
  3386. RUN [ "$abc" = "foo" ]
  3387. ENV abc 'foo'
  3388. RUN [ "$abc" = 'foo' ]
  3389. ENV abc \'foo\'
  3390. RUN [ "$abc" = "'foo'" ]
  3391. ENV abc \"foo\"
  3392. RUN [ "$abc" = '"foo"' ]
  3393. ENV abc=ABC
  3394. RUN [ "$abc" = "ABC" ]
  3395. ENV def=${abc:-DEF}
  3396. RUN [ "$def" = "ABC" ]
  3397. ENV def=${ccc:-DEF}
  3398. RUN [ "$def" = "DEF" ]
  3399. ENV def=${ccc:-${def}xx}
  3400. RUN [ "$def" = "DEFxx" ]
  3401. ENV def=${def:+ALT}
  3402. RUN [ "$def" = "ALT" ]
  3403. ENV def=${def:+${abc}:}
  3404. RUN [ "$def" = "ABC:" ]
  3405. ENV def=${ccc:-\$abc:}
  3406. RUN [ "$def" = '$abc:' ]
  3407. ENV def=${ccc:-\${abc}:}
  3408. RUN [ "$def" = '${abc:}' ]
  3409. ENV mypath=${mypath:+$mypath:}/home
  3410. RUN [ "$mypath" = '/home' ]
  3411. ENV mypath=${mypath:+$mypath:}/away
  3412. RUN [ "$mypath" = '/home:/away' ]
  3413. ENV e1=bar
  3414. ENV e2=$e1
  3415. ENV e3=$e11
  3416. ENV e4=\$e1
  3417. ENV e5=\$e11
  3418. RUN [ "$e0,$e1,$e2,$e3,$e4,$e5" = ',bar,bar,,$e1,$e11' ]
  3419. ENV ee1 bar
  3420. ENV ee2 $ee1
  3421. ENV ee3 $ee11
  3422. ENV ee4 \$ee1
  3423. ENV ee5 \$ee11
  3424. RUN [ "$ee1,$ee2,$ee3,$ee4,$ee5" = 'bar,bar,,$ee1,$ee11' ]
  3425. ENV eee1="foo"
  3426. ENV eee2='foo'
  3427. ENV eee3 "foo"
  3428. ENV eee4 'foo'
  3429. RUN [ "$eee1,$eee2,$eee3,$eee4" = 'foo,foo,foo,foo' ]
  3430. `
  3431. ctx, err := fakeContext(dockerfile, map[string]string{
  3432. "hello/docker/world": "hello",
  3433. })
  3434. if err != nil {
  3435. c.Fatal(err)
  3436. }
  3437. defer ctx.Close()
  3438. _, err = buildImageFromContext(name, ctx, true)
  3439. if err != nil {
  3440. c.Fatal(err)
  3441. }
  3442. }
  3443. func (s *DockerSuite) TestBuildAddScript(c *check.C) {
  3444. name := "testbuildaddscript"
  3445. dockerfile := `
  3446. FROM busybox
  3447. ADD test /test
  3448. RUN ["chmod","+x","/test"]
  3449. RUN ["/test"]
  3450. RUN [ "$(cat /testfile)" = 'test!' ]`
  3451. ctx, err := fakeContext(dockerfile, map[string]string{
  3452. "test": "#!/bin/sh\necho 'test!' > /testfile",
  3453. })
  3454. if err != nil {
  3455. c.Fatal(err)
  3456. }
  3457. defer ctx.Close()
  3458. _, err = buildImageFromContext(name, ctx, true)
  3459. if err != nil {
  3460. c.Fatal(err)
  3461. }
  3462. }
  3463. func (s *DockerSuite) TestBuildAddTar(c *check.C) {
  3464. name := "testbuildaddtar"
  3465. ctx := func() *FakeContext {
  3466. dockerfile := `
  3467. FROM busybox
  3468. ADD test.tar /
  3469. RUN cat /test/foo | grep Hi
  3470. ADD test.tar /test.tar
  3471. RUN cat /test.tar/test/foo | grep Hi
  3472. ADD test.tar /unlikely-to-exist
  3473. RUN cat /unlikely-to-exist/test/foo | grep Hi
  3474. ADD test.tar /unlikely-to-exist-trailing-slash/
  3475. RUN cat /unlikely-to-exist-trailing-slash/test/foo | grep Hi
  3476. RUN mkdir /existing-directory
  3477. ADD test.tar /existing-directory
  3478. RUN cat /existing-directory/test/foo | grep Hi
  3479. ADD test.tar /existing-directory-trailing-slash/
  3480. RUN cat /existing-directory-trailing-slash/test/foo | grep Hi`
  3481. tmpDir, err := ioutil.TempDir("", "fake-context")
  3482. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3483. if err != nil {
  3484. c.Fatalf("failed to create test.tar archive: %v", err)
  3485. }
  3486. defer testTar.Close()
  3487. tw := tar.NewWriter(testTar)
  3488. if err := tw.WriteHeader(&tar.Header{
  3489. Name: "test/foo",
  3490. Size: 2,
  3491. }); err != nil {
  3492. c.Fatalf("failed to write tar file header: %v", err)
  3493. }
  3494. if _, err := tw.Write([]byte("Hi")); err != nil {
  3495. c.Fatalf("failed to write tar file content: %v", err)
  3496. }
  3497. if err := tw.Close(); err != nil {
  3498. c.Fatalf("failed to close tar archive: %v", err)
  3499. }
  3500. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3501. c.Fatalf("failed to open destination dockerfile: %v", err)
  3502. }
  3503. return fakeContextFromDir(tmpDir)
  3504. }()
  3505. defer ctx.Close()
  3506. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3507. c.Fatalf("build failed to complete for TestBuildAddTar: %v", err)
  3508. }
  3509. }
  3510. func (s *DockerSuite) TestBuildAddTarXz(c *check.C) {
  3511. name := "testbuildaddtarxz"
  3512. ctx := func() *FakeContext {
  3513. dockerfile := `
  3514. FROM busybox
  3515. ADD test.tar.xz /
  3516. RUN cat /test/foo | grep Hi`
  3517. tmpDir, err := ioutil.TempDir("", "fake-context")
  3518. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3519. if err != nil {
  3520. c.Fatalf("failed to create test.tar archive: %v", err)
  3521. }
  3522. defer testTar.Close()
  3523. tw := tar.NewWriter(testTar)
  3524. if err := tw.WriteHeader(&tar.Header{
  3525. Name: "test/foo",
  3526. Size: 2,
  3527. }); err != nil {
  3528. c.Fatalf("failed to write tar file header: %v", err)
  3529. }
  3530. if _, err := tw.Write([]byte("Hi")); err != nil {
  3531. c.Fatalf("failed to write tar file content: %v", err)
  3532. }
  3533. if err := tw.Close(); err != nil {
  3534. c.Fatalf("failed to close tar archive: %v", err)
  3535. }
  3536. xzCompressCmd := exec.Command("xz", "-k", "test.tar")
  3537. xzCompressCmd.Dir = tmpDir
  3538. out, _, err := runCommandWithOutput(xzCompressCmd)
  3539. if err != nil {
  3540. c.Fatal(err, out)
  3541. }
  3542. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3543. c.Fatalf("failed to open destination dockerfile: %v", err)
  3544. }
  3545. return fakeContextFromDir(tmpDir)
  3546. }()
  3547. defer ctx.Close()
  3548. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3549. c.Fatalf("build failed to complete for TestBuildAddTarXz: %v", err)
  3550. }
  3551. }
  3552. func (s *DockerSuite) TestBuildAddTarXzGz(c *check.C) {
  3553. name := "testbuildaddtarxzgz"
  3554. ctx := func() *FakeContext {
  3555. dockerfile := `
  3556. FROM busybox
  3557. ADD test.tar.xz.gz /
  3558. RUN ls /test.tar.xz.gz`
  3559. tmpDir, err := ioutil.TempDir("", "fake-context")
  3560. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3561. if err != nil {
  3562. c.Fatalf("failed to create test.tar archive: %v", err)
  3563. }
  3564. defer testTar.Close()
  3565. tw := tar.NewWriter(testTar)
  3566. if err := tw.WriteHeader(&tar.Header{
  3567. Name: "test/foo",
  3568. Size: 2,
  3569. }); err != nil {
  3570. c.Fatalf("failed to write tar file header: %v", err)
  3571. }
  3572. if _, err := tw.Write([]byte("Hi")); err != nil {
  3573. c.Fatalf("failed to write tar file content: %v", err)
  3574. }
  3575. if err := tw.Close(); err != nil {
  3576. c.Fatalf("failed to close tar archive: %v", err)
  3577. }
  3578. xzCompressCmd := exec.Command("xz", "-k", "test.tar")
  3579. xzCompressCmd.Dir = tmpDir
  3580. out, _, err := runCommandWithOutput(xzCompressCmd)
  3581. if err != nil {
  3582. c.Fatal(err, out)
  3583. }
  3584. gzipCompressCmd := exec.Command("gzip", "test.tar.xz")
  3585. gzipCompressCmd.Dir = tmpDir
  3586. out, _, err = runCommandWithOutput(gzipCompressCmd)
  3587. if err != nil {
  3588. c.Fatal(err, out)
  3589. }
  3590. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3591. c.Fatalf("failed to open destination dockerfile: %v", err)
  3592. }
  3593. return fakeContextFromDir(tmpDir)
  3594. }()
  3595. defer ctx.Close()
  3596. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3597. c.Fatalf("build failed to complete for TestBuildAddTarXz: %v", err)
  3598. }
  3599. }
  3600. func (s *DockerSuite) TestBuildFromGIT(c *check.C) {
  3601. name := "testbuildfromgit"
  3602. git, err := fakeGIT("repo", map[string]string{
  3603. "Dockerfile": `FROM busybox
  3604. ADD first /first
  3605. RUN [ -f /first ]
  3606. MAINTAINER docker`,
  3607. "first": "test git data",
  3608. }, true)
  3609. if err != nil {
  3610. c.Fatal(err)
  3611. }
  3612. defer git.Close()
  3613. _, err = buildImageFromPath(name, git.RepoURL, true)
  3614. if err != nil {
  3615. c.Fatal(err)
  3616. }
  3617. res, err := inspectField(name, "Author")
  3618. if err != nil {
  3619. c.Fatal(err)
  3620. }
  3621. if res != "docker" {
  3622. c.Fatalf("Maintainer should be docker, got %s", res)
  3623. }
  3624. }
  3625. func (s *DockerSuite) TestBuildFromGITWithContext(c *check.C) {
  3626. name := "testbuildfromgit"
  3627. defer deleteImages(name)
  3628. git, err := fakeGIT("repo", map[string]string{
  3629. "docker/Dockerfile": `FROM busybox
  3630. ADD first /first
  3631. RUN [ -f /first ]
  3632. MAINTAINER docker`,
  3633. "docker/first": "test git data",
  3634. }, true)
  3635. if err != nil {
  3636. c.Fatal(err)
  3637. }
  3638. defer git.Close()
  3639. u := fmt.Sprintf("%s#master:docker", git.RepoURL)
  3640. _, err = buildImageFromPath(name, u, true)
  3641. if err != nil {
  3642. c.Fatal(err)
  3643. }
  3644. res, err := inspectField(name, "Author")
  3645. if err != nil {
  3646. c.Fatal(err)
  3647. }
  3648. if res != "docker" {
  3649. c.Fatalf("Maintainer should be docker, got %s", res)
  3650. }
  3651. }
  3652. func (s *DockerSuite) TestBuildFromRemoteTarball(c *check.C) {
  3653. name := "testbuildfromremotetarball"
  3654. buffer := new(bytes.Buffer)
  3655. tw := tar.NewWriter(buffer)
  3656. defer tw.Close()
  3657. dockerfile := []byte(`FROM busybox
  3658. MAINTAINER docker`)
  3659. if err := tw.WriteHeader(&tar.Header{
  3660. Name: "Dockerfile",
  3661. Size: int64(len(dockerfile)),
  3662. }); err != nil {
  3663. c.Fatalf("failed to write tar file header: %v", err)
  3664. }
  3665. if _, err := tw.Write(dockerfile); err != nil {
  3666. c.Fatalf("failed to write tar file content: %v", err)
  3667. }
  3668. if err := tw.Close(); err != nil {
  3669. c.Fatalf("failed to close tar archive: %v", err)
  3670. }
  3671. server, err := fakeBinaryStorage(map[string]*bytes.Buffer{
  3672. "testT.tar": buffer,
  3673. })
  3674. c.Assert(err, check.IsNil)
  3675. defer server.Close()
  3676. _, err = buildImageFromPath(name, server.URL()+"/testT.tar", true)
  3677. c.Assert(err, check.IsNil)
  3678. res, err := inspectField(name, "Author")
  3679. c.Assert(err, check.IsNil)
  3680. if res != "docker" {
  3681. c.Fatalf("Maintainer should be docker, got %s", res)
  3682. }
  3683. }
  3684. func (s *DockerSuite) TestBuildCleanupCmdOnEntrypoint(c *check.C) {
  3685. name := "testbuildcmdcleanuponentrypoint"
  3686. if _, err := buildImage(name,
  3687. `FROM scratch
  3688. CMD ["test"]
  3689. ENTRYPOINT ["echo"]`,
  3690. true); err != nil {
  3691. c.Fatal(err)
  3692. }
  3693. if _, err := buildImage(name,
  3694. fmt.Sprintf(`FROM %s
  3695. ENTRYPOINT ["cat"]`, name),
  3696. true); err != nil {
  3697. c.Fatal(err)
  3698. }
  3699. res, err := inspectField(name, "Config.Cmd")
  3700. if err != nil {
  3701. c.Fatal(err)
  3702. }
  3703. if res != "<nil>" {
  3704. c.Fatalf("Cmd %s, expected nil", res)
  3705. }
  3706. res, err = inspectField(name, "Config.Entrypoint")
  3707. if err != nil {
  3708. c.Fatal(err)
  3709. }
  3710. if expected := "{[cat]}"; res != expected {
  3711. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  3712. }
  3713. }
  3714. func (s *DockerSuite) TestBuildClearCmd(c *check.C) {
  3715. name := "testbuildclearcmd"
  3716. _, err := buildImage(name,
  3717. `From scratch
  3718. ENTRYPOINT ["/bin/bash"]
  3719. CMD []`,
  3720. true)
  3721. if err != nil {
  3722. c.Fatal(err)
  3723. }
  3724. res, err := inspectFieldJSON(name, "Config.Cmd")
  3725. if err != nil {
  3726. c.Fatal(err)
  3727. }
  3728. if res != "[]" {
  3729. c.Fatalf("Cmd %s, expected %s", res, "[]")
  3730. }
  3731. }
  3732. func (s *DockerSuite) TestBuildEmptyCmd(c *check.C) {
  3733. name := "testbuildemptycmd"
  3734. if _, err := buildImage(name, "FROM scratch\nMAINTAINER quux\n", true); err != nil {
  3735. c.Fatal(err)
  3736. }
  3737. res, err := inspectFieldJSON(name, "Config.Cmd")
  3738. if err != nil {
  3739. c.Fatal(err)
  3740. }
  3741. if res != "null" {
  3742. c.Fatalf("Cmd %s, expected %s", res, "null")
  3743. }
  3744. }
  3745. func (s *DockerSuite) TestBuildOnBuildOutput(c *check.C) {
  3746. name := "testbuildonbuildparent"
  3747. if _, err := buildImage(name, "FROM busybox\nONBUILD RUN echo foo\n", true); err != nil {
  3748. c.Fatal(err)
  3749. }
  3750. _, out, err := buildImageWithOut(name, "FROM "+name+"\nMAINTAINER quux\n", true)
  3751. if err != nil {
  3752. c.Fatal(err)
  3753. }
  3754. if !strings.Contains(out, "Trigger 0, RUN echo foo") {
  3755. c.Fatal("failed to find the ONBUILD output", out)
  3756. }
  3757. }
  3758. func (s *DockerSuite) TestBuildInvalidTag(c *check.C) {
  3759. name := "abcd:" + stringutils.GenerateRandomAlphaOnlyString(200)
  3760. _, out, err := buildImageWithOut(name, "FROM scratch\nMAINTAINER quux\n", true)
  3761. // if the error doesnt check for illegal tag name, or the image is built
  3762. // then this should fail
  3763. if !strings.Contains(out, "Illegal tag name") || strings.Contains(out, "Sending build context to Docker daemon") {
  3764. c.Fatalf("failed to stop before building. Error: %s, Output: %s", err, out)
  3765. }
  3766. }
  3767. func (s *DockerSuite) TestBuildCmdShDashC(c *check.C) {
  3768. name := "testbuildcmdshc"
  3769. if _, err := buildImage(name, "FROM busybox\nCMD echo cmd\n", true); err != nil {
  3770. c.Fatal(err)
  3771. }
  3772. res, err := inspectFieldJSON(name, "Config.Cmd")
  3773. if err != nil {
  3774. c.Fatal(err, res)
  3775. }
  3776. expected := `["/bin/sh","-c","echo cmd"]`
  3777. if res != expected {
  3778. c.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  3779. }
  3780. }
  3781. func (s *DockerSuite) TestBuildCmdSpaces(c *check.C) {
  3782. // Test to make sure that when we strcat arrays we take into account
  3783. // the arg separator to make sure ["echo","hi"] and ["echo hi"] don't
  3784. // look the same
  3785. name := "testbuildcmdspaces"
  3786. var id1 string
  3787. var id2 string
  3788. var err error
  3789. if id1, err = buildImage(name, "FROM busybox\nCMD [\"echo hi\"]\n", true); err != nil {
  3790. c.Fatal(err)
  3791. }
  3792. if id2, err = buildImage(name, "FROM busybox\nCMD [\"echo\", \"hi\"]\n", true); err != nil {
  3793. c.Fatal(err)
  3794. }
  3795. if id1 == id2 {
  3796. c.Fatal("Should not have resulted in the same CMD")
  3797. }
  3798. // Now do the same with ENTRYPOINT
  3799. if id1, err = buildImage(name, "FROM busybox\nENTRYPOINT [\"echo hi\"]\n", true); err != nil {
  3800. c.Fatal(err)
  3801. }
  3802. if id2, err = buildImage(name, "FROM busybox\nENTRYPOINT [\"echo\", \"hi\"]\n", true); err != nil {
  3803. c.Fatal(err)
  3804. }
  3805. if id1 == id2 {
  3806. c.Fatal("Should not have resulted in the same ENTRYPOINT")
  3807. }
  3808. }
  3809. func (s *DockerSuite) TestBuildCmdJSONNoShDashC(c *check.C) {
  3810. name := "testbuildcmdjson"
  3811. if _, err := buildImage(name, "FROM busybox\nCMD [\"echo\", \"cmd\"]", true); err != nil {
  3812. c.Fatal(err)
  3813. }
  3814. res, err := inspectFieldJSON(name, "Config.Cmd")
  3815. if err != nil {
  3816. c.Fatal(err, res)
  3817. }
  3818. expected := `["echo","cmd"]`
  3819. if res != expected {
  3820. c.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  3821. }
  3822. }
  3823. func (s *DockerSuite) TestBuildErrorInvalidInstruction(c *check.C) {
  3824. name := "testbuildignoreinvalidinstruction"
  3825. out, _, err := buildImageWithOut(name, "FROM busybox\nfoo bar", true)
  3826. if err == nil {
  3827. c.Fatalf("Should have failed: %s", out)
  3828. }
  3829. }
  3830. func (s *DockerSuite) TestBuildEntrypointInheritance(c *check.C) {
  3831. if _, err := buildImage("parent", `
  3832. FROM busybox
  3833. ENTRYPOINT exit 130
  3834. `, true); err != nil {
  3835. c.Fatal(err)
  3836. }
  3837. status, _ := runCommand(exec.Command(dockerBinary, "run", "parent"))
  3838. if status != 130 {
  3839. c.Fatalf("expected exit code 130 but received %d", status)
  3840. }
  3841. if _, err := buildImage("child", `
  3842. FROM parent
  3843. ENTRYPOINT exit 5
  3844. `, true); err != nil {
  3845. c.Fatal(err)
  3846. }
  3847. status, _ = runCommand(exec.Command(dockerBinary, "run", "child"))
  3848. if status != 5 {
  3849. c.Fatalf("expected exit code 5 but received %d", status)
  3850. }
  3851. }
  3852. func (s *DockerSuite) TestBuildEntrypointInheritanceInspect(c *check.C) {
  3853. var (
  3854. name = "testbuildepinherit"
  3855. name2 = "testbuildepinherit2"
  3856. expected = `["/bin/sh","-c","echo quux"]`
  3857. )
  3858. if _, err := buildImage(name, "FROM busybox\nENTRYPOINT /foo/bar", true); err != nil {
  3859. c.Fatal(err)
  3860. }
  3861. if _, err := buildImage(name2, fmt.Sprintf("FROM %s\nENTRYPOINT echo quux", name), true); err != nil {
  3862. c.Fatal(err)
  3863. }
  3864. res, err := inspectFieldJSON(name2, "Config.Entrypoint")
  3865. if err != nil {
  3866. c.Fatal(err, res)
  3867. }
  3868. if res != expected {
  3869. c.Fatalf("Expected value %s not in Config.Entrypoint: %s", expected, res)
  3870. }
  3871. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-t", name2))
  3872. if err != nil {
  3873. c.Fatal(err, out)
  3874. }
  3875. expected = "quux"
  3876. if strings.TrimSpace(out) != expected {
  3877. c.Fatalf("Expected output is %s, got %s", expected, out)
  3878. }
  3879. }
  3880. func (s *DockerSuite) TestBuildRunShEntrypoint(c *check.C) {
  3881. name := "testbuildentrypoint"
  3882. _, err := buildImage(name,
  3883. `FROM busybox
  3884. ENTRYPOINT /bin/echo`,
  3885. true)
  3886. if err != nil {
  3887. c.Fatal(err)
  3888. }
  3889. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--rm", name))
  3890. if err != nil {
  3891. c.Fatal(err, out)
  3892. }
  3893. }
  3894. func (s *DockerSuite) TestBuildExoticShellInterpolation(c *check.C) {
  3895. name := "testbuildexoticshellinterpolation"
  3896. _, err := buildImage(name, `
  3897. FROM busybox
  3898. ENV SOME_VAR a.b.c
  3899. RUN [ "$SOME_VAR" = 'a.b.c' ]
  3900. RUN [ "${SOME_VAR}" = 'a.b.c' ]
  3901. RUN [ "${SOME_VAR%.*}" = 'a.b' ]
  3902. RUN [ "${SOME_VAR%%.*}" = 'a' ]
  3903. RUN [ "${SOME_VAR#*.}" = 'b.c' ]
  3904. RUN [ "${SOME_VAR##*.}" = 'c' ]
  3905. RUN [ "${SOME_VAR/c/d}" = 'a.b.d' ]
  3906. RUN [ "${#SOME_VAR}" = '5' ]
  3907. RUN [ "${SOME_UNSET_VAR:-$SOME_VAR}" = 'a.b.c' ]
  3908. RUN [ "${SOME_VAR:+Version: ${SOME_VAR}}" = 'Version: a.b.c' ]
  3909. RUN [ "${SOME_UNSET_VAR:+${SOME_VAR}}" = '' ]
  3910. RUN [ "${SOME_UNSET_VAR:-${SOME_VAR:-d.e.f}}" = 'a.b.c' ]
  3911. `, false)
  3912. if err != nil {
  3913. c.Fatal(err)
  3914. }
  3915. }
  3916. func (s *DockerSuite) TestBuildVerifySingleQuoteFails(c *check.C) {
  3917. // This testcase is supposed to generate an error because the
  3918. // JSON array we're passing in on the CMD uses single quotes instead
  3919. // of double quotes (per the JSON spec). This means we interpret it
  3920. // as a "string" insead of "JSON array" and pass it on to "sh -c" and
  3921. // it should barf on it.
  3922. name := "testbuildsinglequotefails"
  3923. _, err := buildImage(name,
  3924. `FROM busybox
  3925. CMD [ '/bin/sh', '-c', 'echo hi' ]`,
  3926. true)
  3927. _, _, err = runCommandWithOutput(exec.Command(dockerBinary, "run", "--rm", name))
  3928. if err == nil {
  3929. c.Fatal("The image was not supposed to be able to run")
  3930. }
  3931. }
  3932. func (s *DockerSuite) TestBuildVerboseOut(c *check.C) {
  3933. name := "testbuildverboseout"
  3934. _, out, err := buildImageWithOut(name,
  3935. `FROM busybox
  3936. RUN echo 123`,
  3937. false)
  3938. if err != nil {
  3939. c.Fatal(err)
  3940. }
  3941. if !strings.Contains(out, "\n123\n") {
  3942. c.Fatalf("Output should contain %q: %q", "123", out)
  3943. }
  3944. }
  3945. func (s *DockerSuite) TestBuildWithTabs(c *check.C) {
  3946. name := "testbuildwithtabs"
  3947. _, err := buildImage(name,
  3948. "FROM busybox\nRUN echo\tone\t\ttwo", true)
  3949. if err != nil {
  3950. c.Fatal(err)
  3951. }
  3952. res, err := inspectFieldJSON(name, "ContainerConfig.Cmd")
  3953. if err != nil {
  3954. c.Fatal(err)
  3955. }
  3956. expected1 := `["/bin/sh","-c","echo\tone\t\ttwo"]`
  3957. expected2 := `["/bin/sh","-c","echo\u0009one\u0009\u0009two"]` // syntactically equivalent, and what Go 1.3 generates
  3958. if res != expected1 && res != expected2 {
  3959. c.Fatalf("Missing tabs.\nGot: %s\nExp: %s or %s", res, expected1, expected2)
  3960. }
  3961. }
  3962. func (s *DockerSuite) TestBuildLabels(c *check.C) {
  3963. name := "testbuildlabel"
  3964. expected := `{"License":"GPL","Vendor":"Acme"}`
  3965. _, err := buildImage(name,
  3966. `FROM busybox
  3967. LABEL Vendor=Acme
  3968. LABEL License GPL`,
  3969. true)
  3970. if err != nil {
  3971. c.Fatal(err)
  3972. }
  3973. res, err := inspectFieldJSON(name, "Config.Labels")
  3974. if err != nil {
  3975. c.Fatal(err)
  3976. }
  3977. if res != expected {
  3978. c.Fatalf("Labels %s, expected %s", res, expected)
  3979. }
  3980. }
  3981. func (s *DockerSuite) TestBuildLabelsCache(c *check.C) {
  3982. name := "testbuildlabelcache"
  3983. id1, err := buildImage(name,
  3984. `FROM busybox
  3985. LABEL Vendor=Acme`, false)
  3986. if err != nil {
  3987. c.Fatalf("Build 1 should have worked: %v", err)
  3988. }
  3989. id2, err := buildImage(name,
  3990. `FROM busybox
  3991. LABEL Vendor=Acme`, true)
  3992. if err != nil || id1 != id2 {
  3993. c.Fatalf("Build 2 should have worked & used cache(%s,%s): %v", id1, id2, err)
  3994. }
  3995. id2, err = buildImage(name,
  3996. `FROM busybox
  3997. LABEL Vendor=Acme1`, true)
  3998. if err != nil || id1 == id2 {
  3999. c.Fatalf("Build 3 should have worked & NOT used cache(%s,%s): %v", id1, id2, err)
  4000. }
  4001. id2, err = buildImage(name,
  4002. `FROM busybox
  4003. LABEL Vendor Acme`, true) // Note: " " and "=" should be same
  4004. if err != nil || id1 != id2 {
  4005. c.Fatalf("Build 4 should have worked & used cache(%s,%s): %v", id1, id2, err)
  4006. }
  4007. // Now make sure the cache isn't used by mistake
  4008. id1, err = buildImage(name,
  4009. `FROM busybox
  4010. LABEL f1=b1 f2=b2`, false)
  4011. if err != nil {
  4012. c.Fatalf("Build 5 should have worked: %q", err)
  4013. }
  4014. id2, err = buildImage(name,
  4015. `FROM busybox
  4016. LABEL f1="b1 f2=b2"`, true)
  4017. if err != nil || id1 == id2 {
  4018. c.Fatalf("Build 6 should have worked & NOT used the cache(%s,%s): %q", id1, id2, err)
  4019. }
  4020. }
  4021. func (s *DockerSuite) TestBuildStderr(c *check.C) {
  4022. // This test just makes sure that no non-error output goes
  4023. // to stderr
  4024. name := "testbuildstderr"
  4025. _, _, stderr, err := buildImageWithStdoutStderr(name,
  4026. "FROM busybox\nRUN echo one", true)
  4027. if err != nil {
  4028. c.Fatal(err)
  4029. }
  4030. if runtime.GOOS == "windows" {
  4031. // stderr might contain a security warning on windows
  4032. lines := strings.Split(stderr, "\n")
  4033. for _, v := range lines {
  4034. if v != "" && !strings.Contains(v, "SECURITY WARNING:") {
  4035. c.Fatalf("Stderr contains unexpected output line: %q", v)
  4036. }
  4037. }
  4038. } else {
  4039. if stderr != "" {
  4040. c.Fatalf("Stderr should have been empty, instead its: %q", stderr)
  4041. }
  4042. }
  4043. }
  4044. func (s *DockerSuite) TestBuildChownSingleFile(c *check.C) {
  4045. testRequires(c, UnixCli) // test uses chown: not available on windows
  4046. name := "testbuildchownsinglefile"
  4047. ctx, err := fakeContext(`
  4048. FROM busybox
  4049. COPY test /
  4050. RUN ls -l /test
  4051. RUN [ $(ls -l /test | awk '{print $3":"$4}') = 'root:root' ]
  4052. `, map[string]string{
  4053. "test": "test",
  4054. })
  4055. if err != nil {
  4056. c.Fatal(err)
  4057. }
  4058. defer ctx.Close()
  4059. if err := os.Chown(filepath.Join(ctx.Dir, "test"), 4242, 4242); err != nil {
  4060. c.Fatal(err)
  4061. }
  4062. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  4063. c.Fatal(err)
  4064. }
  4065. }
  4066. func (s *DockerSuite) TestBuildSymlinkBreakout(c *check.C) {
  4067. name := "testbuildsymlinkbreakout"
  4068. tmpdir, err := ioutil.TempDir("", name)
  4069. if err != nil {
  4070. c.Fatal(err)
  4071. }
  4072. defer os.RemoveAll(tmpdir)
  4073. ctx := filepath.Join(tmpdir, "context")
  4074. if err := os.MkdirAll(ctx, 0755); err != nil {
  4075. c.Fatal(err)
  4076. }
  4077. if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte(`
  4078. from busybox
  4079. add symlink.tar /
  4080. add inject /symlink/
  4081. `), 0644); err != nil {
  4082. c.Fatal(err)
  4083. }
  4084. inject := filepath.Join(ctx, "inject")
  4085. if err := ioutil.WriteFile(inject, nil, 0644); err != nil {
  4086. c.Fatal(err)
  4087. }
  4088. f, err := os.Create(filepath.Join(ctx, "symlink.tar"))
  4089. if err != nil {
  4090. c.Fatal(err)
  4091. }
  4092. w := tar.NewWriter(f)
  4093. w.WriteHeader(&tar.Header{
  4094. Name: "symlink2",
  4095. Typeflag: tar.TypeSymlink,
  4096. Linkname: "/../../../../../../../../../../../../../../",
  4097. Uid: os.Getuid(),
  4098. Gid: os.Getgid(),
  4099. })
  4100. w.WriteHeader(&tar.Header{
  4101. Name: "symlink",
  4102. Typeflag: tar.TypeSymlink,
  4103. Linkname: filepath.Join("symlink2", tmpdir),
  4104. Uid: os.Getuid(),
  4105. Gid: os.Getgid(),
  4106. })
  4107. w.Close()
  4108. f.Close()
  4109. if _, err := buildImageFromContext(name, fakeContextFromDir(ctx), false); err != nil {
  4110. c.Fatal(err)
  4111. }
  4112. if _, err := os.Lstat(filepath.Join(tmpdir, "inject")); err == nil {
  4113. c.Fatal("symlink breakout - inject")
  4114. } else if !os.IsNotExist(err) {
  4115. c.Fatalf("unexpected error: %v", err)
  4116. }
  4117. }
  4118. func (s *DockerSuite) TestBuildXZHost(c *check.C) {
  4119. name := "testbuildxzhost"
  4120. ctx, err := fakeContext(`
  4121. FROM busybox
  4122. ADD xz /usr/local/sbin/
  4123. RUN chmod 755 /usr/local/sbin/xz
  4124. ADD test.xz /
  4125. RUN [ ! -e /injected ]`,
  4126. map[string]string{
  4127. "test.xz": "\xfd\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00" +
  4128. "\x21\x01\x16\x00\x00\x00\x74\x2f\xe5\xa3\x01\x00\x3f\xfd" +
  4129. "\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00\x21",
  4130. "xz": "#!/bin/sh\ntouch /injected",
  4131. })
  4132. if err != nil {
  4133. c.Fatal(err)
  4134. }
  4135. defer ctx.Close()
  4136. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  4137. c.Fatal(err)
  4138. }
  4139. }
  4140. func (s *DockerSuite) TestBuildVolumesRetainContents(c *check.C) {
  4141. var (
  4142. name = "testbuildvolumescontent"
  4143. expected = "some text"
  4144. )
  4145. ctx, err := fakeContext(`
  4146. FROM busybox
  4147. COPY content /foo/file
  4148. VOLUME /foo
  4149. CMD cat /foo/file`,
  4150. map[string]string{
  4151. "content": expected,
  4152. })
  4153. if err != nil {
  4154. c.Fatal(err)
  4155. }
  4156. defer ctx.Close()
  4157. if _, err := buildImageFromContext(name, ctx, false); err != nil {
  4158. c.Fatal(err)
  4159. }
  4160. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--rm", name))
  4161. if err != nil {
  4162. c.Fatal(err)
  4163. }
  4164. if out != expected {
  4165. c.Fatalf("expected file contents for /foo/file to be %q but received %q", expected, out)
  4166. }
  4167. }
  4168. func (s *DockerSuite) TestBuildRenamedDockerfile(c *check.C) {
  4169. ctx, err := fakeContext(`FROM busybox
  4170. RUN echo from Dockerfile`,
  4171. map[string]string{
  4172. "Dockerfile": "FROM busybox\nRUN echo from Dockerfile",
  4173. "files/Dockerfile": "FROM busybox\nRUN echo from files/Dockerfile",
  4174. "files/dFile": "FROM busybox\nRUN echo from files/dFile",
  4175. "dFile": "FROM busybox\nRUN echo from dFile",
  4176. "files/dFile2": "FROM busybox\nRUN echo from files/dFile2",
  4177. })
  4178. defer ctx.Close()
  4179. if err != nil {
  4180. c.Fatal(err)
  4181. }
  4182. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", "test1", ".")
  4183. if err != nil {
  4184. c.Fatalf("Failed to build: %s\n%s", out, err)
  4185. }
  4186. if !strings.Contains(out, "from Dockerfile") {
  4187. c.Fatalf("test1 should have used Dockerfile, output:%s", out)
  4188. }
  4189. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", "-f", filepath.Join("files", "Dockerfile"), "-t", "test2", ".")
  4190. if err != nil {
  4191. c.Fatal(err)
  4192. }
  4193. if !strings.Contains(out, "from files/Dockerfile") {
  4194. c.Fatalf("test2 should have used files/Dockerfile, output:%s", out)
  4195. }
  4196. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", fmt.Sprintf("--file=%s", filepath.Join("files", "dFile")), "-t", "test3", ".")
  4197. if err != nil {
  4198. c.Fatal(err)
  4199. }
  4200. if !strings.Contains(out, "from files/dFile") {
  4201. c.Fatalf("test3 should have used files/dFile, output:%s", out)
  4202. }
  4203. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", "--file=dFile", "-t", "test4", ".")
  4204. if err != nil {
  4205. c.Fatal(err)
  4206. }
  4207. if !strings.Contains(out, "from dFile") {
  4208. c.Fatalf("test4 should have used dFile, output:%s", out)
  4209. }
  4210. dirWithNoDockerfile, _ := ioutil.TempDir(os.TempDir(), "test5")
  4211. nonDockerfileFile := filepath.Join(dirWithNoDockerfile, "notDockerfile")
  4212. if _, err = os.Create(nonDockerfileFile); err != nil {
  4213. c.Fatal(err)
  4214. }
  4215. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", fmt.Sprintf("--file=%s", nonDockerfileFile), "-t", "test5", ".")
  4216. if err == nil {
  4217. c.Fatalf("test5 was supposed to fail to find passwd")
  4218. }
  4219. if expected := fmt.Sprintf("The Dockerfile (%s) must be within the build context (.)", nonDockerfileFile); !strings.Contains(out, expected) {
  4220. c.Fatalf("wrong error messsage:%v\nexpected to contain=%v", out, expected)
  4221. }
  4222. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join("..", "Dockerfile"), "-t", "test6", "..")
  4223. if err != nil {
  4224. c.Fatalf("test6 failed: %s", err)
  4225. }
  4226. if !strings.Contains(out, "from Dockerfile") {
  4227. c.Fatalf("test6 should have used root Dockerfile, output:%s", out)
  4228. }
  4229. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join(ctx.Dir, "files", "Dockerfile"), "-t", "test7", "..")
  4230. if err != nil {
  4231. c.Fatalf("test7 failed: %s", err)
  4232. }
  4233. if !strings.Contains(out, "from files/Dockerfile") {
  4234. c.Fatalf("test7 should have used files Dockerfile, output:%s", out)
  4235. }
  4236. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join("..", "Dockerfile"), "-t", "test8", ".")
  4237. if err == nil || !strings.Contains(out, "must be within the build context") {
  4238. c.Fatalf("test8 should have failed with Dockerfile out of context: %s", err)
  4239. }
  4240. tmpDir := os.TempDir()
  4241. out, _, err = dockerCmdInDir(c, tmpDir, "build", "-t", "test9", ctx.Dir)
  4242. if err != nil {
  4243. c.Fatalf("test9 - failed: %s", err)
  4244. }
  4245. if !strings.Contains(out, "from Dockerfile") {
  4246. c.Fatalf("test9 should have used root Dockerfile, output:%s", out)
  4247. }
  4248. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", "dFile2", "-t", "test10", ".")
  4249. if err != nil {
  4250. c.Fatalf("test10 should have worked: %s", err)
  4251. }
  4252. if !strings.Contains(out, "from files/dFile2") {
  4253. c.Fatalf("test10 should have used files/dFile2, output:%s", out)
  4254. }
  4255. }
  4256. func (s *DockerSuite) TestBuildFromMixedcaseDockerfile(c *check.C) {
  4257. testRequires(c, UnixCli) // Dockerfile overwrites dockerfile on windows
  4258. ctx, err := fakeContext(`FROM busybox
  4259. RUN echo from dockerfile`,
  4260. map[string]string{
  4261. "dockerfile": "FROM busybox\nRUN echo from dockerfile",
  4262. })
  4263. defer ctx.Close()
  4264. if err != nil {
  4265. c.Fatal(err)
  4266. }
  4267. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", "test1", ".")
  4268. if err != nil {
  4269. c.Fatalf("Failed to build: %s\n%s", out, err)
  4270. }
  4271. if !strings.Contains(out, "from dockerfile") {
  4272. c.Fatalf("Missing proper output: %s", out)
  4273. }
  4274. }
  4275. func (s *DockerSuite) TestBuildWithTwoDockerfiles(c *check.C) {
  4276. testRequires(c, UnixCli) // Dockerfile overwrites dockerfile on windows
  4277. ctx, err := fakeContext(`FROM busybox
  4278. RUN echo from Dockerfile`,
  4279. map[string]string{
  4280. "dockerfile": "FROM busybox\nRUN echo from dockerfile",
  4281. })
  4282. defer ctx.Close()
  4283. if err != nil {
  4284. c.Fatal(err)
  4285. }
  4286. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", "test1", ".")
  4287. if err != nil {
  4288. c.Fatalf("Failed to build: %s\n%s", out, err)
  4289. }
  4290. if !strings.Contains(out, "from Dockerfile") {
  4291. c.Fatalf("Missing proper output: %s", out)
  4292. }
  4293. }
  4294. func (s *DockerSuite) TestBuildFromURLWithF(c *check.C) {
  4295. server, err := fakeStorage(map[string]string{"baz": `FROM busybox
  4296. RUN echo from baz
  4297. COPY * /tmp/
  4298. RUN find /tmp/`})
  4299. if err != nil {
  4300. c.Fatal(err)
  4301. }
  4302. defer server.Close()
  4303. ctx, err := fakeContext(`FROM busybox
  4304. RUN echo from Dockerfile`,
  4305. map[string]string{})
  4306. defer ctx.Close()
  4307. if err != nil {
  4308. c.Fatal(err)
  4309. }
  4310. // Make sure that -f is ignored and that we don't use the Dockerfile
  4311. // that's in the current dir
  4312. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-f", "baz", "-t", "test1", server.URL()+"/baz")
  4313. if err != nil {
  4314. c.Fatalf("Failed to build: %s\n%s", out, err)
  4315. }
  4316. if !strings.Contains(out, "from baz") ||
  4317. strings.Contains(out, "/tmp/baz") ||
  4318. !strings.Contains(out, "/tmp/Dockerfile") {
  4319. c.Fatalf("Missing proper output: %s", out)
  4320. }
  4321. }
  4322. func (s *DockerSuite) TestBuildFromStdinWithF(c *check.C) {
  4323. ctx, err := fakeContext(`FROM busybox
  4324. RUN echo from Dockerfile`,
  4325. map[string]string{})
  4326. defer ctx.Close()
  4327. if err != nil {
  4328. c.Fatal(err)
  4329. }
  4330. // Make sure that -f is ignored and that we don't use the Dockerfile
  4331. // that's in the current dir
  4332. dockerCommand := exec.Command(dockerBinary, "build", "-f", "baz", "-t", "test1", "-")
  4333. dockerCommand.Dir = ctx.Dir
  4334. dockerCommand.Stdin = strings.NewReader(`FROM busybox
  4335. RUN echo from baz
  4336. COPY * /tmp/
  4337. RUN find /tmp/`)
  4338. out, status, err := runCommandWithOutput(dockerCommand)
  4339. if err != nil || status != 0 {
  4340. c.Fatalf("Error building: %s", err)
  4341. }
  4342. if !strings.Contains(out, "from baz") ||
  4343. strings.Contains(out, "/tmp/baz") ||
  4344. !strings.Contains(out, "/tmp/Dockerfile") {
  4345. c.Fatalf("Missing proper output: %s", out)
  4346. }
  4347. }
  4348. func (s *DockerSuite) TestBuildFromOfficialNames(c *check.C) {
  4349. name := "testbuildfromofficial"
  4350. fromNames := []string{
  4351. "busybox",
  4352. "docker.io/busybox",
  4353. "index.docker.io/busybox",
  4354. "library/busybox",
  4355. "docker.io/library/busybox",
  4356. "index.docker.io/library/busybox",
  4357. }
  4358. for idx, fromName := range fromNames {
  4359. imgName := fmt.Sprintf("%s%d", name, idx)
  4360. _, err := buildImage(imgName, "FROM "+fromName, true)
  4361. if err != nil {
  4362. c.Errorf("Build failed using FROM %s: %s", fromName, err)
  4363. }
  4364. deleteImages(imgName)
  4365. }
  4366. }
  4367. func (s *DockerSuite) TestBuildDockerfileOutsideContext(c *check.C) {
  4368. testRequires(c, UnixCli) // uses os.Symlink: not implemented in windows at the time of writing (go-1.4.2)
  4369. name := "testbuilddockerfileoutsidecontext"
  4370. tmpdir, err := ioutil.TempDir("", name)
  4371. if err != nil {
  4372. c.Fatal(err)
  4373. }
  4374. defer os.RemoveAll(tmpdir)
  4375. ctx := filepath.Join(tmpdir, "context")
  4376. if err := os.MkdirAll(ctx, 0755); err != nil {
  4377. c.Fatal(err)
  4378. }
  4379. if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte("FROM scratch\nENV X Y"), 0644); err != nil {
  4380. c.Fatal(err)
  4381. }
  4382. wd, err := os.Getwd()
  4383. if err != nil {
  4384. c.Fatal(err)
  4385. }
  4386. defer os.Chdir(wd)
  4387. if err := os.Chdir(ctx); err != nil {
  4388. c.Fatal(err)
  4389. }
  4390. if err := ioutil.WriteFile(filepath.Join(tmpdir, "outsideDockerfile"), []byte("FROM scratch\nENV x y"), 0644); err != nil {
  4391. c.Fatal(err)
  4392. }
  4393. if err := os.Symlink(filepath.Join("..", "outsideDockerfile"), filepath.Join(ctx, "dockerfile1")); err != nil {
  4394. c.Fatal(err)
  4395. }
  4396. if err := os.Symlink(filepath.Join(tmpdir, "outsideDockerfile"), filepath.Join(ctx, "dockerfile2")); err != nil {
  4397. c.Fatal(err)
  4398. }
  4399. for _, dockerfilePath := range []string{
  4400. filepath.Join("..", "outsideDockerfile"),
  4401. filepath.Join(ctx, "dockerfile1"),
  4402. filepath.Join(ctx, "dockerfile2"),
  4403. } {
  4404. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "build", "-t", name, "--no-cache", "-f", dockerfilePath, "."))
  4405. if err == nil {
  4406. c.Fatalf("Expected error with %s. Out: %s", dockerfilePath, out)
  4407. }
  4408. if !strings.Contains(out, "must be within the build context") && !strings.Contains(out, "Cannot locate Dockerfile") {
  4409. c.Fatalf("Unexpected error with %s. Out: %s", dockerfilePath, out)
  4410. }
  4411. deleteImages(name)
  4412. }
  4413. os.Chdir(tmpdir)
  4414. // Path to Dockerfile should be resolved relative to working directory, not relative to context.
  4415. // There is a Dockerfile in the context, but since there is no Dockerfile in the current directory, the following should fail
  4416. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "build", "-t", name, "--no-cache", "-f", "Dockerfile", ctx))
  4417. if err == nil {
  4418. c.Fatalf("Expected error. Out: %s", out)
  4419. }
  4420. }
  4421. func (s *DockerSuite) TestBuildSpaces(c *check.C) {
  4422. // Test to make sure that leading/trailing spaces on a command
  4423. // doesn't change the error msg we get
  4424. var (
  4425. err1 error
  4426. err2 error
  4427. )
  4428. name := "testspaces"
  4429. ctx, err := fakeContext("FROM busybox\nCOPY\n",
  4430. map[string]string{
  4431. "Dockerfile": "FROM busybox\nCOPY\n",
  4432. })
  4433. if err != nil {
  4434. c.Fatal(err)
  4435. }
  4436. defer ctx.Close()
  4437. if _, err1 = buildImageFromContext(name, ctx, false); err1 == nil {
  4438. c.Fatal("Build 1 was supposed to fail, but didn't")
  4439. }
  4440. ctx.Add("Dockerfile", "FROM busybox\nCOPY ")
  4441. if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil {
  4442. c.Fatal("Build 2 was supposed to fail, but didn't")
  4443. }
  4444. removeLogTimestamps := func(s string) string {
  4445. return regexp.MustCompile(`time="(.*?)"`).ReplaceAllString(s, `time=[TIMESTAMP]`)
  4446. }
  4447. // Skip over the times
  4448. e1 := removeLogTimestamps(err1.Error())
  4449. e2 := removeLogTimestamps(err2.Error())
  4450. // Ignore whitespace since that's what were verifying doesn't change stuff
  4451. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  4452. c.Fatalf("Build 2's error wasn't the same as build 1's\n1:%s\n2:%s", err1, err2)
  4453. }
  4454. ctx.Add("Dockerfile", "FROM busybox\n COPY")
  4455. if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil {
  4456. c.Fatal("Build 3 was supposed to fail, but didn't")
  4457. }
  4458. // Skip over the times
  4459. e1 = removeLogTimestamps(err1.Error())
  4460. e2 = removeLogTimestamps(err2.Error())
  4461. // Ignore whitespace since that's what were verifying doesn't change stuff
  4462. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  4463. c.Fatalf("Build 3's error wasn't the same as build 1's\n1:%s\n3:%s", err1, err2)
  4464. }
  4465. ctx.Add("Dockerfile", "FROM busybox\n COPY ")
  4466. if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil {
  4467. c.Fatal("Build 4 was supposed to fail, but didn't")
  4468. }
  4469. // Skip over the times
  4470. e1 = removeLogTimestamps(err1.Error())
  4471. e2 = removeLogTimestamps(err2.Error())
  4472. // Ignore whitespace since that's what were verifying doesn't change stuff
  4473. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  4474. c.Fatalf("Build 4's error wasn't the same as build 1's\n1:%s\n4:%s", err1, err2)
  4475. }
  4476. }
  4477. func (s *DockerSuite) TestBuildSpacesWithQuotes(c *check.C) {
  4478. // Test to make sure that spaces in quotes aren't lost
  4479. name := "testspacesquotes"
  4480. dockerfile := `FROM busybox
  4481. RUN echo " \
  4482. foo "`
  4483. _, out, err := buildImageWithOut(name, dockerfile, false)
  4484. if err != nil {
  4485. c.Fatal("Build failed:", err)
  4486. }
  4487. expecting := "\n foo \n"
  4488. if !strings.Contains(out, expecting) {
  4489. c.Fatalf("Bad output: %q expecting to contain %q", out, expecting)
  4490. }
  4491. }
  4492. // #4393
  4493. func (s *DockerSuite) TestBuildVolumeFileExistsinContainer(c *check.C) {
  4494. buildCmd := exec.Command(dockerBinary, "build", "-t", "docker-test-errcreatevolumewithfile", "-")
  4495. buildCmd.Stdin = strings.NewReader(`
  4496. FROM busybox
  4497. RUN touch /foo
  4498. VOLUME /foo
  4499. `)
  4500. out, _, err := runCommandWithOutput(buildCmd)
  4501. if err == nil || !strings.Contains(out, "file exists") {
  4502. c.Fatalf("expected build to fail when file exists in container at requested volume path")
  4503. }
  4504. }
  4505. func (s *DockerSuite) TestBuildMissingArgs(c *check.C) {
  4506. // Test to make sure that all Dockerfile commands (except the ones listed
  4507. // in skipCmds) will generate an error if no args are provided.
  4508. // Note: INSERT is deprecated so we exclude it because of that.
  4509. skipCmds := map[string]struct{}{
  4510. "CMD": {},
  4511. "RUN": {},
  4512. "ENTRYPOINT": {},
  4513. "INSERT": {},
  4514. }
  4515. for cmd := range command.Commands {
  4516. cmd = strings.ToUpper(cmd)
  4517. if _, ok := skipCmds[cmd]; ok {
  4518. continue
  4519. }
  4520. var dockerfile string
  4521. if cmd == "FROM" {
  4522. dockerfile = cmd
  4523. } else {
  4524. // Add FROM to make sure we don't complain about it missing
  4525. dockerfile = "FROM busybox\n" + cmd
  4526. }
  4527. ctx, err := fakeContext(dockerfile, map[string]string{})
  4528. if err != nil {
  4529. c.Fatal(err)
  4530. }
  4531. defer ctx.Close()
  4532. var out string
  4533. if out, err = buildImageFromContext("args", ctx, true); err == nil {
  4534. c.Fatalf("%s was supposed to fail. Out:%s", cmd, out)
  4535. }
  4536. if !strings.Contains(err.Error(), cmd+" requires") {
  4537. c.Fatalf("%s returned the wrong type of error:%s", cmd, err)
  4538. }
  4539. }
  4540. }
  4541. func (s *DockerSuite) TestBuildEmptyScratch(c *check.C) {
  4542. _, out, err := buildImageWithOut("sc", "FROM scratch", true)
  4543. if err == nil {
  4544. c.Fatalf("Build was supposed to fail")
  4545. }
  4546. if !strings.Contains(out, "No image was generated") {
  4547. c.Fatalf("Wrong error message: %v", out)
  4548. }
  4549. }
  4550. func (s *DockerSuite) TestBuildDotDotFile(c *check.C) {
  4551. ctx, err := fakeContext("FROM busybox\n",
  4552. map[string]string{
  4553. "..gitme": "",
  4554. })
  4555. if err != nil {
  4556. c.Fatal(err)
  4557. }
  4558. defer ctx.Close()
  4559. if _, err = buildImageFromContext("sc", ctx, false); err != nil {
  4560. c.Fatalf("Build was supposed to work: %s", err)
  4561. }
  4562. }
  4563. func (s *DockerSuite) TestBuildNotVerbose(c *check.C) {
  4564. ctx, err := fakeContext("FROM busybox\nENV abc=hi\nRUN echo $abc there", map[string]string{})
  4565. if err != nil {
  4566. c.Fatal(err)
  4567. }
  4568. defer ctx.Close()
  4569. // First do it w/verbose - baseline
  4570. buildCmd := exec.Command(dockerBinary, "build", "--no-cache", "-t", "verbose", ".")
  4571. buildCmd.Dir = ctx.Dir
  4572. out, _, err := runCommandWithOutput(buildCmd)
  4573. if err != nil {
  4574. c.Fatalf("failed to build the image w/o -q: %s, %v", out, err)
  4575. }
  4576. if !strings.Contains(out, "hi there") {
  4577. c.Fatalf("missing output:%s\n", out)
  4578. }
  4579. // Now do it w/o verbose
  4580. buildCmd = exec.Command(dockerBinary, "build", "--no-cache", "-q", "-t", "verbose", ".")
  4581. buildCmd.Dir = ctx.Dir
  4582. out, _, err = runCommandWithOutput(buildCmd)
  4583. if err != nil {
  4584. c.Fatalf("failed to build the image w/ -q: %s, %v", out, err)
  4585. }
  4586. if strings.Contains(out, "hi there") {
  4587. c.Fatalf("Bad output, should not contain 'hi there':%s", out)
  4588. }
  4589. }
  4590. func (s *DockerSuite) TestBuildRUNoneJSON(c *check.C) {
  4591. name := "testbuildrunonejson"
  4592. ctx, err := fakeContext(`FROM hello-world:frozen
  4593. RUN [ "/hello" ]`, map[string]string{})
  4594. if err != nil {
  4595. c.Fatal(err)
  4596. }
  4597. defer ctx.Close()
  4598. buildCmd := exec.Command(dockerBinary, "build", "--no-cache", "-t", name, ".")
  4599. buildCmd.Dir = ctx.Dir
  4600. out, _, err := runCommandWithOutput(buildCmd)
  4601. if err != nil {
  4602. c.Fatalf("failed to build the image: %s, %v", out, err)
  4603. }
  4604. if !strings.Contains(out, "Hello from Docker") {
  4605. c.Fatalf("bad output: %s", out)
  4606. }
  4607. }
  4608. func (s *DockerSuite) TestBuildEmptyStringVolume(c *check.C) {
  4609. name := "testbuildemptystringvolume"
  4610. _, err := buildImage(name, `
  4611. FROM busybox
  4612. ENV foo=""
  4613. VOLUME $foo
  4614. `, false)
  4615. if err == nil {
  4616. c.Fatal("Should have failed to build")
  4617. }
  4618. }
  4619. func (s *DockerSuite) TestBuildContainerWithCgroupParent(c *check.C) {
  4620. testRequires(c, NativeExecDriver)
  4621. testRequires(c, SameHostDaemon)
  4622. defer deleteImages()
  4623. cgroupParent := "test"
  4624. data, err := ioutil.ReadFile("/proc/self/cgroup")
  4625. if err != nil {
  4626. c.Fatalf("failed to read '/proc/self/cgroup - %v", err)
  4627. }
  4628. selfCgroupPaths := parseCgroupPaths(string(data))
  4629. _, found := selfCgroupPaths["memory"]
  4630. if !found {
  4631. c.Fatalf("unable to find self cpu cgroup path. CgroupsPath: %v", selfCgroupPaths)
  4632. }
  4633. cmd := exec.Command(dockerBinary, "build", "--cgroup-parent", cgroupParent, "-")
  4634. cmd.Stdin = strings.NewReader(`
  4635. FROM busybox
  4636. RUN cat /proc/self/cgroup
  4637. `)
  4638. out, _, err := runCommandWithOutput(cmd)
  4639. if err != nil {
  4640. c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err)
  4641. }
  4642. }
  4643. func (s *DockerSuite) TestBuildNoDupOutput(c *check.C) {
  4644. // Check to make sure our build output prints the Dockerfile cmd
  4645. // property - there was a bug that caused it to be duplicated on the
  4646. // Step X line
  4647. name := "testbuildnodupoutput"
  4648. _, out, err := buildImageWithOut(name, `
  4649. FROM busybox
  4650. RUN env`, false)
  4651. if err != nil {
  4652. c.Fatalf("Build should have worked: %q", err)
  4653. }
  4654. exp := "\nStep 1 : RUN env\n"
  4655. if !strings.Contains(out, exp) {
  4656. c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", out, exp)
  4657. }
  4658. }
  4659. func (s *DockerSuite) TestBuildBadCmdFlag(c *check.C) {
  4660. name := "testbuildbadcmdflag"
  4661. _, out, err := buildImageWithOut(name, `
  4662. FROM busybox
  4663. MAINTAINER --boo joe@example.com`, false)
  4664. if err == nil {
  4665. c.Fatal("Build should have failed")
  4666. }
  4667. exp := "\nUnknown flag: boo\n"
  4668. if !strings.Contains(out, exp) {
  4669. c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", out, exp)
  4670. }
  4671. }
  4672. func (s *DockerSuite) TestBuildRUNErrMsg(c *check.C) {
  4673. // Test to make sure the bad command is quoted with just "s and
  4674. // not as a Go []string
  4675. name := "testbuildbadrunerrmsg"
  4676. _, out, err := buildImageWithOut(name, `
  4677. FROM busybox
  4678. RUN badEXE a1 \& a2 a3`, false) // tab between a2 and a3
  4679. if err == nil {
  4680. c.Fatal("Should have failed to build")
  4681. }
  4682. exp := `The command '/bin/sh -c badEXE a1 \& a2 a3' returned a non-zero code: 127`
  4683. if !strings.Contains(out, exp) {
  4684. c.Fatalf("RUN doesn't have the correct output:\nGot:%s\nExpected:%s", out, exp)
  4685. }
  4686. }