docker_cli_build_test.go 185 KB

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