docker_cli_build_test.go 197 KB

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