docker_cli_build_test.go 197 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246
  1. package main
  2. import (
  3. "archive/tar"
  4. "bytes"
  5. "encoding/json"
  6. "fmt"
  7. "io/ioutil"
  8. "os"
  9. "path/filepath"
  10. "reflect"
  11. "regexp"
  12. "runtime"
  13. "strconv"
  14. "strings"
  15. "testing"
  16. "text/template"
  17. "time"
  18. "github.com/docker/docker/integration-cli/cli"
  19. "github.com/docker/docker/integration-cli/cli/build"
  20. "github.com/docker/docker/internal/test/fakecontext"
  21. "github.com/docker/docker/internal/test/fakegit"
  22. "github.com/docker/docker/internal/test/fakestorage"
  23. "github.com/docker/docker/internal/testutil"
  24. "github.com/docker/docker/pkg/archive"
  25. "github.com/docker/docker/pkg/system"
  26. "github.com/go-check/check"
  27. "github.com/moby/buildkit/frontend/dockerfile/command"
  28. "github.com/opencontainers/go-digest"
  29. "gotest.tools/assert"
  30. "gotest.tools/assert/cmp"
  31. "gotest.tools/icmd"
  32. )
  33. func (s *DockerSuite) TestBuildJSONEmptyRun(c *testing.T) {
  34. cli.BuildCmd(c, "testbuildjsonemptyrun", build.WithDockerfile(`
  35. FROM busybox
  36. RUN []
  37. `))
  38. }
  39. func (s *DockerSuite) TestBuildShCmdJSONEntrypoint(c *testing.T) {
  40. name := "testbuildshcmdjsonentrypoint"
  41. expected := "/bin/sh -c echo test"
  42. if testEnv.OSType == "windows" {
  43. expected = "cmd /S /C echo test"
  44. }
  45. buildImageSuccessfully(c, name, build.WithDockerfile(`
  46. FROM busybox
  47. ENTRYPOINT ["echo"]
  48. CMD echo test
  49. `))
  50. out, _ := dockerCmd(c, "run", "--rm", name)
  51. if strings.TrimSpace(out) != expected {
  52. c.Fatalf("CMD did not contain %q : %q", expected, out)
  53. }
  54. }
  55. func (s *DockerSuite) TestBuildEnvironmentReplacementUser(c *testing.T) {
  56. // Windows does not support FROM scratch or the USER command
  57. testRequires(c, DaemonIsLinux)
  58. name := "testbuildenvironmentreplacement"
  59. buildImageSuccessfully(c, name, build.WithDockerfile(`
  60. FROM scratch
  61. ENV user foo
  62. USER ${user}
  63. `))
  64. res := inspectFieldJSON(c, name, "Config.User")
  65. if res != `"foo"` {
  66. c.Fatal("User foo from environment not in Config.User on image")
  67. }
  68. }
  69. func (s *DockerSuite) TestBuildEnvironmentReplacementVolume(c *testing.T) {
  70. name := "testbuildenvironmentreplacement"
  71. var volumePath string
  72. if testEnv.OSType == "windows" {
  73. volumePath = "c:/quux"
  74. } else {
  75. volumePath = "/quux"
  76. }
  77. buildImageSuccessfully(c, name, build.WithDockerfile(`
  78. FROM `+minimalBaseImage()+`
  79. ENV volume `+volumePath+`
  80. VOLUME ${volume}
  81. `))
  82. var volumes map[string]interface{}
  83. inspectFieldAndUnmarshall(c, name, "Config.Volumes", &volumes)
  84. if _, ok := volumes[volumePath]; !ok {
  85. c.Fatal("Volume " + volumePath + " from environment not in Config.Volumes on image")
  86. }
  87. }
  88. func (s *DockerSuite) TestBuildEnvironmentReplacementExpose(c *testing.T) {
  89. // Windows does not support FROM scratch or the EXPOSE command
  90. testRequires(c, DaemonIsLinux)
  91. name := "testbuildenvironmentreplacement"
  92. buildImageSuccessfully(c, name, build.WithDockerfile(`
  93. FROM scratch
  94. ENV port 80
  95. EXPOSE ${port}
  96. ENV ports " 99 100 "
  97. EXPOSE ${ports}
  98. `))
  99. var exposedPorts map[string]interface{}
  100. inspectFieldAndUnmarshall(c, name, "Config.ExposedPorts", &exposedPorts)
  101. exp := []int{80, 99, 100}
  102. for _, p := range exp {
  103. tmp := fmt.Sprintf("%d/tcp", p)
  104. if _, ok := exposedPorts[tmp]; !ok {
  105. c.Fatalf("Exposed port %d from environment not in Config.ExposedPorts on image", p)
  106. }
  107. }
  108. }
  109. func (s *DockerSuite) TestBuildEnvironmentReplacementWorkdir(c *testing.T) {
  110. name := "testbuildenvironmentreplacement"
  111. buildImageSuccessfully(c, name, build.WithDockerfile(`
  112. FROM busybox
  113. ENV MYWORKDIR /work
  114. RUN mkdir ${MYWORKDIR}
  115. WORKDIR ${MYWORKDIR}
  116. `))
  117. res := inspectFieldJSON(c, name, "Config.WorkingDir")
  118. expected := `"/work"`
  119. if testEnv.OSType == "windows" {
  120. expected = `"C:\\work"`
  121. }
  122. if res != expected {
  123. c.Fatalf("Workdir /workdir from environment not in Config.WorkingDir on image: %s", res)
  124. }
  125. }
  126. func (s *DockerSuite) TestBuildEnvironmentReplacementAddCopy(c *testing.T) {
  127. name := "testbuildenvironmentreplacement"
  128. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  129. build.WithFile("Dockerfile", `
  130. FROM `+minimalBaseImage()+`
  131. ENV baz foo
  132. ENV quux bar
  133. ENV dot .
  134. ENV fee fff
  135. ENV gee ggg
  136. ADD ${baz} ${dot}
  137. COPY ${quux} ${dot}
  138. ADD ${zzz:-${fee}} ${dot}
  139. COPY ${zzz:-${gee}} ${dot}
  140. `),
  141. build.WithFile("foo", "test1"),
  142. build.WithFile("bar", "test2"),
  143. build.WithFile("fff", "test3"),
  144. build.WithFile("ggg", "test4"),
  145. ))
  146. }
  147. func (s *DockerSuite) TestBuildEnvironmentReplacementEnv(c *testing.T) {
  148. // ENV expansions work differently in Windows
  149. testRequires(c, DaemonIsLinux)
  150. name := "testbuildenvironmentreplacement"
  151. buildImageSuccessfully(c, name, build.WithDockerfile(`
  152. FROM busybox
  153. ENV foo zzz
  154. ENV bar ${foo}
  155. ENV abc1='$foo'
  156. ENV env1=$foo env2=${foo} env3="$foo" env4="${foo}"
  157. RUN [ "$abc1" = '$foo' ] && (echo "$abc1" | grep -q foo)
  158. ENV abc2="\$foo"
  159. RUN [ "$abc2" = '$foo' ] && (echo "$abc2" | grep -q foo)
  160. ENV abc3 '$foo'
  161. RUN [ "$abc3" = '$foo' ] && (echo "$abc3" | grep -q foo)
  162. ENV abc4 "\$foo"
  163. RUN [ "$abc4" = '$foo' ] && (echo "$abc4" | grep -q foo)
  164. ENV foo2="abc\def"
  165. RUN [ "$foo2" = 'abc\def' ]
  166. ENV foo3="abc\\def"
  167. RUN [ "$foo3" = 'abc\def' ]
  168. ENV foo4='abc\\def'
  169. RUN [ "$foo4" = 'abc\\def' ]
  170. ENV foo5='abc\def'
  171. RUN [ "$foo5" = 'abc\def' ]
  172. `))
  173. var envResult []string
  174. inspectFieldAndUnmarshall(c, name, "Config.Env", &envResult)
  175. found := false
  176. envCount := 0
  177. for _, env := range envResult {
  178. parts := strings.SplitN(env, "=", 2)
  179. if parts[0] == "bar" {
  180. found = true
  181. if parts[1] != "zzz" {
  182. c.Fatalf("Could not find replaced var for env `bar`: got %q instead of `zzz`", parts[1])
  183. }
  184. } else if strings.HasPrefix(parts[0], "env") {
  185. envCount++
  186. if parts[1] != "zzz" {
  187. c.Fatalf("%s should be 'zzz' but instead its %q", parts[0], parts[1])
  188. }
  189. } else if strings.HasPrefix(parts[0], "env") {
  190. envCount++
  191. if parts[1] != "foo" {
  192. c.Fatalf("%s should be 'foo' but instead its %q", parts[0], parts[1])
  193. }
  194. }
  195. }
  196. if !found {
  197. c.Fatal("Never found the `bar` env variable")
  198. }
  199. if envCount != 4 {
  200. c.Fatalf("Didn't find all env vars - only saw %d\n%s", envCount, envResult)
  201. }
  202. }
  203. func (s *DockerSuite) TestBuildHandleEscapesInVolume(c *testing.T) {
  204. // The volume paths used in this test are invalid on Windows
  205. testRequires(c, DaemonIsLinux)
  206. name := "testbuildhandleescapes"
  207. testCases := []struct {
  208. volumeValue string
  209. expected string
  210. }{
  211. {
  212. volumeValue: "${FOO}",
  213. expected: "bar",
  214. },
  215. {
  216. volumeValue: `\${FOO}`,
  217. expected: "${FOO}",
  218. },
  219. // this test in particular provides *7* backslashes and expects 6 to come back.
  220. // Like above, the first escape is swallowed and the rest are treated as
  221. // literals, this one is just less obvious because of all the character noise.
  222. {
  223. volumeValue: `\\\\\\\${FOO}`,
  224. expected: `\\\${FOO}`,
  225. },
  226. }
  227. for _, tc := range testCases {
  228. buildImageSuccessfully(c, name, build.WithDockerfile(fmt.Sprintf(`
  229. FROM scratch
  230. ENV FOO bar
  231. VOLUME %s
  232. `, tc.volumeValue)))
  233. var result map[string]map[string]struct{}
  234. inspectFieldAndUnmarshall(c, name, "Config.Volumes", &result)
  235. if _, ok := result[tc.expected]; !ok {
  236. c.Fatalf("Could not find volume %s set from env foo in volumes table, got %q", tc.expected, result)
  237. }
  238. // Remove the image for the next iteration
  239. dockerCmd(c, "rmi", name)
  240. }
  241. }
  242. func (s *DockerSuite) TestBuildOnBuildLowercase(c *testing.T) {
  243. name := "testbuildonbuildlowercase"
  244. name2 := "testbuildonbuildlowercase2"
  245. buildImageSuccessfully(c, name, build.WithDockerfile(`
  246. FROM busybox
  247. onbuild run echo quux
  248. `))
  249. result := buildImage(name2, build.WithDockerfile(fmt.Sprintf(`
  250. FROM %s
  251. `, name)))
  252. result.Assert(c, icmd.Success)
  253. if !strings.Contains(result.Combined(), "quux") {
  254. c.Fatalf("Did not receive the expected echo text, got %s", result.Combined())
  255. }
  256. if strings.Contains(result.Combined(), "ONBUILD ONBUILD") {
  257. c.Fatalf("Got an ONBUILD ONBUILD error with no error: got %s", result.Combined())
  258. }
  259. }
  260. func (s *DockerSuite) TestBuildEnvEscapes(c *testing.T) {
  261. // ENV expansions work differently in Windows
  262. testRequires(c, DaemonIsLinux)
  263. name := "testbuildenvescapes"
  264. buildImageSuccessfully(c, name, build.WithDockerfile(`
  265. FROM busybox
  266. ENV TEST foo
  267. CMD echo \$
  268. `))
  269. out, _ := dockerCmd(c, "run", "-t", name)
  270. if strings.TrimSpace(out) != "$" {
  271. c.Fatalf("Env TEST was not overwritten with bar when foo was supplied to dockerfile: was %q", strings.TrimSpace(out))
  272. }
  273. }
  274. func (s *DockerSuite) TestBuildEnvOverwrite(c *testing.T) {
  275. // ENV expansions work differently in Windows
  276. testRequires(c, DaemonIsLinux)
  277. name := "testbuildenvoverwrite"
  278. buildImageSuccessfully(c, name, build.WithDockerfile(`
  279. FROM busybox
  280. ENV TEST foo
  281. CMD echo ${TEST}
  282. `))
  283. out, _ := dockerCmd(c, "run", "-e", "TEST=bar", "-t", name)
  284. if strings.TrimSpace(out) != "bar" {
  285. c.Fatalf("Env TEST was not overwritten with bar when foo was supplied to dockerfile: was %q", strings.TrimSpace(out))
  286. }
  287. }
  288. // FIXME(vdemeester) why we disabled cache here ?
  289. func (s *DockerSuite) TestBuildOnBuildCmdEntrypointJSON(c *testing.T) {
  290. name1 := "onbuildcmd"
  291. name2 := "onbuildgenerated"
  292. cli.BuildCmd(c, name1, build.WithDockerfile(`
  293. FROM busybox
  294. ONBUILD CMD ["hello world"]
  295. ONBUILD ENTRYPOINT ["echo"]
  296. ONBUILD RUN ["true"]`))
  297. cli.BuildCmd(c, name2, build.WithDockerfile(fmt.Sprintf(`FROM %s`, name1)))
  298. result := cli.DockerCmd(c, "run", name2)
  299. result.Assert(c, icmd.Expected{Out: "hello world"})
  300. }
  301. // FIXME(vdemeester) why we disabled cache here ?
  302. func (s *DockerSuite) TestBuildOnBuildEntrypointJSON(c *testing.T) {
  303. name1 := "onbuildcmd"
  304. name2 := "onbuildgenerated"
  305. buildImageSuccessfully(c, name1, build.WithDockerfile(`
  306. FROM busybox
  307. ONBUILD ENTRYPOINT ["echo"]`))
  308. buildImageSuccessfully(c, name2, build.WithDockerfile(fmt.Sprintf("FROM %s\nCMD [\"hello world\"]\n", name1)))
  309. out, _ := dockerCmd(c, "run", name2)
  310. if !regexp.MustCompile(`(?m)^hello world`).MatchString(out) {
  311. c.Fatal("got malformed output from onbuild", out)
  312. }
  313. }
  314. func (s *DockerSuite) TestBuildCacheAdd(c *testing.T) {
  315. testRequires(c, DaemonIsLinux) // Windows doesn't have httpserver image yet
  316. name := "testbuildtwoimageswithadd"
  317. server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{
  318. "robots.txt": "hello",
  319. "index.html": "world",
  320. }))
  321. defer server.Close()
  322. cli.BuildCmd(c, name, build.WithDockerfile(fmt.Sprintf(`FROM scratch
  323. ADD %s/robots.txt /`, server.URL())))
  324. result := cli.Docker(cli.Build(name), build.WithDockerfile(fmt.Sprintf(`FROM scratch
  325. ADD %s/index.html /`, server.URL())))
  326. result.Assert(c, icmd.Success)
  327. if strings.Contains(result.Combined(), "Using cache") {
  328. c.Fatal("2nd build used cache on ADD, it shouldn't")
  329. }
  330. }
  331. func (s *DockerSuite) TestBuildLastModified(c *testing.T) {
  332. // Temporary fix for #30890. TODO @jhowardmsft figure out what
  333. // has changed in the master busybox image.
  334. testRequires(c, DaemonIsLinux)
  335. name := "testbuildlastmodified"
  336. server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{
  337. "file": "hello",
  338. }))
  339. defer server.Close()
  340. var out, out2 string
  341. args := []string{"run", name, "ls", "-l", "--full-time", "/file"}
  342. dFmt := `FROM busybox
  343. ADD %s/file /`
  344. dockerfile := fmt.Sprintf(dFmt, server.URL())
  345. cli.BuildCmd(c, name, build.WithoutCache, build.WithDockerfile(dockerfile))
  346. out = cli.DockerCmd(c, args...).Combined()
  347. // Build it again and make sure the mtime of the file didn't change.
  348. // Wait a few seconds to make sure the time changed enough to notice
  349. time.Sleep(2 * time.Second)
  350. cli.BuildCmd(c, name, build.WithoutCache, build.WithDockerfile(dockerfile))
  351. out2 = cli.DockerCmd(c, args...).Combined()
  352. if out != out2 {
  353. c.Fatalf("MTime changed:\nOrigin:%s\nNew:%s", out, out2)
  354. }
  355. // Now 'touch' the file and make sure the timestamp DID change this time
  356. // Create a new fakeStorage instead of just using Add() to help windows
  357. server = fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{
  358. "file": "hello",
  359. }))
  360. defer server.Close()
  361. dockerfile = fmt.Sprintf(dFmt, server.URL())
  362. cli.BuildCmd(c, name, build.WithoutCache, build.WithDockerfile(dockerfile))
  363. out2 = cli.DockerCmd(c, args...).Combined()
  364. if out == out2 {
  365. c.Fatalf("MTime didn't change:\nOrigin:%s\nNew:%s", out, out2)
  366. }
  367. }
  368. // Regression for https://github.com/docker/docker/pull/27805
  369. // Makes sure that we don't use the cache if the contents of
  370. // a file in a subfolder of the context is modified and we re-build.
  371. func (s *DockerSuite) TestBuildModifyFileInFolder(c *testing.T) {
  372. name := "testbuildmodifyfileinfolder"
  373. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(`FROM busybox
  374. RUN ["mkdir", "/test"]
  375. ADD folder/file /test/changetarget`))
  376. defer ctx.Close()
  377. if err := ctx.Add("folder/file", "first"); err != nil {
  378. c.Fatal(err)
  379. }
  380. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  381. id1 := getIDByName(c, name)
  382. if err := ctx.Add("folder/file", "second"); err != nil {
  383. c.Fatal(err)
  384. }
  385. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  386. id2 := getIDByName(c, name)
  387. if id1 == id2 {
  388. c.Fatal("cache was used even though file contents in folder was changed")
  389. }
  390. }
  391. func (s *DockerSuite) TestBuildAddSingleFileToRoot(c *testing.T) {
  392. testRequires(c, DaemonIsLinux) // Linux specific test
  393. buildImageSuccessfully(c, "testaddimg", build.WithBuildContext(c,
  394. build.WithFile("Dockerfile", fmt.Sprintf(`FROM busybox
  395. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  396. RUN echo 'dockerio:x:1001:' >> /etc/group
  397. RUN touch /exists
  398. RUN chown dockerio.dockerio /exists
  399. ADD test_file /
  400. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  401. RUN [ $(ls -l /test_file | awk '{print $1}') = '%s' ]
  402. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod)),
  403. build.WithFile("test_file", "test1")))
  404. }
  405. // Issue #3960: "ADD src ." hangs
  406. func (s *DockerSuite) TestBuildAddSingleFileToWorkdir(c *testing.T) {
  407. name := "testaddsinglefiletoworkdir"
  408. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(
  409. `FROM busybox
  410. ADD test_file .`),
  411. fakecontext.WithFiles(map[string]string{
  412. "test_file": "test1",
  413. }))
  414. defer ctx.Close()
  415. errChan := make(chan error)
  416. go func() {
  417. errChan <- buildImage(name, build.WithExternalBuildContext(ctx)).Error
  418. close(errChan)
  419. }()
  420. select {
  421. case <-time.After(15 * time.Second):
  422. c.Fatal("Build with adding to workdir timed out")
  423. case err := <-errChan:
  424. assert.NilError(c, err)
  425. }
  426. }
  427. func (s *DockerSuite) TestBuildAddSingleFileToExistDir(c *testing.T) {
  428. testRequires(c, DaemonIsLinux) // Linux specific test
  429. cli.BuildCmd(c, "testaddsinglefiletoexistdir", build.WithBuildContext(c,
  430. build.WithFile("Dockerfile", `FROM busybox
  431. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  432. RUN echo 'dockerio:x:1001:' >> /etc/group
  433. RUN mkdir /exists
  434. RUN touch /exists/exists_file
  435. RUN chown -R dockerio.dockerio /exists
  436. ADD test_file /exists/
  437. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  438. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]
  439. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`),
  440. build.WithFile("test_file", "test1")))
  441. }
  442. func (s *DockerSuite) TestBuildCopyAddMultipleFiles(c *testing.T) {
  443. testRequires(c, DaemonIsLinux) // Linux specific test
  444. server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{
  445. "robots.txt": "hello",
  446. }))
  447. defer server.Close()
  448. cli.BuildCmd(c, "testcopymultiplefilestofile", build.WithBuildContext(c,
  449. build.WithFile("Dockerfile", fmt.Sprintf(`FROM busybox
  450. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  451. RUN echo 'dockerio:x:1001:' >> /etc/group
  452. RUN mkdir /exists
  453. RUN touch /exists/exists_file
  454. RUN chown -R dockerio.dockerio /exists
  455. COPY test_file1 test_file2 /exists/
  456. ADD test_file3 test_file4 %s/robots.txt /exists/
  457. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  458. RUN [ $(ls -l /exists/test_file1 | awk '{print $3":"$4}') = 'root:root' ]
  459. RUN [ $(ls -l /exists/test_file2 | awk '{print $3":"$4}') = 'root:root' ]
  460. RUN [ $(ls -l /exists/test_file3 | awk '{print $3":"$4}') = 'root:root' ]
  461. RUN [ $(ls -l /exists/test_file4 | awk '{print $3":"$4}') = 'root:root' ]
  462. RUN [ $(ls -l /exists/robots.txt | awk '{print $3":"$4}') = 'root:root' ]
  463. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  464. `, server.URL())),
  465. build.WithFile("test_file1", "test1"),
  466. build.WithFile("test_file2", "test2"),
  467. build.WithFile("test_file3", "test3"),
  468. build.WithFile("test_file3", "test3"),
  469. build.WithFile("test_file4", "test4")))
  470. }
  471. // These tests are mainly for user namespaces to verify that new directories
  472. // are created as the remapped root uid/gid pair
  473. func (s *DockerSuite) TestBuildUsernamespaceValidateRemappedRoot(c *testing.T) {
  474. testRequires(c, DaemonIsLinux)
  475. testCases := []string{
  476. "ADD . /new_dir",
  477. "COPY test_dir /new_dir",
  478. "WORKDIR /new_dir",
  479. }
  480. name := "testbuildusernamespacevalidateremappedroot"
  481. for _, tc := range testCases {
  482. cli.BuildCmd(c, name, build.WithBuildContext(c,
  483. build.WithFile("Dockerfile", fmt.Sprintf(`FROM busybox
  484. %s
  485. RUN [ $(ls -l / | grep new_dir | awk '{print $3":"$4}') = 'root:root' ]`, tc)),
  486. build.WithFile("test_dir/test_file", "test file")))
  487. cli.DockerCmd(c, "rmi", name)
  488. }
  489. }
  490. func (s *DockerSuite) TestBuildAddAndCopyFileWithWhitespace(c *testing.T) {
  491. testRequires(c, DaemonIsLinux) // Not currently passing on Windows
  492. name := "testaddfilewithwhitespace"
  493. for _, command := range []string{"ADD", "COPY"} {
  494. cli.BuildCmd(c, name, build.WithBuildContext(c,
  495. build.WithFile("Dockerfile", fmt.Sprintf(`FROM busybox
  496. RUN mkdir "/test dir"
  497. RUN mkdir "/test_dir"
  498. %s [ "test file1", "/test_file1" ]
  499. %s [ "test_file2", "/test file2" ]
  500. %s [ "test file3", "/test file3" ]
  501. %s [ "test dir/test_file4", "/test_dir/test_file4" ]
  502. %s [ "test_dir/test_file5", "/test dir/test_file5" ]
  503. %s [ "test dir/test_file6", "/test dir/test_file6" ]
  504. RUN [ $(cat "/test_file1") = 'test1' ]
  505. RUN [ $(cat "/test file2") = 'test2' ]
  506. RUN [ $(cat "/test file3") = 'test3' ]
  507. RUN [ $(cat "/test_dir/test_file4") = 'test4' ]
  508. RUN [ $(cat "/test dir/test_file5") = 'test5' ]
  509. RUN [ $(cat "/test dir/test_file6") = 'test6' ]`, command, command, command, command, command, command)),
  510. build.WithFile("test file1", "test1"),
  511. build.WithFile("test_file2", "test2"),
  512. build.WithFile("test file3", "test3"),
  513. build.WithFile("test dir/test_file4", "test4"),
  514. build.WithFile("test_dir/test_file5", "test5"),
  515. build.WithFile("test dir/test_file6", "test6"),
  516. ))
  517. cli.DockerCmd(c, "rmi", name)
  518. }
  519. }
  520. func (s *DockerSuite) TestBuildCopyFileWithWhitespaceOnWindows(c *testing.T) {
  521. testRequires(c, DaemonIsWindows)
  522. dockerfile := `FROM ` + testEnv.PlatformDefaults.BaseImage + `
  523. RUN mkdir "C:/test dir"
  524. RUN mkdir "C:/test_dir"
  525. COPY [ "test file1", "/test_file1" ]
  526. COPY [ "test_file2", "/test file2" ]
  527. COPY [ "test file3", "/test file3" ]
  528. COPY [ "test dir/test_file4", "/test_dir/test_file4" ]
  529. COPY [ "test_dir/test_file5", "/test dir/test_file5" ]
  530. COPY [ "test dir/test_file6", "/test dir/test_file6" ]
  531. RUN find "test1" "C:/test_file1"
  532. RUN find "test2" "C:/test file2"
  533. RUN find "test3" "C:/test file3"
  534. RUN find "test4" "C:/test_dir/test_file4"
  535. RUN find "test5" "C:/test dir/test_file5"
  536. RUN find "test6" "C:/test dir/test_file6"`
  537. name := "testcopyfilewithwhitespace"
  538. cli.BuildCmd(c, name, build.WithBuildContext(c,
  539. build.WithFile("Dockerfile", dockerfile),
  540. build.WithFile("test file1", "test1"),
  541. build.WithFile("test_file2", "test2"),
  542. build.WithFile("test file3", "test3"),
  543. build.WithFile("test dir/test_file4", "test4"),
  544. build.WithFile("test_dir/test_file5", "test5"),
  545. build.WithFile("test dir/test_file6", "test6"),
  546. ))
  547. }
  548. func (s *DockerSuite) TestBuildCopyWildcard(c *testing.T) {
  549. name := "testcopywildcard"
  550. server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{
  551. "robots.txt": "hello",
  552. "index.html": "world",
  553. }))
  554. defer server.Close()
  555. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(fmt.Sprintf(`FROM busybox
  556. COPY file*.txt /tmp/
  557. RUN ls /tmp/file1.txt /tmp/file2.txt
  558. RUN [ "mkdir", "/tmp1" ]
  559. COPY dir* /tmp1/
  560. RUN ls /tmp1/dirt /tmp1/nested_file /tmp1/nested_dir/nest_nest_file
  561. RUN [ "mkdir", "/tmp2" ]
  562. ADD dir/*dir %s/robots.txt /tmp2/
  563. RUN ls /tmp2/nest_nest_file /tmp2/robots.txt
  564. `, server.URL())),
  565. fakecontext.WithFiles(map[string]string{
  566. "file1.txt": "test1",
  567. "file2.txt": "test2",
  568. "dir/nested_file": "nested file",
  569. "dir/nested_dir/nest_nest_file": "2 times nested",
  570. "dirt": "dirty",
  571. }))
  572. defer ctx.Close()
  573. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  574. id1 := getIDByName(c, name)
  575. // Now make sure we use a cache the 2nd time
  576. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  577. id2 := getIDByName(c, name)
  578. if id1 != id2 {
  579. c.Fatal("didn't use the cache")
  580. }
  581. }
  582. func (s *DockerSuite) TestBuildCopyWildcardInName(c *testing.T) {
  583. // Run this only on Linux
  584. // Below is the original comment (that I don't agree with — vdemeester)
  585. // Normally we would do c.Fatal(err) here but given that
  586. // the odds of this failing are so rare, it must be because
  587. // the OS we're running the client on doesn't support * in
  588. // filenames (like windows). So, instead of failing the test
  589. // just let it pass. Then we don't need to explicitly
  590. // say which OSs this works on or not.
  591. testRequires(c, DaemonIsLinux, UnixCli)
  592. buildImageSuccessfully(c, "testcopywildcardinname", build.WithBuildContext(c,
  593. build.WithFile("Dockerfile", `FROM busybox
  594. COPY *.txt /tmp/
  595. RUN [ "$(cat /tmp/\*.txt)" = 'hi there' ]
  596. `),
  597. build.WithFile("*.txt", "hi there"),
  598. ))
  599. }
  600. func (s *DockerSuite) TestBuildCopyWildcardCache(c *testing.T) {
  601. name := "testcopywildcardcache"
  602. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(`FROM busybox
  603. COPY file1.txt /tmp/`),
  604. fakecontext.WithFiles(map[string]string{
  605. "file1.txt": "test1",
  606. }))
  607. defer ctx.Close()
  608. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  609. id1 := getIDByName(c, name)
  610. // Now make sure we use a cache the 2nd time even with wild cards.
  611. // Use the same context so the file is the same and the checksum will match
  612. ctx.Add("Dockerfile", `FROM busybox
  613. COPY file*.txt /tmp/`)
  614. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  615. id2 := getIDByName(c, name)
  616. if id1 != id2 {
  617. c.Fatal("didn't use the cache")
  618. }
  619. }
  620. func (s *DockerSuite) TestBuildAddSingleFileToNonExistingDir(c *testing.T) {
  621. testRequires(c, DaemonIsLinux) // Linux specific test
  622. buildImageSuccessfully(c, "testaddsinglefiletononexistingdir", build.WithBuildContext(c,
  623. build.WithFile("Dockerfile", `FROM busybox
  624. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  625. RUN echo 'dockerio:x:1001:' >> /etc/group
  626. RUN touch /exists
  627. RUN chown dockerio.dockerio /exists
  628. ADD test_file /test_dir/
  629. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  630. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  631. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`),
  632. build.WithFile("test_file", "test1")))
  633. }
  634. func (s *DockerSuite) TestBuildAddDirContentToRoot(c *testing.T) {
  635. testRequires(c, DaemonIsLinux) // Linux specific test
  636. buildImageSuccessfully(c, "testadddircontenttoroot", build.WithBuildContext(c,
  637. build.WithFile("Dockerfile", `FROM busybox
  638. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  639. RUN echo 'dockerio:x:1001:' >> /etc/group
  640. RUN touch /exists
  641. RUN chown dockerio.dockerio exists
  642. ADD test_dir /
  643. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  644. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`),
  645. build.WithFile("test_dir/test_file", "test1")))
  646. }
  647. func (s *DockerSuite) TestBuildAddDirContentToExistingDir(c *testing.T) {
  648. testRequires(c, DaemonIsLinux) // Linux specific test
  649. buildImageSuccessfully(c, "testadddircontenttoexistingdir", build.WithBuildContext(c,
  650. build.WithFile("Dockerfile", `FROM busybox
  651. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  652. RUN echo 'dockerio:x:1001:' >> /etc/group
  653. RUN mkdir /exists
  654. RUN touch /exists/exists_file
  655. RUN chown -R dockerio.dockerio /exists
  656. ADD test_dir/ /exists/
  657. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  658. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  659. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]`),
  660. build.WithFile("test_dir/test_file", "test1")))
  661. }
  662. func (s *DockerSuite) TestBuildAddWholeDirToRoot(c *testing.T) {
  663. testRequires(c, DaemonIsLinux) // Linux specific test
  664. buildImageSuccessfully(c, "testaddwholedirtoroot", build.WithBuildContext(c,
  665. build.WithFile("Dockerfile", fmt.Sprintf(`FROM busybox
  666. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  667. RUN echo 'dockerio:x:1001:' >> /etc/group
  668. RUN touch /exists
  669. RUN chown dockerio.dockerio exists
  670. ADD test_dir /test_dir
  671. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  672. RUN [ $(ls -l / | grep test_dir | awk '{print $1}') = 'drwxr-xr-x' ]
  673. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  674. RUN [ $(ls -l /test_dir/test_file | awk '{print $1}') = '%s' ]
  675. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod)),
  676. build.WithFile("test_dir/test_file", "test1")))
  677. }
  678. // Testing #5941 : Having an etc directory in context conflicts with the /etc/mtab
  679. func (s *DockerSuite) TestBuildAddOrCopyEtcToRootShouldNotConflict(c *testing.T) {
  680. buildImageSuccessfully(c, "testaddetctoroot", build.WithBuildContext(c,
  681. build.WithFile("Dockerfile", `FROM `+minimalBaseImage()+`
  682. ADD . /`),
  683. build.WithFile("etc/test_file", "test1")))
  684. buildImageSuccessfully(c, "testcopyetctoroot", build.WithBuildContext(c,
  685. build.WithFile("Dockerfile", `FROM `+minimalBaseImage()+`
  686. COPY . /`),
  687. build.WithFile("etc/test_file", "test1")))
  688. }
  689. // Testing #9401 : Losing setuid flag after a ADD
  690. func (s *DockerSuite) TestBuildAddPreservesFilesSpecialBits(c *testing.T) {
  691. testRequires(c, DaemonIsLinux) // Linux specific test
  692. buildImageSuccessfully(c, "testaddetctoroot", build.WithBuildContext(c,
  693. build.WithFile("Dockerfile", `FROM busybox
  694. ADD suidbin /usr/bin/suidbin
  695. RUN chmod 4755 /usr/bin/suidbin
  696. RUN [ $(ls -l /usr/bin/suidbin | awk '{print $1}') = '-rwsr-xr-x' ]
  697. ADD ./data/ /
  698. RUN [ $(ls -l /usr/bin/suidbin | awk '{print $1}') = '-rwsr-xr-x' ]`),
  699. build.WithFile("suidbin", "suidbin"),
  700. build.WithFile("/data/usr/test_file", "test1")))
  701. }
  702. func (s *DockerSuite) TestBuildCopySingleFileToRoot(c *testing.T) {
  703. testRequires(c, DaemonIsLinux) // Linux specific test
  704. buildImageSuccessfully(c, "testcopysinglefiletoroot", build.WithBuildContext(c,
  705. build.WithFile("Dockerfile", fmt.Sprintf(`FROM busybox
  706. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  707. RUN echo 'dockerio:x:1001:' >> /etc/group
  708. RUN touch /exists
  709. RUN chown dockerio.dockerio /exists
  710. COPY test_file /
  711. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  712. RUN [ $(ls -l /test_file | awk '{print $1}') = '%s' ]
  713. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod)),
  714. build.WithFile("test_file", "test1")))
  715. }
  716. // Issue #3960: "ADD src ." hangs - adapted for COPY
  717. func (s *DockerSuite) TestBuildCopySingleFileToWorkdir(c *testing.T) {
  718. name := "testcopysinglefiletoworkdir"
  719. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(`FROM busybox
  720. COPY test_file .`),
  721. fakecontext.WithFiles(map[string]string{
  722. "test_file": "test1",
  723. }))
  724. defer ctx.Close()
  725. errChan := make(chan error)
  726. go func() {
  727. errChan <- buildImage(name, build.WithExternalBuildContext(ctx)).Error
  728. close(errChan)
  729. }()
  730. select {
  731. case <-time.After(15 * time.Second):
  732. c.Fatal("Build with adding to workdir timed out")
  733. case err := <-errChan:
  734. assert.NilError(c, err)
  735. }
  736. }
  737. func (s *DockerSuite) TestBuildCopySingleFileToExistDir(c *testing.T) {
  738. testRequires(c, DaemonIsLinux) // Linux specific test
  739. buildImageSuccessfully(c, "testcopysinglefiletoexistdir", build.WithBuildContext(c,
  740. build.WithFile("Dockerfile", `FROM busybox
  741. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  742. RUN echo 'dockerio:x:1001:' >> /etc/group
  743. RUN mkdir /exists
  744. RUN touch /exists/exists_file
  745. RUN chown -R dockerio.dockerio /exists
  746. COPY test_file /exists/
  747. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  748. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]
  749. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`),
  750. build.WithFile("test_file", "test1")))
  751. }
  752. func (s *DockerSuite) TestBuildCopySingleFileToNonExistDir(c *testing.T) {
  753. testRequires(c, DaemonIsLinux) // Linux specific
  754. buildImageSuccessfully(c, "testcopysinglefiletononexistdir", build.WithBuildContext(c,
  755. build.WithFile("Dockerfile", `FROM busybox
  756. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  757. RUN echo 'dockerio:x:1001:' >> /etc/group
  758. RUN touch /exists
  759. RUN chown dockerio.dockerio /exists
  760. COPY test_file /test_dir/
  761. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  762. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  763. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`),
  764. build.WithFile("test_file", "test1")))
  765. }
  766. func (s *DockerSuite) TestBuildCopyDirContentToRoot(c *testing.T) {
  767. testRequires(c, DaemonIsLinux) // Linux specific test
  768. buildImageSuccessfully(c, "testcopydircontenttoroot", build.WithBuildContext(c,
  769. build.WithFile("Dockerfile", `FROM busybox
  770. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  771. RUN echo 'dockerio:x:1001:' >> /etc/group
  772. RUN touch /exists
  773. RUN chown dockerio.dockerio exists
  774. COPY test_dir /
  775. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  776. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`),
  777. build.WithFile("test_dir/test_file", "test1")))
  778. }
  779. func (s *DockerSuite) TestBuildCopyDirContentToExistDir(c *testing.T) {
  780. testRequires(c, DaemonIsLinux) // Linux specific test
  781. buildImageSuccessfully(c, "testcopydircontenttoexistdir", build.WithBuildContext(c,
  782. build.WithFile("Dockerfile", `FROM busybox
  783. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  784. RUN echo 'dockerio:x:1001:' >> /etc/group
  785. RUN mkdir /exists
  786. RUN touch /exists/exists_file
  787. RUN chown -R dockerio.dockerio /exists
  788. COPY test_dir/ /exists/
  789. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  790. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  791. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]`),
  792. build.WithFile("test_dir/test_file", "test1")))
  793. }
  794. func (s *DockerSuite) TestBuildCopyWholeDirToRoot(c *testing.T) {
  795. testRequires(c, DaemonIsLinux) // Linux specific test
  796. buildImageSuccessfully(c, "testcopywholedirtoroot", build.WithBuildContext(c,
  797. build.WithFile("Dockerfile", fmt.Sprintf(`FROM busybox
  798. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  799. RUN echo 'dockerio:x:1001:' >> /etc/group
  800. RUN touch /exists
  801. RUN chown dockerio.dockerio exists
  802. COPY test_dir /test_dir
  803. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  804. RUN [ $(ls -l / | grep test_dir | awk '{print $1}') = 'drwxr-xr-x' ]
  805. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  806. RUN [ $(ls -l /test_dir/test_file | awk '{print $1}') = '%s' ]
  807. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod)),
  808. build.WithFile("test_dir/test_file", "test1")))
  809. }
  810. func (s *DockerSuite) TestBuildAddBadLinks(c *testing.T) {
  811. testRequires(c, DaemonIsLinux) // Not currently working on Windows
  812. dockerfile := `
  813. FROM scratch
  814. ADD links.tar /
  815. ADD foo.txt /symlink/
  816. `
  817. targetFile := "foo.txt"
  818. var (
  819. name = "test-link-absolute"
  820. )
  821. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(dockerfile))
  822. defer ctx.Close()
  823. tempDir, err := ioutil.TempDir("", "test-link-absolute-temp-")
  824. if err != nil {
  825. c.Fatalf("failed to create temporary directory: %s", tempDir)
  826. }
  827. defer os.RemoveAll(tempDir)
  828. var symlinkTarget string
  829. if runtime.GOOS == "windows" {
  830. var driveLetter string
  831. if abs, err := filepath.Abs(tempDir); err != nil {
  832. c.Fatal(err)
  833. } else {
  834. driveLetter = abs[:1]
  835. }
  836. tempDirWithoutDrive := tempDir[2:]
  837. symlinkTarget = fmt.Sprintf(`%s:\..\..\..\..\..\..\..\..\..\..\..\..%s`, driveLetter, tempDirWithoutDrive)
  838. } else {
  839. symlinkTarget = fmt.Sprintf("/../../../../../../../../../../../..%s", tempDir)
  840. }
  841. tarPath := filepath.Join(ctx.Dir, "links.tar")
  842. nonExistingFile := filepath.Join(tempDir, targetFile)
  843. fooPath := filepath.Join(ctx.Dir, targetFile)
  844. tarOut, err := os.Create(tarPath)
  845. if err != nil {
  846. c.Fatal(err)
  847. }
  848. tarWriter := tar.NewWriter(tarOut)
  849. header := &tar.Header{
  850. Name: "symlink",
  851. Typeflag: tar.TypeSymlink,
  852. Linkname: symlinkTarget,
  853. Mode: 0755,
  854. Uid: 0,
  855. Gid: 0,
  856. }
  857. err = tarWriter.WriteHeader(header)
  858. if err != nil {
  859. c.Fatal(err)
  860. }
  861. tarWriter.Close()
  862. tarOut.Close()
  863. foo, err := os.Create(fooPath)
  864. if err != nil {
  865. c.Fatal(err)
  866. }
  867. defer foo.Close()
  868. if _, err := foo.WriteString("test"); err != nil {
  869. c.Fatal(err)
  870. }
  871. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  872. if _, err := os.Stat(nonExistingFile); err == nil || err != nil && !os.IsNotExist(err) {
  873. c.Fatalf("%s shouldn't have been written and it shouldn't exist", nonExistingFile)
  874. }
  875. }
  876. func (s *DockerSuite) TestBuildAddBadLinksVolume(c *testing.T) {
  877. testRequires(c, DaemonIsLinux) // ln not implemented on Windows busybox
  878. const (
  879. dockerfileTemplate = `
  880. FROM busybox
  881. RUN ln -s /../../../../../../../../%s /x
  882. VOLUME /x
  883. ADD foo.txt /x/`
  884. targetFile = "foo.txt"
  885. )
  886. tempDir, err := ioutil.TempDir("", "test-link-absolute-volume-temp-")
  887. if err != nil {
  888. c.Fatalf("failed to create temporary directory: %s", tempDir)
  889. }
  890. defer os.RemoveAll(tempDir)
  891. dockerfile := fmt.Sprintf(dockerfileTemplate, tempDir)
  892. nonExistingFile := filepath.Join(tempDir, targetFile)
  893. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(dockerfile))
  894. defer ctx.Close()
  895. fooPath := filepath.Join(ctx.Dir, targetFile)
  896. foo, err := os.Create(fooPath)
  897. if err != nil {
  898. c.Fatal(err)
  899. }
  900. defer foo.Close()
  901. if _, err := foo.WriteString("test"); err != nil {
  902. c.Fatal(err)
  903. }
  904. buildImageSuccessfully(c, "test-link-absolute-volume", build.WithExternalBuildContext(ctx))
  905. if _, err := os.Stat(nonExistingFile); err == nil || err != nil && !os.IsNotExist(err) {
  906. c.Fatalf("%s shouldn't have been written and it shouldn't exist", nonExistingFile)
  907. }
  908. }
  909. // Issue #5270 - ensure we throw a better error than "unexpected EOF"
  910. // when we can't access files in the context.
  911. func (s *DockerSuite) TestBuildWithInaccessibleFilesInContext(c *testing.T) {
  912. testRequires(c, DaemonIsLinux, UnixCli, testEnv.IsLocalDaemon) // test uses chown/chmod: not available on windows
  913. {
  914. name := "testbuildinaccessiblefiles"
  915. ctx := fakecontext.New(c, "",
  916. fakecontext.WithDockerfile("FROM scratch\nADD . /foo/"),
  917. fakecontext.WithFiles(map[string]string{"fileWithoutReadAccess": "foo"}),
  918. )
  919. defer ctx.Close()
  920. // This is used to ensure we detect inaccessible files early during build in the cli client
  921. pathToFileWithoutReadAccess := filepath.Join(ctx.Dir, "fileWithoutReadAccess")
  922. if err := os.Chown(pathToFileWithoutReadAccess, 0, 0); err != nil {
  923. c.Fatalf("failed to chown file to root: %s", err)
  924. }
  925. if err := os.Chmod(pathToFileWithoutReadAccess, 0700); err != nil {
  926. c.Fatalf("failed to chmod file to 700: %s", err)
  927. }
  928. result := icmd.RunCmd(icmd.Cmd{
  929. Command: []string{"su", "unprivilegeduser", "-c", fmt.Sprintf("%s build -t %s .", dockerBinary, name)},
  930. Dir: ctx.Dir,
  931. })
  932. if result.Error == nil {
  933. c.Fatalf("build should have failed: %s %s", result.Error, result.Combined())
  934. }
  935. // check if we've detected the failure before we started building
  936. if !strings.Contains(result.Combined(), "no permission to read from ") {
  937. c.Fatalf("output should've contained the string: no permission to read from but contained: %s", result.Combined())
  938. }
  939. if !strings.Contains(result.Combined(), "error checking context") {
  940. c.Fatalf("output should've contained the string: error checking context")
  941. }
  942. }
  943. {
  944. name := "testbuildinaccessibledirectory"
  945. ctx := fakecontext.New(c, "",
  946. fakecontext.WithDockerfile("FROM scratch\nADD . /foo/"),
  947. fakecontext.WithFiles(map[string]string{"directoryWeCantStat/bar": "foo"}),
  948. )
  949. defer ctx.Close()
  950. // This is used to ensure we detect inaccessible directories early during build in the cli client
  951. pathToDirectoryWithoutReadAccess := filepath.Join(ctx.Dir, "directoryWeCantStat")
  952. pathToFileInDirectoryWithoutReadAccess := filepath.Join(pathToDirectoryWithoutReadAccess, "bar")
  953. if err := os.Chown(pathToDirectoryWithoutReadAccess, 0, 0); err != nil {
  954. c.Fatalf("failed to chown directory to root: %s", err)
  955. }
  956. if err := os.Chmod(pathToDirectoryWithoutReadAccess, 0444); err != nil {
  957. c.Fatalf("failed to chmod directory to 444: %s", err)
  958. }
  959. if err := os.Chmod(pathToFileInDirectoryWithoutReadAccess, 0700); err != nil {
  960. c.Fatalf("failed to chmod file to 700: %s", err)
  961. }
  962. result := icmd.RunCmd(icmd.Cmd{
  963. Command: []string{"su", "unprivilegeduser", "-c", fmt.Sprintf("%s build -t %s .", dockerBinary, name)},
  964. Dir: ctx.Dir,
  965. })
  966. if result.Error == nil {
  967. c.Fatalf("build should have failed: %s %s", result.Error, result.Combined())
  968. }
  969. // check if we've detected the failure before we started building
  970. if !strings.Contains(result.Combined(), "can't stat") {
  971. c.Fatalf("output should've contained the string: can't access %s", result.Combined())
  972. }
  973. if !strings.Contains(result.Combined(), "error checking context") {
  974. c.Fatalf("output should've contained the string: error checking context\ngot:%s", result.Combined())
  975. }
  976. }
  977. {
  978. name := "testlinksok"
  979. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile("FROM scratch\nADD . /foo/"))
  980. defer ctx.Close()
  981. target := "../../../../../../../../../../../../../../../../../../../azA"
  982. if err := os.Symlink(filepath.Join(ctx.Dir, "g"), target); err != nil {
  983. c.Fatal(err)
  984. }
  985. defer os.Remove(target)
  986. // This is used to ensure we don't follow links when checking if everything in the context is accessible
  987. // This test doesn't require that we run commands as an unprivileged user
  988. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  989. }
  990. {
  991. name := "testbuildignoredinaccessible"
  992. ctx := fakecontext.New(c, "",
  993. fakecontext.WithDockerfile("FROM scratch\nADD . /foo/"),
  994. fakecontext.WithFiles(map[string]string{
  995. "directoryWeCantStat/bar": "foo",
  996. ".dockerignore": "directoryWeCantStat",
  997. }),
  998. )
  999. defer ctx.Close()
  1000. // This is used to ensure we don't try to add inaccessible files when they are ignored by a .dockerignore pattern
  1001. pathToDirectoryWithoutReadAccess := filepath.Join(ctx.Dir, "directoryWeCantStat")
  1002. pathToFileInDirectoryWithoutReadAccess := filepath.Join(pathToDirectoryWithoutReadAccess, "bar")
  1003. if err := os.Chown(pathToDirectoryWithoutReadAccess, 0, 0); err != nil {
  1004. c.Fatalf("failed to chown directory to root: %s", err)
  1005. }
  1006. if err := os.Chmod(pathToDirectoryWithoutReadAccess, 0444); err != nil {
  1007. c.Fatalf("failed to chmod directory to 444: %s", err)
  1008. }
  1009. if err := os.Chmod(pathToFileInDirectoryWithoutReadAccess, 0700); err != nil {
  1010. c.Fatalf("failed to chmod file to 700: %s", err)
  1011. }
  1012. result := icmd.RunCmd(icmd.Cmd{
  1013. Dir: ctx.Dir,
  1014. Command: []string{"su", "unprivilegeduser", "-c",
  1015. fmt.Sprintf("%s build -t %s .", dockerBinary, name)},
  1016. })
  1017. result.Assert(c, icmd.Expected{})
  1018. }
  1019. }
  1020. func (s *DockerSuite) TestBuildForceRm(c *testing.T) {
  1021. containerCountBefore := getContainerCount(c)
  1022. name := "testbuildforcerm"
  1023. r := buildImage(name, cli.WithFlags("--force-rm"), build.WithBuildContext(c,
  1024. build.WithFile("Dockerfile", `FROM busybox
  1025. RUN true
  1026. RUN thiswillfail`)))
  1027. if r.ExitCode != 1 && r.ExitCode != 127 { // different on Linux / Windows
  1028. c.Fatalf("Wrong exit code")
  1029. }
  1030. containerCountAfter := getContainerCount(c)
  1031. if containerCountBefore != containerCountAfter {
  1032. c.Fatalf("--force-rm shouldn't have left containers behind")
  1033. }
  1034. }
  1035. func (s *DockerSuite) TestBuildRm(c *testing.T) {
  1036. name := "testbuildrm"
  1037. testCases := []struct {
  1038. buildflags []string
  1039. shouldLeftContainerBehind bool
  1040. }{
  1041. // Default case (i.e. --rm=true)
  1042. {
  1043. buildflags: []string{},
  1044. shouldLeftContainerBehind: false,
  1045. },
  1046. {
  1047. buildflags: []string{"--rm"},
  1048. shouldLeftContainerBehind: false,
  1049. },
  1050. {
  1051. buildflags: []string{"--rm=false"},
  1052. shouldLeftContainerBehind: true,
  1053. },
  1054. }
  1055. for _, tc := range testCases {
  1056. containerCountBefore := getContainerCount(c)
  1057. buildImageSuccessfully(c, name, cli.WithFlags(tc.buildflags...), build.WithDockerfile(`FROM busybox
  1058. RUN echo hello world`))
  1059. containerCountAfter := getContainerCount(c)
  1060. if tc.shouldLeftContainerBehind {
  1061. if containerCountBefore == containerCountAfter {
  1062. c.Fatalf("flags %v should have left containers behind", tc.buildflags)
  1063. }
  1064. } else {
  1065. if containerCountBefore != containerCountAfter {
  1066. c.Fatalf("flags %v shouldn't have left containers behind", tc.buildflags)
  1067. }
  1068. }
  1069. dockerCmd(c, "rmi", name)
  1070. }
  1071. }
  1072. func (s *DockerSuite) TestBuildWithVolumes(c *testing.T) {
  1073. testRequires(c, DaemonIsLinux) // Invalid volume paths on Windows
  1074. var (
  1075. result map[string]map[string]struct{}
  1076. name = "testbuildvolumes"
  1077. emptyMap = make(map[string]struct{})
  1078. expected = map[string]map[string]struct{}{
  1079. "/test1": emptyMap,
  1080. "/test2": emptyMap,
  1081. "/test3": emptyMap,
  1082. "/test4": emptyMap,
  1083. "/test5": emptyMap,
  1084. "/test6": emptyMap,
  1085. "[/test7": emptyMap,
  1086. "/test8]": emptyMap,
  1087. }
  1088. )
  1089. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM scratch
  1090. VOLUME /test1
  1091. VOLUME /test2
  1092. VOLUME /test3 /test4
  1093. VOLUME ["/test5", "/test6"]
  1094. VOLUME [/test7 /test8]
  1095. `))
  1096. inspectFieldAndUnmarshall(c, name, "Config.Volumes", &result)
  1097. equal := reflect.DeepEqual(&result, &expected)
  1098. if !equal {
  1099. c.Fatalf("Volumes %s, expected %s", result, expected)
  1100. }
  1101. }
  1102. func (s *DockerSuite) TestBuildMaintainer(c *testing.T) {
  1103. name := "testbuildmaintainer"
  1104. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  1105. MAINTAINER dockerio`))
  1106. expected := "dockerio"
  1107. res := inspectField(c, name, "Author")
  1108. if res != expected {
  1109. c.Fatalf("Maintainer %s, expected %s", res, expected)
  1110. }
  1111. }
  1112. func (s *DockerSuite) TestBuildUser(c *testing.T) {
  1113. testRequires(c, DaemonIsLinux)
  1114. name := "testbuilduser"
  1115. expected := "dockerio"
  1116. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  1117. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1118. USER dockerio
  1119. RUN [ $(whoami) = 'dockerio' ]`))
  1120. res := inspectField(c, name, "Config.User")
  1121. if res != expected {
  1122. c.Fatalf("User %s, expected %s", res, expected)
  1123. }
  1124. }
  1125. func (s *DockerSuite) TestBuildRelativeWorkdir(c *testing.T) {
  1126. name := "testbuildrelativeworkdir"
  1127. var (
  1128. expected1 string
  1129. expected2 string
  1130. expected3 string
  1131. expected4 string
  1132. expectedFinal string
  1133. )
  1134. if testEnv.OSType == "windows" {
  1135. expected1 = `C:/`
  1136. expected2 = `C:/test1`
  1137. expected3 = `C:/test2`
  1138. expected4 = `C:/test2/test3`
  1139. expectedFinal = `C:\test2\test3` // Note inspect is going to return Windows paths, as it's not in busybox
  1140. } else {
  1141. expected1 = `/`
  1142. expected2 = `/test1`
  1143. expected3 = `/test2`
  1144. expected4 = `/test2/test3`
  1145. expectedFinal = `/test2/test3`
  1146. }
  1147. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  1148. RUN sh -c "[ "$PWD" = "`+expected1+`" ]"
  1149. WORKDIR test1
  1150. RUN sh -c "[ "$PWD" = "`+expected2+`" ]"
  1151. WORKDIR /test2
  1152. RUN sh -c "[ "$PWD" = "`+expected3+`" ]"
  1153. WORKDIR test3
  1154. RUN sh -c "[ "$PWD" = "`+expected4+`" ]"`))
  1155. res := inspectField(c, name, "Config.WorkingDir")
  1156. if res != expectedFinal {
  1157. c.Fatalf("Workdir %s, expected %s", res, expectedFinal)
  1158. }
  1159. }
  1160. // #22181 Regression test. Single end-to-end test of using
  1161. // Windows semantics. Most path handling verifications are in unit tests
  1162. func (s *DockerSuite) TestBuildWindowsWorkdirProcessing(c *testing.T) {
  1163. testRequires(c, DaemonIsWindows)
  1164. buildImageSuccessfully(c, "testbuildwindowsworkdirprocessing", build.WithDockerfile(`FROM busybox
  1165. WORKDIR C:\\foo
  1166. WORKDIR bar
  1167. RUN sh -c "[ "$PWD" = "C:/foo/bar" ]"
  1168. `))
  1169. }
  1170. // #22181 Regression test. Most paths handling verifications are in unit test.
  1171. // One functional test for end-to-end
  1172. func (s *DockerSuite) TestBuildWindowsAddCopyPathProcessing(c *testing.T) {
  1173. testRequires(c, DaemonIsWindows)
  1174. // TODO Windows (@jhowardmsft). Needs a follow-up PR to 22181 to
  1175. // support backslash such as .\\ being equivalent to ./ and c:\\ being
  1176. // equivalent to c:/. This is not currently (nor ever has been) supported
  1177. // by docker on the Windows platform.
  1178. buildImageSuccessfully(c, "testbuildwindowsaddcopypathprocessing", build.WithBuildContext(c,
  1179. build.WithFile("Dockerfile", `FROM busybox
  1180. # No trailing slash on COPY/ADD
  1181. # Results in dir being changed to a file
  1182. WORKDIR /wc1
  1183. COPY wc1 c:/wc1
  1184. WORKDIR /wc2
  1185. ADD wc2 c:/wc2
  1186. WORKDIR c:/
  1187. RUN sh -c "[ $(cat c:/wc1/wc1) = 'hellowc1' ]"
  1188. RUN sh -c "[ $(cat c:/wc2/wc2) = 'worldwc2' ]"
  1189. # Trailing slash on COPY/ADD, Windows-style path.
  1190. WORKDIR /wd1
  1191. COPY wd1 c:/wd1/
  1192. WORKDIR /wd2
  1193. ADD wd2 c:/wd2/
  1194. RUN sh -c "[ $(cat c:/wd1/wd1) = 'hellowd1' ]"
  1195. RUN sh -c "[ $(cat c:/wd2/wd2) = 'worldwd2' ]"
  1196. `),
  1197. build.WithFile("wc1", "hellowc1"),
  1198. build.WithFile("wc2", "worldwc2"),
  1199. build.WithFile("wd1", "hellowd1"),
  1200. build.WithFile("wd2", "worldwd2"),
  1201. ))
  1202. }
  1203. func (s *DockerSuite) TestBuildWorkdirWithEnvVariables(c *testing.T) {
  1204. name := "testbuildworkdirwithenvvariables"
  1205. var expected string
  1206. if testEnv.OSType == "windows" {
  1207. expected = `C:\test1\test2`
  1208. } else {
  1209. expected = `/test1/test2`
  1210. }
  1211. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  1212. ENV DIRPATH /test1
  1213. ENV SUBDIRNAME test2
  1214. WORKDIR $DIRPATH
  1215. WORKDIR $SUBDIRNAME/$MISSING_VAR`))
  1216. res := inspectField(c, name, "Config.WorkingDir")
  1217. if res != expected {
  1218. c.Fatalf("Workdir %s, expected %s", res, expected)
  1219. }
  1220. }
  1221. func (s *DockerSuite) TestBuildRelativeCopy(c *testing.T) {
  1222. // cat /test1/test2/foo gets permission denied for the user
  1223. testRequires(c, NotUserNamespace)
  1224. var expected string
  1225. if testEnv.OSType == "windows" {
  1226. expected = `C:/test1/test2`
  1227. } else {
  1228. expected = `/test1/test2`
  1229. }
  1230. buildImageSuccessfully(c, "testbuildrelativecopy", build.WithBuildContext(c,
  1231. build.WithFile("Dockerfile", `FROM busybox
  1232. WORKDIR /test1
  1233. WORKDIR test2
  1234. RUN sh -c "[ "$PWD" = '`+expected+`' ]"
  1235. COPY foo ./
  1236. RUN sh -c "[ $(cat /test1/test2/foo) = 'hello' ]"
  1237. ADD foo ./bar/baz
  1238. RUN sh -c "[ $(cat /test1/test2/bar/baz) = 'hello' ]"
  1239. COPY foo ./bar/baz2
  1240. RUN sh -c "[ $(cat /test1/test2/bar/baz2) = 'hello' ]"
  1241. WORKDIR ..
  1242. COPY foo ./
  1243. RUN sh -c "[ $(cat /test1/foo) = 'hello' ]"
  1244. COPY foo /test3/
  1245. RUN sh -c "[ $(cat /test3/foo) = 'hello' ]"
  1246. WORKDIR /test4
  1247. COPY . .
  1248. RUN sh -c "[ $(cat /test4/foo) = 'hello' ]"
  1249. WORKDIR /test5/test6
  1250. COPY foo ../
  1251. RUN sh -c "[ $(cat /test5/foo) = 'hello' ]"
  1252. `),
  1253. build.WithFile("foo", "hello"),
  1254. ))
  1255. }
  1256. // FIXME(vdemeester) should be unit test
  1257. func (s *DockerSuite) TestBuildBlankName(c *testing.T) {
  1258. name := "testbuildblankname"
  1259. testCases := []struct {
  1260. expression string
  1261. expectedStderr string
  1262. }{
  1263. {
  1264. expression: "ENV =",
  1265. expectedStderr: "ENV names can not be blank",
  1266. },
  1267. {
  1268. expression: "LABEL =",
  1269. expectedStderr: "LABEL names can not be blank",
  1270. },
  1271. {
  1272. expression: "ARG =foo",
  1273. expectedStderr: "ARG names can not be blank",
  1274. },
  1275. }
  1276. for _, tc := range testCases {
  1277. buildImage(name, build.WithDockerfile(fmt.Sprintf(`FROM busybox
  1278. %s`, tc.expression))).Assert(c, icmd.Expected{
  1279. ExitCode: 1,
  1280. Err: tc.expectedStderr,
  1281. })
  1282. }
  1283. }
  1284. func (s *DockerSuite) TestBuildEnv(c *testing.T) {
  1285. testRequires(c, DaemonIsLinux) // ENV expansion is different in Windows
  1286. name := "testbuildenv"
  1287. expected := "[PATH=/test:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin PORT=2375]"
  1288. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  1289. ENV PATH /test:$PATH
  1290. ENV PORT 2375
  1291. RUN [ $(env | grep PORT) = 'PORT=2375' ]`))
  1292. res := inspectField(c, name, "Config.Env")
  1293. if res != expected {
  1294. c.Fatalf("Env %s, expected %s", res, expected)
  1295. }
  1296. }
  1297. func (s *DockerSuite) TestBuildPATH(c *testing.T) {
  1298. testRequires(c, DaemonIsLinux) // ENV expansion is different in Windows
  1299. defPath := "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
  1300. fn := func(dockerfile string, expected string) {
  1301. buildImageSuccessfully(c, "testbldpath", build.WithDockerfile(dockerfile))
  1302. res := inspectField(c, "testbldpath", "Config.Env")
  1303. if res != expected {
  1304. c.Fatalf("Env %q, expected %q for dockerfile:%q", res, expected, dockerfile)
  1305. }
  1306. }
  1307. tests := []struct{ dockerfile, exp string }{
  1308. {"FROM scratch\nMAINTAINER me", "[PATH=" + defPath + "]"},
  1309. {"FROM busybox\nMAINTAINER me", "[PATH=" + defPath + "]"},
  1310. {"FROM scratch\nENV FOO=bar", "[PATH=" + defPath + " FOO=bar]"},
  1311. {"FROM busybox\nENV FOO=bar", "[PATH=" + defPath + " FOO=bar]"},
  1312. {"FROM scratch\nENV PATH=/test", "[PATH=/test]"},
  1313. {"FROM busybox\nENV PATH=/test", "[PATH=/test]"},
  1314. {"FROM scratch\nENV PATH=''", "[PATH=]"},
  1315. {"FROM busybox\nENV PATH=''", "[PATH=]"},
  1316. }
  1317. for _, test := range tests {
  1318. fn(test.dockerfile, test.exp)
  1319. }
  1320. }
  1321. func (s *DockerSuite) TestBuildContextCleanup(c *testing.T) {
  1322. testRequires(c, testEnv.IsLocalDaemon)
  1323. name := "testbuildcontextcleanup"
  1324. entries, err := ioutil.ReadDir(filepath.Join(testEnv.DaemonInfo.DockerRootDir, "tmp"))
  1325. if err != nil {
  1326. c.Fatalf("failed to list contents of tmp dir: %s", err)
  1327. }
  1328. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  1329. ENTRYPOINT ["/bin/echo"]`))
  1330. entriesFinal, err := ioutil.ReadDir(filepath.Join(testEnv.DaemonInfo.DockerRootDir, "tmp"))
  1331. if err != nil {
  1332. c.Fatalf("failed to list contents of tmp dir: %s", err)
  1333. }
  1334. if err = compareDirectoryEntries(entries, entriesFinal); err != nil {
  1335. c.Fatalf("context should have been deleted, but wasn't")
  1336. }
  1337. }
  1338. func (s *DockerSuite) TestBuildContextCleanupFailedBuild(c *testing.T) {
  1339. testRequires(c, testEnv.IsLocalDaemon)
  1340. name := "testbuildcontextcleanup"
  1341. entries, err := ioutil.ReadDir(filepath.Join(testEnv.DaemonInfo.DockerRootDir, "tmp"))
  1342. if err != nil {
  1343. c.Fatalf("failed to list contents of tmp dir: %s", err)
  1344. }
  1345. buildImage(name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  1346. RUN /non/existing/command`)).Assert(c, icmd.Expected{
  1347. ExitCode: 1,
  1348. })
  1349. entriesFinal, err := ioutil.ReadDir(filepath.Join(testEnv.DaemonInfo.DockerRootDir, "tmp"))
  1350. if err != nil {
  1351. c.Fatalf("failed to list contents of tmp dir: %s", err)
  1352. }
  1353. if err = compareDirectoryEntries(entries, entriesFinal); err != nil {
  1354. c.Fatalf("context should have been deleted, but wasn't")
  1355. }
  1356. }
  1357. // compareDirectoryEntries compares two sets of FileInfo (usually taken from a directory)
  1358. // and returns an error if different.
  1359. func compareDirectoryEntries(e1 []os.FileInfo, e2 []os.FileInfo) error {
  1360. var (
  1361. e1Entries = make(map[string]struct{})
  1362. e2Entries = make(map[string]struct{})
  1363. )
  1364. for _, e := range e1 {
  1365. e1Entries[e.Name()] = struct{}{}
  1366. }
  1367. for _, e := range e2 {
  1368. e2Entries[e.Name()] = struct{}{}
  1369. }
  1370. if !reflect.DeepEqual(e1Entries, e2Entries) {
  1371. return fmt.Errorf("entries differ")
  1372. }
  1373. return nil
  1374. }
  1375. func (s *DockerSuite) TestBuildCmd(c *testing.T) {
  1376. name := "testbuildcmd"
  1377. expected := "[/bin/echo Hello World]"
  1378. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  1379. CMD ["/bin/echo", "Hello World"]`))
  1380. res := inspectField(c, name, "Config.Cmd")
  1381. if res != expected {
  1382. c.Fatalf("Cmd %s, expected %s", res, expected)
  1383. }
  1384. }
  1385. func (s *DockerSuite) TestBuildExpose(c *testing.T) {
  1386. testRequires(c, DaemonIsLinux) // Expose not implemented on Windows
  1387. name := "testbuildexpose"
  1388. expected := "map[2375/tcp:{}]"
  1389. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM scratch
  1390. EXPOSE 2375`))
  1391. res := inspectField(c, name, "Config.ExposedPorts")
  1392. if res != expected {
  1393. c.Fatalf("Exposed ports %s, expected %s", res, expected)
  1394. }
  1395. }
  1396. func (s *DockerSuite) TestBuildExposeMorePorts(c *testing.T) {
  1397. testRequires(c, DaemonIsLinux) // Expose not implemented on Windows
  1398. // start building docker file with a large number of ports
  1399. portList := make([]string, 50)
  1400. line := make([]string, 100)
  1401. expectedPorts := make([]int, len(portList)*len(line))
  1402. for i := 0; i < len(portList); i++ {
  1403. for j := 0; j < len(line); j++ {
  1404. p := i*len(line) + j + 1
  1405. line[j] = strconv.Itoa(p)
  1406. expectedPorts[p-1] = p
  1407. }
  1408. if i == len(portList)-1 {
  1409. portList[i] = strings.Join(line, " ")
  1410. } else {
  1411. portList[i] = strings.Join(line, " ") + ` \`
  1412. }
  1413. }
  1414. dockerfile := `FROM scratch
  1415. EXPOSE {{range .}} {{.}}
  1416. {{end}}`
  1417. tmpl := template.Must(template.New("dockerfile").Parse(dockerfile))
  1418. buf := bytes.NewBuffer(nil)
  1419. tmpl.Execute(buf, portList)
  1420. name := "testbuildexpose"
  1421. buildImageSuccessfully(c, name, build.WithDockerfile(buf.String()))
  1422. // check if all the ports are saved inside Config.ExposedPorts
  1423. res := inspectFieldJSON(c, name, "Config.ExposedPorts")
  1424. var exposedPorts map[string]interface{}
  1425. if err := json.Unmarshal([]byte(res), &exposedPorts); err != nil {
  1426. c.Fatal(err)
  1427. }
  1428. for _, p := range expectedPorts {
  1429. ep := fmt.Sprintf("%d/tcp", p)
  1430. if _, ok := exposedPorts[ep]; !ok {
  1431. c.Errorf("Port(%s) is not exposed", ep)
  1432. } else {
  1433. delete(exposedPorts, ep)
  1434. }
  1435. }
  1436. if len(exposedPorts) != 0 {
  1437. c.Errorf("Unexpected extra exposed ports %v", exposedPorts)
  1438. }
  1439. }
  1440. func (s *DockerSuite) TestBuildExposeOrder(c *testing.T) {
  1441. testRequires(c, DaemonIsLinux) // Expose not implemented on Windows
  1442. buildID := func(name, exposed string) string {
  1443. buildImageSuccessfully(c, name, build.WithDockerfile(fmt.Sprintf(`FROM scratch
  1444. EXPOSE %s`, exposed)))
  1445. id := inspectField(c, name, "Id")
  1446. return id
  1447. }
  1448. id1 := buildID("testbuildexpose1", "80 2375")
  1449. id2 := buildID("testbuildexpose2", "2375 80")
  1450. if id1 != id2 {
  1451. c.Errorf("EXPOSE should invalidate the cache only when ports actually changed")
  1452. }
  1453. }
  1454. func (s *DockerSuite) TestBuildExposeUpperCaseProto(c *testing.T) {
  1455. testRequires(c, DaemonIsLinux) // Expose not implemented on Windows
  1456. name := "testbuildexposeuppercaseproto"
  1457. expected := "map[5678/udp:{}]"
  1458. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM scratch
  1459. EXPOSE 5678/UDP`))
  1460. res := inspectField(c, name, "Config.ExposedPorts")
  1461. if res != expected {
  1462. c.Fatalf("Exposed ports %s, expected %s", res, expected)
  1463. }
  1464. }
  1465. func (s *DockerSuite) TestBuildEmptyEntrypointInheritance(c *testing.T) {
  1466. name := "testbuildentrypointinheritance"
  1467. name2 := "testbuildentrypointinheritance2"
  1468. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  1469. ENTRYPOINT ["/bin/echo"]`))
  1470. res := inspectField(c, name, "Config.Entrypoint")
  1471. expected := "[/bin/echo]"
  1472. if res != expected {
  1473. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  1474. }
  1475. buildImageSuccessfully(c, name2, build.WithDockerfile(fmt.Sprintf(`FROM %s
  1476. ENTRYPOINT []`, name)))
  1477. res = inspectField(c, name2, "Config.Entrypoint")
  1478. expected = "[]"
  1479. if res != expected {
  1480. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  1481. }
  1482. }
  1483. func (s *DockerSuite) TestBuildEmptyEntrypoint(c *testing.T) {
  1484. name := "testbuildentrypoint"
  1485. expected := "[]"
  1486. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  1487. ENTRYPOINT []`))
  1488. res := inspectField(c, name, "Config.Entrypoint")
  1489. if res != expected {
  1490. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  1491. }
  1492. }
  1493. func (s *DockerSuite) TestBuildEntrypoint(c *testing.T) {
  1494. name := "testbuildentrypoint"
  1495. expected := "[/bin/echo]"
  1496. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  1497. ENTRYPOINT ["/bin/echo"]`))
  1498. res := inspectField(c, name, "Config.Entrypoint")
  1499. if res != expected {
  1500. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  1501. }
  1502. }
  1503. // #6445 ensure ONBUILD triggers aren't committed to grandchildren
  1504. func (s *DockerSuite) TestBuildOnBuildLimitedInheritance(c *testing.T) {
  1505. buildImageSuccessfully(c, "testonbuildtrigger1", build.WithDockerfile(`
  1506. FROM busybox
  1507. RUN echo "GRANDPARENT"
  1508. ONBUILD RUN echo "ONBUILD PARENT"
  1509. `))
  1510. // ONBUILD should be run in second build.
  1511. buildImage("testonbuildtrigger2", build.WithDockerfile("FROM testonbuildtrigger1")).Assert(c, icmd.Expected{
  1512. Out: "ONBUILD PARENT",
  1513. })
  1514. // ONBUILD should *not* be run in third build.
  1515. result := buildImage("testonbuildtrigger3", build.WithDockerfile("FROM testonbuildtrigger2"))
  1516. result.Assert(c, icmd.Success)
  1517. if strings.Contains(result.Combined(), "ONBUILD PARENT") {
  1518. c.Fatalf("ONBUILD instruction ran in grandchild of ONBUILD parent")
  1519. }
  1520. }
  1521. func (s *DockerSuite) TestBuildSameDockerfileWithAndWithoutCache(c *testing.T) {
  1522. testRequires(c, DaemonIsLinux) // Expose not implemented on Windows
  1523. name := "testbuildwithcache"
  1524. dockerfile := `FROM scratch
  1525. MAINTAINER dockerio
  1526. EXPOSE 5432
  1527. ENTRYPOINT ["/bin/echo"]`
  1528. buildImageSuccessfully(c, name, build.WithDockerfile(dockerfile))
  1529. id1 := getIDByName(c, name)
  1530. buildImageSuccessfully(c, name, build.WithDockerfile(dockerfile))
  1531. id2 := getIDByName(c, name)
  1532. buildImageSuccessfully(c, name, build.WithoutCache, build.WithDockerfile(dockerfile))
  1533. id3 := getIDByName(c, name)
  1534. if id1 != id2 {
  1535. c.Fatal("The cache should have been used but hasn't.")
  1536. }
  1537. if id1 == id3 {
  1538. c.Fatal("The cache should have been invalided but hasn't.")
  1539. }
  1540. }
  1541. // Make sure that ADD/COPY still populate the cache even if they don't use it
  1542. func (s *DockerSuite) TestBuildConditionalCache(c *testing.T) {
  1543. name := "testbuildconditionalcache"
  1544. dockerfile := `
  1545. FROM busybox
  1546. ADD foo /tmp/`
  1547. ctx := fakecontext.New(c, "",
  1548. fakecontext.WithDockerfile(dockerfile),
  1549. fakecontext.WithFiles(map[string]string{
  1550. "foo": "hello",
  1551. }))
  1552. defer ctx.Close()
  1553. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  1554. id1 := getIDByName(c, name)
  1555. if err := ctx.Add("foo", "bye"); err != nil {
  1556. c.Fatalf("Error modifying foo: %s", err)
  1557. }
  1558. // Updating a file should invalidate the cache
  1559. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  1560. id2 := getIDByName(c, name)
  1561. if id2 == id1 {
  1562. c.Fatal("Should not have used the cache")
  1563. }
  1564. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  1565. id3 := getIDByName(c, name)
  1566. if id3 != id2 {
  1567. c.Fatal("Should have used the cache")
  1568. }
  1569. }
  1570. func (s *DockerSuite) TestBuildAddMultipleLocalFileWithAndWithoutCache(c *testing.T) {
  1571. name := "testbuildaddmultiplelocalfilewithcache"
  1572. baseName := name + "-base"
  1573. cli.BuildCmd(c, baseName, build.WithDockerfile(`
  1574. FROM busybox
  1575. ENTRYPOINT ["/bin/sh"]
  1576. `))
  1577. dockerfile := `
  1578. FROM testbuildaddmultiplelocalfilewithcache-base
  1579. MAINTAINER dockerio
  1580. ADD foo Dockerfile /usr/lib/bla/
  1581. RUN sh -c "[ $(cat /usr/lib/bla/foo) = "hello" ]"`
  1582. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(dockerfile), fakecontext.WithFiles(map[string]string{
  1583. "foo": "hello",
  1584. }))
  1585. defer ctx.Close()
  1586. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  1587. id1 := getIDByName(c, name)
  1588. result2 := cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  1589. id2 := getIDByName(c, name)
  1590. result3 := cli.BuildCmd(c, name, build.WithoutCache, build.WithExternalBuildContext(ctx))
  1591. id3 := getIDByName(c, name)
  1592. if id1 != id2 {
  1593. c.Fatalf("The cache should have been used but hasn't: %s", result2.Stdout())
  1594. }
  1595. if id1 == id3 {
  1596. c.Fatalf("The cache should have been invalided but hasn't: %s", result3.Stdout())
  1597. }
  1598. }
  1599. func (s *DockerSuite) TestBuildCopyDirButNotFile(c *testing.T) {
  1600. name := "testbuildcopydirbutnotfile"
  1601. name2 := "testbuildcopydirbutnotfile2"
  1602. dockerfile := `
  1603. FROM ` + minimalBaseImage() + `
  1604. COPY dir /tmp/`
  1605. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(dockerfile), fakecontext.WithFiles(map[string]string{
  1606. "dir/foo": "hello",
  1607. }))
  1608. defer ctx.Close()
  1609. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  1610. id1 := getIDByName(c, name)
  1611. // Check that adding file with similar name doesn't mess with cache
  1612. if err := ctx.Add("dir_file", "hello2"); err != nil {
  1613. c.Fatal(err)
  1614. }
  1615. cli.BuildCmd(c, name2, build.WithExternalBuildContext(ctx))
  1616. id2 := getIDByName(c, name2)
  1617. if id1 != id2 {
  1618. c.Fatal("The cache should have been used but wasn't")
  1619. }
  1620. }
  1621. func (s *DockerSuite) TestBuildAddCurrentDirWithCache(c *testing.T) {
  1622. name := "testbuildaddcurrentdirwithcache"
  1623. name2 := name + "2"
  1624. name3 := name + "3"
  1625. name4 := name + "4"
  1626. dockerfile := `
  1627. FROM ` + minimalBaseImage() + `
  1628. MAINTAINER dockerio
  1629. ADD . /usr/lib/bla`
  1630. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(dockerfile), fakecontext.WithFiles(map[string]string{
  1631. "foo": "hello",
  1632. }))
  1633. defer ctx.Close()
  1634. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  1635. id1 := getIDByName(c, name)
  1636. // Check that adding file invalidate cache of "ADD ."
  1637. if err := ctx.Add("bar", "hello2"); err != nil {
  1638. c.Fatal(err)
  1639. }
  1640. buildImageSuccessfully(c, name2, build.WithExternalBuildContext(ctx))
  1641. id2 := getIDByName(c, name2)
  1642. if id1 == id2 {
  1643. c.Fatal("The cache should have been invalided but hasn't.")
  1644. }
  1645. // Check that changing file invalidate cache of "ADD ."
  1646. if err := ctx.Add("foo", "hello1"); err != nil {
  1647. c.Fatal(err)
  1648. }
  1649. buildImageSuccessfully(c, name3, build.WithExternalBuildContext(ctx))
  1650. id3 := getIDByName(c, name3)
  1651. if id2 == id3 {
  1652. c.Fatal("The cache should have been invalided but hasn't.")
  1653. }
  1654. // Check that changing file to same content with different mtime does not
  1655. // invalidate cache of "ADD ."
  1656. time.Sleep(1 * time.Second) // wait second because of mtime precision
  1657. if err := ctx.Add("foo", "hello1"); err != nil {
  1658. c.Fatal(err)
  1659. }
  1660. buildImageSuccessfully(c, name4, build.WithExternalBuildContext(ctx))
  1661. id4 := getIDByName(c, name4)
  1662. if id3 != id4 {
  1663. c.Fatal("The cache should have been used but hasn't.")
  1664. }
  1665. }
  1666. // FIXME(vdemeester) this really seems to test the same thing as before (TestBuildAddMultipleLocalFileWithAndWithoutCache)
  1667. func (s *DockerSuite) TestBuildAddCurrentDirWithoutCache(c *testing.T) {
  1668. name := "testbuildaddcurrentdirwithoutcache"
  1669. dockerfile := `
  1670. FROM ` + minimalBaseImage() + `
  1671. MAINTAINER dockerio
  1672. ADD . /usr/lib/bla`
  1673. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(dockerfile), fakecontext.WithFiles(map[string]string{
  1674. "foo": "hello",
  1675. }))
  1676. defer ctx.Close()
  1677. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  1678. id1 := getIDByName(c, name)
  1679. buildImageSuccessfully(c, name, build.WithoutCache, build.WithExternalBuildContext(ctx))
  1680. id2 := getIDByName(c, name)
  1681. if id1 == id2 {
  1682. c.Fatal("The cache should have been invalided but hasn't.")
  1683. }
  1684. }
  1685. func (s *DockerSuite) TestBuildAddRemoteFileWithAndWithoutCache(c *testing.T) {
  1686. name := "testbuildaddremotefilewithcache"
  1687. server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{
  1688. "baz": "hello",
  1689. }))
  1690. defer server.Close()
  1691. dockerfile := fmt.Sprintf(`FROM `+minimalBaseImage()+`
  1692. MAINTAINER dockerio
  1693. ADD %s/baz /usr/lib/baz/quux`, server.URL())
  1694. cli.BuildCmd(c, name, build.WithDockerfile(dockerfile))
  1695. id1 := getIDByName(c, name)
  1696. cli.BuildCmd(c, name, build.WithDockerfile(dockerfile))
  1697. id2 := getIDByName(c, name)
  1698. cli.BuildCmd(c, name, build.WithoutCache, build.WithDockerfile(dockerfile))
  1699. id3 := getIDByName(c, name)
  1700. if id1 != id2 {
  1701. c.Fatal("The cache should have been used but hasn't.")
  1702. }
  1703. if id1 == id3 {
  1704. c.Fatal("The cache should have been invalided but hasn't.")
  1705. }
  1706. }
  1707. func (s *DockerSuite) TestBuildAddRemoteFileMTime(c *testing.T) {
  1708. name := "testbuildaddremotefilemtime"
  1709. name2 := name + "2"
  1710. name3 := name + "3"
  1711. files := map[string]string{"baz": "hello"}
  1712. server := fakestorage.New(c, "", fakecontext.WithFiles(files))
  1713. defer server.Close()
  1714. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(fmt.Sprintf(`FROM `+minimalBaseImage()+`
  1715. MAINTAINER dockerio
  1716. ADD %s/baz /usr/lib/baz/quux`, server.URL())))
  1717. defer ctx.Close()
  1718. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  1719. id1 := getIDByName(c, name)
  1720. cli.BuildCmd(c, name2, build.WithExternalBuildContext(ctx))
  1721. id2 := getIDByName(c, name2)
  1722. if id1 != id2 {
  1723. c.Fatal("The cache should have been used but wasn't - #1")
  1724. }
  1725. // Now create a different server with same contents (causes different mtime)
  1726. // The cache should still be used
  1727. // allow some time for clock to pass as mtime precision is only 1s
  1728. time.Sleep(2 * time.Second)
  1729. server2 := fakestorage.New(c, "", fakecontext.WithFiles(files))
  1730. defer server2.Close()
  1731. ctx2 := fakecontext.New(c, "", fakecontext.WithDockerfile(fmt.Sprintf(`FROM `+minimalBaseImage()+`
  1732. MAINTAINER dockerio
  1733. ADD %s/baz /usr/lib/baz/quux`, server2.URL())))
  1734. defer ctx2.Close()
  1735. cli.BuildCmd(c, name3, build.WithExternalBuildContext(ctx2))
  1736. id3 := getIDByName(c, name3)
  1737. if id1 != id3 {
  1738. c.Fatal("The cache should have been used but wasn't")
  1739. }
  1740. }
  1741. // FIXME(vdemeester) this really seems to test the same thing as before (combined)
  1742. func (s *DockerSuite) TestBuildAddLocalAndRemoteFilesWithAndWithoutCache(c *testing.T) {
  1743. name := "testbuildaddlocalandremotefilewithcache"
  1744. server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{
  1745. "baz": "hello",
  1746. }))
  1747. defer server.Close()
  1748. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(fmt.Sprintf(`FROM `+minimalBaseImage()+`
  1749. MAINTAINER dockerio
  1750. ADD foo /usr/lib/bla/bar
  1751. ADD %s/baz /usr/lib/baz/quux`, server.URL())),
  1752. fakecontext.WithFiles(map[string]string{
  1753. "foo": "hello world",
  1754. }))
  1755. defer ctx.Close()
  1756. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  1757. id1 := getIDByName(c, name)
  1758. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  1759. id2 := getIDByName(c, name)
  1760. buildImageSuccessfully(c, name, build.WithoutCache, build.WithExternalBuildContext(ctx))
  1761. id3 := getIDByName(c, name)
  1762. if id1 != id2 {
  1763. c.Fatal("The cache should have been used but hasn't.")
  1764. }
  1765. if id1 == id3 {
  1766. c.Fatal("The cache should have been invalidated but hasn't.")
  1767. }
  1768. }
  1769. func testContextTar(c *testing.T, compression archive.Compression) {
  1770. ctx := fakecontext.New(c, "",
  1771. fakecontext.WithDockerfile(`FROM busybox
  1772. ADD foo /foo
  1773. CMD ["cat", "/foo"]`),
  1774. fakecontext.WithFiles(map[string]string{
  1775. "foo": "bar",
  1776. }),
  1777. )
  1778. defer ctx.Close()
  1779. context, err := archive.Tar(ctx.Dir, compression)
  1780. if err != nil {
  1781. c.Fatalf("failed to build context tar: %v", err)
  1782. }
  1783. name := "contexttar"
  1784. cli.BuildCmd(c, name, build.WithStdinContext(context))
  1785. }
  1786. func (s *DockerSuite) TestBuildContextTarGzip(c *testing.T) {
  1787. testContextTar(c, archive.Gzip)
  1788. }
  1789. func (s *DockerSuite) TestBuildContextTarNoCompression(c *testing.T) {
  1790. testContextTar(c, archive.Uncompressed)
  1791. }
  1792. func (s *DockerSuite) TestBuildNoContext(c *testing.T) {
  1793. name := "nocontext"
  1794. icmd.RunCmd(icmd.Cmd{
  1795. Command: []string{dockerBinary, "build", "-t", name, "-"},
  1796. Stdin: strings.NewReader(
  1797. `FROM busybox
  1798. CMD ["echo", "ok"]`),
  1799. }).Assert(c, icmd.Success)
  1800. if out, _ := dockerCmd(c, "run", "--rm", "nocontext"); out != "ok\n" {
  1801. c.Fatalf("run produced invalid output: %q, expected %q", out, "ok")
  1802. }
  1803. }
  1804. // FIXME(vdemeester) migrate to docker/cli e2e
  1805. func (s *DockerSuite) TestBuildDockerfileStdin(c *testing.T) {
  1806. name := "stdindockerfile"
  1807. tmpDir, err := ioutil.TempDir("", "fake-context")
  1808. assert.NilError(c, err)
  1809. err = ioutil.WriteFile(filepath.Join(tmpDir, "foo"), []byte("bar"), 0600)
  1810. assert.NilError(c, err)
  1811. icmd.RunCmd(icmd.Cmd{
  1812. Command: []string{dockerBinary, "build", "-t", name, "-f", "-", tmpDir},
  1813. Stdin: strings.NewReader(
  1814. `FROM busybox
  1815. ADD foo /foo
  1816. CMD ["cat", "/foo"]`),
  1817. }).Assert(c, icmd.Success)
  1818. res := inspectField(c, name, "Config.Cmd")
  1819. assert.Equal(c, strings.TrimSpace(string(res)), `[cat /foo]`)
  1820. }
  1821. // FIXME(vdemeester) migrate to docker/cli tests (unit or e2e)
  1822. func (s *DockerSuite) TestBuildDockerfileStdinConflict(c *testing.T) {
  1823. name := "stdindockerfiletarcontext"
  1824. icmd.RunCmd(icmd.Cmd{
  1825. Command: []string{dockerBinary, "build", "-t", name, "-f", "-", "-"},
  1826. }).Assert(c, icmd.Expected{
  1827. ExitCode: 1,
  1828. Err: "use stdin for both build context and dockerfile",
  1829. })
  1830. }
  1831. func (s *DockerSuite) TestBuildDockerfileStdinNoExtraFiles(c *testing.T) {
  1832. s.testBuildDockerfileStdinNoExtraFiles(c, false, false)
  1833. }
  1834. func (s *DockerSuite) TestBuildDockerfileStdinDockerignore(c *testing.T) {
  1835. s.testBuildDockerfileStdinNoExtraFiles(c, true, false)
  1836. }
  1837. func (s *DockerSuite) TestBuildDockerfileStdinDockerignoreIgnored(c *testing.T) {
  1838. s.testBuildDockerfileStdinNoExtraFiles(c, true, true)
  1839. }
  1840. func (s *DockerSuite) testBuildDockerfileStdinNoExtraFiles(c *testing.T, hasDockerignore, ignoreDockerignore bool) {
  1841. name := "stdindockerfilenoextra"
  1842. tmpDir, err := ioutil.TempDir("", "fake-context")
  1843. assert.NilError(c, err)
  1844. defer os.RemoveAll(tmpDir)
  1845. writeFile := func(filename, content string) {
  1846. err = ioutil.WriteFile(filepath.Join(tmpDir, filename), []byte(content), 0600)
  1847. assert.NilError(c, err)
  1848. }
  1849. writeFile("foo", "bar")
  1850. if hasDockerignore {
  1851. // Add an empty Dockerfile to verify that it is not added to the image
  1852. writeFile("Dockerfile", "")
  1853. ignores := "Dockerfile\n"
  1854. if ignoreDockerignore {
  1855. ignores += ".dockerignore\n"
  1856. }
  1857. writeFile(".dockerignore", ignores)
  1858. }
  1859. result := icmd.RunCmd(icmd.Cmd{
  1860. Command: []string{dockerBinary, "build", "-t", name, "-f", "-", tmpDir},
  1861. Stdin: strings.NewReader(
  1862. `FROM busybox
  1863. COPY . /baz`),
  1864. })
  1865. result.Assert(c, icmd.Success)
  1866. result = cli.DockerCmd(c, "run", "--rm", name, "ls", "-A", "/baz")
  1867. if hasDockerignore && !ignoreDockerignore {
  1868. assert.Equal(c, result.Stdout(), ".dockerignore\nfoo\n")
  1869. } else {
  1870. assert.Equal(c, result.Stdout(), "foo\n")
  1871. }
  1872. }
  1873. func (s *DockerSuite) TestBuildWithVolumeOwnership(c *testing.T) {
  1874. testRequires(c, DaemonIsLinux)
  1875. name := "testbuildimg"
  1876. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox:latest
  1877. RUN mkdir /test && chown daemon:daemon /test && chmod 0600 /test
  1878. VOLUME /test`))
  1879. out, _ := dockerCmd(c, "run", "--rm", "testbuildimg", "ls", "-la", "/test")
  1880. if expected := "drw-------"; !strings.Contains(out, expected) {
  1881. c.Fatalf("expected %s received %s", expected, out)
  1882. }
  1883. if expected := "daemon daemon"; !strings.Contains(out, expected) {
  1884. c.Fatalf("expected %s received %s", expected, out)
  1885. }
  1886. }
  1887. // testing #1405 - config.Cmd does not get cleaned up if
  1888. // utilizing cache
  1889. func (s *DockerSuite) TestBuildEntrypointRunCleanup(c *testing.T) {
  1890. name := "testbuildcmdcleanup"
  1891. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  1892. RUN echo "hello"`))
  1893. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  1894. build.WithFile("Dockerfile", `FROM busybox
  1895. RUN echo "hello"
  1896. ADD foo /foo
  1897. ENTRYPOINT ["/bin/echo"]`),
  1898. build.WithFile("foo", "hello")))
  1899. res := inspectField(c, name, "Config.Cmd")
  1900. // Cmd must be cleaned up
  1901. if res != "[]" {
  1902. c.Fatalf("Cmd %s, expected nil", res)
  1903. }
  1904. }
  1905. func (s *DockerSuite) TestBuildAddFileNotFound(c *testing.T) {
  1906. name := "testbuildaddnotfound"
  1907. expected := "foo: no such file or directory"
  1908. if testEnv.OSType == "windows" {
  1909. expected = "foo: The system cannot find the file specified"
  1910. }
  1911. buildImage(name, build.WithBuildContext(c,
  1912. build.WithFile("Dockerfile", `FROM `+minimalBaseImage()+`
  1913. ADD foo /usr/local/bar`),
  1914. build.WithFile("bar", "hello"))).Assert(c, icmd.Expected{
  1915. ExitCode: 1,
  1916. Err: expected,
  1917. })
  1918. }
  1919. func (s *DockerSuite) TestBuildInheritance(c *testing.T) {
  1920. testRequires(c, DaemonIsLinux)
  1921. name := "testbuildinheritance"
  1922. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM scratch
  1923. EXPOSE 2375`))
  1924. ports1 := inspectField(c, name, "Config.ExposedPorts")
  1925. buildImageSuccessfully(c, name, build.WithDockerfile(fmt.Sprintf(`FROM %s
  1926. ENTRYPOINT ["/bin/echo"]`, name)))
  1927. res := inspectField(c, name, "Config.Entrypoint")
  1928. if expected := "[/bin/echo]"; res != expected {
  1929. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  1930. }
  1931. ports2 := inspectField(c, name, "Config.ExposedPorts")
  1932. if ports1 != ports2 {
  1933. c.Fatalf("Ports must be same: %s != %s", ports1, ports2)
  1934. }
  1935. }
  1936. func (s *DockerSuite) TestBuildFails(c *testing.T) {
  1937. name := "testbuildfails"
  1938. buildImage(name, build.WithDockerfile(`FROM busybox
  1939. RUN sh -c "exit 23"`)).Assert(c, icmd.Expected{
  1940. ExitCode: 23,
  1941. Err: "returned a non-zero code: 23",
  1942. })
  1943. }
  1944. func (s *DockerSuite) TestBuildOnBuild(c *testing.T) {
  1945. name := "testbuildonbuild"
  1946. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  1947. ONBUILD RUN touch foobar`))
  1948. buildImageSuccessfully(c, name, build.WithDockerfile(fmt.Sprintf(`FROM %s
  1949. RUN [ -f foobar ]`, name)))
  1950. }
  1951. // gh #2446
  1952. func (s *DockerSuite) TestBuildAddToSymlinkDest(c *testing.T) {
  1953. makeLink := `ln -s /foo /bar`
  1954. if testEnv.OSType == "windows" {
  1955. makeLink = `mklink /D C:\bar C:\foo`
  1956. }
  1957. name := "testbuildaddtosymlinkdest"
  1958. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  1959. build.WithFile("Dockerfile", `
  1960. FROM busybox
  1961. RUN sh -c "mkdir /foo"
  1962. RUN `+makeLink+`
  1963. ADD foo /bar/
  1964. RUN sh -c "[ -f /bar/foo ]"
  1965. RUN sh -c "[ -f /foo/foo ]"`),
  1966. build.WithFile("foo", "hello"),
  1967. ))
  1968. }
  1969. func (s *DockerSuite) TestBuildEscapeWhitespace(c *testing.T) {
  1970. name := "testbuildescapewhitespace"
  1971. buildImageSuccessfully(c, name, build.WithDockerfile(`
  1972. # ESCAPE=\
  1973. FROM busybox
  1974. MAINTAINER "Docker \
  1975. IO <io@\
  1976. docker.com>"
  1977. `))
  1978. res := inspectField(c, name, "Author")
  1979. if res != "\"Docker IO <io@docker.com>\"" {
  1980. c.Fatalf("Parsed string did not match the escaped string. Got: %q", res)
  1981. }
  1982. }
  1983. func (s *DockerSuite) TestBuildVerifyIntString(c *testing.T) {
  1984. // Verify that strings that look like ints are still passed as strings
  1985. name := "testbuildstringing"
  1986. buildImageSuccessfully(c, name, build.WithDockerfile(`
  1987. FROM busybox
  1988. MAINTAINER 123`))
  1989. out, _ := dockerCmd(c, "inspect", name)
  1990. if !strings.Contains(out, "\"123\"") {
  1991. c.Fatalf("Output does not contain the int as a string:\n%s", out)
  1992. }
  1993. }
  1994. func (s *DockerSuite) TestBuildDockerignore(c *testing.T) {
  1995. name := "testbuilddockerignore"
  1996. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  1997. build.WithFile("Dockerfile", `
  1998. FROM busybox
  1999. ADD . /bla
  2000. RUN sh -c "[[ -f /bla/src/x.go ]]"
  2001. RUN sh -c "[[ -f /bla/Makefile ]]"
  2002. RUN sh -c "[[ ! -e /bla/src/_vendor ]]"
  2003. RUN sh -c "[[ ! -e /bla/.gitignore ]]"
  2004. RUN sh -c "[[ ! -e /bla/README.md ]]"
  2005. RUN sh -c "[[ ! -e /bla/dir/foo ]]"
  2006. RUN sh -c "[[ ! -e /bla/foo ]]"
  2007. RUN sh -c "[[ ! -e /bla/.git ]]"
  2008. RUN sh -c "[[ ! -e v.cc ]]"
  2009. RUN sh -c "[[ ! -e src/v.cc ]]"
  2010. RUN sh -c "[[ ! -e src/_vendor/v.cc ]]"`),
  2011. build.WithFile("Makefile", "all:"),
  2012. build.WithFile(".git/HEAD", "ref: foo"),
  2013. build.WithFile("src/x.go", "package main"),
  2014. build.WithFile("src/_vendor/v.go", "package main"),
  2015. build.WithFile("src/_vendor/v.cc", "package main"),
  2016. build.WithFile("src/v.cc", "package main"),
  2017. build.WithFile("v.cc", "package main"),
  2018. build.WithFile("dir/foo", ""),
  2019. build.WithFile(".gitignore", ""),
  2020. build.WithFile("README.md", "readme"),
  2021. build.WithFile(".dockerignore", `
  2022. .git
  2023. pkg
  2024. .gitignore
  2025. src/_vendor
  2026. *.md
  2027. **/*.cc
  2028. dir`),
  2029. ))
  2030. }
  2031. func (s *DockerSuite) TestBuildDockerignoreCleanPaths(c *testing.T) {
  2032. name := "testbuilddockerignorecleanpaths"
  2033. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2034. build.WithFile("Dockerfile", `
  2035. FROM busybox
  2036. ADD . /tmp/
  2037. RUN sh -c "(! ls /tmp/foo) && (! ls /tmp/foo2) && (! ls /tmp/dir1/foo)"`),
  2038. build.WithFile("foo", "foo"),
  2039. build.WithFile("foo2", "foo2"),
  2040. build.WithFile("dir1/foo", "foo in dir1"),
  2041. build.WithFile(".dockerignore", "./foo\ndir1//foo\n./dir1/../foo2"),
  2042. ))
  2043. }
  2044. func (s *DockerSuite) TestBuildDockerignoreExceptions(c *testing.T) {
  2045. name := "testbuilddockerignoreexceptions"
  2046. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2047. build.WithFile("Dockerfile", `
  2048. FROM busybox
  2049. ADD . /bla
  2050. RUN sh -c "[[ -f /bla/src/x.go ]]"
  2051. RUN sh -c "[[ -f /bla/Makefile ]]"
  2052. RUN sh -c "[[ ! -e /bla/src/_vendor ]]"
  2053. RUN sh -c "[[ ! -e /bla/.gitignore ]]"
  2054. RUN sh -c "[[ ! -e /bla/README.md ]]"
  2055. RUN sh -c "[[ -e /bla/dir/dir/foo ]]"
  2056. RUN sh -c "[[ ! -e /bla/dir/foo1 ]]"
  2057. RUN sh -c "[[ -f /bla/dir/e ]]"
  2058. RUN sh -c "[[ -f /bla/dir/e-dir/foo ]]"
  2059. RUN sh -c "[[ ! -e /bla/foo ]]"
  2060. RUN sh -c "[[ ! -e /bla/.git ]]"
  2061. RUN sh -c "[[ -e /bla/dir/a.cc ]]"`),
  2062. build.WithFile("Makefile", "all:"),
  2063. build.WithFile(".git/HEAD", "ref: foo"),
  2064. build.WithFile("src/x.go", "package main"),
  2065. build.WithFile("src/_vendor/v.go", "package main"),
  2066. build.WithFile("dir/foo", ""),
  2067. build.WithFile("dir/foo1", ""),
  2068. build.WithFile("dir/dir/f1", ""),
  2069. build.WithFile("dir/dir/foo", ""),
  2070. build.WithFile("dir/e", ""),
  2071. build.WithFile("dir/e-dir/foo", ""),
  2072. build.WithFile(".gitignore", ""),
  2073. build.WithFile("README.md", "readme"),
  2074. build.WithFile("dir/a.cc", "hello"),
  2075. build.WithFile(".dockerignore", `
  2076. .git
  2077. pkg
  2078. .gitignore
  2079. src/_vendor
  2080. *.md
  2081. dir
  2082. !dir/e*
  2083. !dir/dir/foo
  2084. **/*.cc
  2085. !**/*.cc`),
  2086. ))
  2087. }
  2088. func (s *DockerSuite) TestBuildDockerignoringDockerfile(c *testing.T) {
  2089. name := "testbuilddockerignoredockerfile"
  2090. dockerfile := `
  2091. FROM busybox
  2092. ADD . /tmp/
  2093. RUN sh -c "! ls /tmp/Dockerfile"
  2094. RUN ls /tmp/.dockerignore`
  2095. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2096. build.WithFile("Dockerfile", dockerfile),
  2097. build.WithFile(".dockerignore", "Dockerfile\n"),
  2098. ))
  2099. // FIXME(vdemeester) why twice ?
  2100. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2101. build.WithFile("Dockerfile", dockerfile),
  2102. build.WithFile(".dockerignore", "./Dockerfile\n"),
  2103. ))
  2104. }
  2105. func (s *DockerSuite) TestBuildDockerignoringRenamedDockerfile(c *testing.T) {
  2106. name := "testbuilddockerignoredockerfile"
  2107. dockerfile := `
  2108. FROM busybox
  2109. ADD . /tmp/
  2110. RUN ls /tmp/Dockerfile
  2111. RUN sh -c "! ls /tmp/MyDockerfile"
  2112. RUN ls /tmp/.dockerignore`
  2113. buildImageSuccessfully(c, name, cli.WithFlags("-f", "MyDockerfile"), build.WithBuildContext(c,
  2114. build.WithFile("Dockerfile", "Should not use me"),
  2115. build.WithFile("MyDockerfile", dockerfile),
  2116. build.WithFile(".dockerignore", "MyDockerfile\n"),
  2117. ))
  2118. // FIXME(vdemeester) why twice ?
  2119. buildImageSuccessfully(c, name, cli.WithFlags("-f", "MyDockerfile"), build.WithBuildContext(c,
  2120. build.WithFile("Dockerfile", "Should not use me"),
  2121. build.WithFile("MyDockerfile", dockerfile),
  2122. build.WithFile(".dockerignore", "./MyDockerfile\n"),
  2123. ))
  2124. }
  2125. func (s *DockerSuite) TestBuildDockerignoringDockerignore(c *testing.T) {
  2126. name := "testbuilddockerignoredockerignore"
  2127. dockerfile := `
  2128. FROM busybox
  2129. ADD . /tmp/
  2130. RUN sh -c "! ls /tmp/.dockerignore"
  2131. RUN ls /tmp/Dockerfile`
  2132. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2133. build.WithFile("Dockerfile", dockerfile),
  2134. build.WithFile(".dockerignore", ".dockerignore\n"),
  2135. ))
  2136. }
  2137. func (s *DockerSuite) TestBuildDockerignoreTouchDockerfile(c *testing.T) {
  2138. name := "testbuilddockerignoretouchdockerfile"
  2139. dockerfile := `
  2140. FROM busybox
  2141. ADD . /tmp/`
  2142. ctx := fakecontext.New(c, "",
  2143. fakecontext.WithDockerfile(dockerfile),
  2144. fakecontext.WithFiles(map[string]string{
  2145. ".dockerignore": "Dockerfile\n",
  2146. }))
  2147. defer ctx.Close()
  2148. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  2149. id1 := getIDByName(c, name)
  2150. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  2151. id2 := getIDByName(c, name)
  2152. if id1 != id2 {
  2153. c.Fatalf("Didn't use the cache - 1")
  2154. }
  2155. // Now make sure touching Dockerfile doesn't invalidate the cache
  2156. if err := ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil {
  2157. c.Fatalf("Didn't add Dockerfile: %s", err)
  2158. }
  2159. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  2160. id2 = getIDByName(c, name)
  2161. if id1 != id2 {
  2162. c.Fatalf("Didn't use the cache - 2")
  2163. }
  2164. // One more time but just 'touch' it instead of changing the content
  2165. if err := ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil {
  2166. c.Fatalf("Didn't add Dockerfile: %s", err)
  2167. }
  2168. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  2169. id2 = getIDByName(c, name)
  2170. if id1 != id2 {
  2171. c.Fatalf("Didn't use the cache - 3")
  2172. }
  2173. }
  2174. func (s *DockerSuite) TestBuildDockerignoringWholeDir(c *testing.T) {
  2175. name := "testbuilddockerignorewholedir"
  2176. dockerfile := `
  2177. FROM busybox
  2178. COPY . /
  2179. RUN sh -c "[[ ! -e /.gitignore ]]"
  2180. RUN sh -c "[[ ! -e /Makefile ]]"`
  2181. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2182. build.WithFile("Dockerfile", dockerfile),
  2183. build.WithFile(".dockerignore", "*\n"),
  2184. build.WithFile("Makefile", "all:"),
  2185. build.WithFile(".gitignore", ""),
  2186. ))
  2187. }
  2188. func (s *DockerSuite) TestBuildDockerignoringOnlyDotfiles(c *testing.T) {
  2189. name := "testbuilddockerignorewholedir"
  2190. dockerfile := `
  2191. FROM busybox
  2192. COPY . /
  2193. RUN sh -c "[[ ! -e /.gitignore ]]"
  2194. RUN sh -c "[[ -f /Makefile ]]"`
  2195. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2196. build.WithFile("Dockerfile", dockerfile),
  2197. build.WithFile(".dockerignore", ".*"),
  2198. build.WithFile("Makefile", "all:"),
  2199. build.WithFile(".gitignore", ""),
  2200. ))
  2201. }
  2202. func (s *DockerSuite) TestBuildDockerignoringBadExclusion(c *testing.T) {
  2203. name := "testbuilddockerignorebadexclusion"
  2204. buildImage(name, build.WithBuildContext(c,
  2205. build.WithFile("Dockerfile", `
  2206. FROM busybox
  2207. COPY . /
  2208. RUN sh -c "[[ ! -e /.gitignore ]]"
  2209. RUN sh -c "[[ -f /Makefile ]]"`),
  2210. build.WithFile("Makefile", "all:"),
  2211. build.WithFile(".gitignore", ""),
  2212. build.WithFile(".dockerignore", "!\n"),
  2213. )).Assert(c, icmd.Expected{
  2214. ExitCode: 1,
  2215. Err: `illegal exclusion pattern: "!"`,
  2216. })
  2217. }
  2218. func (s *DockerSuite) TestBuildDockerignoringWildTopDir(c *testing.T) {
  2219. dockerfile := `
  2220. FROM busybox
  2221. COPY . /
  2222. RUN sh -c "[[ ! -e /.dockerignore ]]"
  2223. RUN sh -c "[[ ! -e /Dockerfile ]]"
  2224. RUN sh -c "[[ ! -e /file1 ]]"
  2225. RUN sh -c "[[ ! -e /dir ]]"`
  2226. // All of these should result in ignoring all files
  2227. for _, variant := range []string{"**", "**/", "**/**", "*"} {
  2228. buildImageSuccessfully(c, "noname", build.WithBuildContext(c,
  2229. build.WithFile("Dockerfile", dockerfile),
  2230. build.WithFile("file1", ""),
  2231. build.WithFile("dir/file1", ""),
  2232. build.WithFile(".dockerignore", variant),
  2233. ))
  2234. dockerCmd(c, "rmi", "noname")
  2235. }
  2236. }
  2237. func (s *DockerSuite) TestBuildDockerignoringWildDirs(c *testing.T) {
  2238. dockerfile := `
  2239. FROM busybox
  2240. COPY . /
  2241. #RUN sh -c "[[ -e /.dockerignore ]]"
  2242. RUN sh -c "[[ -e /Dockerfile ]] && \
  2243. [[ ! -e /file0 ]] && \
  2244. [[ ! -e /dir1/file0 ]] && \
  2245. [[ ! -e /dir2/file0 ]] && \
  2246. [[ ! -e /file1 ]] && \
  2247. [[ ! -e /dir1/file1 ]] && \
  2248. [[ ! -e /dir1/dir2/file1 ]] && \
  2249. [[ ! -e /dir1/file2 ]] && \
  2250. [[ -e /dir1/dir2/file2 ]] && \
  2251. [[ ! -e /dir1/dir2/file4 ]] && \
  2252. [[ ! -e /dir1/dir2/file5 ]] && \
  2253. [[ ! -e /dir1/dir2/file6 ]] && \
  2254. [[ ! -e /dir1/dir3/file7 ]] && \
  2255. [[ ! -e /dir1/dir3/file8 ]] && \
  2256. [[ -e /dir1/dir3 ]] && \
  2257. [[ -e /dir1/dir4 ]] && \
  2258. [[ ! -e 'dir1/dir5/fileAA' ]] && \
  2259. [[ -e 'dir1/dir5/fileAB' ]] && \
  2260. [[ -e 'dir1/dir5/fileB' ]]" # "." in pattern means nothing
  2261. RUN echo all done!`
  2262. dockerignore := `
  2263. **/file0
  2264. **/*file1
  2265. **/dir1/file2
  2266. dir1/**/file4
  2267. **/dir2/file5
  2268. **/dir1/dir2/file6
  2269. dir1/dir3/**
  2270. **/dir4/**
  2271. **/file?A
  2272. **/file\?B
  2273. **/dir5/file.
  2274. `
  2275. buildImageSuccessfully(c, "noname", build.WithBuildContext(c,
  2276. build.WithFile("Dockerfile", dockerfile),
  2277. build.WithFile(".dockerignore", dockerignore),
  2278. build.WithFile("dir1/file0", ""),
  2279. build.WithFile("dir1/dir2/file0", ""),
  2280. build.WithFile("file1", ""),
  2281. build.WithFile("dir1/file1", ""),
  2282. build.WithFile("dir1/dir2/file1", ""),
  2283. build.WithFile("dir1/file2", ""),
  2284. build.WithFile("dir1/dir2/file2", ""), // remains
  2285. build.WithFile("dir1/dir2/file4", ""),
  2286. build.WithFile("dir1/dir2/file5", ""),
  2287. build.WithFile("dir1/dir2/file6", ""),
  2288. build.WithFile("dir1/dir3/file7", ""),
  2289. build.WithFile("dir1/dir3/file8", ""),
  2290. build.WithFile("dir1/dir4/file9", ""),
  2291. build.WithFile("dir1/dir5/fileAA", ""),
  2292. build.WithFile("dir1/dir5/fileAB", ""),
  2293. build.WithFile("dir1/dir5/fileB", ""),
  2294. ))
  2295. }
  2296. func (s *DockerSuite) TestBuildLineBreak(c *testing.T) {
  2297. testRequires(c, DaemonIsLinux)
  2298. name := "testbuildlinebreak"
  2299. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2300. RUN sh -c 'echo root:testpass \
  2301. > /tmp/passwd'
  2302. RUN mkdir -p /var/run/sshd
  2303. RUN sh -c "[ "$(cat /tmp/passwd)" = "root:testpass" ]"
  2304. RUN sh -c "[ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]"`))
  2305. }
  2306. func (s *DockerSuite) TestBuildEOLInLine(c *testing.T) {
  2307. testRequires(c, DaemonIsLinux)
  2308. name := "testbuildeolinline"
  2309. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2310. RUN sh -c 'echo root:testpass > /tmp/passwd'
  2311. RUN echo "foo \n bar"; echo "baz"
  2312. RUN mkdir -p /var/run/sshd
  2313. RUN sh -c "[ "$(cat /tmp/passwd)" = "root:testpass" ]"
  2314. RUN sh -c "[ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]"`))
  2315. }
  2316. func (s *DockerSuite) TestBuildCommentsShebangs(c *testing.T) {
  2317. testRequires(c, DaemonIsLinux)
  2318. name := "testbuildcomments"
  2319. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2320. # This is an ordinary comment.
  2321. RUN { echo '#!/bin/sh'; echo 'echo hello world'; } > /hello.sh
  2322. RUN [ ! -x /hello.sh ]
  2323. # comment with line break \
  2324. RUN chmod +x /hello.sh
  2325. RUN [ -x /hello.sh ]
  2326. RUN [ "$(cat /hello.sh)" = $'#!/bin/sh\necho hello world' ]
  2327. RUN [ "$(/hello.sh)" = "hello world" ]`))
  2328. }
  2329. func (s *DockerSuite) TestBuildUsersAndGroups(c *testing.T) {
  2330. testRequires(c, DaemonIsLinux)
  2331. name := "testbuildusers"
  2332. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2333. # Make sure our defaults work
  2334. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)" = '0:0/root:root' ]
  2335. # 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)
  2336. USER root
  2337. RUN [ "$(id -G):$(id -Gn)" = '0 10:root wheel' ]
  2338. # Setup dockerio user and group
  2339. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd && \
  2340. echo 'dockerio:x:1001:' >> /etc/group
  2341. # Make sure we can switch to our user and all the information is exactly as we expect it to be
  2342. USER dockerio
  2343. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  2344. # Switch back to root and double check that worked exactly as we might expect it to
  2345. USER root
  2346. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '0:0/root:root/0 10:root wheel' ] && \
  2347. # Add a "supplementary" group for our dockerio user
  2348. echo 'supplementary:x:1002:dockerio' >> /etc/group
  2349. # ... and then go verify that we get it like we expect
  2350. USER dockerio
  2351. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  2352. USER 1001
  2353. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  2354. # super test the new "user:group" syntax
  2355. USER dockerio:dockerio
  2356. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  2357. USER 1001:dockerio
  2358. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  2359. USER dockerio:1001
  2360. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  2361. USER 1001:1001
  2362. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  2363. USER dockerio:supplementary
  2364. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  2365. USER dockerio:1002
  2366. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  2367. USER 1001:supplementary
  2368. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  2369. USER 1001:1002
  2370. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  2371. # make sure unknown uid/gid still works properly
  2372. USER 1042:1043
  2373. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1042:1043/1042:1043/1043:1043' ]`))
  2374. }
  2375. // FIXME(vdemeester) rename this test (and probably "merge" it with the one below TestBuildEnvUsage2)
  2376. func (s *DockerSuite) TestBuildEnvUsage(c *testing.T) {
  2377. // /docker/world/hello is not owned by the correct user
  2378. testRequires(c, NotUserNamespace)
  2379. testRequires(c, DaemonIsLinux)
  2380. name := "testbuildenvusage"
  2381. dockerfile := `FROM busybox
  2382. ENV HOME /root
  2383. ENV PATH $HOME/bin:$PATH
  2384. ENV PATH /tmp:$PATH
  2385. RUN [ "$PATH" = "/tmp:$HOME/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ]
  2386. ENV FOO /foo/baz
  2387. ENV BAR /bar
  2388. ENV BAZ $BAR
  2389. ENV FOOPATH $PATH:$FOO
  2390. RUN [ "$BAR" = "$BAZ" ]
  2391. RUN [ "$FOOPATH" = "$PATH:/foo/baz" ]
  2392. ENV FROM hello/docker/world
  2393. ENV TO /docker/world/hello
  2394. ADD $FROM $TO
  2395. RUN [ "$(cat $TO)" = "hello" ]
  2396. ENV abc=def
  2397. ENV ghi=$abc
  2398. RUN [ "$ghi" = "def" ]
  2399. `
  2400. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2401. build.WithFile("Dockerfile", dockerfile),
  2402. build.WithFile("hello/docker/world", "hello"),
  2403. ))
  2404. }
  2405. // FIXME(vdemeester) rename this test (and probably "merge" it with the one above TestBuildEnvUsage)
  2406. func (s *DockerSuite) TestBuildEnvUsage2(c *testing.T) {
  2407. // /docker/world/hello is not owned by the correct user
  2408. testRequires(c, NotUserNamespace)
  2409. testRequires(c, DaemonIsLinux)
  2410. name := "testbuildenvusage2"
  2411. dockerfile := `FROM busybox
  2412. ENV abc=def def="hello world"
  2413. RUN [ "$abc,$def" = "def,hello world" ]
  2414. ENV def=hello\ world v1=abc v2="hi there" v3='boogie nights' v4="with'quotes too"
  2415. RUN [ "$def,$v1,$v2,$v3,$v4" = "hello world,abc,hi there,boogie nights,with'quotes too" ]
  2416. ENV abc=zzz FROM=hello/docker/world
  2417. ENV abc=zzz TO=/docker/world/hello
  2418. ADD $FROM $TO
  2419. RUN [ "$abc,$(cat $TO)" = "zzz,hello" ]
  2420. ENV abc 'yyy'
  2421. RUN [ $abc = 'yyy' ]
  2422. ENV abc=
  2423. RUN [ "$abc" = "" ]
  2424. # use grep to make sure if the builder substitutes \$foo by mistake
  2425. # we don't get a false positive
  2426. ENV abc=\$foo
  2427. RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep foo)
  2428. ENV abc \$foo
  2429. RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep foo)
  2430. ENV abc=\'foo\' abc2=\"foo\"
  2431. RUN [ "$abc,$abc2" = "'foo',\"foo\"" ]
  2432. ENV abc "foo"
  2433. RUN [ "$abc" = "foo" ]
  2434. ENV abc 'foo'
  2435. RUN [ "$abc" = 'foo' ]
  2436. ENV abc \'foo\'
  2437. RUN [ "$abc" = "'foo'" ]
  2438. ENV abc \"foo\"
  2439. RUN [ "$abc" = '"foo"' ]
  2440. ENV abc=ABC
  2441. RUN [ "$abc" = "ABC" ]
  2442. ENV def1=${abc:-DEF} def2=${ccc:-DEF}
  2443. ENV def3=${ccc:-${def2}xx} def4=${abc:+ALT} def5=${def2:+${abc}:} def6=${ccc:-\$abc:} def7=${ccc:-\${abc}:}
  2444. RUN [ "$def1,$def2,$def3,$def4,$def5,$def6,$def7" = 'ABC,DEF,DEFxx,ALT,ABC:,$abc:,${abc:}' ]
  2445. ENV mypath=${mypath:+$mypath:}/home
  2446. ENV mypath=${mypath:+$mypath:}/away
  2447. RUN [ "$mypath" = '/home:/away' ]
  2448. ENV e1=bar
  2449. ENV e2=$e1 e3=$e11 e4=\$e1 e5=\$e11
  2450. RUN [ "$e0,$e1,$e2,$e3,$e4,$e5" = ',bar,bar,,$e1,$e11' ]
  2451. ENV ee1 bar
  2452. ENV ee2 $ee1
  2453. ENV ee3 $ee11
  2454. ENV ee4 \$ee1
  2455. ENV ee5 \$ee11
  2456. RUN [ "$ee1,$ee2,$ee3,$ee4,$ee5" = 'bar,bar,,$ee1,$ee11' ]
  2457. ENV eee1="foo" eee2='foo'
  2458. ENV eee3 "foo"
  2459. ENV eee4 'foo'
  2460. RUN [ "$eee1,$eee2,$eee3,$eee4" = 'foo,foo,foo,foo' ]
  2461. `
  2462. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2463. build.WithFile("Dockerfile", dockerfile),
  2464. build.WithFile("hello/docker/world", "hello"),
  2465. ))
  2466. }
  2467. func (s *DockerSuite) TestBuildAddScript(c *testing.T) {
  2468. testRequires(c, DaemonIsLinux)
  2469. name := "testbuildaddscript"
  2470. dockerfile := `
  2471. FROM busybox
  2472. ADD test /test
  2473. RUN ["chmod","+x","/test"]
  2474. RUN ["/test"]
  2475. RUN [ "$(cat /testfile)" = 'test!' ]`
  2476. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2477. build.WithFile("Dockerfile", dockerfile),
  2478. build.WithFile("test", "#!/bin/sh\necho 'test!' > /testfile"),
  2479. ))
  2480. }
  2481. func (s *DockerSuite) TestBuildAddTar(c *testing.T) {
  2482. // /test/foo is not owned by the correct user
  2483. testRequires(c, NotUserNamespace)
  2484. name := "testbuildaddtar"
  2485. ctx := func() *fakecontext.Fake {
  2486. dockerfile := `
  2487. FROM busybox
  2488. ADD test.tar /
  2489. RUN cat /test/foo | grep Hi
  2490. ADD test.tar /test.tar
  2491. RUN cat /test.tar/test/foo | grep Hi
  2492. ADD test.tar /unlikely-to-exist
  2493. RUN cat /unlikely-to-exist/test/foo | grep Hi
  2494. ADD test.tar /unlikely-to-exist-trailing-slash/
  2495. RUN cat /unlikely-to-exist-trailing-slash/test/foo | grep Hi
  2496. RUN sh -c "mkdir /existing-directory" #sh -c is needed on Windows to use the correct mkdir
  2497. ADD test.tar /existing-directory
  2498. RUN cat /existing-directory/test/foo | grep Hi
  2499. ADD test.tar /existing-directory-trailing-slash/
  2500. RUN cat /existing-directory-trailing-slash/test/foo | grep Hi`
  2501. tmpDir, err := ioutil.TempDir("", "fake-context")
  2502. assert.NilError(c, err)
  2503. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  2504. if err != nil {
  2505. c.Fatalf("failed to create test.tar archive: %v", err)
  2506. }
  2507. defer testTar.Close()
  2508. tw := tar.NewWriter(testTar)
  2509. if err := tw.WriteHeader(&tar.Header{
  2510. Name: "test/foo",
  2511. Size: 2,
  2512. }); err != nil {
  2513. c.Fatalf("failed to write tar file header: %v", err)
  2514. }
  2515. if _, err := tw.Write([]byte("Hi")); err != nil {
  2516. c.Fatalf("failed to write tar file content: %v", err)
  2517. }
  2518. if err := tw.Close(); err != nil {
  2519. c.Fatalf("failed to close tar archive: %v", err)
  2520. }
  2521. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  2522. c.Fatalf("failed to open destination dockerfile: %v", err)
  2523. }
  2524. return fakecontext.New(c, tmpDir)
  2525. }()
  2526. defer ctx.Close()
  2527. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  2528. }
  2529. func (s *DockerSuite) TestBuildAddBrokenTar(c *testing.T) {
  2530. name := "testbuildaddbrokentar"
  2531. ctx := func() *fakecontext.Fake {
  2532. dockerfile := `
  2533. FROM busybox
  2534. ADD test.tar /`
  2535. tmpDir, err := ioutil.TempDir("", "fake-context")
  2536. assert.NilError(c, err)
  2537. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  2538. if err != nil {
  2539. c.Fatalf("failed to create test.tar archive: %v", err)
  2540. }
  2541. defer testTar.Close()
  2542. tw := tar.NewWriter(testTar)
  2543. if err := tw.WriteHeader(&tar.Header{
  2544. Name: "test/foo",
  2545. Size: 2,
  2546. }); err != nil {
  2547. c.Fatalf("failed to write tar file header: %v", err)
  2548. }
  2549. if _, err := tw.Write([]byte("Hi")); err != nil {
  2550. c.Fatalf("failed to write tar file content: %v", err)
  2551. }
  2552. if err := tw.Close(); err != nil {
  2553. c.Fatalf("failed to close tar archive: %v", err)
  2554. }
  2555. // Corrupt the tar by removing one byte off the end
  2556. stat, err := testTar.Stat()
  2557. if err != nil {
  2558. c.Fatalf("failed to stat tar archive: %v", err)
  2559. }
  2560. if err := testTar.Truncate(stat.Size() - 1); err != nil {
  2561. c.Fatalf("failed to truncate tar archive: %v", err)
  2562. }
  2563. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  2564. c.Fatalf("failed to open destination dockerfile: %v", err)
  2565. }
  2566. return fakecontext.New(c, tmpDir)
  2567. }()
  2568. defer ctx.Close()
  2569. buildImage(name, build.WithExternalBuildContext(ctx)).Assert(c, icmd.Expected{
  2570. ExitCode: 1,
  2571. })
  2572. }
  2573. func (s *DockerSuite) TestBuildAddNonTar(c *testing.T) {
  2574. name := "testbuildaddnontar"
  2575. // Should not try to extract test.tar
  2576. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2577. build.WithFile("Dockerfile", `
  2578. FROM busybox
  2579. ADD test.tar /
  2580. RUN test -f /test.tar`),
  2581. build.WithFile("test.tar", "not_a_tar_file"),
  2582. ))
  2583. }
  2584. func (s *DockerSuite) TestBuildAddTarXz(c *testing.T) {
  2585. // /test/foo is not owned by the correct user
  2586. testRequires(c, NotUserNamespace)
  2587. testRequires(c, DaemonIsLinux)
  2588. name := "testbuildaddtarxz"
  2589. ctx := func() *fakecontext.Fake {
  2590. dockerfile := `
  2591. FROM busybox
  2592. ADD test.tar.xz /
  2593. RUN cat /test/foo | grep Hi`
  2594. tmpDir, err := ioutil.TempDir("", "fake-context")
  2595. assert.NilError(c, err)
  2596. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  2597. if err != nil {
  2598. c.Fatalf("failed to create test.tar archive: %v", err)
  2599. }
  2600. defer testTar.Close()
  2601. tw := tar.NewWriter(testTar)
  2602. if err := tw.WriteHeader(&tar.Header{
  2603. Name: "test/foo",
  2604. Size: 2,
  2605. }); err != nil {
  2606. c.Fatalf("failed to write tar file header: %v", err)
  2607. }
  2608. if _, err := tw.Write([]byte("Hi")); err != nil {
  2609. c.Fatalf("failed to write tar file content: %v", err)
  2610. }
  2611. if err := tw.Close(); err != nil {
  2612. c.Fatalf("failed to close tar archive: %v", err)
  2613. }
  2614. icmd.RunCmd(icmd.Cmd{
  2615. Command: []string{"xz", "-k", "test.tar"},
  2616. Dir: tmpDir,
  2617. }).Assert(c, icmd.Success)
  2618. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  2619. c.Fatalf("failed to open destination dockerfile: %v", err)
  2620. }
  2621. return fakecontext.New(c, tmpDir)
  2622. }()
  2623. defer ctx.Close()
  2624. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  2625. }
  2626. func (s *DockerSuite) TestBuildAddTarXzGz(c *testing.T) {
  2627. testRequires(c, DaemonIsLinux)
  2628. name := "testbuildaddtarxzgz"
  2629. ctx := func() *fakecontext.Fake {
  2630. dockerfile := `
  2631. FROM busybox
  2632. ADD test.tar.xz.gz /
  2633. RUN ls /test.tar.xz.gz`
  2634. tmpDir, err := ioutil.TempDir("", "fake-context")
  2635. assert.NilError(c, err)
  2636. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  2637. if err != nil {
  2638. c.Fatalf("failed to create test.tar archive: %v", err)
  2639. }
  2640. defer testTar.Close()
  2641. tw := tar.NewWriter(testTar)
  2642. if err := tw.WriteHeader(&tar.Header{
  2643. Name: "test/foo",
  2644. Size: 2,
  2645. }); err != nil {
  2646. c.Fatalf("failed to write tar file header: %v", err)
  2647. }
  2648. if _, err := tw.Write([]byte("Hi")); err != nil {
  2649. c.Fatalf("failed to write tar file content: %v", err)
  2650. }
  2651. if err := tw.Close(); err != nil {
  2652. c.Fatalf("failed to close tar archive: %v", err)
  2653. }
  2654. icmd.RunCmd(icmd.Cmd{
  2655. Command: []string{"xz", "-k", "test.tar"},
  2656. Dir: tmpDir,
  2657. }).Assert(c, icmd.Success)
  2658. icmd.RunCmd(icmd.Cmd{
  2659. Command: []string{"gzip", "test.tar.xz"},
  2660. Dir: tmpDir,
  2661. })
  2662. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  2663. c.Fatalf("failed to open destination dockerfile: %v", err)
  2664. }
  2665. return fakecontext.New(c, tmpDir)
  2666. }()
  2667. defer ctx.Close()
  2668. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  2669. }
  2670. // FIXME(vdemeester) most of the from git tests could be moved to `docker/cli` e2e tests
  2671. func (s *DockerSuite) TestBuildFromGit(c *testing.T) {
  2672. name := "testbuildfromgit"
  2673. git := fakegit.New(c, "repo", map[string]string{
  2674. "Dockerfile": `FROM busybox
  2675. ADD first /first
  2676. RUN [ -f /first ]
  2677. MAINTAINER docker`,
  2678. "first": "test git data",
  2679. }, true)
  2680. defer git.Close()
  2681. buildImageSuccessfully(c, name, build.WithContextPath(git.RepoURL))
  2682. res := inspectField(c, name, "Author")
  2683. if res != "docker" {
  2684. c.Fatalf("Maintainer should be docker, got %s", res)
  2685. }
  2686. }
  2687. func (s *DockerSuite) TestBuildFromGitWithContext(c *testing.T) {
  2688. name := "testbuildfromgit"
  2689. git := fakegit.New(c, "repo", map[string]string{
  2690. "docker/Dockerfile": `FROM busybox
  2691. ADD first /first
  2692. RUN [ -f /first ]
  2693. MAINTAINER docker`,
  2694. "docker/first": "test git data",
  2695. }, true)
  2696. defer git.Close()
  2697. buildImageSuccessfully(c, name, build.WithContextPath(fmt.Sprintf("%s#master:docker", git.RepoURL)))
  2698. res := inspectField(c, name, "Author")
  2699. if res != "docker" {
  2700. c.Fatalf("Maintainer should be docker, got %s", res)
  2701. }
  2702. }
  2703. func (s *DockerSuite) TestBuildFromGitWithF(c *testing.T) {
  2704. name := "testbuildfromgitwithf"
  2705. git := fakegit.New(c, "repo", map[string]string{
  2706. "myApp/myDockerfile": `FROM busybox
  2707. RUN echo hi from Dockerfile`,
  2708. }, true)
  2709. defer git.Close()
  2710. buildImage(name, cli.WithFlags("-f", "myApp/myDockerfile"), build.WithContextPath(git.RepoURL)).Assert(c, icmd.Expected{
  2711. Out: "hi from Dockerfile",
  2712. })
  2713. }
  2714. func (s *DockerSuite) TestBuildFromRemoteTarball(c *testing.T) {
  2715. name := "testbuildfromremotetarball"
  2716. buffer := new(bytes.Buffer)
  2717. tw := tar.NewWriter(buffer)
  2718. defer tw.Close()
  2719. dockerfile := []byte(`FROM busybox
  2720. MAINTAINER docker`)
  2721. if err := tw.WriteHeader(&tar.Header{
  2722. Name: "Dockerfile",
  2723. Size: int64(len(dockerfile)),
  2724. }); err != nil {
  2725. c.Fatalf("failed to write tar file header: %v", err)
  2726. }
  2727. if _, err := tw.Write(dockerfile); err != nil {
  2728. c.Fatalf("failed to write tar file content: %v", err)
  2729. }
  2730. if err := tw.Close(); err != nil {
  2731. c.Fatalf("failed to close tar archive: %v", err)
  2732. }
  2733. server := fakestorage.New(c, "", fakecontext.WithBinaryFiles(map[string]*bytes.Buffer{
  2734. "testT.tar": buffer,
  2735. }))
  2736. defer server.Close()
  2737. cli.BuildCmd(c, name, build.WithContextPath(server.URL()+"/testT.tar"))
  2738. res := inspectField(c, name, "Author")
  2739. if res != "docker" {
  2740. c.Fatalf("Maintainer should be docker, got %s", res)
  2741. }
  2742. }
  2743. func (s *DockerSuite) TestBuildCleanupCmdOnEntrypoint(c *testing.T) {
  2744. name := "testbuildcmdcleanuponentrypoint"
  2745. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  2746. CMD ["test"]
  2747. ENTRYPOINT ["echo"]`))
  2748. buildImageSuccessfully(c, name, build.WithDockerfile(fmt.Sprintf(`FROM %s
  2749. ENTRYPOINT ["cat"]`, name)))
  2750. res := inspectField(c, name, "Config.Cmd")
  2751. if res != "[]" {
  2752. c.Fatalf("Cmd %s, expected nil", res)
  2753. }
  2754. res = inspectField(c, name, "Config.Entrypoint")
  2755. if expected := "[cat]"; res != expected {
  2756. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  2757. }
  2758. }
  2759. func (s *DockerSuite) TestBuildClearCmd(c *testing.T) {
  2760. name := "testbuildclearcmd"
  2761. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  2762. ENTRYPOINT ["/bin/bash"]
  2763. CMD []`))
  2764. res := inspectFieldJSON(c, name, "Config.Cmd")
  2765. if res != "[]" {
  2766. c.Fatalf("Cmd %s, expected %s", res, "[]")
  2767. }
  2768. }
  2769. func (s *DockerSuite) TestBuildEmptyCmd(c *testing.T) {
  2770. // Skip on Windows. Base image on Windows has a CMD set in the image.
  2771. testRequires(c, DaemonIsLinux)
  2772. name := "testbuildemptycmd"
  2773. buildImageSuccessfully(c, name, build.WithDockerfile("FROM "+minimalBaseImage()+"\nMAINTAINER quux\n"))
  2774. res := inspectFieldJSON(c, name, "Config.Cmd")
  2775. if res != "null" {
  2776. c.Fatalf("Cmd %s, expected %s", res, "null")
  2777. }
  2778. }
  2779. func (s *DockerSuite) TestBuildOnBuildOutput(c *testing.T) {
  2780. name := "testbuildonbuildparent"
  2781. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nONBUILD RUN echo foo\n"))
  2782. buildImage(name, build.WithDockerfile("FROM "+name+"\nMAINTAINER quux\n")).Assert(c, icmd.Expected{
  2783. Out: "# Executing 1 build trigger",
  2784. })
  2785. }
  2786. // FIXME(vdemeester) should be a unit test
  2787. func (s *DockerSuite) TestBuildInvalidTag(c *testing.T) {
  2788. name := "abcd:" + testutil.GenerateRandomAlphaOnlyString(200)
  2789. buildImage(name, build.WithDockerfile("FROM "+minimalBaseImage()+"\nMAINTAINER quux\n")).Assert(c, icmd.Expected{
  2790. ExitCode: 125,
  2791. Err: "invalid reference format",
  2792. })
  2793. }
  2794. func (s *DockerSuite) TestBuildCmdShDashC(c *testing.T) {
  2795. name := "testbuildcmdshc"
  2796. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nCMD echo cmd\n"))
  2797. res := inspectFieldJSON(c, name, "Config.Cmd")
  2798. expected := `["/bin/sh","-c","echo cmd"]`
  2799. if testEnv.OSType == "windows" {
  2800. expected = `["cmd /S /C echo cmd"]`
  2801. }
  2802. if res != expected {
  2803. c.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  2804. }
  2805. }
  2806. func (s *DockerSuite) TestBuildCmdSpaces(c *testing.T) {
  2807. // Test to make sure that when we strcat arrays we take into account
  2808. // the arg separator to make sure ["echo","hi"] and ["echo hi"] don't
  2809. // look the same
  2810. name := "testbuildcmdspaces"
  2811. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nCMD [\"echo hi\"]\n"))
  2812. id1 := getIDByName(c, name)
  2813. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nCMD [\"echo\", \"hi\"]\n"))
  2814. id2 := getIDByName(c, name)
  2815. if id1 == id2 {
  2816. c.Fatal("Should not have resulted in the same CMD")
  2817. }
  2818. // Now do the same with ENTRYPOINT
  2819. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nENTRYPOINT [\"echo hi\"]\n"))
  2820. id1 = getIDByName(c, name)
  2821. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nENTRYPOINT [\"echo\", \"hi\"]\n"))
  2822. id2 = getIDByName(c, name)
  2823. if id1 == id2 {
  2824. c.Fatal("Should not have resulted in the same ENTRYPOINT")
  2825. }
  2826. }
  2827. func (s *DockerSuite) TestBuildCmdJSONNoShDashC(c *testing.T) {
  2828. name := "testbuildcmdjson"
  2829. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nCMD [\"echo\", \"cmd\"]"))
  2830. res := inspectFieldJSON(c, name, "Config.Cmd")
  2831. expected := `["echo","cmd"]`
  2832. if res != expected {
  2833. c.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  2834. }
  2835. }
  2836. func (s *DockerSuite) TestBuildEntrypointCanBeOverriddenByChild(c *testing.T) {
  2837. buildImageSuccessfully(c, "parent", build.WithDockerfile(`
  2838. FROM busybox
  2839. ENTRYPOINT exit 130
  2840. `))
  2841. icmd.RunCommand(dockerBinary, "run", "parent").Assert(c, icmd.Expected{
  2842. ExitCode: 130,
  2843. })
  2844. buildImageSuccessfully(c, "child", build.WithDockerfile(`
  2845. FROM parent
  2846. ENTRYPOINT exit 5
  2847. `))
  2848. icmd.RunCommand(dockerBinary, "run", "child").Assert(c, icmd.Expected{
  2849. ExitCode: 5,
  2850. })
  2851. }
  2852. func (s *DockerSuite) TestBuildEntrypointCanBeOverriddenByChildInspect(c *testing.T) {
  2853. var (
  2854. name = "testbuildepinherit"
  2855. name2 = "testbuildepinherit2"
  2856. expected = `["/bin/sh","-c","echo quux"]`
  2857. )
  2858. if testEnv.OSType == "windows" {
  2859. expected = `["cmd /S /C echo quux"]`
  2860. }
  2861. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nENTRYPOINT /foo/bar"))
  2862. buildImageSuccessfully(c, name2, build.WithDockerfile(fmt.Sprintf("FROM %s\nENTRYPOINT echo quux", name)))
  2863. res := inspectFieldJSON(c, name2, "Config.Entrypoint")
  2864. if res != expected {
  2865. c.Fatalf("Expected value %s not in Config.Entrypoint: %s", expected, res)
  2866. }
  2867. icmd.RunCommand(dockerBinary, "run", name2).Assert(c, icmd.Expected{
  2868. Out: "quux",
  2869. })
  2870. }
  2871. func (s *DockerSuite) TestBuildRunShEntrypoint(c *testing.T) {
  2872. name := "testbuildentrypoint"
  2873. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2874. ENTRYPOINT echo`))
  2875. dockerCmd(c, "run", "--rm", name)
  2876. }
  2877. func (s *DockerSuite) TestBuildExoticShellInterpolation(c *testing.T) {
  2878. testRequires(c, DaemonIsLinux)
  2879. name := "testbuildexoticshellinterpolation"
  2880. buildImageSuccessfully(c, name, build.WithDockerfile(`
  2881. FROM busybox
  2882. ENV SOME_VAR a.b.c
  2883. RUN [ "$SOME_VAR" = 'a.b.c' ]
  2884. RUN [ "${SOME_VAR}" = 'a.b.c' ]
  2885. RUN [ "${SOME_VAR%.*}" = 'a.b' ]
  2886. RUN [ "${SOME_VAR%%.*}" = 'a' ]
  2887. RUN [ "${SOME_VAR#*.}" = 'b.c' ]
  2888. RUN [ "${SOME_VAR##*.}" = 'c' ]
  2889. RUN [ "${SOME_VAR/c/d}" = 'a.b.d' ]
  2890. RUN [ "${#SOME_VAR}" = '5' ]
  2891. RUN [ "${SOME_UNSET_VAR:-$SOME_VAR}" = 'a.b.c' ]
  2892. RUN [ "${SOME_VAR:+Version: ${SOME_VAR}}" = 'Version: a.b.c' ]
  2893. RUN [ "${SOME_UNSET_VAR:+${SOME_VAR}}" = '' ]
  2894. RUN [ "${SOME_UNSET_VAR:-${SOME_VAR:-d.e.f}}" = 'a.b.c' ]
  2895. `))
  2896. }
  2897. func (s *DockerSuite) TestBuildVerifySingleQuoteFails(c *testing.T) {
  2898. // This testcase is supposed to generate an error because the
  2899. // JSON array we're passing in on the CMD uses single quotes instead
  2900. // of double quotes (per the JSON spec). This means we interpret it
  2901. // as a "string" instead of "JSON array" and pass it on to "sh -c" and
  2902. // it should barf on it.
  2903. name := "testbuildsinglequotefails"
  2904. expectedExitCode := 2
  2905. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2906. CMD [ '/bin/sh', '-c', 'echo hi' ]`))
  2907. icmd.RunCommand(dockerBinary, "run", "--rm", name).Assert(c, icmd.Expected{
  2908. ExitCode: expectedExitCode,
  2909. })
  2910. }
  2911. func (s *DockerSuite) TestBuildVerboseOut(c *testing.T) {
  2912. name := "testbuildverboseout"
  2913. expected := "\n123\n"
  2914. if testEnv.OSType == "windows" {
  2915. expected = "\n123\r\n"
  2916. }
  2917. buildImage(name, build.WithDockerfile(`FROM busybox
  2918. RUN echo 123`)).Assert(c, icmd.Expected{
  2919. Out: expected,
  2920. })
  2921. }
  2922. func (s *DockerSuite) TestBuildWithTabs(c *testing.T) {
  2923. name := "testbuildwithtabs"
  2924. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nRUN echo\tone\t\ttwo"))
  2925. res := inspectFieldJSON(c, name, "ContainerConfig.Cmd")
  2926. expected1 := `["/bin/sh","-c","echo\tone\t\ttwo"]`
  2927. expected2 := `["/bin/sh","-c","echo\u0009one\u0009\u0009two"]` // syntactically equivalent, and what Go 1.3 generates
  2928. if testEnv.OSType == "windows" {
  2929. expected1 = `["cmd /S /C echo\tone\t\ttwo"]`
  2930. expected2 = `["cmd /S /C echo\u0009one\u0009\u0009two"]` // syntactically equivalent, and what Go 1.3 generates
  2931. }
  2932. if res != expected1 && res != expected2 {
  2933. c.Fatalf("Missing tabs.\nGot: %s\nExp: %s or %s", res, expected1, expected2)
  2934. }
  2935. }
  2936. func (s *DockerSuite) TestBuildLabels(c *testing.T) {
  2937. name := "testbuildlabel"
  2938. expected := `{"License":"GPL","Vendor":"Acme"}`
  2939. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2940. LABEL Vendor=Acme
  2941. LABEL License GPL`))
  2942. res := inspectFieldJSON(c, name, "Config.Labels")
  2943. if res != expected {
  2944. c.Fatalf("Labels %s, expected %s", res, expected)
  2945. }
  2946. }
  2947. func (s *DockerSuite) TestBuildLabelsCache(c *testing.T) {
  2948. name := "testbuildlabelcache"
  2949. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2950. LABEL Vendor=Acme`))
  2951. id1 := getIDByName(c, name)
  2952. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2953. LABEL Vendor=Acme`))
  2954. id2 := getIDByName(c, name)
  2955. if id1 != id2 {
  2956. c.Fatalf("Build 2 should have worked & used cache(%s,%s)", id1, id2)
  2957. }
  2958. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2959. LABEL Vendor=Acme1`))
  2960. id2 = getIDByName(c, name)
  2961. if id1 == id2 {
  2962. c.Fatalf("Build 3 should have worked & NOT used cache(%s,%s)", id1, id2)
  2963. }
  2964. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2965. LABEL Vendor Acme`))
  2966. id2 = getIDByName(c, name)
  2967. if id1 != id2 {
  2968. c.Fatalf("Build 4 should have worked & used cache(%s,%s)", id1, id2)
  2969. }
  2970. // Now make sure the cache isn't used by mistake
  2971. buildImageSuccessfully(c, name, build.WithoutCache, build.WithDockerfile(`FROM busybox
  2972. LABEL f1=b1 f2=b2`))
  2973. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2974. LABEL f1=b1 f2=b2`))
  2975. id2 = getIDByName(c, name)
  2976. if id1 == id2 {
  2977. c.Fatalf("Build 6 should have worked & NOT used the cache(%s,%s)", id1, id2)
  2978. }
  2979. }
  2980. // FIXME(vdemeester) port to docker/cli e2e tests (api tests should test suppressOutput option though)
  2981. func (s *DockerSuite) TestBuildNotVerboseSuccess(c *testing.T) {
  2982. // This test makes sure that -q works correctly when build is successful:
  2983. // stdout has only the image ID (long image ID) and stderr is empty.
  2984. outRegexp := regexp.MustCompile("^(sha256:|)[a-z0-9]{64}\\n$")
  2985. buildFlags := cli.WithFlags("-q")
  2986. tt := []struct {
  2987. Name string
  2988. BuildFunc func(string) *icmd.Result
  2989. }{
  2990. {
  2991. Name: "quiet_build_stdin_success",
  2992. BuildFunc: func(name string) *icmd.Result {
  2993. return buildImage(name, buildFlags, build.WithDockerfile("FROM busybox"))
  2994. },
  2995. },
  2996. {
  2997. Name: "quiet_build_ctx_success",
  2998. BuildFunc: func(name string) *icmd.Result {
  2999. return buildImage(name, buildFlags, build.WithBuildContext(c,
  3000. build.WithFile("Dockerfile", "FROM busybox"),
  3001. build.WithFile("quiet_build_success_fctx", "test"),
  3002. ))
  3003. },
  3004. },
  3005. {
  3006. Name: "quiet_build_git_success",
  3007. BuildFunc: func(name string) *icmd.Result {
  3008. git := fakegit.New(c, "repo", map[string]string{
  3009. "Dockerfile": "FROM busybox",
  3010. }, true)
  3011. return buildImage(name, buildFlags, build.WithContextPath(git.RepoURL))
  3012. },
  3013. },
  3014. }
  3015. for _, te := range tt {
  3016. result := te.BuildFunc(te.Name)
  3017. result.Assert(c, icmd.Success)
  3018. if outRegexp.Find([]byte(result.Stdout())) == nil {
  3019. c.Fatalf("Test %s expected stdout to match the [%v] regexp, but it is [%v]", te.Name, outRegexp, result.Stdout())
  3020. }
  3021. if result.Stderr() != "" {
  3022. c.Fatalf("Test %s expected stderr to be empty, but it is [%#v]", te.Name, result.Stderr())
  3023. }
  3024. }
  3025. }
  3026. // FIXME(vdemeester) migrate to docker/cli tests
  3027. func (s *DockerSuite) TestBuildNotVerboseFailureWithNonExistImage(c *testing.T) {
  3028. // This test makes sure that -q works correctly when build fails by
  3029. // comparing between the stderr output in quiet mode and in stdout
  3030. // and stderr output in verbose mode
  3031. testRequires(c, Network)
  3032. testName := "quiet_build_not_exists_image"
  3033. dockerfile := "FROM busybox11"
  3034. quietResult := buildImage(testName, cli.WithFlags("-q"), build.WithDockerfile(dockerfile))
  3035. quietResult.Assert(c, icmd.Expected{
  3036. ExitCode: 1,
  3037. })
  3038. result := buildImage(testName, build.WithDockerfile(dockerfile))
  3039. result.Assert(c, icmd.Expected{
  3040. ExitCode: 1,
  3041. })
  3042. if quietResult.Stderr() != result.Combined() {
  3043. c.Fatal(fmt.Errorf("Test[%s] expected that quiet stderr and verbose stdout are equal; quiet [%v], verbose [%v]", testName, quietResult.Stderr(), result.Combined()))
  3044. }
  3045. }
  3046. // FIXME(vdemeester) migrate to docker/cli tests
  3047. func (s *DockerSuite) TestBuildNotVerboseFailure(c *testing.T) {
  3048. // This test makes sure that -q works correctly when build fails by
  3049. // comparing between the stderr output in quiet mode and in stdout
  3050. // and stderr output in verbose mode
  3051. testCases := []struct {
  3052. testName string
  3053. dockerfile string
  3054. }{
  3055. {"quiet_build_no_from_at_the_beginning", "RUN whoami"},
  3056. {"quiet_build_unknown_instr", "FROMD busybox"},
  3057. }
  3058. for _, tc := range testCases {
  3059. quietResult := buildImage(tc.testName, cli.WithFlags("-q"), build.WithDockerfile(tc.dockerfile))
  3060. quietResult.Assert(c, icmd.Expected{
  3061. ExitCode: 1,
  3062. })
  3063. result := buildImage(tc.testName, build.WithDockerfile(tc.dockerfile))
  3064. result.Assert(c, icmd.Expected{
  3065. ExitCode: 1,
  3066. })
  3067. if quietResult.Stderr() != result.Combined() {
  3068. c.Fatal(fmt.Errorf("Test[%s] expected that quiet stderr and verbose stdout are equal; quiet [%v], verbose [%v]", tc.testName, quietResult.Stderr(), result.Combined()))
  3069. }
  3070. }
  3071. }
  3072. // FIXME(vdemeester) migrate to docker/cli tests
  3073. func (s *DockerSuite) TestBuildNotVerboseFailureRemote(c *testing.T) {
  3074. // This test ensures that when given a wrong URL, stderr in quiet mode and
  3075. // stderr in verbose mode are identical.
  3076. // TODO(vdemeester) with cobra, stdout has a carriage return too much so this test should not check stdout
  3077. URL := "http://something.invalid"
  3078. name := "quiet_build_wrong_remote"
  3079. quietResult := buildImage(name, cli.WithFlags("-q"), build.WithContextPath(URL))
  3080. quietResult.Assert(c, icmd.Expected{
  3081. ExitCode: 1,
  3082. })
  3083. result := buildImage(name, build.WithContextPath(URL))
  3084. result.Assert(c, icmd.Expected{
  3085. ExitCode: 1,
  3086. })
  3087. // An error message should contain name server IP and port, like this:
  3088. // "dial tcp: lookup something.invalid on 172.29.128.11:53: no such host"
  3089. // The IP:port need to be removed in order to not trigger a test failur
  3090. // when more than one nameserver is configured.
  3091. // While at it, also strip excessive newlines.
  3092. normalize := func(msg string) string {
  3093. return strings.TrimSpace(regexp.MustCompile("[1-9][0-9.]+:[0-9]+").ReplaceAllLiteralString(msg, "<ip:port>"))
  3094. }
  3095. if normalize(quietResult.Stderr()) != normalize(result.Combined()) {
  3096. c.Fatal(fmt.Errorf("Test[%s] expected that quiet stderr and verbose stdout are equal; quiet [%v], verbose [%v]", name, quietResult.Stderr(), result.Combined()))
  3097. }
  3098. }
  3099. // FIXME(vdemeester) migrate to docker/cli tests
  3100. func (s *DockerSuite) TestBuildStderr(c *testing.T) {
  3101. // This test just makes sure that no non-error output goes
  3102. // to stderr
  3103. name := "testbuildstderr"
  3104. result := buildImage(name, build.WithDockerfile("FROM busybox\nRUN echo one"))
  3105. result.Assert(c, icmd.Success)
  3106. // Windows to non-Windows should have a security warning
  3107. if runtime.GOOS == "windows" && testEnv.OSType != "windows" && !strings.Contains(result.Stdout(), "SECURITY WARNING:") {
  3108. c.Fatalf("Stdout contains unexpected output: %q", result.Stdout())
  3109. }
  3110. // Stderr should always be empty
  3111. if result.Stderr() != "" {
  3112. c.Fatalf("Stderr should have been empty, instead it's: %q", result.Stderr())
  3113. }
  3114. }
  3115. func (s *DockerSuite) TestBuildChownSingleFile(c *testing.T) {
  3116. testRequires(c, UnixCli, DaemonIsLinux) // test uses chown: not available on windows
  3117. name := "testbuildchownsinglefile"
  3118. ctx := fakecontext.New(c, "",
  3119. fakecontext.WithDockerfile(`
  3120. FROM busybox
  3121. COPY test /
  3122. RUN ls -l /test
  3123. RUN [ $(ls -l /test | awk '{print $3":"$4}') = 'root:root' ]
  3124. `),
  3125. fakecontext.WithFiles(map[string]string{
  3126. "test": "test",
  3127. }))
  3128. defer ctx.Close()
  3129. if err := os.Chown(filepath.Join(ctx.Dir, "test"), 4242, 4242); err != nil {
  3130. c.Fatal(err)
  3131. }
  3132. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  3133. }
  3134. func (s *DockerSuite) TestBuildSymlinkBreakout(c *testing.T) {
  3135. name := "testbuildsymlinkbreakout"
  3136. tmpdir, err := ioutil.TempDir("", name)
  3137. assert.NilError(c, err)
  3138. // See https://github.com/moby/moby/pull/37770 for reason for next line.
  3139. tmpdir, err = system.GetLongPathName(tmpdir)
  3140. assert.NilError(c, err)
  3141. defer os.RemoveAll(tmpdir)
  3142. ctx := filepath.Join(tmpdir, "context")
  3143. if err := os.MkdirAll(ctx, 0755); err != nil {
  3144. c.Fatal(err)
  3145. }
  3146. if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte(`
  3147. from busybox
  3148. add symlink.tar /
  3149. add inject /symlink/
  3150. `), 0644); err != nil {
  3151. c.Fatal(err)
  3152. }
  3153. inject := filepath.Join(ctx, "inject")
  3154. if err := ioutil.WriteFile(inject, nil, 0644); err != nil {
  3155. c.Fatal(err)
  3156. }
  3157. f, err := os.Create(filepath.Join(ctx, "symlink.tar"))
  3158. if err != nil {
  3159. c.Fatal(err)
  3160. }
  3161. w := tar.NewWriter(f)
  3162. w.WriteHeader(&tar.Header{
  3163. Name: "symlink2",
  3164. Typeflag: tar.TypeSymlink,
  3165. Linkname: "/../../../../../../../../../../../../../../",
  3166. Uid: os.Getuid(),
  3167. Gid: os.Getgid(),
  3168. })
  3169. w.WriteHeader(&tar.Header{
  3170. Name: "symlink",
  3171. Typeflag: tar.TypeSymlink,
  3172. Linkname: filepath.Join("symlink2", tmpdir),
  3173. Uid: os.Getuid(),
  3174. Gid: os.Getgid(),
  3175. })
  3176. w.Close()
  3177. f.Close()
  3178. buildImageSuccessfully(c, name, build.WithoutCache, build.WithExternalBuildContext(fakecontext.New(c, ctx)))
  3179. if _, err := os.Lstat(filepath.Join(tmpdir, "inject")); err == nil {
  3180. c.Fatal("symlink breakout - inject")
  3181. } else if !os.IsNotExist(err) {
  3182. c.Fatalf("unexpected error: %v", err)
  3183. }
  3184. }
  3185. func (s *DockerSuite) TestBuildXZHost(c *testing.T) {
  3186. // /usr/local/sbin/xz gets permission denied for the user
  3187. testRequires(c, NotUserNamespace)
  3188. testRequires(c, DaemonIsLinux)
  3189. name := "testbuildxzhost"
  3190. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  3191. build.WithFile("Dockerfile", `
  3192. FROM busybox
  3193. ADD xz /usr/local/sbin/
  3194. RUN chmod 755 /usr/local/sbin/xz
  3195. ADD test.xz /
  3196. RUN [ ! -e /injected ]`),
  3197. build.WithFile("test.xz", "\xfd\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00"+"\x21\x01\x16\x00\x00\x00\x74\x2f\xe5\xa3\x01\x00\x3f\xfd"+"\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00\x21"),
  3198. build.WithFile("xz", "#!/bin/sh\ntouch /injected"),
  3199. ))
  3200. }
  3201. func (s *DockerSuite) TestBuildVolumesRetainContents(c *testing.T) {
  3202. // /foo/file gets permission denied for the user
  3203. testRequires(c, NotUserNamespace)
  3204. testRequires(c, DaemonIsLinux) // TODO Windows: Issue #20127
  3205. var (
  3206. name = "testbuildvolumescontent"
  3207. expected = "some text"
  3208. volName = "/foo"
  3209. )
  3210. if testEnv.OSType == "windows" {
  3211. volName = "C:/foo"
  3212. }
  3213. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  3214. build.WithFile("Dockerfile", `
  3215. FROM busybox
  3216. COPY content /foo/file
  3217. VOLUME `+volName+`
  3218. CMD cat /foo/file`),
  3219. build.WithFile("content", expected),
  3220. ))
  3221. out, _ := dockerCmd(c, "run", "--rm", name)
  3222. if out != expected {
  3223. c.Fatalf("expected file contents for /foo/file to be %q but received %q", expected, out)
  3224. }
  3225. }
  3226. func (s *DockerSuite) TestBuildFromMixedcaseDockerfile(c *testing.T) {
  3227. testRequires(c, UnixCli) // Dockerfile overwrites dockerfile on windows
  3228. testRequires(c, DaemonIsLinux)
  3229. // If Dockerfile is not present, use dockerfile
  3230. buildImage("test1", build.WithBuildContext(c,
  3231. build.WithFile("dockerfile", `FROM busybox
  3232. RUN echo from dockerfile`),
  3233. )).Assert(c, icmd.Expected{
  3234. Out: "from dockerfile",
  3235. })
  3236. // Prefer Dockerfile in place of dockerfile
  3237. buildImage("test1", build.WithBuildContext(c,
  3238. build.WithFile("dockerfile", `FROM busybox
  3239. RUN echo from dockerfile`),
  3240. build.WithFile("Dockerfile", `FROM busybox
  3241. RUN echo from Dockerfile`),
  3242. )).Assert(c, icmd.Expected{
  3243. Out: "from Dockerfile",
  3244. })
  3245. }
  3246. // FIXME(vdemeester) should migrate to docker/cli tests
  3247. func (s *DockerSuite) TestBuildFromURLWithF(c *testing.T) {
  3248. server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{"baz": `FROM busybox
  3249. RUN echo from baz
  3250. COPY * /tmp/
  3251. RUN find /tmp/`}))
  3252. defer server.Close()
  3253. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(`FROM busybox
  3254. RUN echo from Dockerfile`))
  3255. defer ctx.Close()
  3256. // Make sure that -f is ignored and that we don't use the Dockerfile
  3257. // that's in the current dir
  3258. result := cli.BuildCmd(c, "test1", cli.WithFlags("-f", "baz", server.URL()+"/baz"), func(cmd *icmd.Cmd) func() {
  3259. cmd.Dir = ctx.Dir
  3260. return nil
  3261. })
  3262. if !strings.Contains(result.Combined(), "from baz") ||
  3263. strings.Contains(result.Combined(), "/tmp/baz") ||
  3264. !strings.Contains(result.Combined(), "/tmp/Dockerfile") {
  3265. c.Fatalf("Missing proper output: %s", result.Combined())
  3266. }
  3267. }
  3268. // FIXME(vdemeester) should migrate to docker/cli tests
  3269. func (s *DockerSuite) TestBuildFromStdinWithF(c *testing.T) {
  3270. testRequires(c, DaemonIsLinux) // TODO Windows: This test is flaky; no idea why
  3271. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(`FROM busybox
  3272. RUN echo "from Dockerfile"`))
  3273. defer ctx.Close()
  3274. // Make sure that -f is ignored and that we don't use the Dockerfile
  3275. // that's in the current dir
  3276. result := cli.BuildCmd(c, "test1", cli.WithFlags("-f", "baz", "-"), func(cmd *icmd.Cmd) func() {
  3277. cmd.Dir = ctx.Dir
  3278. cmd.Stdin = strings.NewReader(`FROM busybox
  3279. RUN echo "from baz"
  3280. COPY * /tmp/
  3281. RUN sh -c "find /tmp/" # sh -c is needed on Windows to use the correct find`)
  3282. return nil
  3283. })
  3284. if !strings.Contains(result.Combined(), "from baz") ||
  3285. strings.Contains(result.Combined(), "/tmp/baz") ||
  3286. !strings.Contains(result.Combined(), "/tmp/Dockerfile") {
  3287. c.Fatalf("Missing proper output: %s", result.Combined())
  3288. }
  3289. }
  3290. func (s *DockerSuite) TestBuildFromOfficialNames(c *testing.T) {
  3291. name := "testbuildfromofficial"
  3292. fromNames := []string{
  3293. "busybox",
  3294. "docker.io/busybox",
  3295. "index.docker.io/busybox",
  3296. "library/busybox",
  3297. "docker.io/library/busybox",
  3298. "index.docker.io/library/busybox",
  3299. }
  3300. for idx, fromName := range fromNames {
  3301. imgName := fmt.Sprintf("%s%d", name, idx)
  3302. buildImageSuccessfully(c, imgName, build.WithDockerfile("FROM "+fromName))
  3303. dockerCmd(c, "rmi", imgName)
  3304. }
  3305. }
  3306. // FIXME(vdemeester) should be a unit test
  3307. func (s *DockerSuite) TestBuildSpaces(c *testing.T) {
  3308. // Test to make sure that leading/trailing spaces on a command
  3309. // doesn't change the error msg we get
  3310. name := "testspaces"
  3311. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile("FROM busybox\nCOPY\n"))
  3312. defer ctx.Close()
  3313. result1 := cli.Docker(cli.Build(name), build.WithExternalBuildContext(ctx))
  3314. result1.Assert(c, icmd.Expected{
  3315. ExitCode: 1,
  3316. })
  3317. ctx.Add("Dockerfile", "FROM busybox\nCOPY ")
  3318. result2 := cli.Docker(cli.Build(name), build.WithExternalBuildContext(ctx))
  3319. result2.Assert(c, icmd.Expected{
  3320. ExitCode: 1,
  3321. })
  3322. removeLogTimestamps := func(s string) string {
  3323. return regexp.MustCompile(`time="(.*?)"`).ReplaceAllString(s, `time=[TIMESTAMP]`)
  3324. }
  3325. // Skip over the times
  3326. e1 := removeLogTimestamps(result1.Error.Error())
  3327. e2 := removeLogTimestamps(result2.Error.Error())
  3328. // Ignore whitespace since that's what were verifying doesn't change stuff
  3329. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  3330. c.Fatalf("Build 2's error wasn't the same as build 1's\n1:%s\n2:%s", result1.Error, result2.Error)
  3331. }
  3332. ctx.Add("Dockerfile", "FROM busybox\n COPY")
  3333. result2 = cli.Docker(cli.Build(name), build.WithoutCache, build.WithExternalBuildContext(ctx))
  3334. result2.Assert(c, icmd.Expected{
  3335. ExitCode: 1,
  3336. })
  3337. // Skip over the times
  3338. e1 = removeLogTimestamps(result1.Error.Error())
  3339. e2 = removeLogTimestamps(result2.Error.Error())
  3340. // Ignore whitespace since that's what were verifying doesn't change stuff
  3341. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  3342. c.Fatalf("Build 3's error wasn't the same as build 1's\n1:%s\n3:%s", result1.Error, result2.Error)
  3343. }
  3344. ctx.Add("Dockerfile", "FROM busybox\n COPY ")
  3345. result2 = cli.Docker(cli.Build(name), build.WithoutCache, build.WithExternalBuildContext(ctx))
  3346. result2.Assert(c, icmd.Expected{
  3347. ExitCode: 1,
  3348. })
  3349. // Skip over the times
  3350. e1 = removeLogTimestamps(result1.Error.Error())
  3351. e2 = removeLogTimestamps(result2.Error.Error())
  3352. // Ignore whitespace since that's what were verifying doesn't change stuff
  3353. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  3354. c.Fatalf("Build 4's error wasn't the same as build 1's\n1:%s\n4:%s", result1.Error, result2.Error)
  3355. }
  3356. }
  3357. func (s *DockerSuite) TestBuildSpacesWithQuotes(c *testing.T) {
  3358. // Test to make sure that spaces in quotes aren't lost
  3359. name := "testspacesquotes"
  3360. dockerfile := `FROM busybox
  3361. RUN echo " \
  3362. foo "`
  3363. expected := "\n foo \n"
  3364. // Windows uses the builtin echo, which preserves quotes
  3365. if testEnv.OSType == "windows" {
  3366. expected = "\" foo \""
  3367. }
  3368. buildImage(name, build.WithDockerfile(dockerfile)).Assert(c, icmd.Expected{
  3369. Out: expected,
  3370. })
  3371. }
  3372. // #4393
  3373. func (s *DockerSuite) TestBuildVolumeFileExistsinContainer(c *testing.T) {
  3374. testRequires(c, DaemonIsLinux) // TODO Windows: This should error out
  3375. buildImage("docker-test-errcreatevolumewithfile", build.WithDockerfile(`
  3376. FROM busybox
  3377. RUN touch /foo
  3378. VOLUME /foo
  3379. `)).Assert(c, icmd.Expected{
  3380. ExitCode: 1,
  3381. Err: "file exists",
  3382. })
  3383. }
  3384. // FIXME(vdemeester) should be a unit test
  3385. func (s *DockerSuite) TestBuildMissingArgs(c *testing.T) {
  3386. // Test to make sure that all Dockerfile commands (except the ones listed
  3387. // in skipCmds) will generate an error if no args are provided.
  3388. // Note: INSERT is deprecated so we exclude it because of that.
  3389. skipCmds := map[string]struct{}{
  3390. "CMD": {},
  3391. "RUN": {},
  3392. "ENTRYPOINT": {},
  3393. "INSERT": {},
  3394. }
  3395. if testEnv.OSType == "windows" {
  3396. skipCmds = map[string]struct{}{
  3397. "CMD": {},
  3398. "RUN": {},
  3399. "ENTRYPOINT": {},
  3400. "INSERT": {},
  3401. "STOPSIGNAL": {},
  3402. "ARG": {},
  3403. "USER": {},
  3404. "EXPOSE": {},
  3405. }
  3406. }
  3407. for cmd := range command.Commands {
  3408. cmd = strings.ToUpper(cmd)
  3409. if _, ok := skipCmds[cmd]; ok {
  3410. continue
  3411. }
  3412. var dockerfile string
  3413. if cmd == "FROM" {
  3414. dockerfile = cmd
  3415. } else {
  3416. // Add FROM to make sure we don't complain about it missing
  3417. dockerfile = "FROM busybox\n" + cmd
  3418. }
  3419. buildImage("args", build.WithDockerfile(dockerfile)).Assert(c, icmd.Expected{
  3420. ExitCode: 1,
  3421. Err: cmd + " requires",
  3422. })
  3423. }
  3424. }
  3425. func (s *DockerSuite) TestBuildEmptyScratch(c *testing.T) {
  3426. testRequires(c, DaemonIsLinux)
  3427. buildImage("sc", build.WithDockerfile("FROM scratch")).Assert(c, icmd.Expected{
  3428. ExitCode: 1,
  3429. Err: "No image was generated",
  3430. })
  3431. }
  3432. func (s *DockerSuite) TestBuildDotDotFile(c *testing.T) {
  3433. buildImageSuccessfully(c, "sc", build.WithBuildContext(c,
  3434. build.WithFile("Dockerfile", "FROM busybox\n"),
  3435. build.WithFile("..gitme", ""),
  3436. ))
  3437. }
  3438. func (s *DockerSuite) TestBuildRUNoneJSON(c *testing.T) {
  3439. testRequires(c, DaemonIsLinux) // No hello-world Windows image
  3440. name := "testbuildrunonejson"
  3441. buildImage(name, build.WithDockerfile(`FROM hello-world:frozen
  3442. RUN [ "/hello" ]`)).Assert(c, icmd.Expected{
  3443. Out: "Hello from Docker",
  3444. })
  3445. }
  3446. func (s *DockerSuite) TestBuildEmptyStringVolume(c *testing.T) {
  3447. name := "testbuildemptystringvolume"
  3448. buildImage(name, build.WithDockerfile(`
  3449. FROM busybox
  3450. ENV foo=""
  3451. VOLUME $foo
  3452. `)).Assert(c, icmd.Expected{
  3453. ExitCode: 1,
  3454. })
  3455. }
  3456. func (s *DockerSuite) TestBuildContainerWithCgroupParent(c *testing.T) {
  3457. testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
  3458. cgroupParent := "test"
  3459. data, err := ioutil.ReadFile("/proc/self/cgroup")
  3460. if err != nil {
  3461. c.Fatalf("failed to read '/proc/self/cgroup - %v", err)
  3462. }
  3463. selfCgroupPaths := ParseCgroupPaths(string(data))
  3464. _, found := selfCgroupPaths["memory"]
  3465. if !found {
  3466. c.Fatalf("unable to find self memory cgroup path. CgroupsPath: %v", selfCgroupPaths)
  3467. }
  3468. result := buildImage("buildcgroupparent",
  3469. cli.WithFlags("--cgroup-parent", cgroupParent),
  3470. build.WithDockerfile(`
  3471. FROM busybox
  3472. RUN cat /proc/self/cgroup
  3473. `))
  3474. result.Assert(c, icmd.Success)
  3475. m, err := regexp.MatchString(fmt.Sprintf("memory:.*/%s/.*", cgroupParent), result.Combined())
  3476. assert.NilError(c, err)
  3477. if !m {
  3478. c.Fatalf("There is no expected memory cgroup with parent /%s/: %s", cgroupParent, result.Combined())
  3479. }
  3480. }
  3481. // FIXME(vdemeester) could be a unit test
  3482. func (s *DockerSuite) TestBuildNoDupOutput(c *testing.T) {
  3483. // Check to make sure our build output prints the Dockerfile cmd
  3484. // property - there was a bug that caused it to be duplicated on the
  3485. // Step X line
  3486. name := "testbuildnodupoutput"
  3487. result := buildImage(name, build.WithDockerfile(`
  3488. FROM busybox
  3489. RUN env`))
  3490. result.Assert(c, icmd.Success)
  3491. exp := "\nStep 2/2 : RUN env\n"
  3492. if !strings.Contains(result.Combined(), exp) {
  3493. c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", result.Combined(), exp)
  3494. }
  3495. }
  3496. // GH15826
  3497. // FIXME(vdemeester) could be a unit test
  3498. func (s *DockerSuite) TestBuildStartsFromOne(c *testing.T) {
  3499. // Explicit check to ensure that build starts from step 1 rather than 0
  3500. name := "testbuildstartsfromone"
  3501. result := buildImage(name, build.WithDockerfile(`FROM busybox`))
  3502. result.Assert(c, icmd.Success)
  3503. exp := "\nStep 1/1 : FROM busybox\n"
  3504. if !strings.Contains(result.Combined(), exp) {
  3505. c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", result.Combined(), exp)
  3506. }
  3507. }
  3508. func (s *DockerSuite) TestBuildRUNErrMsg(c *testing.T) {
  3509. // Test to make sure the bad command is quoted with just "s and
  3510. // not as a Go []string
  3511. name := "testbuildbadrunerrmsg"
  3512. shell := "/bin/sh -c"
  3513. exitCode := 127
  3514. if testEnv.OSType == "windows" {
  3515. shell = "cmd /S /C"
  3516. // architectural - Windows has to start the container to determine the exe is bad, Linux does not
  3517. exitCode = 1
  3518. }
  3519. exp := fmt.Sprintf(`The command '%s badEXE a1 \& a2 a3' returned a non-zero code: %d`, shell, exitCode)
  3520. buildImage(name, build.WithDockerfile(`
  3521. FROM busybox
  3522. RUN badEXE a1 \& a2 a3`)).Assert(c, icmd.Expected{
  3523. ExitCode: exitCode,
  3524. Err: exp,
  3525. })
  3526. }
  3527. // Issue #15634: COPY fails when path starts with "null"
  3528. func (s *DockerSuite) TestBuildNullStringInAddCopyVolume(c *testing.T) {
  3529. name := "testbuildnullstringinaddcopyvolume"
  3530. volName := "nullvolume"
  3531. if testEnv.OSType == "windows" {
  3532. volName = `C:\\nullvolume`
  3533. }
  3534. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  3535. build.WithFile("Dockerfile", `
  3536. FROM busybox
  3537. ADD null /
  3538. COPY nullfile /
  3539. VOLUME `+volName+`
  3540. `),
  3541. build.WithFile("null", "test1"),
  3542. build.WithFile("nullfile", "test2"),
  3543. ))
  3544. }
  3545. func (s *DockerSuite) TestBuildStopSignal(c *testing.T) {
  3546. testRequires(c, DaemonIsLinux) // Windows does not support STOPSIGNAL yet
  3547. imgName := "test_build_stop_signal"
  3548. buildImageSuccessfully(c, imgName, build.WithDockerfile(`FROM busybox
  3549. STOPSIGNAL SIGKILL`))
  3550. res := inspectFieldJSON(c, imgName, "Config.StopSignal")
  3551. if res != `"SIGKILL"` {
  3552. c.Fatalf("Signal %s, expected SIGKILL", res)
  3553. }
  3554. containerName := "test-container-stop-signal"
  3555. dockerCmd(c, "run", "-d", "--name", containerName, imgName, "top")
  3556. res = inspectFieldJSON(c, containerName, "Config.StopSignal")
  3557. if res != `"SIGKILL"` {
  3558. c.Fatalf("Signal %s, expected SIGKILL", res)
  3559. }
  3560. }
  3561. func (s *DockerSuite) TestBuildBuildTimeArg(c *testing.T) {
  3562. imgName := "bldargtest"
  3563. envKey := "foo"
  3564. envVal := "bar"
  3565. var dockerfile string
  3566. if testEnv.OSType == "windows" {
  3567. // Bugs in Windows busybox port - use the default base image and native cmd stuff
  3568. dockerfile = fmt.Sprintf(`FROM `+minimalBaseImage()+`
  3569. ARG %s
  3570. RUN echo %%%s%%
  3571. CMD setlocal enableextensions && if defined %s (echo %%%s%%)`, envKey, envKey, envKey, envKey)
  3572. } else {
  3573. dockerfile = fmt.Sprintf(`FROM busybox
  3574. ARG %s
  3575. RUN echo $%s
  3576. CMD echo $%s`, envKey, envKey, envKey)
  3577. }
  3578. buildImage(imgName,
  3579. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3580. build.WithDockerfile(dockerfile),
  3581. ).Assert(c, icmd.Expected{
  3582. Out: envVal,
  3583. })
  3584. containerName := "bldargCont"
  3585. out, _ := dockerCmd(c, "run", "--name", containerName, imgName)
  3586. out = strings.Trim(out, " \r\n'")
  3587. if out != "" {
  3588. c.Fatalf("run produced invalid output: %q, expected empty string", out)
  3589. }
  3590. }
  3591. func (s *DockerSuite) TestBuildBuildTimeArgHistory(c *testing.T) {
  3592. imgName := "bldargtest"
  3593. envKey := "foo"
  3594. envVal := "bar"
  3595. envDef := "bar1"
  3596. dockerfile := fmt.Sprintf(`FROM busybox
  3597. ARG %s=%s`, envKey, envDef)
  3598. buildImage(imgName,
  3599. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3600. build.WithDockerfile(dockerfile),
  3601. ).Assert(c, icmd.Expected{
  3602. Out: envVal,
  3603. })
  3604. out, _ := dockerCmd(c, "history", "--no-trunc", imgName)
  3605. outputTabs := strings.Split(out, "\n")[1]
  3606. if !strings.Contains(outputTabs, envDef) {
  3607. c.Fatalf("failed to find arg default in image history output: %q expected: %q", outputTabs, envDef)
  3608. }
  3609. }
  3610. func (s *DockerSuite) TestBuildTimeArgHistoryExclusions(c *testing.T) {
  3611. imgName := "bldargtest"
  3612. envKey := "foo"
  3613. envVal := "bar"
  3614. proxy := "HTTP_PROXY=http://user:password@proxy.example.com"
  3615. explicitProxyKey := "http_proxy"
  3616. explicitProxyVal := "http://user:password@someproxy.example.com"
  3617. dockerfile := fmt.Sprintf(`FROM busybox
  3618. ARG %s
  3619. ARG %s
  3620. RUN echo "Testing Build Args!"`, envKey, explicitProxyKey)
  3621. buildImage := func(imgName string) string {
  3622. cli.BuildCmd(c, imgName,
  3623. cli.WithFlags("--build-arg", "https_proxy=https://proxy.example.com",
  3624. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  3625. "--build-arg", fmt.Sprintf("%s=%s", explicitProxyKey, explicitProxyVal),
  3626. "--build-arg", proxy),
  3627. build.WithDockerfile(dockerfile),
  3628. )
  3629. return getIDByName(c, imgName)
  3630. }
  3631. origID := buildImage(imgName)
  3632. result := cli.DockerCmd(c, "history", "--no-trunc", imgName)
  3633. out := result.Stdout()
  3634. if strings.Contains(out, proxy) {
  3635. c.Fatalf("failed to exclude proxy settings from history!")
  3636. }
  3637. if strings.Contains(out, "https_proxy") {
  3638. c.Fatalf("failed to exclude proxy settings from history!")
  3639. }
  3640. result.Assert(c, icmd.Expected{Out: fmt.Sprintf("%s=%s", envKey, envVal)})
  3641. result.Assert(c, icmd.Expected{Out: fmt.Sprintf("%s=%s", explicitProxyKey, explicitProxyVal)})
  3642. cacheID := buildImage(imgName + "-two")
  3643. assert.Equal(c, origID, cacheID)
  3644. }
  3645. func (s *DockerSuite) TestBuildBuildTimeArgCacheHit(c *testing.T) {
  3646. imgName := "bldargtest"
  3647. envKey := "foo"
  3648. envVal := "bar"
  3649. dockerfile := fmt.Sprintf(`FROM busybox
  3650. ARG %s
  3651. RUN echo $%s`, envKey, envKey)
  3652. buildImageSuccessfully(c, imgName,
  3653. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3654. build.WithDockerfile(dockerfile),
  3655. )
  3656. origImgID := getIDByName(c, imgName)
  3657. imgNameCache := "bldargtestcachehit"
  3658. buildImageSuccessfully(c, imgNameCache,
  3659. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3660. build.WithDockerfile(dockerfile),
  3661. )
  3662. newImgID := getIDByName(c, imgName)
  3663. if newImgID != origImgID {
  3664. c.Fatalf("build didn't use cache! expected image id: %q built image id: %q", origImgID, newImgID)
  3665. }
  3666. }
  3667. func (s *DockerSuite) TestBuildBuildTimeArgCacheMissExtraArg(c *testing.T) {
  3668. imgName := "bldargtest"
  3669. envKey := "foo"
  3670. envVal := "bar"
  3671. extraEnvKey := "foo1"
  3672. extraEnvVal := "bar1"
  3673. dockerfile := fmt.Sprintf(`FROM busybox
  3674. ARG %s
  3675. ARG %s
  3676. RUN echo $%s`, envKey, extraEnvKey, envKey)
  3677. buildImageSuccessfully(c, imgName,
  3678. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3679. build.WithDockerfile(dockerfile),
  3680. )
  3681. origImgID := getIDByName(c, imgName)
  3682. imgNameCache := "bldargtestcachemiss"
  3683. buildImageSuccessfully(c, imgNameCache,
  3684. cli.WithFlags(
  3685. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  3686. "--build-arg", fmt.Sprintf("%s=%s", extraEnvKey, extraEnvVal),
  3687. ),
  3688. build.WithDockerfile(dockerfile),
  3689. )
  3690. newImgID := getIDByName(c, imgNameCache)
  3691. if newImgID == origImgID {
  3692. c.Fatalf("build used cache, expected a miss!")
  3693. }
  3694. }
  3695. func (s *DockerSuite) TestBuildBuildTimeArgCacheMissSameArgDiffVal(c *testing.T) {
  3696. imgName := "bldargtest"
  3697. envKey := "foo"
  3698. envVal := "bar"
  3699. newEnvVal := "bar1"
  3700. dockerfile := fmt.Sprintf(`FROM busybox
  3701. ARG %s
  3702. RUN echo $%s`, envKey, envKey)
  3703. buildImageSuccessfully(c, imgName,
  3704. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3705. build.WithDockerfile(dockerfile),
  3706. )
  3707. origImgID := getIDByName(c, imgName)
  3708. imgNameCache := "bldargtestcachemiss"
  3709. buildImageSuccessfully(c, imgNameCache,
  3710. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, newEnvVal)),
  3711. build.WithDockerfile(dockerfile),
  3712. )
  3713. newImgID := getIDByName(c, imgNameCache)
  3714. if newImgID == origImgID {
  3715. c.Fatalf("build used cache, expected a miss!")
  3716. }
  3717. }
  3718. func (s *DockerSuite) TestBuildBuildTimeArgOverrideArgDefinedBeforeEnv(c *testing.T) {
  3719. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3720. imgName := "bldargtest"
  3721. envKey := "foo"
  3722. envVal := "bar"
  3723. envValOverride := "barOverride"
  3724. dockerfile := fmt.Sprintf(`FROM busybox
  3725. ARG %s
  3726. ENV %s %s
  3727. RUN echo $%s
  3728. CMD echo $%s
  3729. `, envKey, envKey, envValOverride, envKey, envKey)
  3730. result := buildImage(imgName,
  3731. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3732. build.WithDockerfile(dockerfile),
  3733. )
  3734. result.Assert(c, icmd.Success)
  3735. if strings.Count(result.Combined(), envValOverride) != 2 {
  3736. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envValOverride)
  3737. }
  3738. containerName := "bldargCont"
  3739. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOverride) {
  3740. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOverride)
  3741. }
  3742. }
  3743. // FIXME(vdemeester) might be useful to merge with the one above ?
  3744. func (s *DockerSuite) TestBuildBuildTimeArgOverrideEnvDefinedBeforeArg(c *testing.T) {
  3745. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3746. imgName := "bldargtest"
  3747. envKey := "foo"
  3748. envVal := "bar"
  3749. envValOverride := "barOverride"
  3750. dockerfile := fmt.Sprintf(`FROM busybox
  3751. ENV %s %s
  3752. ARG %s
  3753. RUN echo $%s
  3754. CMD echo $%s
  3755. `, envKey, envValOverride, envKey, envKey, envKey)
  3756. result := buildImage(imgName,
  3757. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3758. build.WithDockerfile(dockerfile),
  3759. )
  3760. result.Assert(c, icmd.Success)
  3761. if strings.Count(result.Combined(), envValOverride) != 2 {
  3762. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envValOverride)
  3763. }
  3764. containerName := "bldargCont"
  3765. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOverride) {
  3766. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOverride)
  3767. }
  3768. }
  3769. func (s *DockerSuite) TestBuildBuildTimeArgExpansion(c *testing.T) {
  3770. imgName := "bldvarstest"
  3771. wdVar := "WDIR"
  3772. wdVal := "/tmp/"
  3773. addVar := "AFILE"
  3774. addVal := "addFile"
  3775. copyVar := "CFILE"
  3776. copyVal := "copyFile"
  3777. envVar := "foo"
  3778. envVal := "bar"
  3779. exposeVar := "EPORT"
  3780. exposeVal := "9999"
  3781. userVar := "USER"
  3782. userVal := "testUser"
  3783. volVar := "VOL"
  3784. volVal := "/testVol/"
  3785. if DaemonIsWindows() {
  3786. volVal = "C:\\testVol"
  3787. wdVal = "C:\\tmp"
  3788. }
  3789. buildImageSuccessfully(c, imgName,
  3790. cli.WithFlags(
  3791. "--build-arg", fmt.Sprintf("%s=%s", wdVar, wdVal),
  3792. "--build-arg", fmt.Sprintf("%s=%s", addVar, addVal),
  3793. "--build-arg", fmt.Sprintf("%s=%s", copyVar, copyVal),
  3794. "--build-arg", fmt.Sprintf("%s=%s", envVar, envVal),
  3795. "--build-arg", fmt.Sprintf("%s=%s", exposeVar, exposeVal),
  3796. "--build-arg", fmt.Sprintf("%s=%s", userVar, userVal),
  3797. "--build-arg", fmt.Sprintf("%s=%s", volVar, volVal),
  3798. ),
  3799. build.WithBuildContext(c,
  3800. build.WithFile("Dockerfile", fmt.Sprintf(`FROM busybox
  3801. ARG %s
  3802. WORKDIR ${%s}
  3803. ARG %s
  3804. ADD ${%s} testDir/
  3805. ARG %s
  3806. COPY $%s testDir/
  3807. ARG %s
  3808. ENV %s=${%s}
  3809. ARG %s
  3810. EXPOSE $%s
  3811. ARG %s
  3812. USER $%s
  3813. ARG %s
  3814. VOLUME ${%s}`,
  3815. wdVar, wdVar, addVar, addVar, copyVar, copyVar, envVar, envVar,
  3816. envVar, exposeVar, exposeVar, userVar, userVar, volVar, volVar)),
  3817. build.WithFile(addVal, "some stuff"),
  3818. build.WithFile(copyVal, "some stuff"),
  3819. ),
  3820. )
  3821. res := inspectField(c, imgName, "Config.WorkingDir")
  3822. assert.Equal(c, filepath.ToSlash(res), filepath.ToSlash(wdVal))
  3823. var resArr []string
  3824. inspectFieldAndUnmarshall(c, imgName, "Config.Env", &resArr)
  3825. found := false
  3826. for _, v := range resArr {
  3827. if fmt.Sprintf("%s=%s", envVar, envVal) == v {
  3828. found = true
  3829. break
  3830. }
  3831. }
  3832. if !found {
  3833. c.Fatalf("Config.Env value mismatch. Expected <key=value> to exist: %s=%s, got: %v",
  3834. envVar, envVal, resArr)
  3835. }
  3836. var resMap map[string]interface{}
  3837. inspectFieldAndUnmarshall(c, imgName, "Config.ExposedPorts", &resMap)
  3838. if _, ok := resMap[fmt.Sprintf("%s/tcp", exposeVal)]; !ok {
  3839. c.Fatalf("Config.ExposedPorts value mismatch. Expected exposed port: %s/tcp, got: %v", exposeVal, resMap)
  3840. }
  3841. res = inspectField(c, imgName, "Config.User")
  3842. if res != userVal {
  3843. c.Fatalf("Config.User value mismatch. Expected: %s, got: %s", userVal, res)
  3844. }
  3845. inspectFieldAndUnmarshall(c, imgName, "Config.Volumes", &resMap)
  3846. if _, ok := resMap[volVal]; !ok {
  3847. c.Fatalf("Config.Volumes value mismatch. Expected volume: %s, got: %v", volVal, resMap)
  3848. }
  3849. }
  3850. func (s *DockerSuite) TestBuildBuildTimeArgExpansionOverride(c *testing.T) {
  3851. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3852. imgName := "bldvarstest"
  3853. envKey := "foo"
  3854. envVal := "bar"
  3855. envKey1 := "foo1"
  3856. envValOverride := "barOverride"
  3857. dockerfile := fmt.Sprintf(`FROM busybox
  3858. ARG %s
  3859. ENV %s %s
  3860. ENV %s ${%s}
  3861. RUN echo $%s
  3862. CMD echo $%s`, envKey, envKey, envValOverride, envKey1, envKey, envKey1, envKey1)
  3863. result := buildImage(imgName,
  3864. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3865. build.WithDockerfile(dockerfile),
  3866. )
  3867. result.Assert(c, icmd.Success)
  3868. if strings.Count(result.Combined(), envValOverride) != 2 {
  3869. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envValOverride)
  3870. }
  3871. containerName := "bldargCont"
  3872. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOverride) {
  3873. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOverride)
  3874. }
  3875. }
  3876. func (s *DockerSuite) TestBuildBuildTimeArgUntrustedDefinedAfterUse(c *testing.T) {
  3877. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3878. imgName := "bldargtest"
  3879. envKey := "foo"
  3880. envVal := "bar"
  3881. dockerfile := fmt.Sprintf(`FROM busybox
  3882. RUN echo $%s
  3883. ARG %s
  3884. CMD echo $%s`, envKey, envKey, envKey)
  3885. result := buildImage(imgName,
  3886. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3887. build.WithDockerfile(dockerfile),
  3888. )
  3889. result.Assert(c, icmd.Success)
  3890. if strings.Contains(result.Combined(), envVal) {
  3891. c.Fatalf("able to access environment variable in output: %q expected to be missing", result.Combined())
  3892. }
  3893. containerName := "bldargCont"
  3894. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); out != "\n" {
  3895. c.Fatalf("run produced invalid output: %q, expected empty string", out)
  3896. }
  3897. }
  3898. func (s *DockerSuite) TestBuildBuildTimeArgBuiltinArg(c *testing.T) {
  3899. testRequires(c, DaemonIsLinux) // Windows does not support --build-arg
  3900. imgName := "bldargtest"
  3901. envKey := "HTTP_PROXY"
  3902. envVal := "bar"
  3903. dockerfile := fmt.Sprintf(`FROM busybox
  3904. RUN echo $%s
  3905. CMD echo $%s`, envKey, envKey)
  3906. result := buildImage(imgName,
  3907. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3908. build.WithDockerfile(dockerfile),
  3909. )
  3910. result.Assert(c, icmd.Success)
  3911. if !strings.Contains(result.Combined(), envVal) {
  3912. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envVal)
  3913. }
  3914. containerName := "bldargCont"
  3915. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); out != "\n" {
  3916. c.Fatalf("run produced invalid output: %q, expected empty string", out)
  3917. }
  3918. }
  3919. func (s *DockerSuite) TestBuildBuildTimeArgDefaultOverride(c *testing.T) {
  3920. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3921. imgName := "bldargtest"
  3922. envKey := "foo"
  3923. envVal := "bar"
  3924. envValOverride := "barOverride"
  3925. dockerfile := fmt.Sprintf(`FROM busybox
  3926. ARG %s=%s
  3927. ENV %s $%s
  3928. RUN echo $%s
  3929. CMD echo $%s`, envKey, envVal, envKey, envKey, envKey, envKey)
  3930. result := buildImage(imgName,
  3931. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envValOverride)),
  3932. build.WithDockerfile(dockerfile),
  3933. )
  3934. result.Assert(c, icmd.Success)
  3935. if strings.Count(result.Combined(), envValOverride) != 1 {
  3936. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envValOverride)
  3937. }
  3938. containerName := "bldargCont"
  3939. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOverride) {
  3940. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOverride)
  3941. }
  3942. }
  3943. func (s *DockerSuite) TestBuildBuildTimeArgUnconsumedArg(c *testing.T) {
  3944. imgName := "bldargtest"
  3945. envKey := "foo"
  3946. envVal := "bar"
  3947. dockerfile := fmt.Sprintf(`FROM busybox
  3948. RUN echo $%s
  3949. CMD echo $%s`, envKey, envKey)
  3950. warnStr := "[Warning] One or more build-args"
  3951. buildImage(imgName,
  3952. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3953. build.WithDockerfile(dockerfile),
  3954. ).Assert(c, icmd.Expected{
  3955. Out: warnStr,
  3956. })
  3957. }
  3958. func (s *DockerSuite) TestBuildBuildTimeArgEnv(c *testing.T) {
  3959. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3960. dockerfile := `FROM busybox
  3961. ARG FOO1=fromfile
  3962. ARG FOO2=fromfile
  3963. ARG FOO3=fromfile
  3964. ARG FOO4=fromfile
  3965. ARG FOO5
  3966. ARG FOO6
  3967. ARG FO10
  3968. RUN env
  3969. RUN [ "$FOO1" = "fromcmd" ]
  3970. RUN [ "$FOO2" = "" ]
  3971. RUN [ "$FOO3" = "fromenv" ]
  3972. RUN [ "$FOO4" = "fromfile" ]
  3973. RUN [ "$FOO5" = "fromcmd" ]
  3974. # The following should not exist at all in the env
  3975. RUN [ "$(env | grep FOO6)" = "" ]
  3976. RUN [ "$(env | grep FOO7)" = "" ]
  3977. RUN [ "$(env | grep FOO8)" = "" ]
  3978. RUN [ "$(env | grep FOO9)" = "" ]
  3979. RUN [ "$FO10" = "" ]
  3980. `
  3981. result := buildImage("testbuildtimeargenv",
  3982. cli.WithFlags(
  3983. "--build-arg", fmt.Sprintf("FOO1=fromcmd"),
  3984. "--build-arg", fmt.Sprintf("FOO2="),
  3985. "--build-arg", fmt.Sprintf("FOO3"), // set in env
  3986. "--build-arg", fmt.Sprintf("FOO4"), // not set in env
  3987. "--build-arg", fmt.Sprintf("FOO5=fromcmd"),
  3988. // FOO6 is not set at all
  3989. "--build-arg", fmt.Sprintf("FOO7=fromcmd"), // should produce a warning
  3990. "--build-arg", fmt.Sprintf("FOO8="), // should produce a warning
  3991. "--build-arg", fmt.Sprintf("FOO9"), // should produce a warning
  3992. "--build-arg", fmt.Sprintf("FO10"), // not set in env, empty value
  3993. ),
  3994. cli.WithEnvironmentVariables(append(os.Environ(),
  3995. "FOO1=fromenv",
  3996. "FOO2=fromenv",
  3997. "FOO3=fromenv")...),
  3998. build.WithBuildContext(c,
  3999. build.WithFile("Dockerfile", dockerfile),
  4000. ),
  4001. )
  4002. result.Assert(c, icmd.Success)
  4003. // Now check to make sure we got a warning msg about unused build-args
  4004. i := strings.Index(result.Combined(), "[Warning]")
  4005. if i < 0 {
  4006. c.Fatalf("Missing the build-arg warning in %q", result.Combined())
  4007. }
  4008. out := result.Combined()[i:] // "out" should contain just the warning message now
  4009. // These were specified on a --build-arg but no ARG was in the Dockerfile
  4010. assert.Assert(c, strings.Contains(out, "FOO7"))
  4011. assert.Assert(c, strings.Contains(out, "FOO8"))
  4012. assert.Assert(c, strings.Contains(out, "FOO9"))
  4013. }
  4014. func (s *DockerSuite) TestBuildBuildTimeArgQuotedValVariants(c *testing.T) {
  4015. imgName := "bldargtest"
  4016. envKey := "foo"
  4017. envKey1 := "foo1"
  4018. envKey2 := "foo2"
  4019. envKey3 := "foo3"
  4020. dockerfile := fmt.Sprintf(`FROM busybox
  4021. ARG %s=""
  4022. ARG %s=''
  4023. ARG %s="''"
  4024. ARG %s='""'
  4025. RUN [ "$%s" != "$%s" ]
  4026. RUN [ "$%s" != "$%s" ]
  4027. RUN [ "$%s" != "$%s" ]
  4028. RUN [ "$%s" != "$%s" ]
  4029. RUN [ "$%s" != "$%s" ]`, envKey, envKey1, envKey2, envKey3,
  4030. envKey, envKey2, envKey, envKey3, envKey1, envKey2, envKey1, envKey3,
  4031. envKey2, envKey3)
  4032. buildImageSuccessfully(c, imgName, build.WithDockerfile(dockerfile))
  4033. }
  4034. func (s *DockerSuite) TestBuildBuildTimeArgEmptyValVariants(c *testing.T) {
  4035. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  4036. imgName := "bldargtest"
  4037. envKey := "foo"
  4038. envKey1 := "foo1"
  4039. envKey2 := "foo2"
  4040. dockerfile := fmt.Sprintf(`FROM busybox
  4041. ARG %s=
  4042. ARG %s=""
  4043. ARG %s=''
  4044. RUN [ "$%s" = "$%s" ]
  4045. RUN [ "$%s" = "$%s" ]
  4046. RUN [ "$%s" = "$%s" ]`, envKey, envKey1, envKey2, envKey, envKey1, envKey1, envKey2, envKey, envKey2)
  4047. buildImageSuccessfully(c, imgName, build.WithDockerfile(dockerfile))
  4048. }
  4049. func (s *DockerSuite) TestBuildBuildTimeArgDefinitionWithNoEnvInjection(c *testing.T) {
  4050. imgName := "bldargtest"
  4051. envKey := "foo"
  4052. dockerfile := fmt.Sprintf(`FROM busybox
  4053. ARG %s
  4054. RUN env`, envKey)
  4055. result := cli.BuildCmd(c, imgName, build.WithDockerfile(dockerfile))
  4056. result.Assert(c, icmd.Success)
  4057. if strings.Count(result.Combined(), envKey) != 1 {
  4058. c.Fatalf("unexpected number of occurrences of the arg in output: %q expected: 1", result.Combined())
  4059. }
  4060. }
  4061. func (s *DockerSuite) TestBuildMultiStageArg(c *testing.T) {
  4062. imgName := "multifrombldargtest"
  4063. dockerfile := `FROM busybox
  4064. ARG foo=abc
  4065. LABEL multifromtest=1
  4066. RUN env > /out
  4067. FROM busybox
  4068. ARG bar=def
  4069. RUN env > /out`
  4070. result := cli.BuildCmd(c, imgName, build.WithDockerfile(dockerfile))
  4071. result.Assert(c, icmd.Success)
  4072. result = cli.DockerCmd(c, "images", "-q", "-f", "label=multifromtest=1")
  4073. parentID := strings.TrimSpace(result.Stdout())
  4074. result = cli.DockerCmd(c, "run", "--rm", parentID, "cat", "/out")
  4075. assert.Assert(c, strings.Contains(result.Stdout(), "foo=abc"))
  4076. result = cli.DockerCmd(c, "run", "--rm", imgName, "cat", "/out")
  4077. assert.Assert(c, !strings.Contains(result.Stdout(), "foo"))
  4078. assert.Assert(c, strings.Contains(result.Stdout(), "bar=def"))
  4079. }
  4080. func (s *DockerSuite) TestBuildMultiStageGlobalArg(c *testing.T) {
  4081. imgName := "multifrombldargtest"
  4082. dockerfile := `ARG tag=nosuchtag
  4083. FROM busybox:${tag}
  4084. LABEL multifromtest=1
  4085. RUN env > /out
  4086. FROM busybox:${tag}
  4087. ARG tag
  4088. RUN env > /out`
  4089. result := cli.BuildCmd(c, imgName,
  4090. build.WithDockerfile(dockerfile),
  4091. cli.WithFlags("--build-arg", fmt.Sprintf("tag=latest")))
  4092. result.Assert(c, icmd.Success)
  4093. result = cli.DockerCmd(c, "images", "-q", "-f", "label=multifromtest=1")
  4094. parentID := strings.TrimSpace(result.Stdout())
  4095. result = cli.DockerCmd(c, "run", "--rm", parentID, "cat", "/out")
  4096. assert.Assert(c, !strings.Contains(result.Stdout(), "tag"))
  4097. result = cli.DockerCmd(c, "run", "--rm", imgName, "cat", "/out")
  4098. assert.Assert(c, strings.Contains(result.Stdout(), "tag=latest"))
  4099. }
  4100. func (s *DockerSuite) TestBuildMultiStageUnusedArg(c *testing.T) {
  4101. imgName := "multifromunusedarg"
  4102. dockerfile := `FROM busybox
  4103. ARG foo
  4104. FROM busybox
  4105. ARG bar
  4106. RUN env > /out`
  4107. result := cli.BuildCmd(c, imgName,
  4108. build.WithDockerfile(dockerfile),
  4109. cli.WithFlags("--build-arg", fmt.Sprintf("baz=abc")))
  4110. result.Assert(c, icmd.Success)
  4111. assert.Assert(c, strings.Contains(result.Combined(), "[Warning]"))
  4112. assert.Assert(c, strings.Contains(result.Combined(), "[baz] were not consumed"))
  4113. result = cli.DockerCmd(c, "run", "--rm", imgName, "cat", "/out")
  4114. assert.Assert(c, !strings.Contains(result.Stdout(), "bar"))
  4115. assert.Assert(c, !strings.Contains(result.Stdout(), "baz"))
  4116. }
  4117. func (s *DockerSuite) TestBuildNoNamedVolume(c *testing.T) {
  4118. volName := "testname:/foo"
  4119. if testEnv.OSType == "windows" {
  4120. volName = "testname:C:\\foo"
  4121. }
  4122. dockerCmd(c, "run", "-v", volName, "busybox", "sh", "-c", "touch /foo/oops")
  4123. dockerFile := `FROM busybox
  4124. VOLUME ` + volName + `
  4125. RUN ls /foo/oops
  4126. `
  4127. buildImage("test", build.WithDockerfile(dockerFile)).Assert(c, icmd.Expected{
  4128. ExitCode: 1,
  4129. })
  4130. }
  4131. func (s *DockerSuite) TestBuildTagEvent(c *testing.T) {
  4132. since := daemonUnixTime(c)
  4133. dockerFile := `FROM busybox
  4134. RUN echo events
  4135. `
  4136. buildImageSuccessfully(c, "test", build.WithDockerfile(dockerFile))
  4137. until := daemonUnixTime(c)
  4138. out, _ := dockerCmd(c, "events", "--since", since, "--until", until, "--filter", "type=image")
  4139. events := strings.Split(strings.TrimSpace(out), "\n")
  4140. actions := eventActionsByIDAndType(c, events, "test:latest", "image")
  4141. var foundTag bool
  4142. for _, a := range actions {
  4143. if a == "tag" {
  4144. foundTag = true
  4145. break
  4146. }
  4147. }
  4148. assert.Assert(c, foundTag, fmt.Sprintf("No tag event found:\n%s", out))
  4149. }
  4150. // #15780
  4151. func (s *DockerSuite) TestBuildMultipleTags(c *testing.T) {
  4152. dockerfile := `
  4153. FROM busybox
  4154. MAINTAINER test-15780
  4155. `
  4156. buildImageSuccessfully(c, "tag1", cli.WithFlags("-t", "tag2:v2", "-t", "tag1:latest", "-t", "tag1"), build.WithDockerfile(dockerfile))
  4157. id1 := getIDByName(c, "tag1")
  4158. id2 := getIDByName(c, "tag2:v2")
  4159. assert.Equal(c, id1, id2)
  4160. }
  4161. // #17290
  4162. func (s *DockerSuite) TestBuildCacheBrokenSymlink(c *testing.T) {
  4163. name := "testbuildbrokensymlink"
  4164. ctx := fakecontext.New(c, "",
  4165. fakecontext.WithDockerfile(`
  4166. FROM busybox
  4167. COPY . ./`),
  4168. fakecontext.WithFiles(map[string]string{
  4169. "foo": "bar",
  4170. }))
  4171. defer ctx.Close()
  4172. err := os.Symlink(filepath.Join(ctx.Dir, "nosuchfile"), filepath.Join(ctx.Dir, "asymlink"))
  4173. assert.NilError(c, err)
  4174. // warm up cache
  4175. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4176. // add new file to context, should invalidate cache
  4177. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "newfile"), []byte("foo"), 0644)
  4178. assert.NilError(c, err)
  4179. result := cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4180. if strings.Contains(result.Combined(), "Using cache") {
  4181. c.Fatal("2nd build used cache on ADD, it shouldn't")
  4182. }
  4183. }
  4184. func (s *DockerSuite) TestBuildFollowSymlinkToFile(c *testing.T) {
  4185. name := "testbuildbrokensymlink"
  4186. ctx := fakecontext.New(c, "",
  4187. fakecontext.WithDockerfile(`
  4188. FROM busybox
  4189. COPY asymlink target`),
  4190. fakecontext.WithFiles(map[string]string{
  4191. "foo": "bar",
  4192. }))
  4193. defer ctx.Close()
  4194. err := os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink"))
  4195. assert.NilError(c, err)
  4196. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4197. out := cli.DockerCmd(c, "run", "--rm", name, "cat", "target").Combined()
  4198. assert.Assert(c, cmp.Regexp("^"+
  4199. "bar"+
  4200. "$",
  4201. out))
  4202. // change target file should invalidate cache
  4203. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "foo"), []byte("baz"), 0644)
  4204. assert.NilError(c, err)
  4205. result := cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4206. assert.Assert(c, !strings.Contains(result.Combined(), "Using cache"))
  4207. out = cli.DockerCmd(c, "run", "--rm", name, "cat", "target").Combined()
  4208. assert.Assert(c, cmp.Regexp("^"+
  4209. "baz"+
  4210. "$",
  4211. out))
  4212. }
  4213. func (s *DockerSuite) TestBuildFollowSymlinkToDir(c *testing.T) {
  4214. name := "testbuildbrokensymlink"
  4215. ctx := fakecontext.New(c, "",
  4216. fakecontext.WithDockerfile(`
  4217. FROM busybox
  4218. COPY asymlink /`),
  4219. fakecontext.WithFiles(map[string]string{
  4220. "foo/abc": "bar",
  4221. "foo/def": "baz",
  4222. }))
  4223. defer ctx.Close()
  4224. err := os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink"))
  4225. assert.NilError(c, err)
  4226. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4227. out := cli.DockerCmd(c, "run", "--rm", name, "cat", "abc", "def").Combined()
  4228. assert.Assert(c, cmp.Regexp("^"+
  4229. "barbaz"+
  4230. "$",
  4231. out))
  4232. // change target file should invalidate cache
  4233. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "foo/def"), []byte("bax"), 0644)
  4234. assert.NilError(c, err)
  4235. result := cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4236. assert.Assert(c, !strings.Contains(result.Combined(), "Using cache"))
  4237. out = cli.DockerCmd(c, "run", "--rm", name, "cat", "abc", "def").Combined()
  4238. assert.Assert(c, cmp.Regexp("^"+
  4239. "barbax"+
  4240. "$",
  4241. out))
  4242. }
  4243. // TestBuildSymlinkBasename tests that target file gets basename from symlink,
  4244. // not from the target file.
  4245. func (s *DockerSuite) TestBuildSymlinkBasename(c *testing.T) {
  4246. name := "testbuildbrokensymlink"
  4247. ctx := fakecontext.New(c, "",
  4248. fakecontext.WithDockerfile(`
  4249. FROM busybox
  4250. COPY asymlink /`),
  4251. fakecontext.WithFiles(map[string]string{
  4252. "foo": "bar",
  4253. }))
  4254. defer ctx.Close()
  4255. err := os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink"))
  4256. assert.NilError(c, err)
  4257. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4258. out := cli.DockerCmd(c, "run", "--rm", name, "cat", "asymlink").Combined()
  4259. assert.Assert(c, cmp.Regexp("^"+
  4260. "bar"+
  4261. "$",
  4262. out))
  4263. }
  4264. // #17827
  4265. func (s *DockerSuite) TestBuildCacheRootSource(c *testing.T) {
  4266. name := "testbuildrootsource"
  4267. ctx := fakecontext.New(c, "",
  4268. fakecontext.WithDockerfile(`
  4269. FROM busybox
  4270. COPY / /data`),
  4271. fakecontext.WithFiles(map[string]string{
  4272. "foo": "bar",
  4273. }))
  4274. defer ctx.Close()
  4275. // warm up cache
  4276. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4277. // change file, should invalidate cache
  4278. err := ioutil.WriteFile(filepath.Join(ctx.Dir, "foo"), []byte("baz"), 0644)
  4279. assert.NilError(c, err)
  4280. result := cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4281. assert.Assert(c, !strings.Contains(result.Combined(), "Using cache"))
  4282. }
  4283. // #19375
  4284. // FIXME(vdemeester) should migrate to docker/cli tests
  4285. func (s *DockerSuite) TestBuildFailsGitNotCallable(c *testing.T) {
  4286. buildImage("gitnotcallable", cli.WithEnvironmentVariables("PATH="),
  4287. build.WithContextPath("github.com/docker/v1.10-migrator.git")).Assert(c, icmd.Expected{
  4288. ExitCode: 1,
  4289. Err: "unable to prepare context: unable to find 'git': ",
  4290. })
  4291. buildImage("gitnotcallable", cli.WithEnvironmentVariables("PATH="),
  4292. build.WithContextPath("https://github.com/docker/v1.10-migrator.git")).Assert(c, icmd.Expected{
  4293. ExitCode: 1,
  4294. Err: "unable to prepare context: unable to find 'git': ",
  4295. })
  4296. }
  4297. // TestBuildWorkdirWindowsPath tests that a Windows style path works as a workdir
  4298. func (s *DockerSuite) TestBuildWorkdirWindowsPath(c *testing.T) {
  4299. testRequires(c, DaemonIsWindows)
  4300. name := "testbuildworkdirwindowspath"
  4301. buildImageSuccessfully(c, name, build.WithDockerfile(`
  4302. FROM `+testEnv.PlatformDefaults.BaseImage+`
  4303. RUN mkdir C:\\work
  4304. WORKDIR C:\\work
  4305. RUN if "%CD%" NEQ "C:\work" exit -1
  4306. `))
  4307. }
  4308. func (s *DockerSuite) TestBuildLabel(c *testing.T) {
  4309. name := "testbuildlabel"
  4310. testLabel := "foo"
  4311. buildImageSuccessfully(c, name, cli.WithFlags("--label", testLabel),
  4312. build.WithDockerfile(`
  4313. FROM `+minimalBaseImage()+`
  4314. LABEL default foo
  4315. `))
  4316. var labels map[string]string
  4317. inspectFieldAndUnmarshall(c, name, "Config.Labels", &labels)
  4318. if _, ok := labels[testLabel]; !ok {
  4319. c.Fatal("label not found in image")
  4320. }
  4321. }
  4322. func (s *DockerSuite) TestBuildLabelOneNode(c *testing.T) {
  4323. name := "testbuildlabel"
  4324. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo=bar"),
  4325. build.WithDockerfile("FROM busybox"))
  4326. var labels map[string]string
  4327. inspectFieldAndUnmarshall(c, name, "Config.Labels", &labels)
  4328. v, ok := labels["foo"]
  4329. if !ok {
  4330. c.Fatal("label `foo` not found in image")
  4331. }
  4332. assert.Equal(c, v, "bar")
  4333. }
  4334. func (s *DockerSuite) TestBuildLabelCacheCommit(c *testing.T) {
  4335. name := "testbuildlabelcachecommit"
  4336. testLabel := "foo"
  4337. buildImageSuccessfully(c, name, build.WithDockerfile(`
  4338. FROM `+minimalBaseImage()+`
  4339. LABEL default foo
  4340. `))
  4341. buildImageSuccessfully(c, name, cli.WithFlags("--label", testLabel),
  4342. build.WithDockerfile(`
  4343. FROM `+minimalBaseImage()+`
  4344. LABEL default foo
  4345. `))
  4346. var labels map[string]string
  4347. inspectFieldAndUnmarshall(c, name, "Config.Labels", &labels)
  4348. if _, ok := labels[testLabel]; !ok {
  4349. c.Fatal("label not found in image")
  4350. }
  4351. }
  4352. func (s *DockerSuite) TestBuildLabelMultiple(c *testing.T) {
  4353. name := "testbuildlabelmultiple"
  4354. testLabels := map[string]string{
  4355. "foo": "bar",
  4356. "123": "456",
  4357. }
  4358. var labelArgs []string
  4359. for k, v := range testLabels {
  4360. labelArgs = append(labelArgs, "--label", k+"="+v)
  4361. }
  4362. buildImageSuccessfully(c, name, cli.WithFlags(labelArgs...),
  4363. build.WithDockerfile(`
  4364. FROM `+minimalBaseImage()+`
  4365. LABEL default foo
  4366. `))
  4367. var labels map[string]string
  4368. inspectFieldAndUnmarshall(c, name, "Config.Labels", &labels)
  4369. for k, v := range testLabels {
  4370. if x, ok := labels[k]; !ok || x != v {
  4371. c.Fatalf("label %s=%s not found in image", k, v)
  4372. }
  4373. }
  4374. }
  4375. func (s *DockerRegistryAuthHtpasswdSuite) TestBuildFromAuthenticatedRegistry(c *testing.T) {
  4376. dockerCmd(c, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL)
  4377. baseImage := privateRegistryURL + "/baseimage"
  4378. buildImageSuccessfully(c, baseImage, build.WithDockerfile(`
  4379. FROM busybox
  4380. ENV env1 val1
  4381. `))
  4382. dockerCmd(c, "push", baseImage)
  4383. dockerCmd(c, "rmi", baseImage)
  4384. buildImageSuccessfully(c, baseImage, build.WithDockerfile(fmt.Sprintf(`
  4385. FROM %s
  4386. ENV env2 val2
  4387. `, baseImage)))
  4388. }
  4389. func (s *DockerRegistryAuthHtpasswdSuite) TestBuildWithExternalAuth(c *testing.T) {
  4390. osPath := os.Getenv("PATH")
  4391. defer os.Setenv("PATH", osPath)
  4392. workingDir, err := os.Getwd()
  4393. assert.NilError(c, err)
  4394. absolute, err := filepath.Abs(filepath.Join(workingDir, "fixtures", "auth"))
  4395. assert.NilError(c, err)
  4396. testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute)
  4397. os.Setenv("PATH", testPath)
  4398. repoName := fmt.Sprintf("%v/dockercli/busybox:authtest", privateRegistryURL)
  4399. tmp, err := ioutil.TempDir("", "integration-cli-")
  4400. assert.NilError(c, err)
  4401. externalAuthConfig := `{ "credsStore": "shell-test" }`
  4402. configPath := filepath.Join(tmp, "config.json")
  4403. err = ioutil.WriteFile(configPath, []byte(externalAuthConfig), 0644)
  4404. assert.NilError(c, err)
  4405. dockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL)
  4406. b, err := ioutil.ReadFile(configPath)
  4407. assert.NilError(c, err)
  4408. assert.Assert(c, !strings.Contains(string(b), "\"auth\":"))
  4409. dockerCmd(c, "--config", tmp, "tag", "busybox", repoName)
  4410. dockerCmd(c, "--config", tmp, "push", repoName)
  4411. // make sure the image is pulled when building
  4412. dockerCmd(c, "rmi", repoName)
  4413. icmd.RunCmd(icmd.Cmd{
  4414. Command: []string{dockerBinary, "--config", tmp, "build", "-"},
  4415. Stdin: strings.NewReader(fmt.Sprintf("FROM %s", repoName)),
  4416. }).Assert(c, icmd.Success)
  4417. }
  4418. // Test cases in #22036
  4419. func (s *DockerSuite) TestBuildLabelsOverride(c *testing.T) {
  4420. // Command line option labels will always override
  4421. name := "scratchy"
  4422. expected := `{"bar":"from-flag","foo":"from-flag"}`
  4423. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo=from-flag", "--label", "bar=from-flag"),
  4424. build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4425. LABEL foo=from-dockerfile`))
  4426. res := inspectFieldJSON(c, name, "Config.Labels")
  4427. if res != expected {
  4428. c.Fatalf("Labels %s, expected %s", res, expected)
  4429. }
  4430. name = "from"
  4431. expected = `{"foo":"from-dockerfile"}`
  4432. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4433. LABEL foo from-dockerfile`))
  4434. res = inspectFieldJSON(c, name, "Config.Labels")
  4435. if res != expected {
  4436. c.Fatalf("Labels %s, expected %s", res, expected)
  4437. }
  4438. // Command line option label will override even via `FROM`
  4439. name = "new"
  4440. expected = `{"bar":"from-dockerfile2","foo":"new"}`
  4441. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo=new"),
  4442. build.WithDockerfile(`FROM from
  4443. LABEL bar from-dockerfile2`))
  4444. res = inspectFieldJSON(c, name, "Config.Labels")
  4445. if res != expected {
  4446. c.Fatalf("Labels %s, expected %s", res, expected)
  4447. }
  4448. // Command line option without a value set (--label foo, --label bar=)
  4449. // will be treated as --label foo="", --label bar=""
  4450. name = "scratchy2"
  4451. expected = `{"bar":"","foo":""}`
  4452. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo", "--label", "bar="),
  4453. build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4454. LABEL foo=from-dockerfile`))
  4455. res = inspectFieldJSON(c, name, "Config.Labels")
  4456. if res != expected {
  4457. c.Fatalf("Labels %s, expected %s", res, expected)
  4458. }
  4459. // Command line option without a value set (--label foo, --label bar=)
  4460. // will be treated as --label foo="", --label bar=""
  4461. // This time is for inherited images
  4462. name = "new2"
  4463. expected = `{"bar":"","foo":""}`
  4464. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo=", "--label", "bar"),
  4465. build.WithDockerfile(`FROM from
  4466. LABEL bar from-dockerfile2`))
  4467. res = inspectFieldJSON(c, name, "Config.Labels")
  4468. if res != expected {
  4469. c.Fatalf("Labels %s, expected %s", res, expected)
  4470. }
  4471. // Command line option labels with only `FROM`
  4472. name = "scratchy"
  4473. expected = `{"bar":"from-flag","foo":"from-flag"}`
  4474. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo=from-flag", "--label", "bar=from-flag"),
  4475. build.WithDockerfile(`FROM `+minimalBaseImage()))
  4476. res = inspectFieldJSON(c, name, "Config.Labels")
  4477. if res != expected {
  4478. c.Fatalf("Labels %s, expected %s", res, expected)
  4479. }
  4480. // Command line option labels with env var
  4481. name = "scratchz"
  4482. expected = `{"bar":"$PATH"}`
  4483. buildImageSuccessfully(c, name, cli.WithFlags("--label", "bar=$PATH"),
  4484. build.WithDockerfile(`FROM `+minimalBaseImage()))
  4485. res = inspectFieldJSON(c, name, "Config.Labels")
  4486. if res != expected {
  4487. c.Fatalf("Labels %s, expected %s", res, expected)
  4488. }
  4489. }
  4490. // Test case for #22855
  4491. func (s *DockerSuite) TestBuildDeleteCommittedFile(c *testing.T) {
  4492. name := "test-delete-committed-file"
  4493. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  4494. RUN echo test > file
  4495. RUN test -e file
  4496. RUN rm file
  4497. RUN sh -c "! test -e file"`))
  4498. }
  4499. // #20083
  4500. func (s *DockerSuite) TestBuildDockerignoreComment(c *testing.T) {
  4501. // TODO Windows: Figure out why this test is flakey on TP5. If you add
  4502. // something like RUN sleep 5, or even RUN ls /tmp after the ADD line,
  4503. // it is more reliable, but that's not a good fix.
  4504. testRequires(c, DaemonIsLinux)
  4505. name := "testbuilddockerignorecleanpaths"
  4506. dockerfile := `
  4507. FROM busybox
  4508. ADD . /tmp/
  4509. RUN sh -c "(ls -la /tmp/#1)"
  4510. RUN sh -c "(! ls -la /tmp/#2)"
  4511. RUN sh -c "(! ls /tmp/foo) && (! ls /tmp/foo2) && (ls /tmp/dir1/foo)"`
  4512. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  4513. build.WithFile("Dockerfile", dockerfile),
  4514. build.WithFile("foo", "foo"),
  4515. build.WithFile("foo2", "foo2"),
  4516. build.WithFile("dir1/foo", "foo in dir1"),
  4517. build.WithFile("#1", "# file 1"),
  4518. build.WithFile("#2", "# file 2"),
  4519. build.WithFile(".dockerignore", `# Visual C++ cache files
  4520. # because we have git ;-)
  4521. # The above comment is from #20083
  4522. foo
  4523. #dir1/foo
  4524. foo2
  4525. # The following is considered as comment as # is at the beginning
  4526. #1
  4527. # The following is not considered as comment as # is not at the beginning
  4528. #2
  4529. `)))
  4530. }
  4531. // Test case for #23221
  4532. func (s *DockerSuite) TestBuildWithUTF8BOM(c *testing.T) {
  4533. name := "test-with-utf8-bom"
  4534. dockerfile := []byte(`FROM busybox`)
  4535. bomDockerfile := append([]byte{0xEF, 0xBB, 0xBF}, dockerfile...)
  4536. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  4537. build.WithFile("Dockerfile", string(bomDockerfile)),
  4538. ))
  4539. }
  4540. // Test case for UTF-8 BOM in .dockerignore, related to #23221
  4541. func (s *DockerSuite) TestBuildWithUTF8BOMDockerignore(c *testing.T) {
  4542. name := "test-with-utf8-bom-dockerignore"
  4543. dockerfile := `
  4544. FROM busybox
  4545. ADD . /tmp/
  4546. RUN ls -la /tmp
  4547. RUN sh -c "! ls /tmp/Dockerfile"
  4548. RUN ls /tmp/.dockerignore`
  4549. dockerignore := []byte("./Dockerfile\n")
  4550. bomDockerignore := append([]byte{0xEF, 0xBB, 0xBF}, dockerignore...)
  4551. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  4552. build.WithFile("Dockerfile", dockerfile),
  4553. build.WithFile(".dockerignore", string(bomDockerignore)),
  4554. ))
  4555. }
  4556. // #22489 Shell test to confirm config gets updated correctly
  4557. func (s *DockerSuite) TestBuildShellUpdatesConfig(c *testing.T) {
  4558. name := "testbuildshellupdatesconfig"
  4559. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4560. SHELL ["foo", "-bar"]`))
  4561. expected := `["foo","-bar","#(nop) ","SHELL [foo -bar]"]`
  4562. res := inspectFieldJSON(c, name, "ContainerConfig.Cmd")
  4563. if res != expected {
  4564. c.Fatalf("%s, expected %s", res, expected)
  4565. }
  4566. res = inspectFieldJSON(c, name, "ContainerConfig.Shell")
  4567. if res != `["foo","-bar"]` {
  4568. c.Fatalf(`%s, expected ["foo","-bar"]`, res)
  4569. }
  4570. }
  4571. // #22489 Changing the shell multiple times and CMD after.
  4572. func (s *DockerSuite) TestBuildShellMultiple(c *testing.T) {
  4573. name := "testbuildshellmultiple"
  4574. result := buildImage(name, build.WithDockerfile(`FROM busybox
  4575. RUN echo defaultshell
  4576. SHELL ["echo"]
  4577. RUN echoshell
  4578. SHELL ["ls"]
  4579. RUN -l
  4580. CMD -l`))
  4581. result.Assert(c, icmd.Success)
  4582. // Must contain 'defaultshell' twice
  4583. if len(strings.Split(result.Combined(), "defaultshell")) != 3 {
  4584. c.Fatalf("defaultshell should have appeared twice in %s", result.Combined())
  4585. }
  4586. // Must contain 'echoshell' twice
  4587. if len(strings.Split(result.Combined(), "echoshell")) != 3 {
  4588. c.Fatalf("echoshell should have appeared twice in %s", result.Combined())
  4589. }
  4590. // Must contain "total " (part of ls -l)
  4591. if !strings.Contains(result.Combined(), "total ") {
  4592. c.Fatalf("%s should have contained 'total '", result.Combined())
  4593. }
  4594. // A container started from the image uses the shell-form CMD.
  4595. // Last shell is ls. CMD is -l. So should contain 'total '.
  4596. outrun, _ := dockerCmd(c, "run", "--rm", name)
  4597. if !strings.Contains(outrun, "total ") {
  4598. c.Fatalf("Expected started container to run ls -l. %s", outrun)
  4599. }
  4600. }
  4601. // #22489. Changed SHELL with ENTRYPOINT
  4602. func (s *DockerSuite) TestBuildShellEntrypoint(c *testing.T) {
  4603. name := "testbuildshellentrypoint"
  4604. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  4605. SHELL ["ls"]
  4606. ENTRYPOINT -l`))
  4607. // A container started from the image uses the shell-form ENTRYPOINT.
  4608. // Shell is ls. ENTRYPOINT is -l. So should contain 'total '.
  4609. outrun, _ := dockerCmd(c, "run", "--rm", name)
  4610. if !strings.Contains(outrun, "total ") {
  4611. c.Fatalf("Expected started container to run ls -l. %s", outrun)
  4612. }
  4613. }
  4614. // #22489 Shell test to confirm shell is inherited in a subsequent build
  4615. func (s *DockerSuite) TestBuildShellInherited(c *testing.T) {
  4616. name1 := "testbuildshellinherited1"
  4617. buildImageSuccessfully(c, name1, build.WithDockerfile(`FROM busybox
  4618. SHELL ["ls"]`))
  4619. name2 := "testbuildshellinherited2"
  4620. buildImage(name2, build.WithDockerfile(`FROM `+name1+`
  4621. RUN -l`)).Assert(c, icmd.Expected{
  4622. // ls -l has "total " followed by some number in it, ls without -l does not.
  4623. Out: "total ",
  4624. })
  4625. }
  4626. // #22489 Shell test to confirm non-JSON doesn't work
  4627. func (s *DockerSuite) TestBuildShellNotJSON(c *testing.T) {
  4628. name := "testbuildshellnotjson"
  4629. buildImage(name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4630. sHeLl exec -form`, // Casing explicit to ensure error is upper-cased.
  4631. )).Assert(c, icmd.Expected{
  4632. ExitCode: 1,
  4633. Err: "SHELL requires the arguments to be in JSON form",
  4634. })
  4635. }
  4636. // #22489 Windows shell test to confirm native is powershell if executing a PS command
  4637. // This would error if the default shell were still cmd.
  4638. func (s *DockerSuite) TestBuildShellWindowsPowershell(c *testing.T) {
  4639. testRequires(c, DaemonIsWindows)
  4640. name := "testbuildshellpowershell"
  4641. buildImage(name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4642. SHELL ["powershell", "-command"]
  4643. RUN Write-Host John`)).Assert(c, icmd.Expected{
  4644. Out: "\nJohn\n",
  4645. })
  4646. }
  4647. // Verify that escape is being correctly applied to words when escape directive is not \.
  4648. // Tests WORKDIR, ADD
  4649. func (s *DockerSuite) TestBuildEscapeNotBackslashWordTest(c *testing.T) {
  4650. testRequires(c, DaemonIsWindows)
  4651. name := "testbuildescapenotbackslashwordtesta"
  4652. buildImage(name, build.WithDockerfile(`# escape= `+"`"+`
  4653. FROM `+minimalBaseImage()+`
  4654. WORKDIR c:\windows
  4655. RUN dir /w`)).Assert(c, icmd.Expected{
  4656. Out: "[System32]",
  4657. })
  4658. name = "testbuildescapenotbackslashwordtestb"
  4659. buildImage(name, build.WithDockerfile(`# escape= `+"`"+`
  4660. FROM `+minimalBaseImage()+`
  4661. SHELL ["powershell.exe"]
  4662. WORKDIR c:\foo
  4663. ADD Dockerfile c:\foo\
  4664. RUN dir Dockerfile`)).Assert(c, icmd.Expected{
  4665. Out: "-a----",
  4666. })
  4667. }
  4668. // #22868. Make sure shell-form CMD is not marked as escaped in the config of the image,
  4669. // but an exec-form CMD is marked.
  4670. func (s *DockerSuite) TestBuildCmdShellArgsEscaped(c *testing.T) {
  4671. testRequires(c, DaemonIsWindows)
  4672. name1 := "testbuildcmdshellescapedshellform"
  4673. buildImageSuccessfully(c, name1, build.WithDockerfile(`
  4674. FROM `+minimalBaseImage()+`
  4675. CMD "ipconfig"
  4676. `))
  4677. res := inspectFieldJSON(c, name1, "Config.ArgsEscaped")
  4678. if res != "true" {
  4679. c.Fatalf("CMD did not update Config.ArgsEscaped on image: %v", res)
  4680. }
  4681. dockerCmd(c, "run", "--name", "inspectme1", name1)
  4682. dockerCmd(c, "wait", "inspectme1")
  4683. res = inspectFieldJSON(c, name1, "Config.Cmd")
  4684. if res != `["cmd /S /C \"ipconfig\""]` {
  4685. c.Fatalf("CMD incorrect in Config.Cmd: got %v", res)
  4686. }
  4687. // Now in JSON/exec-form
  4688. name2 := "testbuildcmdshellescapedexecform"
  4689. buildImageSuccessfully(c, name2, build.WithDockerfile(`
  4690. FROM `+minimalBaseImage()+`
  4691. CMD ["ipconfig"]
  4692. `))
  4693. res = inspectFieldJSON(c, name2, "Config.ArgsEscaped")
  4694. if res != "false" {
  4695. c.Fatalf("CMD set Config.ArgsEscaped on image: %v", res)
  4696. }
  4697. dockerCmd(c, "run", "--name", "inspectme2", name2)
  4698. dockerCmd(c, "wait", "inspectme2")
  4699. res = inspectFieldJSON(c, name2, "Config.Cmd")
  4700. if res != `["ipconfig"]` {
  4701. c.Fatalf("CMD incorrect in Config.Cmd: got %v", res)
  4702. }
  4703. }
  4704. // Test case for #24912.
  4705. func (s *DockerSuite) TestBuildStepsWithProgress(c *testing.T) {
  4706. name := "testbuildstepswithprogress"
  4707. totalRun := 5
  4708. result := buildImage(name, build.WithDockerfile("FROM busybox\n"+strings.Repeat("RUN echo foo\n", totalRun)))
  4709. result.Assert(c, icmd.Success)
  4710. assert.Assert(c, strings.Contains(result.Combined(), fmt.Sprintf("Step 1/%d : FROM busybox", 1+totalRun)))
  4711. for i := 2; i <= 1+totalRun; i++ {
  4712. assert.Assert(c, strings.Contains(result.Combined(), fmt.Sprintf("Step %d/%d : RUN echo foo", i, 1+totalRun)))
  4713. }
  4714. }
  4715. func (s *DockerSuite) TestBuildWithFailure(c *testing.T) {
  4716. name := "testbuildwithfailure"
  4717. // First test case can only detect `nobody` in runtime so all steps will show up
  4718. dockerfile := "FROM busybox\nRUN nobody"
  4719. result := buildImage(name, build.WithDockerfile(dockerfile))
  4720. assert.Assert(c, result.Error != nil)
  4721. assert.Assert(c, strings.Contains(result.Stdout(), "Step 1/2 : FROM busybox"))
  4722. assert.Assert(c, strings.Contains(result.Stdout(), "Step 2/2 : RUN nobody"))
  4723. // Second test case `FFOM` should have been detected before build runs so no steps
  4724. dockerfile = "FFOM nobody\nRUN nobody"
  4725. result = buildImage(name, build.WithDockerfile(dockerfile))
  4726. assert.Assert(c, result.Error != nil)
  4727. assert.Assert(c, !strings.Contains(result.Stdout(), "Step 1/2 : FROM busybox"))
  4728. assert.Assert(c, !strings.Contains(result.Stdout(), "Step 2/2 : RUN nobody"))
  4729. }
  4730. func (s *DockerSuite) TestBuildCacheFromEqualDiffIDsLength(c *testing.T) {
  4731. dockerfile := `
  4732. FROM busybox
  4733. RUN echo "test"
  4734. ENTRYPOINT ["sh"]`
  4735. ctx := fakecontext.New(c, "",
  4736. fakecontext.WithDockerfile(dockerfile),
  4737. fakecontext.WithFiles(map[string]string{
  4738. "Dockerfile": dockerfile,
  4739. }))
  4740. defer ctx.Close()
  4741. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  4742. id1 := getIDByName(c, "build1")
  4743. // rebuild with cache-from
  4744. result := cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4745. id2 := getIDByName(c, "build2")
  4746. assert.Equal(c, id1, id2)
  4747. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 2)
  4748. }
  4749. func (s *DockerSuite) TestBuildCacheFrom(c *testing.T) {
  4750. testRequires(c, DaemonIsLinux) // All tests that do save are skipped in windows
  4751. dockerfile := `
  4752. FROM busybox
  4753. ENV FOO=bar
  4754. ADD baz /
  4755. RUN touch bax`
  4756. ctx := fakecontext.New(c, "",
  4757. fakecontext.WithDockerfile(dockerfile),
  4758. fakecontext.WithFiles(map[string]string{
  4759. "Dockerfile": dockerfile,
  4760. "baz": "baz",
  4761. }))
  4762. defer ctx.Close()
  4763. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  4764. id1 := getIDByName(c, "build1")
  4765. // rebuild with cache-from
  4766. result := cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4767. id2 := getIDByName(c, "build2")
  4768. assert.Equal(c, id1, id2)
  4769. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 3)
  4770. cli.DockerCmd(c, "rmi", "build2")
  4771. // no cache match with unknown source
  4772. result = cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=nosuchtag"), build.WithExternalBuildContext(ctx))
  4773. id2 = getIDByName(c, "build2")
  4774. assert.Assert(c, id1 != id2)
  4775. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 0)
  4776. cli.DockerCmd(c, "rmi", "build2")
  4777. // clear parent images
  4778. tempDir, err := ioutil.TempDir("", "test-build-cache-from-")
  4779. if err != nil {
  4780. c.Fatalf("failed to create temporary directory: %s", tempDir)
  4781. }
  4782. defer os.RemoveAll(tempDir)
  4783. tempFile := filepath.Join(tempDir, "img.tar")
  4784. cli.DockerCmd(c, "save", "-o", tempFile, "build1")
  4785. cli.DockerCmd(c, "rmi", "build1")
  4786. cli.DockerCmd(c, "load", "-i", tempFile)
  4787. parentID := cli.DockerCmd(c, "inspect", "-f", "{{.Parent}}", "build1").Combined()
  4788. assert.Equal(c, strings.TrimSpace(parentID), "")
  4789. // cache still applies without parents
  4790. result = cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4791. id2 = getIDByName(c, "build2")
  4792. assert.Equal(c, id1, id2)
  4793. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 3)
  4794. history1 := cli.DockerCmd(c, "history", "-q", "build2").Combined()
  4795. // Retry, no new intermediate images
  4796. result = cli.BuildCmd(c, "build3", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4797. id3 := getIDByName(c, "build3")
  4798. assert.Equal(c, id1, id3)
  4799. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 3)
  4800. history2 := cli.DockerCmd(c, "history", "-q", "build3").Combined()
  4801. assert.Equal(c, history1, history2)
  4802. cli.DockerCmd(c, "rmi", "build2")
  4803. cli.DockerCmd(c, "rmi", "build3")
  4804. cli.DockerCmd(c, "rmi", "build1")
  4805. cli.DockerCmd(c, "load", "-i", tempFile)
  4806. // Modify file, everything up to last command and layers are reused
  4807. dockerfile = `
  4808. FROM busybox
  4809. ENV FOO=bar
  4810. ADD baz /
  4811. RUN touch newfile`
  4812. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "Dockerfile"), []byte(dockerfile), 0644)
  4813. assert.NilError(c, err)
  4814. result = cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4815. id2 = getIDByName(c, "build2")
  4816. assert.Assert(c, id1 != id2)
  4817. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 2)
  4818. layers1Str := cli.DockerCmd(c, "inspect", "-f", "{{json .RootFS.Layers}}", "build1").Combined()
  4819. layers2Str := cli.DockerCmd(c, "inspect", "-f", "{{json .RootFS.Layers}}", "build2").Combined()
  4820. var layers1 []string
  4821. var layers2 []string
  4822. assert.Assert(c, json.Unmarshal([]byte(layers1Str), &layers1) == nil)
  4823. assert.Assert(c, json.Unmarshal([]byte(layers2Str), &layers2) == nil)
  4824. assert.Equal(c, len(layers1), len(layers2))
  4825. for i := 0; i < len(layers1)-1; i++ {
  4826. assert.Equal(c, layers1[i], layers2[i])
  4827. }
  4828. assert.Assert(c, layers1[len(layers1)-1] != layers2[len(layers1)-1])
  4829. }
  4830. func (s *DockerSuite) TestBuildMultiStageCache(c *testing.T) {
  4831. testRequires(c, DaemonIsLinux) // All tests that do save are skipped in windows
  4832. dockerfile := `
  4833. FROM busybox
  4834. ADD baz /
  4835. FROM busybox
  4836. ADD baz /`
  4837. ctx := fakecontext.New(c, "",
  4838. fakecontext.WithDockerfile(dockerfile),
  4839. fakecontext.WithFiles(map[string]string{
  4840. "Dockerfile": dockerfile,
  4841. "baz": "baz",
  4842. }))
  4843. defer ctx.Close()
  4844. result := cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  4845. // second part of dockerfile was a repeat of first so should be cached
  4846. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 1)
  4847. result = cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4848. // now both parts of dockerfile should be cached
  4849. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 2)
  4850. }
  4851. func (s *DockerSuite) TestBuildNetNone(c *testing.T) {
  4852. testRequires(c, DaemonIsLinux)
  4853. name := "testbuildnetnone"
  4854. buildImage(name, cli.WithFlags("--network=none"), build.WithDockerfile(`
  4855. FROM busybox
  4856. RUN ping -c 1 8.8.8.8
  4857. `)).Assert(c, icmd.Expected{
  4858. ExitCode: 1,
  4859. Out: "unreachable",
  4860. })
  4861. }
  4862. func (s *DockerSuite) TestBuildNetContainer(c *testing.T) {
  4863. testRequires(c, DaemonIsLinux)
  4864. id, _ := dockerCmd(c, "run", "--hostname", "foobar", "-d", "busybox", "nc", "-ll", "-p", "1234", "-e", "hostname")
  4865. name := "testbuildnetcontainer"
  4866. buildImageSuccessfully(c, name, cli.WithFlags("--network=container:"+strings.TrimSpace(id)),
  4867. build.WithDockerfile(`
  4868. FROM busybox
  4869. RUN nc localhost 1234 > /otherhost
  4870. `))
  4871. host, _ := dockerCmd(c, "run", "testbuildnetcontainer", "cat", "/otherhost")
  4872. assert.Equal(c, strings.TrimSpace(host), "foobar")
  4873. }
  4874. func (s *DockerSuite) TestBuildWithExtraHost(c *testing.T) {
  4875. testRequires(c, DaemonIsLinux)
  4876. name := "testbuildwithextrahost"
  4877. buildImageSuccessfully(c, name,
  4878. cli.WithFlags(
  4879. "--add-host", "foo:127.0.0.1",
  4880. "--add-host", "bar:127.0.0.1",
  4881. ),
  4882. build.WithDockerfile(`
  4883. FROM busybox
  4884. RUN ping -c 1 foo
  4885. RUN ping -c 1 bar
  4886. `))
  4887. }
  4888. func (s *DockerSuite) TestBuildWithExtraHostInvalidFormat(c *testing.T) {
  4889. testRequires(c, DaemonIsLinux)
  4890. dockerfile := `
  4891. FROM busybox
  4892. RUN ping -c 1 foo`
  4893. testCases := []struct {
  4894. testName string
  4895. dockerfile string
  4896. buildFlag string
  4897. }{
  4898. {"extra_host_missing_ip", dockerfile, "--add-host=foo"},
  4899. {"extra_host_missing_ip_with_delimiter", dockerfile, "--add-host=foo:"},
  4900. {"extra_host_missing_hostname", dockerfile, "--add-host=:127.0.0.1"},
  4901. {"extra_host_invalid_ipv4", dockerfile, "--add-host=foo:101.10.2"},
  4902. {"extra_host_invalid_ipv6", dockerfile, "--add-host=foo:2001::1::3F"},
  4903. }
  4904. for _, tc := range testCases {
  4905. result := buildImage(tc.testName, cli.WithFlags(tc.buildFlag), build.WithDockerfile(tc.dockerfile))
  4906. result.Assert(c, icmd.Expected{
  4907. ExitCode: 125,
  4908. })
  4909. }
  4910. }
  4911. func (s *DockerSuite) TestBuildContChar(c *testing.T) {
  4912. name := "testbuildcontchar"
  4913. buildImage(name, build.WithDockerfile(`FROM busybox\`)).Assert(c, icmd.Expected{
  4914. Out: "Step 1/1 : FROM busybox",
  4915. })
  4916. result := buildImage(name, build.WithDockerfile(`FROM busybox
  4917. RUN echo hi \`))
  4918. result.Assert(c, icmd.Success)
  4919. assert.Assert(c, strings.Contains(result.Combined(), "Step 1/2 : FROM busybox"))
  4920. assert.Assert(c, strings.Contains(result.Combined(), "Step 2/2 : RUN echo hi\n"))
  4921. result = buildImage(name, build.WithDockerfile(`FROM busybox
  4922. RUN echo hi \\`))
  4923. result.Assert(c, icmd.Success)
  4924. assert.Assert(c, strings.Contains(result.Combined(), "Step 1/2 : FROM busybox"))
  4925. assert.Assert(c, strings.Contains(result.Combined(), "Step 2/2 : RUN echo hi \\\n"))
  4926. result = buildImage(name, build.WithDockerfile(`FROM busybox
  4927. RUN echo hi \\\`))
  4928. result.Assert(c, icmd.Success)
  4929. assert.Assert(c, strings.Contains(result.Combined(), "Step 1/2 : FROM busybox"))
  4930. assert.Assert(c, strings.Contains(result.Combined(), "Step 2/2 : RUN echo hi \\\\\n"))
  4931. }
  4932. func (s *DockerSuite) TestBuildMultiStageCopyFromSyntax(c *testing.T) {
  4933. dockerfile := `
  4934. FROM busybox AS first
  4935. COPY foo bar
  4936. FROM busybox
  4937. %s
  4938. COPY baz baz
  4939. RUN echo mno > baz/cc
  4940. FROM busybox
  4941. COPY bar /
  4942. COPY --from=1 baz sub/
  4943. COPY --from=0 bar baz
  4944. COPY --from=first bar bay`
  4945. ctx := fakecontext.New(c, "",
  4946. fakecontext.WithDockerfile(fmt.Sprintf(dockerfile, "")),
  4947. fakecontext.WithFiles(map[string]string{
  4948. "foo": "abc",
  4949. "bar": "def",
  4950. "baz/aa": "ghi",
  4951. "baz/bb": "jkl",
  4952. }))
  4953. defer ctx.Close()
  4954. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  4955. cli.DockerCmd(c, "run", "build1", "cat", "bar").Assert(c, icmd.Expected{Out: "def"})
  4956. cli.DockerCmd(c, "run", "build1", "cat", "sub/aa").Assert(c, icmd.Expected{Out: "ghi"})
  4957. cli.DockerCmd(c, "run", "build1", "cat", "sub/cc").Assert(c, icmd.Expected{Out: "mno"})
  4958. cli.DockerCmd(c, "run", "build1", "cat", "baz").Assert(c, icmd.Expected{Out: "abc"})
  4959. cli.DockerCmd(c, "run", "build1", "cat", "bay").Assert(c, icmd.Expected{Out: "abc"})
  4960. result := cli.BuildCmd(c, "build2", build.WithExternalBuildContext(ctx))
  4961. // all commands should be cached
  4962. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 7)
  4963. assert.Equal(c, getIDByName(c, "build1"), getIDByName(c, "build2"))
  4964. err := ioutil.WriteFile(filepath.Join(ctx.Dir, "Dockerfile"), []byte(fmt.Sprintf(dockerfile, "COPY baz/aa foo")), 0644)
  4965. assert.NilError(c, err)
  4966. // changing file in parent block should not affect last block
  4967. result = cli.BuildCmd(c, "build3", build.WithExternalBuildContext(ctx))
  4968. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 5)
  4969. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "foo"), []byte("pqr"), 0644)
  4970. assert.NilError(c, err)
  4971. // changing file in parent block should affect both first and last block
  4972. result = cli.BuildCmd(c, "build4", build.WithExternalBuildContext(ctx))
  4973. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 5)
  4974. cli.DockerCmd(c, "run", "build4", "cat", "bay").Assert(c, icmd.Expected{Out: "pqr"})
  4975. cli.DockerCmd(c, "run", "build4", "cat", "baz").Assert(c, icmd.Expected{Out: "pqr"})
  4976. }
  4977. func (s *DockerSuite) TestBuildMultiStageCopyFromErrors(c *testing.T) {
  4978. testCases := []struct {
  4979. dockerfile string
  4980. expectedError string
  4981. }{
  4982. {
  4983. dockerfile: `
  4984. FROM busybox
  4985. COPY --from=foo foo bar`,
  4986. expectedError: "invalid from flag value foo",
  4987. },
  4988. {
  4989. dockerfile: `
  4990. FROM busybox
  4991. COPY --from=0 foo bar`,
  4992. expectedError: "invalid from flag value 0: refers to current build stage",
  4993. },
  4994. {
  4995. dockerfile: `
  4996. FROM busybox AS foo
  4997. COPY --from=bar foo bar`,
  4998. expectedError: "invalid from flag value bar",
  4999. },
  5000. {
  5001. dockerfile: `
  5002. FROM busybox AS 1
  5003. COPY --from=1 foo bar`,
  5004. expectedError: "invalid name for build stage",
  5005. },
  5006. }
  5007. for _, tc := range testCases {
  5008. ctx := fakecontext.New(c, "",
  5009. fakecontext.WithDockerfile(tc.dockerfile),
  5010. fakecontext.WithFiles(map[string]string{
  5011. "foo": "abc",
  5012. }))
  5013. cli.Docker(cli.Build("build1"), build.WithExternalBuildContext(ctx)).Assert(c, icmd.Expected{
  5014. ExitCode: 1,
  5015. Err: tc.expectedError,
  5016. })
  5017. ctx.Close()
  5018. }
  5019. }
  5020. func (s *DockerSuite) TestBuildMultiStageMultipleBuilds(c *testing.T) {
  5021. dockerfile := `
  5022. FROM busybox
  5023. COPY foo bar`
  5024. ctx := fakecontext.New(c, "",
  5025. fakecontext.WithDockerfile(dockerfile),
  5026. fakecontext.WithFiles(map[string]string{
  5027. "foo": "abc",
  5028. }))
  5029. defer ctx.Close()
  5030. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5031. dockerfile = `
  5032. FROM build1:latest AS foo
  5033. FROM busybox
  5034. COPY --from=foo bar /
  5035. COPY foo /`
  5036. ctx = fakecontext.New(c, "",
  5037. fakecontext.WithDockerfile(dockerfile),
  5038. fakecontext.WithFiles(map[string]string{
  5039. "foo": "def",
  5040. }))
  5041. defer ctx.Close()
  5042. cli.BuildCmd(c, "build2", build.WithExternalBuildContext(ctx))
  5043. out := cli.DockerCmd(c, "run", "build2", "cat", "bar").Combined()
  5044. assert.Equal(c, strings.TrimSpace(out), "abc")
  5045. out = cli.DockerCmd(c, "run", "build2", "cat", "foo").Combined()
  5046. assert.Equal(c, strings.TrimSpace(out), "def")
  5047. }
  5048. func (s *DockerSuite) TestBuildMultiStageImplicitFrom(c *testing.T) {
  5049. dockerfile := `
  5050. FROM busybox
  5051. COPY --from=busybox /etc/passwd /mypasswd
  5052. RUN cmp /etc/passwd /mypasswd`
  5053. if DaemonIsWindows() {
  5054. dockerfile = `
  5055. FROM busybox
  5056. COPY --from=busybox License.txt foo`
  5057. }
  5058. ctx := fakecontext.New(c, "",
  5059. fakecontext.WithDockerfile(dockerfile),
  5060. )
  5061. defer ctx.Close()
  5062. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5063. if DaemonIsWindows() {
  5064. out := cli.DockerCmd(c, "run", "build1", "cat", "License.txt").Combined()
  5065. assert.Assert(c, len(out) > 10)
  5066. out2 := cli.DockerCmd(c, "run", "build1", "cat", "foo").Combined()
  5067. assert.Equal(c, out, out2)
  5068. }
  5069. }
  5070. func (s *DockerRegistrySuite) TestBuildMultiStageImplicitPull(c *testing.T) {
  5071. repoName := fmt.Sprintf("%v/dockercli/testf", privateRegistryURL)
  5072. dockerfile := `
  5073. FROM busybox
  5074. COPY foo bar`
  5075. ctx := fakecontext.New(c, "",
  5076. fakecontext.WithDockerfile(dockerfile),
  5077. fakecontext.WithFiles(map[string]string{
  5078. "foo": "abc",
  5079. }))
  5080. defer ctx.Close()
  5081. cli.BuildCmd(c, repoName, build.WithExternalBuildContext(ctx))
  5082. cli.DockerCmd(c, "push", repoName)
  5083. cli.DockerCmd(c, "rmi", repoName)
  5084. dockerfile = `
  5085. FROM busybox
  5086. COPY --from=%s bar baz`
  5087. ctx = fakecontext.New(c, "", fakecontext.WithDockerfile(fmt.Sprintf(dockerfile, repoName)))
  5088. defer ctx.Close()
  5089. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5090. cli.Docker(cli.Args("run", "build1", "cat", "baz")).Assert(c, icmd.Expected{Out: "abc"})
  5091. }
  5092. func (s *DockerSuite) TestBuildMultiStageNameVariants(c *testing.T) {
  5093. dockerfile := `
  5094. FROM busybox as foo
  5095. COPY foo /
  5096. FROM foo as foo1
  5097. RUN echo 1 >> foo
  5098. FROM foo as foO2
  5099. RUN echo 2 >> foo
  5100. FROM foo
  5101. COPY --from=foo1 foo f1
  5102. COPY --from=FOo2 foo f2
  5103. ` // foo2 case also tests that names are case insensitive
  5104. ctx := fakecontext.New(c, "",
  5105. fakecontext.WithDockerfile(dockerfile),
  5106. fakecontext.WithFiles(map[string]string{
  5107. "foo": "bar",
  5108. }))
  5109. defer ctx.Close()
  5110. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5111. cli.Docker(cli.Args("run", "build1", "cat", "foo")).Assert(c, icmd.Expected{Out: "bar"})
  5112. cli.Docker(cli.Args("run", "build1", "cat", "f1")).Assert(c, icmd.Expected{Out: "bar1"})
  5113. cli.Docker(cli.Args("run", "build1", "cat", "f2")).Assert(c, icmd.Expected{Out: "bar2"})
  5114. }
  5115. func (s *DockerSuite) TestBuildMultiStageMultipleBuildsWindows(c *testing.T) {
  5116. testRequires(c, DaemonIsWindows)
  5117. dockerfile := `
  5118. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5119. COPY foo c:\\bar`
  5120. ctx := fakecontext.New(c, "",
  5121. fakecontext.WithDockerfile(dockerfile),
  5122. fakecontext.WithFiles(map[string]string{
  5123. "foo": "abc",
  5124. }))
  5125. defer ctx.Close()
  5126. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5127. dockerfile = `
  5128. FROM build1:latest
  5129. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5130. COPY --from=0 c:\\bar /
  5131. COPY foo /`
  5132. ctx = fakecontext.New(c, "",
  5133. fakecontext.WithDockerfile(dockerfile),
  5134. fakecontext.WithFiles(map[string]string{
  5135. "foo": "def",
  5136. }))
  5137. defer ctx.Close()
  5138. cli.BuildCmd(c, "build2", build.WithExternalBuildContext(ctx))
  5139. out := cli.DockerCmd(c, "run", "build2", "cmd.exe", "/s", "/c", "type", "c:\\bar").Combined()
  5140. assert.Equal(c, strings.TrimSpace(out), "abc")
  5141. out = cli.DockerCmd(c, "run", "build2", "cmd.exe", "/s", "/c", "type", "c:\\foo").Combined()
  5142. assert.Equal(c, strings.TrimSpace(out), "def")
  5143. }
  5144. func (s *DockerSuite) TestBuildCopyFromForbidWindowsSystemPaths(c *testing.T) {
  5145. testRequires(c, DaemonIsWindows)
  5146. dockerfile := `
  5147. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5148. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5149. COPY --from=0 %s c:\\oscopy
  5150. `
  5151. exp := icmd.Expected{
  5152. ExitCode: 1,
  5153. Err: "copy from c:\\ or c:\\windows is not allowed on windows",
  5154. }
  5155. buildImage("testforbidsystempaths1", build.WithDockerfile(fmt.Sprintf(dockerfile, "c:\\\\"))).Assert(c, exp)
  5156. buildImage("testforbidsystempaths2", build.WithDockerfile(fmt.Sprintf(dockerfile, "C:\\\\"))).Assert(c, exp)
  5157. buildImage("testforbidsystempaths3", build.WithDockerfile(fmt.Sprintf(dockerfile, "c:\\\\windows"))).Assert(c, exp)
  5158. buildImage("testforbidsystempaths4", build.WithDockerfile(fmt.Sprintf(dockerfile, "c:\\\\wInDows"))).Assert(c, exp)
  5159. }
  5160. func (s *DockerSuite) TestBuildCopyFromForbidWindowsRelativePaths(c *testing.T) {
  5161. testRequires(c, DaemonIsWindows)
  5162. dockerfile := `
  5163. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5164. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5165. COPY --from=0 %s c:\\oscopy
  5166. `
  5167. exp := icmd.Expected{
  5168. ExitCode: 1,
  5169. Err: "copy from c:\\ or c:\\windows is not allowed on windows",
  5170. }
  5171. buildImage("testforbidsystempaths1", build.WithDockerfile(fmt.Sprintf(dockerfile, "c:"))).Assert(c, exp)
  5172. buildImage("testforbidsystempaths2", build.WithDockerfile(fmt.Sprintf(dockerfile, "."))).Assert(c, exp)
  5173. buildImage("testforbidsystempaths3", build.WithDockerfile(fmt.Sprintf(dockerfile, "..\\\\"))).Assert(c, exp)
  5174. buildImage("testforbidsystempaths4", build.WithDockerfile(fmt.Sprintf(dockerfile, ".\\\\windows"))).Assert(c, exp)
  5175. buildImage("testforbidsystempaths5", build.WithDockerfile(fmt.Sprintf(dockerfile, "\\\\windows"))).Assert(c, exp)
  5176. }
  5177. func (s *DockerSuite) TestBuildCopyFromWindowsIsCaseInsensitive(c *testing.T) {
  5178. testRequires(c, DaemonIsWindows)
  5179. dockerfile := `
  5180. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5181. COPY foo /
  5182. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5183. COPY --from=0 c:\\fOo c:\\copied
  5184. RUN type c:\\copied
  5185. `
  5186. cli.Docker(cli.Build("copyfrom-windows-insensitive"), build.WithBuildContext(c,
  5187. build.WithFile("Dockerfile", dockerfile),
  5188. build.WithFile("foo", "hello world"),
  5189. )).Assert(c, icmd.Expected{
  5190. ExitCode: 0,
  5191. Out: "hello world",
  5192. })
  5193. }
  5194. // #33176
  5195. func (s *DockerSuite) TestBuildMultiStageResetScratch(c *testing.T) {
  5196. testRequires(c, DaemonIsLinux)
  5197. dockerfile := `
  5198. FROM busybox
  5199. WORKDIR /foo/bar
  5200. FROM scratch
  5201. ENV FOO=bar
  5202. `
  5203. ctx := fakecontext.New(c, "",
  5204. fakecontext.WithDockerfile(dockerfile),
  5205. )
  5206. defer ctx.Close()
  5207. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5208. res := cli.InspectCmd(c, "build1", cli.Format(".Config.WorkingDir")).Combined()
  5209. assert.Equal(c, strings.TrimSpace(res), "")
  5210. }
  5211. func (s *DockerSuite) TestBuildIntermediateTarget(c *testing.T) {
  5212. //todo: need to be removed after 18.06 release
  5213. if strings.Contains(testEnv.DaemonInfo.ServerVersion, "18.05.0") {
  5214. c.Skip(fmt.Sprintf("Bug fixed in 18.06 or higher.Skipping it for %s", testEnv.DaemonInfo.ServerVersion))
  5215. }
  5216. dockerfile := `
  5217. FROM busybox AS build-env
  5218. CMD ["/dev"]
  5219. FROM busybox
  5220. CMD ["/dist"]
  5221. `
  5222. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(dockerfile))
  5223. defer ctx.Close()
  5224. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx),
  5225. cli.WithFlags("--target", "build-env"))
  5226. res := cli.InspectCmd(c, "build1", cli.Format("json .Config.Cmd")).Combined()
  5227. assert.Equal(c, strings.TrimSpace(res), `["/dev"]`)
  5228. // Stage name is case-insensitive by design
  5229. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx),
  5230. cli.WithFlags("--target", "BUIld-EnV"))
  5231. res = cli.InspectCmd(c, "build1", cli.Format("json .Config.Cmd")).Combined()
  5232. assert.Equal(c, strings.TrimSpace(res), `["/dev"]`)
  5233. result := cli.Docker(cli.Build("build1"), build.WithExternalBuildContext(ctx),
  5234. cli.WithFlags("--target", "nosuchtarget"))
  5235. result.Assert(c, icmd.Expected{
  5236. ExitCode: 1,
  5237. Err: "failed to reach build target",
  5238. })
  5239. }
  5240. // TestBuildOpaqueDirectory tests that a build succeeds which
  5241. // creates opaque directories.
  5242. // See https://github.com/docker/docker/issues/25244
  5243. func (s *DockerSuite) TestBuildOpaqueDirectory(c *testing.T) {
  5244. testRequires(c, DaemonIsLinux)
  5245. dockerFile := `
  5246. FROM busybox
  5247. RUN mkdir /dir1 && touch /dir1/f1
  5248. RUN rm -rf /dir1 && mkdir /dir1 && touch /dir1/f2
  5249. RUN touch /dir1/f3
  5250. RUN [ -f /dir1/f2 ]
  5251. `
  5252. // Test that build succeeds, last command fails if opaque directory
  5253. // was not handled correctly
  5254. buildImageSuccessfully(c, "testopaquedirectory", build.WithDockerfile(dockerFile))
  5255. }
  5256. // Windows test for USER in dockerfile
  5257. func (s *DockerSuite) TestBuildWindowsUser(c *testing.T) {
  5258. testRequires(c, DaemonIsWindows)
  5259. name := "testbuildwindowsuser"
  5260. buildImage(name, build.WithDockerfile(`FROM `+testEnv.PlatformDefaults.BaseImage+`
  5261. RUN net user user /add
  5262. USER user
  5263. RUN set username
  5264. `)).Assert(c, icmd.Expected{
  5265. Out: "USERNAME=user",
  5266. })
  5267. }
  5268. // Verifies if COPY file . when WORKDIR is set to a non-existing directory,
  5269. // the directory is created and the file is copied into the directory,
  5270. // as opposed to the file being copied as a file with the name of the
  5271. // directory. Fix for 27545 (found on Windows, but regression good for Linux too).
  5272. // Note 27545 was reverted in 28505, but a new fix was added subsequently in 28514.
  5273. func (s *DockerSuite) TestBuildCopyFileDotWithWorkdir(c *testing.T) {
  5274. name := "testbuildcopyfiledotwithworkdir"
  5275. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  5276. build.WithFile("Dockerfile", `FROM busybox
  5277. WORKDIR /foo
  5278. COPY file .
  5279. RUN ["cat", "/foo/file"]
  5280. `),
  5281. build.WithFile("file", "content"),
  5282. ))
  5283. }
  5284. // Case-insensitive environment variables on Windows
  5285. func (s *DockerSuite) TestBuildWindowsEnvCaseInsensitive(c *testing.T) {
  5286. testRequires(c, DaemonIsWindows)
  5287. name := "testbuildwindowsenvcaseinsensitive"
  5288. buildImageSuccessfully(c, name, build.WithDockerfile(`
  5289. FROM `+testEnv.PlatformDefaults.BaseImage+`
  5290. ENV FOO=bar foo=baz
  5291. `))
  5292. res := inspectFieldJSON(c, name, "Config.Env")
  5293. if res != `["foo=baz"]` { // Should not have FOO=bar in it - takes the last one processed. And only one entry as deduped.
  5294. c.Fatalf("Case insensitive environment variables on Windows failed. Got %s", res)
  5295. }
  5296. }
  5297. // Test case for 29667
  5298. func (s *DockerSuite) TestBuildWorkdirImageCmd(c *testing.T) {
  5299. image := "testworkdirimagecmd"
  5300. buildImageSuccessfully(c, image, build.WithDockerfile(`
  5301. FROM busybox
  5302. WORKDIR /foo/bar
  5303. `))
  5304. out, _ := dockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", image)
  5305. assert.Equal(c, strings.TrimSpace(out), `["sh"]`)
  5306. image = "testworkdirlabelimagecmd"
  5307. buildImageSuccessfully(c, image, build.WithDockerfile(`
  5308. FROM busybox
  5309. WORKDIR /foo/bar
  5310. LABEL a=b
  5311. `))
  5312. out, _ = dockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", image)
  5313. assert.Equal(c, strings.TrimSpace(out), `["sh"]`)
  5314. }
  5315. // Test case for 28902/28909
  5316. func (s *DockerSuite) TestBuildWorkdirCmd(c *testing.T) {
  5317. testRequires(c, DaemonIsLinux)
  5318. name := "testbuildworkdircmd"
  5319. dockerFile := `
  5320. FROM busybox
  5321. WORKDIR /
  5322. `
  5323. buildImageSuccessfully(c, name, build.WithDockerfile(dockerFile))
  5324. result := buildImage(name, build.WithDockerfile(dockerFile))
  5325. result.Assert(c, icmd.Success)
  5326. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 1)
  5327. }
  5328. // FIXME(vdemeester) should be a unit test
  5329. func (s *DockerSuite) TestBuildLineErrorOnBuild(c *testing.T) {
  5330. name := "test_build_line_error_onbuild"
  5331. buildImage(name, build.WithDockerfile(`FROM busybox
  5332. ONBUILD
  5333. `)).Assert(c, icmd.Expected{
  5334. ExitCode: 1,
  5335. Err: "Dockerfile parse error line 2: ONBUILD requires at least one argument",
  5336. })
  5337. }
  5338. // FIXME(vdemeester) should be a unit test
  5339. func (s *DockerSuite) TestBuildLineErrorUnknownInstruction(c *testing.T) {
  5340. name := "test_build_line_error_unknown_instruction"
  5341. cli.Docker(cli.Build(name), build.WithDockerfile(`FROM busybox
  5342. RUN echo hello world
  5343. NOINSTRUCTION echo ba
  5344. RUN echo hello
  5345. ERROR
  5346. `)).Assert(c, icmd.Expected{
  5347. ExitCode: 1,
  5348. Err: "Dockerfile parse error line 3: unknown instruction: NOINSTRUCTION",
  5349. })
  5350. }
  5351. // FIXME(vdemeester) should be a unit test
  5352. func (s *DockerSuite) TestBuildLineErrorWithEmptyLines(c *testing.T) {
  5353. name := "test_build_line_error_with_empty_lines"
  5354. cli.Docker(cli.Build(name), build.WithDockerfile(`
  5355. FROM busybox
  5356. RUN echo hello world
  5357. NOINSTRUCTION echo ba
  5358. CMD ["/bin/init"]
  5359. `)).Assert(c, icmd.Expected{
  5360. ExitCode: 1,
  5361. Err: "Dockerfile parse error line 6: unknown instruction: NOINSTRUCTION",
  5362. })
  5363. }
  5364. // FIXME(vdemeester) should be a unit test
  5365. func (s *DockerSuite) TestBuildLineErrorWithComments(c *testing.T) {
  5366. name := "test_build_line_error_with_comments"
  5367. cli.Docker(cli.Build(name), build.WithDockerfile(`FROM busybox
  5368. # This will print hello world
  5369. # and then ba
  5370. RUN echo hello world
  5371. NOINSTRUCTION echo ba
  5372. `)).Assert(c, icmd.Expected{
  5373. ExitCode: 1,
  5374. Err: "Dockerfile parse error line 5: unknown instruction: NOINSTRUCTION",
  5375. })
  5376. }
  5377. // #31957
  5378. func (s *DockerSuite) TestBuildSetCommandWithDefinedShell(c *testing.T) {
  5379. buildImageSuccessfully(c, "build1", build.WithDockerfile(`
  5380. FROM busybox
  5381. SHELL ["/bin/sh", "-c"]
  5382. `))
  5383. buildImageSuccessfully(c, "build2", build.WithDockerfile(`
  5384. FROM build1
  5385. CMD echo foo
  5386. `))
  5387. out, _ := dockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", "build2")
  5388. expected := `["/bin/sh","-c","echo foo"]`
  5389. if testEnv.OSType == "windows" {
  5390. expected = `["/bin/sh -c echo foo"]`
  5391. }
  5392. assert.Equal(c, strings.TrimSpace(out), expected)
  5393. }
  5394. // FIXME(vdemeester) should migrate to docker/cli tests
  5395. func (s *DockerSuite) TestBuildIidFile(c *testing.T) {
  5396. tmpDir, err := ioutil.TempDir("", "TestBuildIidFile")
  5397. if err != nil {
  5398. c.Fatal(err)
  5399. }
  5400. defer os.RemoveAll(tmpDir)
  5401. tmpIidFile := filepath.Join(tmpDir, "iid")
  5402. name := "testbuildiidfile"
  5403. // Use a Dockerfile with multiple stages to ensure we get the last one
  5404. cli.BuildCmd(c, name,
  5405. build.WithDockerfile(`FROM `+minimalBaseImage()+` AS stage1
  5406. ENV FOO FOO
  5407. FROM `+minimalBaseImage()+`
  5408. ENV BAR BAZ`),
  5409. cli.WithFlags("--iidfile", tmpIidFile))
  5410. id, err := ioutil.ReadFile(tmpIidFile)
  5411. assert.NilError(c, err)
  5412. d, err := digest.Parse(string(id))
  5413. assert.NilError(c, err)
  5414. assert.Equal(c, d.String(), getIDByName(c, name))
  5415. }
  5416. // FIXME(vdemeester) should migrate to docker/cli tests
  5417. func (s *DockerSuite) TestBuildIidFileCleanupOnFail(c *testing.T) {
  5418. tmpDir, err := ioutil.TempDir("", "TestBuildIidFileCleanupOnFail")
  5419. if err != nil {
  5420. c.Fatal(err)
  5421. }
  5422. defer os.RemoveAll(tmpDir)
  5423. tmpIidFile := filepath.Join(tmpDir, "iid")
  5424. err = ioutil.WriteFile(tmpIidFile, []byte("Dummy"), 0666)
  5425. assert.NilError(c, err)
  5426. cli.Docker(cli.Build("testbuildiidfilecleanuponfail"),
  5427. build.WithDockerfile(`FROM `+minimalBaseImage()+`
  5428. RUN /non/existing/command`),
  5429. cli.WithFlags("--iidfile", tmpIidFile)).Assert(c, icmd.Expected{
  5430. ExitCode: 1,
  5431. })
  5432. _, err = os.Stat(tmpIidFile)
  5433. assert.ErrorContains(c, err, "")
  5434. assert.Equal(c, os.IsNotExist(err), true)
  5435. }