docker_cli_build_test.go 184 KB

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