docker_cli_build_test.go 197 KB

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