docker_cli_build_test.go 178 KB

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