docker_cli_build_test.go 206 KB

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