docker_cli_build_test.go 143 KB

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