docker_cli_build_test.go 190 KB

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