docker_cli_build_test.go 206 KB

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