docker_cli_build_test.go 178 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636
  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. 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 -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3345. # Switch back to root and double check that worked exactly as we might expect it to
  3346. USER root
  3347. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '0:0/root:root/0 10:root wheel' ] && \
  3348. # Add a "supplementary" group for our dockerio user \
  3349. echo 'supplementary:x:1002:dockerio' >> /etc/group
  3350. # ... and then go verify that we get it like we expect
  3351. USER dockerio
  3352. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  3353. USER 1001
  3354. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  3355. # super test the new "user:group" syntax
  3356. USER dockerio:dockerio
  3357. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3358. USER 1001:dockerio
  3359. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3360. USER dockerio:1001
  3361. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3362. USER 1001:1001
  3363. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3364. USER dockerio:supplementary
  3365. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3366. USER dockerio:1002
  3367. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3368. USER 1001:supplementary
  3369. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3370. USER 1001:1002
  3371. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3372. # make sure unknown uid/gid still works properly
  3373. USER 1042:1043
  3374. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1042:1043/1042:1043/1043:1043' ]`,
  3375. true)
  3376. if err != nil {
  3377. c.Fatal(err)
  3378. }
  3379. }
  3380. func (s *DockerSuite) TestBuildEnvUsage(c *check.C) {
  3381. // /docker/world/hello is not owned by the correct user
  3382. testRequires(c, NotUserNamespace)
  3383. testRequires(c, DaemonIsLinux)
  3384. name := "testbuildenvusage"
  3385. dockerfile := `FROM busybox
  3386. ENV HOME /root
  3387. ENV PATH $HOME/bin:$PATH
  3388. ENV PATH /tmp:$PATH
  3389. RUN [ "$PATH" = "/tmp:$HOME/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ]
  3390. ENV FOO /foo/baz
  3391. ENV BAR /bar
  3392. ENV BAZ $BAR
  3393. ENV FOOPATH $PATH:$FOO
  3394. RUN [ "$BAR" = "$BAZ" ]
  3395. RUN [ "$FOOPATH" = "$PATH:/foo/baz" ]
  3396. ENV FROM hello/docker/world
  3397. ENV TO /docker/world/hello
  3398. ADD $FROM $TO
  3399. RUN [ "$(cat $TO)" = "hello" ]
  3400. ENV abc=def
  3401. ENV ghi=$abc
  3402. RUN [ "$ghi" = "def" ]
  3403. `
  3404. ctx, err := fakeContext(dockerfile, map[string]string{
  3405. "hello/docker/world": "hello",
  3406. })
  3407. if err != nil {
  3408. c.Fatal(err)
  3409. }
  3410. defer ctx.Close()
  3411. _, err = buildImageFromContext(name, ctx, true)
  3412. if err != nil {
  3413. c.Fatal(err)
  3414. }
  3415. }
  3416. func (s *DockerSuite) TestBuildEnvUsage2(c *check.C) {
  3417. // /docker/world/hello is not owned by the correct user
  3418. testRequires(c, NotUserNamespace)
  3419. testRequires(c, DaemonIsLinux)
  3420. name := "testbuildenvusage2"
  3421. dockerfile := `FROM busybox
  3422. ENV abc=def def="hello world"
  3423. RUN [ "$abc,$def" = "def,hello world" ]
  3424. ENV def=hello\ world v1=abc v2="hi there" v3='boogie nights' v4="with'quotes too"
  3425. RUN [ "$def,$v1,$v2,$v3,$v4" = "hello world,abc,hi there,boogie nights,with'quotes too" ]
  3426. ENV abc=zzz FROM=hello/docker/world
  3427. ENV abc=zzz TO=/docker/world/hello
  3428. ADD $FROM $TO
  3429. RUN [ "$abc,$(cat $TO)" = "zzz,hello" ]
  3430. ENV abc 'yyy'
  3431. RUN [ $abc = 'yyy' ]
  3432. ENV abc=
  3433. RUN [ "$abc" = "" ]
  3434. # use grep to make sure if the builder substitutes \$foo by mistake
  3435. # we don't get a false positive
  3436. ENV abc=\$foo
  3437. RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep foo)
  3438. ENV abc \$foo
  3439. RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep foo)
  3440. ENV abc=\'foo\' abc2=\"foo\"
  3441. RUN [ "$abc,$abc2" = "'foo',\"foo\"" ]
  3442. ENV abc "foo"
  3443. RUN [ "$abc" = "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=ABC
  3451. RUN [ "$abc" = "ABC" ]
  3452. ENV def1=${abc:-DEF} def2=${ccc:-DEF}
  3453. ENV def3=${ccc:-${def2}xx} def4=${abc:+ALT} def5=${def2:+${abc}:} def6=${ccc:-\$abc:} def7=${ccc:-\${abc}:}
  3454. RUN [ "$def1,$def2,$def3,$def4,$def5,$def6,$def7" = 'ABC,DEF,DEFxx,ALT,ABC:,$abc:,${abc:}' ]
  3455. ENV mypath=${mypath:+$mypath:}/home
  3456. ENV mypath=${mypath:+$mypath:}/away
  3457. RUN [ "$mypath" = '/home:/away' ]
  3458. ENV e1=bar
  3459. ENV e2=$e1 e3=$e11 e4=\$e1 e5=\$e11
  3460. RUN [ "$e0,$e1,$e2,$e3,$e4,$e5" = ',bar,bar,,$e1,$e11' ]
  3461. ENV ee1 bar
  3462. ENV ee2 $ee1
  3463. ENV ee3 $ee11
  3464. ENV ee4 \$ee1
  3465. ENV ee5 \$ee11
  3466. RUN [ "$ee1,$ee2,$ee3,$ee4,$ee5" = 'bar,bar,,$ee1,$ee11' ]
  3467. ENV eee1="foo" eee2='foo'
  3468. ENV eee3 "foo"
  3469. ENV eee4 'foo'
  3470. RUN [ "$eee1,$eee2,$eee3,$eee4" = 'foo,foo,foo,foo' ]
  3471. `
  3472. ctx, err := fakeContext(dockerfile, map[string]string{
  3473. "hello/docker/world": "hello",
  3474. })
  3475. if err != nil {
  3476. c.Fatal(err)
  3477. }
  3478. defer ctx.Close()
  3479. _, err = buildImageFromContext(name, ctx, true)
  3480. if err != nil {
  3481. c.Fatal(err)
  3482. }
  3483. }
  3484. func (s *DockerSuite) TestBuildAddScript(c *check.C) {
  3485. testRequires(c, DaemonIsLinux)
  3486. name := "testbuildaddscript"
  3487. dockerfile := `
  3488. FROM busybox
  3489. ADD test /test
  3490. RUN ["chmod","+x","/test"]
  3491. RUN ["/test"]
  3492. RUN [ "$(cat /testfile)" = 'test!' ]`
  3493. ctx, err := fakeContext(dockerfile, map[string]string{
  3494. "test": "#!/bin/sh\necho 'test!' > /testfile",
  3495. })
  3496. if err != nil {
  3497. c.Fatal(err)
  3498. }
  3499. defer ctx.Close()
  3500. _, err = buildImageFromContext(name, ctx, true)
  3501. if err != nil {
  3502. c.Fatal(err)
  3503. }
  3504. }
  3505. func (s *DockerSuite) TestBuildAddTar(c *check.C) {
  3506. // /test/foo is not owned by the correct user
  3507. testRequires(c, NotUserNamespace)
  3508. name := "testbuildaddtar"
  3509. ctx := func() *FakeContext {
  3510. dockerfile := `
  3511. FROM busybox
  3512. ADD test.tar /
  3513. RUN cat /test/foo | grep Hi
  3514. ADD test.tar /test.tar
  3515. RUN cat /test.tar/test/foo | grep Hi
  3516. ADD test.tar /unlikely-to-exist
  3517. RUN cat /unlikely-to-exist/test/foo | grep Hi
  3518. ADD test.tar /unlikely-to-exist-trailing-slash/
  3519. RUN cat /unlikely-to-exist-trailing-slash/test/foo | grep Hi
  3520. RUN sh -c "mkdir /existing-directory" #sh -c is needed on Windows to use the correct mkdir
  3521. ADD test.tar /existing-directory
  3522. RUN cat /existing-directory/test/foo | grep Hi
  3523. ADD test.tar /existing-directory-trailing-slash/
  3524. RUN cat /existing-directory-trailing-slash/test/foo | grep Hi`
  3525. tmpDir, err := ioutil.TempDir("", "fake-context")
  3526. c.Assert(err, check.IsNil)
  3527. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3528. if err != nil {
  3529. c.Fatalf("failed to create test.tar archive: %v", err)
  3530. }
  3531. defer testTar.Close()
  3532. tw := tar.NewWriter(testTar)
  3533. if err := tw.WriteHeader(&tar.Header{
  3534. Name: "test/foo",
  3535. Size: 2,
  3536. }); err != nil {
  3537. c.Fatalf("failed to write tar file header: %v", err)
  3538. }
  3539. if _, err := tw.Write([]byte("Hi")); err != nil {
  3540. c.Fatalf("failed to write tar file content: %v", err)
  3541. }
  3542. if err := tw.Close(); err != nil {
  3543. c.Fatalf("failed to close tar archive: %v", err)
  3544. }
  3545. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3546. c.Fatalf("failed to open destination dockerfile: %v", err)
  3547. }
  3548. return fakeContextFromDir(tmpDir)
  3549. }()
  3550. defer ctx.Close()
  3551. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3552. c.Fatalf("build failed to complete for TestBuildAddTar: %v", err)
  3553. }
  3554. }
  3555. func (s *DockerSuite) TestBuildAddBrokenTar(c *check.C) {
  3556. name := "testbuildaddbrokentar"
  3557. ctx := func() *FakeContext {
  3558. dockerfile := `
  3559. FROM busybox
  3560. ADD test.tar /`
  3561. tmpDir, err := ioutil.TempDir("", "fake-context")
  3562. c.Assert(err, check.IsNil)
  3563. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3564. if err != nil {
  3565. c.Fatalf("failed to create test.tar archive: %v", err)
  3566. }
  3567. defer testTar.Close()
  3568. tw := tar.NewWriter(testTar)
  3569. if err := tw.WriteHeader(&tar.Header{
  3570. Name: "test/foo",
  3571. Size: 2,
  3572. }); err != nil {
  3573. c.Fatalf("failed to write tar file header: %v", err)
  3574. }
  3575. if _, err := tw.Write([]byte("Hi")); err != nil {
  3576. c.Fatalf("failed to write tar file content: %v", err)
  3577. }
  3578. if err := tw.Close(); err != nil {
  3579. c.Fatalf("failed to close tar archive: %v", err)
  3580. }
  3581. // Corrupt the tar by removing one byte off the end
  3582. stat, err := testTar.Stat()
  3583. if err != nil {
  3584. c.Fatalf("failed to stat tar archive: %v", err)
  3585. }
  3586. if err := testTar.Truncate(stat.Size() - 1); err != nil {
  3587. c.Fatalf("failed to truncate tar archive: %v", err)
  3588. }
  3589. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3590. c.Fatalf("failed to open destination dockerfile: %v", err)
  3591. }
  3592. return fakeContextFromDir(tmpDir)
  3593. }()
  3594. defer ctx.Close()
  3595. if _, err := buildImageFromContext(name, ctx, true); err == nil {
  3596. c.Fatalf("build should have failed for TestBuildAddBrokenTar")
  3597. }
  3598. }
  3599. func (s *DockerSuite) TestBuildAddNonTar(c *check.C) {
  3600. name := "testbuildaddnontar"
  3601. // Should not try to extract test.tar
  3602. ctx, err := fakeContext(`
  3603. FROM busybox
  3604. ADD test.tar /
  3605. RUN test -f /test.tar`,
  3606. map[string]string{"test.tar": "not_a_tar_file"})
  3607. if err != nil {
  3608. c.Fatal(err)
  3609. }
  3610. defer ctx.Close()
  3611. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3612. c.Fatalf("build failed for TestBuildAddNonTar")
  3613. }
  3614. }
  3615. func (s *DockerSuite) TestBuildAddTarXz(c *check.C) {
  3616. // /test/foo is not owned by the correct user
  3617. testRequires(c, NotUserNamespace)
  3618. testRequires(c, DaemonIsLinux)
  3619. name := "testbuildaddtarxz"
  3620. ctx := func() *FakeContext {
  3621. dockerfile := `
  3622. FROM busybox
  3623. ADD test.tar.xz /
  3624. RUN cat /test/foo | grep Hi`
  3625. tmpDir, err := ioutil.TempDir("", "fake-context")
  3626. c.Assert(err, check.IsNil)
  3627. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3628. if err != nil {
  3629. c.Fatalf("failed to create test.tar archive: %v", err)
  3630. }
  3631. defer testTar.Close()
  3632. tw := tar.NewWriter(testTar)
  3633. if err := tw.WriteHeader(&tar.Header{
  3634. Name: "test/foo",
  3635. Size: 2,
  3636. }); err != nil {
  3637. c.Fatalf("failed to write tar file header: %v", err)
  3638. }
  3639. if _, err := tw.Write([]byte("Hi")); err != nil {
  3640. c.Fatalf("failed to write tar file content: %v", err)
  3641. }
  3642. if err := tw.Close(); err != nil {
  3643. c.Fatalf("failed to close tar archive: %v", err)
  3644. }
  3645. xzCompressCmd := exec.Command("xz", "-k", "test.tar")
  3646. xzCompressCmd.Dir = tmpDir
  3647. out, _, err := runCommandWithOutput(xzCompressCmd)
  3648. if err != nil {
  3649. c.Fatal(err, out)
  3650. }
  3651. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3652. c.Fatalf("failed to open destination dockerfile: %v", err)
  3653. }
  3654. return fakeContextFromDir(tmpDir)
  3655. }()
  3656. defer ctx.Close()
  3657. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3658. c.Fatalf("build failed to complete for TestBuildAddTarXz: %v", err)
  3659. }
  3660. }
  3661. func (s *DockerSuite) TestBuildAddTarXzGz(c *check.C) {
  3662. testRequires(c, DaemonIsLinux)
  3663. name := "testbuildaddtarxzgz"
  3664. ctx := func() *FakeContext {
  3665. dockerfile := `
  3666. FROM busybox
  3667. ADD test.tar.xz.gz /
  3668. RUN ls /test.tar.xz.gz`
  3669. tmpDir, err := ioutil.TempDir("", "fake-context")
  3670. c.Assert(err, check.IsNil)
  3671. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3672. if err != nil {
  3673. c.Fatalf("failed to create test.tar archive: %v", err)
  3674. }
  3675. defer testTar.Close()
  3676. tw := tar.NewWriter(testTar)
  3677. if err := tw.WriteHeader(&tar.Header{
  3678. Name: "test/foo",
  3679. Size: 2,
  3680. }); err != nil {
  3681. c.Fatalf("failed to write tar file header: %v", err)
  3682. }
  3683. if _, err := tw.Write([]byte("Hi")); err != nil {
  3684. c.Fatalf("failed to write tar file content: %v", err)
  3685. }
  3686. if err := tw.Close(); err != nil {
  3687. c.Fatalf("failed to close tar archive: %v", err)
  3688. }
  3689. xzCompressCmd := exec.Command("xz", "-k", "test.tar")
  3690. xzCompressCmd.Dir = tmpDir
  3691. out, _, err := runCommandWithOutput(xzCompressCmd)
  3692. if err != nil {
  3693. c.Fatal(err, out)
  3694. }
  3695. gzipCompressCmd := exec.Command("gzip", "test.tar.xz")
  3696. gzipCompressCmd.Dir = tmpDir
  3697. out, _, err = runCommandWithOutput(gzipCompressCmd)
  3698. if err != nil {
  3699. c.Fatal(err, out)
  3700. }
  3701. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3702. c.Fatalf("failed to open destination dockerfile: %v", err)
  3703. }
  3704. return fakeContextFromDir(tmpDir)
  3705. }()
  3706. defer ctx.Close()
  3707. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3708. c.Fatalf("build failed to complete for TestBuildAddTarXz: %v", err)
  3709. }
  3710. }
  3711. func (s *DockerSuite) TestBuildFromGIT(c *check.C) {
  3712. name := "testbuildfromgit"
  3713. git, err := newFakeGit("repo", map[string]string{
  3714. "Dockerfile": `FROM busybox
  3715. ADD first /first
  3716. RUN [ -f /first ]
  3717. MAINTAINER docker`,
  3718. "first": "test git data",
  3719. }, true)
  3720. if err != nil {
  3721. c.Fatal(err)
  3722. }
  3723. defer git.Close()
  3724. _, err = buildImageFromPath(name, git.RepoURL, true)
  3725. if err != nil {
  3726. c.Fatal(err)
  3727. }
  3728. res := inspectField(c, name, "Author")
  3729. if res != "docker" {
  3730. c.Fatalf("Maintainer should be docker, got %s", res)
  3731. }
  3732. }
  3733. func (s *DockerSuite) TestBuildFromGITWithContext(c *check.C) {
  3734. name := "testbuildfromgit"
  3735. git, err := newFakeGit("repo", map[string]string{
  3736. "docker/Dockerfile": `FROM busybox
  3737. ADD first /first
  3738. RUN [ -f /first ]
  3739. MAINTAINER docker`,
  3740. "docker/first": "test git data",
  3741. }, true)
  3742. if err != nil {
  3743. c.Fatal(err)
  3744. }
  3745. defer git.Close()
  3746. u := fmt.Sprintf("%s#master:docker", git.RepoURL)
  3747. _, err = buildImageFromPath(name, u, true)
  3748. if err != nil {
  3749. c.Fatal(err)
  3750. }
  3751. res := inspectField(c, name, "Author")
  3752. if res != "docker" {
  3753. c.Fatalf("Maintainer should be docker, got %s", res)
  3754. }
  3755. }
  3756. func (s *DockerSuite) TestBuildFromGITwithF(c *check.C) {
  3757. name := "testbuildfromgitwithf"
  3758. git, err := newFakeGit("repo", map[string]string{
  3759. "myApp/myDockerfile": `FROM busybox
  3760. RUN echo hi from Dockerfile`,
  3761. }, true)
  3762. if err != nil {
  3763. c.Fatal(err)
  3764. }
  3765. defer git.Close()
  3766. out, _, err := dockerCmdWithError("build", "-t", name, "--no-cache", "-f", "myApp/myDockerfile", git.RepoURL)
  3767. if err != nil {
  3768. c.Fatalf("Error on build. Out: %s\nErr: %v", out, err)
  3769. }
  3770. if !strings.Contains(out, "hi from Dockerfile") {
  3771. c.Fatalf("Missing expected output, got:\n%s", out)
  3772. }
  3773. }
  3774. func (s *DockerSuite) TestBuildFromRemoteTarball(c *check.C) {
  3775. testRequires(c, DaemonIsLinux)
  3776. name := "testbuildfromremotetarball"
  3777. buffer := new(bytes.Buffer)
  3778. tw := tar.NewWriter(buffer)
  3779. defer tw.Close()
  3780. dockerfile := []byte(`FROM busybox
  3781. MAINTAINER docker`)
  3782. if err := tw.WriteHeader(&tar.Header{
  3783. Name: "Dockerfile",
  3784. Size: int64(len(dockerfile)),
  3785. }); err != nil {
  3786. c.Fatalf("failed to write tar file header: %v", err)
  3787. }
  3788. if _, err := tw.Write(dockerfile); err != nil {
  3789. c.Fatalf("failed to write tar file content: %v", err)
  3790. }
  3791. if err := tw.Close(); err != nil {
  3792. c.Fatalf("failed to close tar archive: %v", err)
  3793. }
  3794. server, err := fakeBinaryStorage(map[string]*bytes.Buffer{
  3795. "testT.tar": buffer,
  3796. })
  3797. c.Assert(err, check.IsNil)
  3798. defer server.Close()
  3799. _, err = buildImageFromPath(name, server.URL()+"/testT.tar", true)
  3800. c.Assert(err, check.IsNil)
  3801. res := inspectField(c, name, "Author")
  3802. if res != "docker" {
  3803. c.Fatalf("Maintainer should be docker, got %s", res)
  3804. }
  3805. }
  3806. func (s *DockerSuite) TestBuildCleanupCmdOnEntrypoint(c *check.C) {
  3807. name := "testbuildcmdcleanuponentrypoint"
  3808. if _, err := buildImage(name,
  3809. `FROM `+minimalBaseImage()+`
  3810. CMD ["test"]
  3811. ENTRYPOINT ["echo"]`,
  3812. true); err != nil {
  3813. c.Fatal(err)
  3814. }
  3815. if _, err := buildImage(name,
  3816. fmt.Sprintf(`FROM %s
  3817. ENTRYPOINT ["cat"]`, name),
  3818. true); err != nil {
  3819. c.Fatal(err)
  3820. }
  3821. res := inspectField(c, name, "Config.Cmd")
  3822. if res != "[]" {
  3823. c.Fatalf("Cmd %s, expected nil", res)
  3824. }
  3825. res = inspectField(c, name, "Config.Entrypoint")
  3826. if expected := "[cat]"; res != expected {
  3827. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  3828. }
  3829. }
  3830. func (s *DockerSuite) TestBuildClearCmd(c *check.C) {
  3831. name := "testbuildclearcmd"
  3832. _, err := buildImage(name,
  3833. `From `+minimalBaseImage()+`
  3834. ENTRYPOINT ["/bin/bash"]
  3835. CMD []`,
  3836. true)
  3837. if err != nil {
  3838. c.Fatal(err)
  3839. }
  3840. res := inspectFieldJSON(c, name, "Config.Cmd")
  3841. if res != "[]" {
  3842. c.Fatalf("Cmd %s, expected %s", res, "[]")
  3843. }
  3844. }
  3845. func (s *DockerSuite) TestBuildEmptyCmd(c *check.C) {
  3846. name := "testbuildemptycmd"
  3847. if _, err := buildImage(name, "FROM "+minimalBaseImage()+"\nMAINTAINER quux\n", true); err != nil {
  3848. c.Fatal(err)
  3849. }
  3850. res := inspectFieldJSON(c, name, "Config.Cmd")
  3851. if res != "null" {
  3852. c.Fatalf("Cmd %s, expected %s", res, "null")
  3853. }
  3854. }
  3855. func (s *DockerSuite) TestBuildOnBuildOutput(c *check.C) {
  3856. name := "testbuildonbuildparent"
  3857. if _, err := buildImage(name, "FROM busybox\nONBUILD RUN echo foo\n", true); err != nil {
  3858. c.Fatal(err)
  3859. }
  3860. _, out, err := buildImageWithOut(name, "FROM "+name+"\nMAINTAINER quux\n", true)
  3861. if err != nil {
  3862. c.Fatal(err)
  3863. }
  3864. if !strings.Contains(out, "# Executing 1 build trigger") {
  3865. c.Fatal("failed to find the build trigger output", out)
  3866. }
  3867. }
  3868. func (s *DockerSuite) TestBuildInvalidTag(c *check.C) {
  3869. name := "abcd:" + stringutils.GenerateRandomAlphaOnlyString(200)
  3870. _, out, err := buildImageWithOut(name, "FROM "+minimalBaseImage()+"\nMAINTAINER quux\n", true)
  3871. // if the error doesn't check for illegal tag name, or the image is built
  3872. // then this should fail
  3873. if !strings.Contains(out, "Error parsing reference") || strings.Contains(out, "Sending build context to Docker daemon") {
  3874. c.Fatalf("failed to stop before building. Error: %s, Output: %s", err, out)
  3875. }
  3876. }
  3877. func (s *DockerSuite) TestBuildCmdShDashC(c *check.C) {
  3878. name := "testbuildcmdshc"
  3879. if _, err := buildImage(name, "FROM busybox\nCMD echo cmd\n", true); err != nil {
  3880. c.Fatal(err)
  3881. }
  3882. res := inspectFieldJSON(c, name, "Config.Cmd")
  3883. expected := `["/bin/sh","-c","echo cmd"]`
  3884. if daemonPlatform == "windows" {
  3885. expected = `["cmd","/S","/C","echo cmd"]`
  3886. }
  3887. if res != expected {
  3888. c.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  3889. }
  3890. }
  3891. func (s *DockerSuite) TestBuildCmdSpaces(c *check.C) {
  3892. // Test to make sure that when we strcat arrays we take into account
  3893. // the arg separator to make sure ["echo","hi"] and ["echo hi"] don't
  3894. // look the same
  3895. name := "testbuildcmdspaces"
  3896. var id1 string
  3897. var id2 string
  3898. var err error
  3899. if id1, err = buildImage(name, "FROM busybox\nCMD [\"echo hi\"]\n", true); err != nil {
  3900. c.Fatal(err)
  3901. }
  3902. if id2, err = buildImage(name, "FROM busybox\nCMD [\"echo\", \"hi\"]\n", true); err != nil {
  3903. c.Fatal(err)
  3904. }
  3905. if id1 == id2 {
  3906. c.Fatal("Should not have resulted in the same CMD")
  3907. }
  3908. // Now do the same with ENTRYPOINT
  3909. if id1, err = buildImage(name, "FROM busybox\nENTRYPOINT [\"echo hi\"]\n", true); err != nil {
  3910. c.Fatal(err)
  3911. }
  3912. if id2, err = buildImage(name, "FROM busybox\nENTRYPOINT [\"echo\", \"hi\"]\n", true); err != nil {
  3913. c.Fatal(err)
  3914. }
  3915. if id1 == id2 {
  3916. c.Fatal("Should not have resulted in the same ENTRYPOINT")
  3917. }
  3918. }
  3919. func (s *DockerSuite) TestBuildCmdJSONNoShDashC(c *check.C) {
  3920. name := "testbuildcmdjson"
  3921. if _, err := buildImage(name, "FROM busybox\nCMD [\"echo\", \"cmd\"]", true); err != nil {
  3922. c.Fatal(err)
  3923. }
  3924. res := inspectFieldJSON(c, name, "Config.Cmd")
  3925. expected := `["echo","cmd"]`
  3926. if res != expected {
  3927. c.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  3928. }
  3929. }
  3930. func (s *DockerSuite) TestBuildErrorInvalidInstruction(c *check.C) {
  3931. name := "testbuildignoreinvalidinstruction"
  3932. out, _, err := buildImageWithOut(name, "FROM busybox\nfoo bar", true)
  3933. if err == nil {
  3934. c.Fatalf("Should have failed: %s", out)
  3935. }
  3936. }
  3937. func (s *DockerSuite) TestBuildEntrypointInheritance(c *check.C) {
  3938. if _, err := buildImage("parent", `
  3939. FROM busybox
  3940. ENTRYPOINT exit 130
  3941. `, true); err != nil {
  3942. c.Fatal(err)
  3943. }
  3944. if _, status, _ := dockerCmdWithError("run", "parent"); status != 130 {
  3945. c.Fatalf("expected exit code 130 but received %d", status)
  3946. }
  3947. if _, err := buildImage("child", `
  3948. FROM parent
  3949. ENTRYPOINT exit 5
  3950. `, true); err != nil {
  3951. c.Fatal(err)
  3952. }
  3953. if _, status, _ := dockerCmdWithError("run", "child"); status != 5 {
  3954. c.Fatalf("expected exit code 5 but received %d", status)
  3955. }
  3956. }
  3957. func (s *DockerSuite) TestBuildEntrypointInheritanceInspect(c *check.C) {
  3958. var (
  3959. name = "testbuildepinherit"
  3960. name2 = "testbuildepinherit2"
  3961. expected = `["/bin/sh","-c","echo quux"]`
  3962. )
  3963. if daemonPlatform == "windows" {
  3964. expected = `["cmd","/S","/C","echo quux"]`
  3965. }
  3966. if _, err := buildImage(name, "FROM busybox\nENTRYPOINT /foo/bar", true); err != nil {
  3967. c.Fatal(err)
  3968. }
  3969. if _, err := buildImage(name2, fmt.Sprintf("FROM %s\nENTRYPOINT echo quux", name), true); err != nil {
  3970. c.Fatal(err)
  3971. }
  3972. res := inspectFieldJSON(c, name2, "Config.Entrypoint")
  3973. if res != expected {
  3974. c.Fatalf("Expected value %s not in Config.Entrypoint: %s", expected, res)
  3975. }
  3976. out, _ := dockerCmd(c, "run", name2)
  3977. expected = "quux"
  3978. if strings.TrimSpace(out) != expected {
  3979. c.Fatalf("Expected output is %s, got %s", expected, out)
  3980. }
  3981. }
  3982. func (s *DockerSuite) TestBuildRunShEntrypoint(c *check.C) {
  3983. name := "testbuildentrypoint"
  3984. _, err := buildImage(name,
  3985. `FROM busybox
  3986. ENTRYPOINT echo`,
  3987. true)
  3988. if err != nil {
  3989. c.Fatal(err)
  3990. }
  3991. dockerCmd(c, "run", "--rm", name)
  3992. }
  3993. func (s *DockerSuite) TestBuildExoticShellInterpolation(c *check.C) {
  3994. testRequires(c, DaemonIsLinux)
  3995. name := "testbuildexoticshellinterpolation"
  3996. _, err := buildImage(name, `
  3997. FROM busybox
  3998. ENV SOME_VAR a.b.c
  3999. RUN [ "$SOME_VAR" = 'a.b.c' ]
  4000. RUN [ "${SOME_VAR}" = 'a.b.c' ]
  4001. RUN [ "${SOME_VAR%.*}" = 'a.b' ]
  4002. RUN [ "${SOME_VAR%%.*}" = 'a' ]
  4003. RUN [ "${SOME_VAR#*.}" = 'b.c' ]
  4004. RUN [ "${SOME_VAR##*.}" = 'c' ]
  4005. RUN [ "${SOME_VAR/c/d}" = 'a.b.d' ]
  4006. RUN [ "${#SOME_VAR}" = '5' ]
  4007. RUN [ "${SOME_UNSET_VAR:-$SOME_VAR}" = 'a.b.c' ]
  4008. RUN [ "${SOME_VAR:+Version: ${SOME_VAR}}" = 'Version: a.b.c' ]
  4009. RUN [ "${SOME_UNSET_VAR:+${SOME_VAR}}" = '' ]
  4010. RUN [ "${SOME_UNSET_VAR:-${SOME_VAR:-d.e.f}}" = 'a.b.c' ]
  4011. `, false)
  4012. if err != nil {
  4013. c.Fatal(err)
  4014. }
  4015. }
  4016. func (s *DockerSuite) TestBuildVerifySingleQuoteFails(c *check.C) {
  4017. // This testcase is supposed to generate an error because the
  4018. // JSON array we're passing in on the CMD uses single quotes instead
  4019. // of double quotes (per the JSON spec). This means we interpret it
  4020. // as a "string" instead of "JSON array" and pass it on to "sh -c" and
  4021. // it should barf on it.
  4022. name := "testbuildsinglequotefails"
  4023. if _, err := buildImage(name,
  4024. `FROM busybox
  4025. CMD [ '/bin/sh', '-c', 'echo hi' ]`,
  4026. true); err != nil {
  4027. c.Fatal(err)
  4028. }
  4029. if _, _, err := dockerCmdWithError("run", "--rm", name); err == nil {
  4030. c.Fatal("The image was not supposed to be able to run")
  4031. }
  4032. }
  4033. func (s *DockerSuite) TestBuildVerboseOut(c *check.C) {
  4034. name := "testbuildverboseout"
  4035. expected := "\n123\n"
  4036. if daemonPlatform == "windows" {
  4037. expected = "\n123\r\n"
  4038. }
  4039. _, out, err := buildImageWithOut(name,
  4040. `FROM busybox
  4041. RUN echo 123`,
  4042. false)
  4043. if err != nil {
  4044. c.Fatal(err)
  4045. }
  4046. if !strings.Contains(out, expected) {
  4047. c.Fatalf("Output should contain %q: %q", "123", out)
  4048. }
  4049. }
  4050. func (s *DockerSuite) TestBuildWithTabs(c *check.C) {
  4051. name := "testbuildwithtabs"
  4052. _, err := buildImage(name,
  4053. "FROM busybox\nRUN echo\tone\t\ttwo", true)
  4054. if err != nil {
  4055. c.Fatal(err)
  4056. }
  4057. res := inspectFieldJSON(c, name, "ContainerConfig.Cmd")
  4058. expected1 := `["/bin/sh","-c","echo\tone\t\ttwo"]`
  4059. expected2 := `["/bin/sh","-c","echo\u0009one\u0009\u0009two"]` // syntactically equivalent, and what Go 1.3 generates
  4060. if daemonPlatform == "windows" {
  4061. expected1 = `["cmd","/S","/C","echo\tone\t\ttwo"]`
  4062. expected2 = `["cmd","/S","/C","echo\u0009one\u0009\u0009two"]` // syntactically equivalent, and what Go 1.3 generates
  4063. }
  4064. if res != expected1 && res != expected2 {
  4065. c.Fatalf("Missing tabs.\nGot: %s\nExp: %s or %s", res, expected1, expected2)
  4066. }
  4067. }
  4068. func (s *DockerSuite) TestBuildLabels(c *check.C) {
  4069. name := "testbuildlabel"
  4070. expected := `{"License":"GPL","Vendor":"Acme"}`
  4071. _, err := buildImage(name,
  4072. `FROM busybox
  4073. LABEL Vendor=Acme
  4074. LABEL License GPL`,
  4075. true)
  4076. if err != nil {
  4077. c.Fatal(err)
  4078. }
  4079. res := inspectFieldJSON(c, name, "Config.Labels")
  4080. if res != expected {
  4081. c.Fatalf("Labels %s, expected %s", res, expected)
  4082. }
  4083. }
  4084. func (s *DockerSuite) TestBuildLabelsCache(c *check.C) {
  4085. name := "testbuildlabelcache"
  4086. id1, err := buildImage(name,
  4087. `FROM busybox
  4088. LABEL Vendor=Acme`, false)
  4089. if err != nil {
  4090. c.Fatalf("Build 1 should have worked: %v", err)
  4091. }
  4092. id2, err := buildImage(name,
  4093. `FROM busybox
  4094. LABEL Vendor=Acme`, true)
  4095. if err != nil || id1 != id2 {
  4096. c.Fatalf("Build 2 should have worked & used cache(%s,%s): %v", id1, id2, err)
  4097. }
  4098. id2, err = buildImage(name,
  4099. `FROM busybox
  4100. LABEL Vendor=Acme1`, true)
  4101. if err != nil || id1 == id2 {
  4102. c.Fatalf("Build 3 should have worked & NOT used cache(%s,%s): %v", id1, id2, err)
  4103. }
  4104. id2, err = buildImage(name,
  4105. `FROM busybox
  4106. LABEL Vendor Acme`, true) // Note: " " and "=" should be same
  4107. if err != nil || id1 != id2 {
  4108. c.Fatalf("Build 4 should have worked & used cache(%s,%s): %v", id1, id2, err)
  4109. }
  4110. // Now make sure the cache isn't used by mistake
  4111. id1, err = buildImage(name,
  4112. `FROM busybox
  4113. LABEL f1=b1 f2=b2`, false)
  4114. if err != nil {
  4115. c.Fatalf("Build 5 should have worked: %q", err)
  4116. }
  4117. id2, err = buildImage(name,
  4118. `FROM busybox
  4119. LABEL f1="b1 f2=b2"`, true)
  4120. if err != nil || id1 == id2 {
  4121. c.Fatalf("Build 6 should have worked & NOT used the cache(%s,%s): %q", id1, id2, err)
  4122. }
  4123. }
  4124. func (s *DockerSuite) TestBuildNotVerboseSuccess(c *check.C) {
  4125. // This test makes sure that -q works correctly when build is successful:
  4126. // stdout has only the image ID (long image ID) and stderr is empty.
  4127. var stdout, stderr string
  4128. var err error
  4129. outRegexp := regexp.MustCompile("^(sha256:|)[a-z0-9]{64}\\n$")
  4130. tt := []struct {
  4131. Name string
  4132. BuildFunc func(string)
  4133. }{
  4134. {
  4135. Name: "quiet_build_stdin_success",
  4136. BuildFunc: func(name string) {
  4137. _, stdout, stderr, err = buildImageWithStdoutStderr(name, "FROM busybox", true, "-q", "--force-rm", "--rm")
  4138. },
  4139. },
  4140. {
  4141. Name: "quiet_build_ctx_success",
  4142. BuildFunc: func(name string) {
  4143. ctx, err := fakeContext("FROM busybox", map[string]string{
  4144. "quiet_build_success_fctx": "test",
  4145. })
  4146. if err != nil {
  4147. c.Fatalf("Failed to create context: %s", err.Error())
  4148. }
  4149. defer ctx.Close()
  4150. _, stdout, stderr, err = buildImageFromContextWithStdoutStderr(name, ctx, true, "-q", "--force-rm", "--rm")
  4151. },
  4152. },
  4153. {
  4154. Name: "quiet_build_git_success",
  4155. BuildFunc: func(name string) {
  4156. git, err := newFakeGit("repo", map[string]string{
  4157. "Dockerfile": "FROM busybox",
  4158. }, true)
  4159. if err != nil {
  4160. c.Fatalf("Failed to create the git repo: %s", err.Error())
  4161. }
  4162. defer git.Close()
  4163. _, stdout, stderr, err = buildImageFromGitWithStdoutStderr(name, git, true, "-q", "--force-rm", "--rm")
  4164. },
  4165. },
  4166. }
  4167. for _, te := range tt {
  4168. te.BuildFunc(te.Name)
  4169. if err != nil {
  4170. c.Fatalf("Test %s shouldn't fail, but got the following error: %s", te.Name, err.Error())
  4171. }
  4172. if outRegexp.Find([]byte(stdout)) == nil {
  4173. c.Fatalf("Test %s expected stdout to match the [%v] regexp, but it is [%v]", te.Name, outRegexp, stdout)
  4174. }
  4175. if runtime.GOOS == "windows" {
  4176. // stderr contains a security warning on Windows if the daemon isn't Windows
  4177. lines := strings.Split(stderr, "\n")
  4178. warningCount := 0
  4179. for _, v := range lines {
  4180. warningText := "SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host."
  4181. if strings.Contains(v, warningText) {
  4182. warningCount++
  4183. }
  4184. if v != "" && !strings.Contains(v, warningText) {
  4185. c.Fatalf("Stderr contains unexpected output line: %q", v)
  4186. }
  4187. }
  4188. if warningCount != 1 && daemonPlatform != "windows" {
  4189. c.Fatalf("Test %s didn't get security warning running from Windows to non-Windows", te.Name)
  4190. }
  4191. } else {
  4192. if stderr != "" {
  4193. c.Fatalf("Test %s expected stderr to be empty, but it is [%#v]", te.Name, stderr)
  4194. }
  4195. }
  4196. }
  4197. }
  4198. func (s *DockerSuite) TestBuildNotVerboseFailure(c *check.C) {
  4199. // This test makes sure that -q works correctly when build fails by
  4200. // comparing between the stderr output in quiet mode and in stdout
  4201. // and stderr output in verbose mode
  4202. tt := []struct {
  4203. TestName string
  4204. BuildCmds string
  4205. }{
  4206. {"quiet_build_no_from_at_the_beginning", "RUN whoami"},
  4207. {"quiet_build_unknown_instr", "FROMD busybox"},
  4208. {"quiet_build_not_exists_image", "FROM busybox11"},
  4209. }
  4210. for _, te := range tt {
  4211. _, _, qstderr, qerr := buildImageWithStdoutStderr(te.TestName, te.BuildCmds, false, "-q", "--force-rm", "--rm")
  4212. _, vstdout, vstderr, verr := buildImageWithStdoutStderr(te.TestName, te.BuildCmds, false, "--force-rm", "--rm")
  4213. if verr == nil || qerr == nil {
  4214. c.Fatal(fmt.Errorf("Test [%s] expected to fail but didn't", te.TestName))
  4215. }
  4216. if qstderr != vstdout+vstderr {
  4217. c.Fatal(fmt.Errorf("Test[%s] expected that quiet stderr and verbose stdout are equal; quiet [%v], verbose [%v]", te.TestName, qstderr, vstdout+vstderr))
  4218. }
  4219. }
  4220. }
  4221. func (s *DockerSuite) TestBuildNotVerboseFailureRemote(c *check.C) {
  4222. // This test ensures that when given a wrong URL, stderr in quiet mode and
  4223. // stdout and stderr in verbose mode are identical.
  4224. URL := "http://bla.bla.com"
  4225. Name := "quiet_build_wrong_remote"
  4226. _, _, qstderr, qerr := buildImageWithStdoutStderr(Name, "", false, "-q", "--force-rm", "--rm", URL)
  4227. _, vstdout, vstderr, verr := buildImageWithStdoutStderr(Name, "", false, "--force-rm", "--rm", URL)
  4228. if qerr == nil || verr == nil {
  4229. c.Fatal(fmt.Errorf("Test [%s] expected to fail but didn't", Name))
  4230. }
  4231. if qstderr != vstdout+vstderr {
  4232. c.Fatal(fmt.Errorf("Test[%s] expected that quiet stderr and verbose stdout are equal; quiet [%v], verbose [%v]", Name, qstderr, vstdout))
  4233. }
  4234. }
  4235. func (s *DockerSuite) TestBuildStderr(c *check.C) {
  4236. // This test just makes sure that no non-error output goes
  4237. // to stderr
  4238. name := "testbuildstderr"
  4239. _, _, stderr, err := buildImageWithStdoutStderr(name,
  4240. "FROM busybox\nRUN echo one", true)
  4241. if err != nil {
  4242. c.Fatal(err)
  4243. }
  4244. if runtime.GOOS == "windows" {
  4245. // stderr might contain a security warning on windows
  4246. lines := strings.Split(stderr, "\n")
  4247. for _, v := range lines {
  4248. if v != "" && !strings.Contains(v, "SECURITY WARNING:") {
  4249. c.Fatalf("Stderr contains unexpected output line: %q", v)
  4250. }
  4251. }
  4252. } else {
  4253. if stderr != "" {
  4254. c.Fatalf("Stderr should have been empty, instead its: %q", stderr)
  4255. }
  4256. }
  4257. }
  4258. func (s *DockerSuite) TestBuildChownSingleFile(c *check.C) {
  4259. testRequires(c, UnixCli) // test uses chown: not available on windows
  4260. testRequires(c, DaemonIsLinux)
  4261. name := "testbuildchownsinglefile"
  4262. ctx, err := fakeContext(`
  4263. FROM busybox
  4264. COPY test /
  4265. RUN ls -l /test
  4266. RUN [ $(ls -l /test | awk '{print $3":"$4}') = 'root:root' ]
  4267. `, map[string]string{
  4268. "test": "test",
  4269. })
  4270. if err != nil {
  4271. c.Fatal(err)
  4272. }
  4273. defer ctx.Close()
  4274. if err := os.Chown(filepath.Join(ctx.Dir, "test"), 4242, 4242); err != nil {
  4275. c.Fatal(err)
  4276. }
  4277. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  4278. c.Fatal(err)
  4279. }
  4280. }
  4281. func (s *DockerSuite) TestBuildSymlinkBreakout(c *check.C) {
  4282. name := "testbuildsymlinkbreakout"
  4283. tmpdir, err := ioutil.TempDir("", name)
  4284. c.Assert(err, check.IsNil)
  4285. defer os.RemoveAll(tmpdir)
  4286. ctx := filepath.Join(tmpdir, "context")
  4287. if err := os.MkdirAll(ctx, 0755); err != nil {
  4288. c.Fatal(err)
  4289. }
  4290. if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte(`
  4291. from busybox
  4292. add symlink.tar /
  4293. add inject /symlink/
  4294. `), 0644); err != nil {
  4295. c.Fatal(err)
  4296. }
  4297. inject := filepath.Join(ctx, "inject")
  4298. if err := ioutil.WriteFile(inject, nil, 0644); err != nil {
  4299. c.Fatal(err)
  4300. }
  4301. f, err := os.Create(filepath.Join(ctx, "symlink.tar"))
  4302. if err != nil {
  4303. c.Fatal(err)
  4304. }
  4305. w := tar.NewWriter(f)
  4306. w.WriteHeader(&tar.Header{
  4307. Name: "symlink2",
  4308. Typeflag: tar.TypeSymlink,
  4309. Linkname: "/../../../../../../../../../../../../../../",
  4310. Uid: os.Getuid(),
  4311. Gid: os.Getgid(),
  4312. })
  4313. w.WriteHeader(&tar.Header{
  4314. Name: "symlink",
  4315. Typeflag: tar.TypeSymlink,
  4316. Linkname: filepath.Join("symlink2", tmpdir),
  4317. Uid: os.Getuid(),
  4318. Gid: os.Getgid(),
  4319. })
  4320. w.Close()
  4321. f.Close()
  4322. if _, err := buildImageFromContext(name, fakeContextFromDir(ctx), false); err != nil {
  4323. c.Fatal(err)
  4324. }
  4325. if _, err := os.Lstat(filepath.Join(tmpdir, "inject")); err == nil {
  4326. c.Fatal("symlink breakout - inject")
  4327. } else if !os.IsNotExist(err) {
  4328. c.Fatalf("unexpected error: %v", err)
  4329. }
  4330. }
  4331. func (s *DockerSuite) TestBuildXZHost(c *check.C) {
  4332. // /usr/local/sbin/xz gets permission denied for the user
  4333. testRequires(c, NotUserNamespace)
  4334. testRequires(c, DaemonIsLinux)
  4335. name := "testbuildxzhost"
  4336. ctx, err := fakeContext(`
  4337. FROM busybox
  4338. ADD xz /usr/local/sbin/
  4339. RUN chmod 755 /usr/local/sbin/xz
  4340. ADD test.xz /
  4341. RUN [ ! -e /injected ]`,
  4342. map[string]string{
  4343. "test.xz": "\xfd\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00" +
  4344. "\x21\x01\x16\x00\x00\x00\x74\x2f\xe5\xa3\x01\x00\x3f\xfd" +
  4345. "\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00\x21",
  4346. "xz": "#!/bin/sh\ntouch /injected",
  4347. })
  4348. if err != nil {
  4349. c.Fatal(err)
  4350. }
  4351. defer ctx.Close()
  4352. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  4353. c.Fatal(err)
  4354. }
  4355. }
  4356. func (s *DockerSuite) TestBuildVolumesRetainContents(c *check.C) {
  4357. // /foo/file gets permission denied for the user
  4358. testRequires(c, NotUserNamespace)
  4359. testRequires(c, DaemonIsLinux) // TODO Windows: Issue #20127
  4360. var (
  4361. name = "testbuildvolumescontent"
  4362. expected = "some text"
  4363. volName = "/foo"
  4364. )
  4365. if daemonPlatform == "windows" {
  4366. volName = "C:/foo"
  4367. }
  4368. ctx, err := fakeContext(`
  4369. FROM busybox
  4370. COPY content /foo/file
  4371. VOLUME `+volName+`
  4372. CMD cat /foo/file`,
  4373. map[string]string{
  4374. "content": expected,
  4375. })
  4376. if err != nil {
  4377. c.Fatal(err)
  4378. }
  4379. defer ctx.Close()
  4380. if _, err := buildImageFromContext(name, ctx, false); err != nil {
  4381. c.Fatal(err)
  4382. }
  4383. out, _ := dockerCmd(c, "run", "--rm", name)
  4384. if out != expected {
  4385. c.Fatalf("expected file contents for /foo/file to be %q but received %q", expected, out)
  4386. }
  4387. }
  4388. func (s *DockerSuite) TestBuildRenamedDockerfile(c *check.C) {
  4389. ctx, err := fakeContext(`FROM busybox
  4390. RUN echo from Dockerfile`,
  4391. map[string]string{
  4392. "Dockerfile": "FROM busybox\nRUN echo from Dockerfile",
  4393. "files/Dockerfile": "FROM busybox\nRUN echo from files/Dockerfile",
  4394. "files/dFile": "FROM busybox\nRUN echo from files/dFile",
  4395. "dFile": "FROM busybox\nRUN echo from dFile",
  4396. "files/dFile2": "FROM busybox\nRUN echo from files/dFile2",
  4397. })
  4398. if err != nil {
  4399. c.Fatal(err)
  4400. }
  4401. defer ctx.Close()
  4402. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", "test1", ".")
  4403. if err != nil {
  4404. c.Fatalf("Failed to build: %s\n%s", out, err)
  4405. }
  4406. if !strings.Contains(out, "from Dockerfile") {
  4407. c.Fatalf("test1 should have used Dockerfile, output:%s", out)
  4408. }
  4409. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", "-f", filepath.Join("files", "Dockerfile"), "-t", "test2", ".")
  4410. if err != nil {
  4411. c.Fatal(err)
  4412. }
  4413. if !strings.Contains(out, "from files/Dockerfile") {
  4414. c.Fatalf("test2 should have used files/Dockerfile, output:%s", out)
  4415. }
  4416. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", fmt.Sprintf("--file=%s", filepath.Join("files", "dFile")), "-t", "test3", ".")
  4417. if err != nil {
  4418. c.Fatal(err)
  4419. }
  4420. if !strings.Contains(out, "from files/dFile") {
  4421. c.Fatalf("test3 should have used files/dFile, output:%s", out)
  4422. }
  4423. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", "--file=dFile", "-t", "test4", ".")
  4424. if err != nil {
  4425. c.Fatal(err)
  4426. }
  4427. if !strings.Contains(out, "from dFile") {
  4428. c.Fatalf("test4 should have used dFile, output:%s", out)
  4429. }
  4430. dirWithNoDockerfile, err := ioutil.TempDir(os.TempDir(), "test5")
  4431. c.Assert(err, check.IsNil)
  4432. nonDockerfileFile := filepath.Join(dirWithNoDockerfile, "notDockerfile")
  4433. if _, err = os.Create(nonDockerfileFile); err != nil {
  4434. c.Fatal(err)
  4435. }
  4436. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", fmt.Sprintf("--file=%s", nonDockerfileFile), "-t", "test5", ".")
  4437. if err == nil {
  4438. c.Fatalf("test5 was supposed to fail to find passwd")
  4439. }
  4440. if expected := fmt.Sprintf("The Dockerfile (%s) must be within the build context (.)", nonDockerfileFile); !strings.Contains(out, expected) {
  4441. c.Fatalf("wrong error messsage:%v\nexpected to contain=%v", out, expected)
  4442. }
  4443. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join("..", "Dockerfile"), "-t", "test6", "..")
  4444. if err != nil {
  4445. c.Fatalf("test6 failed: %s", err)
  4446. }
  4447. if !strings.Contains(out, "from Dockerfile") {
  4448. c.Fatalf("test6 should have used root Dockerfile, output:%s", out)
  4449. }
  4450. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join(ctx.Dir, "files", "Dockerfile"), "-t", "test7", "..")
  4451. if err != nil {
  4452. c.Fatalf("test7 failed: %s", err)
  4453. }
  4454. if !strings.Contains(out, "from files/Dockerfile") {
  4455. c.Fatalf("test7 should have used files Dockerfile, output:%s", out)
  4456. }
  4457. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join("..", "Dockerfile"), "-t", "test8", ".")
  4458. if err == nil || !strings.Contains(out, "must be within the build context") {
  4459. c.Fatalf("test8 should have failed with Dockerfile out of context: %s", err)
  4460. }
  4461. tmpDir := os.TempDir()
  4462. out, _, err = dockerCmdInDir(c, tmpDir, "build", "-t", "test9", ctx.Dir)
  4463. if err != nil {
  4464. c.Fatalf("test9 - failed: %s", err)
  4465. }
  4466. if !strings.Contains(out, "from Dockerfile") {
  4467. c.Fatalf("test9 should have used root Dockerfile, output:%s", out)
  4468. }
  4469. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", "dFile2", "-t", "test10", ".")
  4470. if err != nil {
  4471. c.Fatalf("test10 should have worked: %s", err)
  4472. }
  4473. if !strings.Contains(out, "from files/dFile2") {
  4474. c.Fatalf("test10 should have used files/dFile2, output:%s", out)
  4475. }
  4476. }
  4477. func (s *DockerSuite) TestBuildFromMixedcaseDockerfile(c *check.C) {
  4478. testRequires(c, UnixCli) // Dockerfile overwrites dockerfile on windows
  4479. testRequires(c, DaemonIsLinux)
  4480. ctx, err := fakeContext(`FROM busybox
  4481. RUN echo from dockerfile`,
  4482. map[string]string{
  4483. "dockerfile": "FROM busybox\nRUN echo from dockerfile",
  4484. })
  4485. if err != nil {
  4486. c.Fatal(err)
  4487. }
  4488. defer ctx.Close()
  4489. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", "test1", ".")
  4490. if err != nil {
  4491. c.Fatalf("Failed to build: %s\n%s", out, err)
  4492. }
  4493. if !strings.Contains(out, "from dockerfile") {
  4494. c.Fatalf("Missing proper output: %s", out)
  4495. }
  4496. }
  4497. func (s *DockerSuite) TestBuildWithTwoDockerfiles(c *check.C) {
  4498. testRequires(c, UnixCli) // Dockerfile overwrites dockerfile on windows
  4499. testRequires(c, DaemonIsLinux)
  4500. ctx, err := fakeContext(`FROM busybox
  4501. RUN echo from Dockerfile`,
  4502. map[string]string{
  4503. "dockerfile": "FROM busybox\nRUN echo from dockerfile",
  4504. })
  4505. if err != nil {
  4506. c.Fatal(err)
  4507. }
  4508. defer ctx.Close()
  4509. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", "test1", ".")
  4510. if err != nil {
  4511. c.Fatalf("Failed to build: %s\n%s", out, err)
  4512. }
  4513. if !strings.Contains(out, "from Dockerfile") {
  4514. c.Fatalf("Missing proper output: %s", out)
  4515. }
  4516. }
  4517. func (s *DockerSuite) TestBuildFromURLWithF(c *check.C) {
  4518. testRequires(c, DaemonIsLinux)
  4519. server, err := fakeStorage(map[string]string{"baz": `FROM busybox
  4520. RUN echo from baz
  4521. COPY * /tmp/
  4522. RUN find /tmp/`})
  4523. if err != nil {
  4524. c.Fatal(err)
  4525. }
  4526. defer server.Close()
  4527. ctx, err := fakeContext(`FROM busybox
  4528. RUN echo from Dockerfile`,
  4529. map[string]string{})
  4530. if err != nil {
  4531. c.Fatal(err)
  4532. }
  4533. defer ctx.Close()
  4534. // Make sure that -f is ignored and that we don't use the Dockerfile
  4535. // that's in the current dir
  4536. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-f", "baz", "-t", "test1", server.URL()+"/baz")
  4537. if err != nil {
  4538. c.Fatalf("Failed to build: %s\n%s", out, err)
  4539. }
  4540. if !strings.Contains(out, "from baz") ||
  4541. strings.Contains(out, "/tmp/baz") ||
  4542. !strings.Contains(out, "/tmp/Dockerfile") {
  4543. c.Fatalf("Missing proper output: %s", out)
  4544. }
  4545. }
  4546. func (s *DockerSuite) TestBuildFromStdinWithF(c *check.C) {
  4547. testRequires(c, DaemonIsLinux) // TODO Windows: This test is flaky; no idea why
  4548. ctx, err := fakeContext(`FROM busybox
  4549. RUN echo "from Dockerfile"`,
  4550. map[string]string{})
  4551. if err != nil {
  4552. c.Fatal(err)
  4553. }
  4554. defer ctx.Close()
  4555. // Make sure that -f is ignored and that we don't use the Dockerfile
  4556. // that's in the current dir
  4557. dockerCommand := exec.Command(dockerBinary, "build", "-f", "baz", "-t", "test1", "-")
  4558. dockerCommand.Dir = ctx.Dir
  4559. dockerCommand.Stdin = strings.NewReader(`FROM busybox
  4560. RUN echo "from baz"
  4561. COPY * /tmp/
  4562. RUN sh -c "find /tmp/" # sh -c is needed on Windows to use the correct find`)
  4563. out, status, err := runCommandWithOutput(dockerCommand)
  4564. if err != nil || status != 0 {
  4565. c.Fatalf("Error building: %s", err)
  4566. }
  4567. if !strings.Contains(out, "from baz") ||
  4568. strings.Contains(out, "/tmp/baz") ||
  4569. !strings.Contains(out, "/tmp/Dockerfile") {
  4570. c.Fatalf("Missing proper output: %s", out)
  4571. }
  4572. }
  4573. func (s *DockerSuite) TestBuildFromOfficialNames(c *check.C) {
  4574. name := "testbuildfromofficial"
  4575. fromNames := []string{
  4576. "busybox",
  4577. "docker.io/busybox",
  4578. "index.docker.io/busybox",
  4579. "library/busybox",
  4580. "docker.io/library/busybox",
  4581. "index.docker.io/library/busybox",
  4582. }
  4583. for idx, fromName := range fromNames {
  4584. imgName := fmt.Sprintf("%s%d", name, idx)
  4585. _, err := buildImage(imgName, "FROM "+fromName, true)
  4586. if err != nil {
  4587. c.Errorf("Build failed using FROM %s: %s", fromName, err)
  4588. }
  4589. deleteImages(imgName)
  4590. }
  4591. }
  4592. func (s *DockerSuite) TestBuildDockerfileOutsideContext(c *check.C) {
  4593. testRequires(c, UnixCli) // uses os.Symlink: not implemented in windows at the time of writing (go-1.4.2)
  4594. testRequires(c, DaemonIsLinux)
  4595. name := "testbuilddockerfileoutsidecontext"
  4596. tmpdir, err := ioutil.TempDir("", name)
  4597. c.Assert(err, check.IsNil)
  4598. defer os.RemoveAll(tmpdir)
  4599. ctx := filepath.Join(tmpdir, "context")
  4600. if err := os.MkdirAll(ctx, 0755); err != nil {
  4601. c.Fatal(err)
  4602. }
  4603. if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte("FROM scratch\nENV X Y"), 0644); err != nil {
  4604. c.Fatal(err)
  4605. }
  4606. wd, err := os.Getwd()
  4607. if err != nil {
  4608. c.Fatal(err)
  4609. }
  4610. defer os.Chdir(wd)
  4611. if err := os.Chdir(ctx); err != nil {
  4612. c.Fatal(err)
  4613. }
  4614. if err := ioutil.WriteFile(filepath.Join(tmpdir, "outsideDockerfile"), []byte("FROM scratch\nENV x y"), 0644); err != nil {
  4615. c.Fatal(err)
  4616. }
  4617. if err := os.Symlink(filepath.Join("..", "outsideDockerfile"), filepath.Join(ctx, "dockerfile1")); err != nil {
  4618. c.Fatal(err)
  4619. }
  4620. if err := os.Symlink(filepath.Join(tmpdir, "outsideDockerfile"), filepath.Join(ctx, "dockerfile2")); err != nil {
  4621. c.Fatal(err)
  4622. }
  4623. for _, dockerfilePath := range []string{
  4624. filepath.Join("..", "outsideDockerfile"),
  4625. filepath.Join(ctx, "dockerfile1"),
  4626. filepath.Join(ctx, "dockerfile2"),
  4627. } {
  4628. out, _, err := dockerCmdWithError("build", "-t", name, "--no-cache", "-f", dockerfilePath, ".")
  4629. if err == nil {
  4630. c.Fatalf("Expected error with %s. Out: %s", dockerfilePath, out)
  4631. }
  4632. if !strings.Contains(out, "must be within the build context") && !strings.Contains(out, "Cannot locate Dockerfile") {
  4633. c.Fatalf("Unexpected error with %s. Out: %s", dockerfilePath, out)
  4634. }
  4635. deleteImages(name)
  4636. }
  4637. os.Chdir(tmpdir)
  4638. // Path to Dockerfile should be resolved relative to working directory, not relative to context.
  4639. // There is a Dockerfile in the context, but since there is no Dockerfile in the current directory, the following should fail
  4640. out, _, err := dockerCmdWithError("build", "-t", name, "--no-cache", "-f", "Dockerfile", ctx)
  4641. if err == nil {
  4642. c.Fatalf("Expected error. Out: %s", out)
  4643. }
  4644. }
  4645. func (s *DockerSuite) TestBuildSpaces(c *check.C) {
  4646. // Test to make sure that leading/trailing spaces on a command
  4647. // doesn't change the error msg we get
  4648. var (
  4649. err1 error
  4650. err2 error
  4651. )
  4652. name := "testspaces"
  4653. ctx, err := fakeContext("FROM busybox\nCOPY\n",
  4654. map[string]string{
  4655. "Dockerfile": "FROM busybox\nCOPY\n",
  4656. })
  4657. if err != nil {
  4658. c.Fatal(err)
  4659. }
  4660. defer ctx.Close()
  4661. if _, err1 = buildImageFromContext(name, ctx, false); err1 == nil {
  4662. c.Fatal("Build 1 was supposed to fail, but didn't")
  4663. }
  4664. ctx.Add("Dockerfile", "FROM busybox\nCOPY ")
  4665. if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil {
  4666. c.Fatal("Build 2 was supposed to fail, but didn't")
  4667. }
  4668. removeLogTimestamps := func(s string) string {
  4669. return regexp.MustCompile(`time="(.*?)"`).ReplaceAllString(s, `time=[TIMESTAMP]`)
  4670. }
  4671. // Skip over the times
  4672. e1 := removeLogTimestamps(err1.Error())
  4673. e2 := removeLogTimestamps(err2.Error())
  4674. // Ignore whitespace since that's what were verifying doesn't change stuff
  4675. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  4676. c.Fatalf("Build 2's error wasn't the same as build 1's\n1:%s\n2:%s", err1, err2)
  4677. }
  4678. ctx.Add("Dockerfile", "FROM busybox\n COPY")
  4679. if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil {
  4680. c.Fatal("Build 3 was supposed to fail, but didn't")
  4681. }
  4682. // Skip over the times
  4683. e1 = removeLogTimestamps(err1.Error())
  4684. e2 = removeLogTimestamps(err2.Error())
  4685. // Ignore whitespace since that's what were verifying doesn't change stuff
  4686. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  4687. c.Fatalf("Build 3's error wasn't the same as build 1's\n1:%s\n3:%s", err1, err2)
  4688. }
  4689. ctx.Add("Dockerfile", "FROM busybox\n COPY ")
  4690. if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil {
  4691. c.Fatal("Build 4 was supposed to fail, but didn't")
  4692. }
  4693. // Skip over the times
  4694. e1 = removeLogTimestamps(err1.Error())
  4695. e2 = removeLogTimestamps(err2.Error())
  4696. // Ignore whitespace since that's what were verifying doesn't change stuff
  4697. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  4698. c.Fatalf("Build 4's error wasn't the same as build 1's\n1:%s\n4:%s", err1, err2)
  4699. }
  4700. }
  4701. func (s *DockerSuite) TestBuildSpacesWithQuotes(c *check.C) {
  4702. testRequires(c, DaemonIsLinux)
  4703. // Test to make sure that spaces in quotes aren't lost
  4704. name := "testspacesquotes"
  4705. dockerfile := `FROM busybox
  4706. RUN echo " \
  4707. foo "`
  4708. _, out, err := buildImageWithOut(name, dockerfile, false)
  4709. if err != nil {
  4710. c.Fatal("Build failed:", err)
  4711. }
  4712. expecting := "\n foo \n"
  4713. if !strings.Contains(out, expecting) {
  4714. c.Fatalf("Bad output: %q expecting to contain %q", out, expecting)
  4715. }
  4716. }
  4717. // #4393
  4718. func (s *DockerSuite) TestBuildVolumeFileExistsinContainer(c *check.C) {
  4719. testRequires(c, DaemonIsLinux) // TODO Windows: This should error out
  4720. buildCmd := exec.Command(dockerBinary, "build", "-t", "docker-test-errcreatevolumewithfile", "-")
  4721. buildCmd.Stdin = strings.NewReader(`
  4722. FROM busybox
  4723. RUN touch /foo
  4724. VOLUME /foo
  4725. `)
  4726. out, _, err := runCommandWithOutput(buildCmd)
  4727. if err == nil || !strings.Contains(out, "file exists") {
  4728. c.Fatalf("expected build to fail when file exists in container at requested volume path")
  4729. }
  4730. }
  4731. func (s *DockerSuite) TestBuildMissingArgs(c *check.C) {
  4732. // Test to make sure that all Dockerfile commands (except the ones listed
  4733. // in skipCmds) will generate an error if no args are provided.
  4734. // Note: INSERT is deprecated so we exclude it because of that.
  4735. skipCmds := map[string]struct{}{
  4736. "CMD": {},
  4737. "RUN": {},
  4738. "ENTRYPOINT": {},
  4739. "INSERT": {},
  4740. }
  4741. if daemonPlatform == "windows" {
  4742. skipCmds = map[string]struct{}{
  4743. "CMD": {},
  4744. "RUN": {},
  4745. "ENTRYPOINT": {},
  4746. "INSERT": {},
  4747. "STOPSIGNAL": {},
  4748. "ARG": {},
  4749. "USER": {},
  4750. "EXPOSE": {},
  4751. }
  4752. }
  4753. for cmd := range command.Commands {
  4754. cmd = strings.ToUpper(cmd)
  4755. if _, ok := skipCmds[cmd]; ok {
  4756. continue
  4757. }
  4758. var dockerfile string
  4759. if cmd == "FROM" {
  4760. dockerfile = cmd
  4761. } else {
  4762. // Add FROM to make sure we don't complain about it missing
  4763. dockerfile = "FROM busybox\n" + cmd
  4764. }
  4765. ctx, err := fakeContext(dockerfile, map[string]string{})
  4766. if err != nil {
  4767. c.Fatal(err)
  4768. }
  4769. defer ctx.Close()
  4770. var out string
  4771. if out, err = buildImageFromContext("args", ctx, true); err == nil {
  4772. c.Fatalf("%s was supposed to fail. Out:%s", cmd, out)
  4773. }
  4774. if !strings.Contains(err.Error(), cmd+" requires") {
  4775. c.Fatalf("%s returned the wrong type of error:%s", cmd, err)
  4776. }
  4777. }
  4778. }
  4779. func (s *DockerSuite) TestBuildEmptyScratch(c *check.C) {
  4780. testRequires(c, DaemonIsLinux)
  4781. _, out, err := buildImageWithOut("sc", "FROM scratch", true)
  4782. if err == nil {
  4783. c.Fatalf("Build was supposed to fail")
  4784. }
  4785. if !strings.Contains(out, "No image was generated") {
  4786. c.Fatalf("Wrong error message: %v", out)
  4787. }
  4788. }
  4789. func (s *DockerSuite) TestBuildDotDotFile(c *check.C) {
  4790. ctx, err := fakeContext("FROM busybox\n",
  4791. map[string]string{
  4792. "..gitme": "",
  4793. })
  4794. if err != nil {
  4795. c.Fatal(err)
  4796. }
  4797. defer ctx.Close()
  4798. if _, err = buildImageFromContext("sc", ctx, false); err != nil {
  4799. c.Fatalf("Build was supposed to work: %s", err)
  4800. }
  4801. }
  4802. func (s *DockerSuite) TestBuildRUNoneJSON(c *check.C) {
  4803. testRequires(c, DaemonIsLinux) // No hello-world Windows image
  4804. name := "testbuildrunonejson"
  4805. ctx, err := fakeContext(`FROM hello-world:frozen
  4806. RUN [ "/hello" ]`, map[string]string{})
  4807. if err != nil {
  4808. c.Fatal(err)
  4809. }
  4810. defer ctx.Close()
  4811. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "--no-cache", "-t", name, ".")
  4812. if err != nil {
  4813. c.Fatalf("failed to build the image: %s, %v", out, err)
  4814. }
  4815. if !strings.Contains(out, "Hello from Docker") {
  4816. c.Fatalf("bad output: %s", out)
  4817. }
  4818. }
  4819. func (s *DockerSuite) TestBuildEmptyStringVolume(c *check.C) {
  4820. name := "testbuildemptystringvolume"
  4821. _, err := buildImage(name, `
  4822. FROM busybox
  4823. ENV foo=""
  4824. VOLUME $foo
  4825. `, false)
  4826. if err == nil {
  4827. c.Fatal("Should have failed to build")
  4828. }
  4829. }
  4830. func (s *DockerSuite) TestBuildContainerWithCgroupParent(c *check.C) {
  4831. testRequires(c, SameHostDaemon)
  4832. testRequires(c, DaemonIsLinux)
  4833. cgroupParent := "test"
  4834. data, err := ioutil.ReadFile("/proc/self/cgroup")
  4835. if err != nil {
  4836. c.Fatalf("failed to read '/proc/self/cgroup - %v", err)
  4837. }
  4838. selfCgroupPaths := parseCgroupPaths(string(data))
  4839. _, found := selfCgroupPaths["memory"]
  4840. if !found {
  4841. c.Fatalf("unable to find self memory cgroup path. CgroupsPath: %v", selfCgroupPaths)
  4842. }
  4843. cmd := exec.Command(dockerBinary, "build", "--cgroup-parent", cgroupParent, "-")
  4844. cmd.Stdin = strings.NewReader(`
  4845. FROM busybox
  4846. RUN cat /proc/self/cgroup
  4847. `)
  4848. out, _, err := runCommandWithOutput(cmd)
  4849. if err != nil {
  4850. c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err)
  4851. }
  4852. m, err := regexp.MatchString(fmt.Sprintf("memory:.*/%s/.*", cgroupParent), out)
  4853. c.Assert(err, check.IsNil)
  4854. if !m {
  4855. c.Fatalf("There is no expected memory cgroup with parent /%s/: %s", cgroupParent, out)
  4856. }
  4857. }
  4858. func (s *DockerSuite) TestBuildNoDupOutput(c *check.C) {
  4859. // Check to make sure our build output prints the Dockerfile cmd
  4860. // property - there was a bug that caused it to be duplicated on the
  4861. // Step X line
  4862. name := "testbuildnodupoutput"
  4863. _, out, err := buildImageWithOut(name, `
  4864. FROM busybox
  4865. RUN env`, false)
  4866. if err != nil {
  4867. c.Fatalf("Build should have worked: %q", err)
  4868. }
  4869. exp := "\nStep 2 : RUN env\n"
  4870. if !strings.Contains(out, exp) {
  4871. c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", out, exp)
  4872. }
  4873. }
  4874. // GH15826
  4875. func (s *DockerSuite) TestBuildStartsFromOne(c *check.C) {
  4876. // Explicit check to ensure that build starts from step 1 rather than 0
  4877. name := "testbuildstartsfromone"
  4878. _, out, err := buildImageWithOut(name, `
  4879. FROM busybox`, false)
  4880. if err != nil {
  4881. c.Fatalf("Build should have worked: %q", err)
  4882. }
  4883. exp := "\nStep 1 : FROM busybox\n"
  4884. if !strings.Contains(out, exp) {
  4885. c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", out, exp)
  4886. }
  4887. }
  4888. func (s *DockerSuite) TestBuildBadCmdFlag(c *check.C) {
  4889. name := "testbuildbadcmdflag"
  4890. _, out, err := buildImageWithOut(name, `
  4891. FROM busybox
  4892. MAINTAINER --boo joe@example.com`, false)
  4893. if err == nil {
  4894. c.Fatal("Build should have failed")
  4895. }
  4896. exp := "\nUnknown flag: boo\n"
  4897. if !strings.Contains(out, exp) {
  4898. c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", out, exp)
  4899. }
  4900. }
  4901. func (s *DockerSuite) TestBuildRUNErrMsg(c *check.C) {
  4902. // Test to make sure the bad command is quoted with just "s and
  4903. // not as a Go []string
  4904. name := "testbuildbadrunerrmsg"
  4905. _, out, err := buildImageWithOut(name, `
  4906. FROM busybox
  4907. RUN badEXE a1 \& a2 a3`, false) // tab between a2 and a3
  4908. if err == nil {
  4909. c.Fatal("Should have failed to build")
  4910. }
  4911. shell := "/bin/sh -c"
  4912. exitCode := "127"
  4913. if daemonPlatform == "windows" {
  4914. shell = "cmd /S /C"
  4915. // architectural - Windows has to start the container to determine the exe is bad, Linux does not
  4916. exitCode = "1"
  4917. }
  4918. exp := `The command '` + shell + ` badEXE a1 \& a2 a3' returned a non-zero code: ` + exitCode
  4919. if !strings.Contains(out, exp) {
  4920. c.Fatalf("RUN doesn't have the correct output:\nGot:%s\nExpected:%s", out, exp)
  4921. }
  4922. }
  4923. func (s *DockerTrustSuite) TestTrustedBuild(c *check.C) {
  4924. repoName := s.setupTrustedImage(c, "trusted-build")
  4925. dockerFile := fmt.Sprintf(`
  4926. FROM %s
  4927. RUN []
  4928. `, repoName)
  4929. name := "testtrustedbuild"
  4930. buildCmd := buildImageCmd(name, dockerFile, true)
  4931. s.trustedCmd(buildCmd)
  4932. out, _, err := runCommandWithOutput(buildCmd)
  4933. if err != nil {
  4934. c.Fatalf("Error running trusted build: %s\n%s", err, out)
  4935. }
  4936. if !strings.Contains(out, fmt.Sprintf("FROM %s@sha", repoName[:len(repoName)-7])) {
  4937. c.Fatalf("Unexpected output on trusted build:\n%s", out)
  4938. }
  4939. // We should also have a tag reference for the image.
  4940. if out, exitCode := dockerCmd(c, "inspect", repoName); exitCode != 0 {
  4941. c.Fatalf("unexpected exit code inspecting image %q: %d: %s", repoName, exitCode, out)
  4942. }
  4943. // We should now be able to remove the tag reference.
  4944. if out, exitCode := dockerCmd(c, "rmi", repoName); exitCode != 0 {
  4945. c.Fatalf("unexpected exit code inspecting image %q: %d: %s", repoName, exitCode, out)
  4946. }
  4947. }
  4948. func (s *DockerTrustSuite) TestTrustedBuildUntrustedTag(c *check.C) {
  4949. repoName := fmt.Sprintf("%v/dockercli/build-untrusted-tag:latest", privateRegistryURL)
  4950. dockerFile := fmt.Sprintf(`
  4951. FROM %s
  4952. RUN []
  4953. `, repoName)
  4954. name := "testtrustedbuilduntrustedtag"
  4955. buildCmd := buildImageCmd(name, dockerFile, true)
  4956. s.trustedCmd(buildCmd)
  4957. out, _, err := runCommandWithOutput(buildCmd)
  4958. if err == nil {
  4959. c.Fatalf("Expected error on trusted build with untrusted tag: %s\n%s", err, out)
  4960. }
  4961. if !strings.Contains(out, "does not have trust data for") {
  4962. c.Fatalf("Unexpected output on trusted build with untrusted tag:\n%s", out)
  4963. }
  4964. }
  4965. func (s *DockerTrustSuite) TestBuildContextDirIsSymlink(c *check.C) {
  4966. testRequires(c, DaemonIsLinux)
  4967. tempDir, err := ioutil.TempDir("", "test-build-dir-is-symlink-")
  4968. c.Assert(err, check.IsNil)
  4969. defer os.RemoveAll(tempDir)
  4970. // Make a real context directory in this temp directory with a simple
  4971. // Dockerfile.
  4972. realContextDirname := filepath.Join(tempDir, "context")
  4973. if err := os.Mkdir(realContextDirname, os.FileMode(0755)); err != nil {
  4974. c.Fatal(err)
  4975. }
  4976. if err = ioutil.WriteFile(
  4977. filepath.Join(realContextDirname, "Dockerfile"),
  4978. []byte(`
  4979. FROM busybox
  4980. RUN echo hello world
  4981. `),
  4982. os.FileMode(0644),
  4983. ); err != nil {
  4984. c.Fatal(err)
  4985. }
  4986. // Make a symlink to the real context directory.
  4987. contextSymlinkName := filepath.Join(tempDir, "context_link")
  4988. if err := os.Symlink(realContextDirname, contextSymlinkName); err != nil {
  4989. c.Fatal(err)
  4990. }
  4991. // Executing the build with the symlink as the specified context should
  4992. // *not* fail.
  4993. if out, exitStatus := dockerCmd(c, "build", contextSymlinkName); exitStatus != 0 {
  4994. c.Fatalf("build failed with exit status %d: %s", exitStatus, out)
  4995. }
  4996. }
  4997. // Issue #15634: COPY fails when path starts with "null"
  4998. func (s *DockerSuite) TestBuildNullStringInAddCopyVolume(c *check.C) {
  4999. name := "testbuildnullstringinaddcopyvolume"
  5000. volName := "nullvolume"
  5001. if daemonPlatform == "windows" {
  5002. volName = `C:\\nullvolume`
  5003. }
  5004. ctx, err := fakeContext(`
  5005. FROM busybox
  5006. ADD null /
  5007. COPY nullfile /
  5008. VOLUME `+volName+`
  5009. `,
  5010. map[string]string{
  5011. "null": "test1",
  5012. "nullfile": "test2",
  5013. },
  5014. )
  5015. c.Assert(err, check.IsNil)
  5016. defer ctx.Close()
  5017. _, err = buildImageFromContext(name, ctx, true)
  5018. c.Assert(err, check.IsNil)
  5019. }
  5020. func (s *DockerSuite) TestBuildStopSignal(c *check.C) {
  5021. testRequires(c, DaemonIsLinux) // Windows does not support STOPSIGNAL yet
  5022. imgName := "test_build_stop_signal"
  5023. _, err := buildImage(imgName,
  5024. `FROM busybox
  5025. STOPSIGNAL SIGKILL`,
  5026. true)
  5027. c.Assert(err, check.IsNil)
  5028. res := inspectFieldJSON(c, imgName, "Config.StopSignal")
  5029. if res != `"SIGKILL"` {
  5030. c.Fatalf("Signal %s, expected SIGKILL", res)
  5031. }
  5032. containerName := "test-container-stop-signal"
  5033. dockerCmd(c, "run", "-d", "--name", containerName, imgName, "top")
  5034. res = inspectFieldJSON(c, containerName, "Config.StopSignal")
  5035. if res != `"SIGKILL"` {
  5036. c.Fatalf("Signal %s, expected SIGKILL", res)
  5037. }
  5038. }
  5039. func (s *DockerSuite) TestBuildBuildTimeArg(c *check.C) {
  5040. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5041. imgName := "bldargtest"
  5042. envKey := "foo"
  5043. envVal := "bar"
  5044. args := []string{
  5045. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5046. }
  5047. dockerfile := fmt.Sprintf(`FROM busybox
  5048. ARG %s
  5049. RUN echo $%s
  5050. CMD echo $%s`, envKey, envKey, envKey)
  5051. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil || !strings.Contains(out, envVal) {
  5052. if err != nil {
  5053. c.Fatalf("build failed to complete: %q %q", out, err)
  5054. }
  5055. c.Fatalf("failed to access environment variable in output: %q expected: %q", out, envVal)
  5056. }
  5057. containerName := "bldargCont"
  5058. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); out != "\n" {
  5059. c.Fatalf("run produced invalid output: %q, expected empty string", out)
  5060. }
  5061. }
  5062. func (s *DockerSuite) TestBuildBuildTimeArgHistory(c *check.C) {
  5063. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5064. imgName := "bldargtest"
  5065. envKey := "foo"
  5066. envVal := "bar"
  5067. envDef := "bar1"
  5068. args := []string{
  5069. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5070. }
  5071. dockerfile := fmt.Sprintf(`FROM busybox
  5072. ARG %s=%s`, envKey, envDef)
  5073. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil || !strings.Contains(out, envVal) {
  5074. if err != nil {
  5075. c.Fatalf("build failed to complete: %q %q", out, err)
  5076. }
  5077. c.Fatalf("failed to access environment variable in output: %q expected: %q", out, envVal)
  5078. }
  5079. out, _ := dockerCmd(c, "history", "--no-trunc", imgName)
  5080. outputTabs := strings.Split(out, "\n")[1]
  5081. if !strings.Contains(outputTabs, envDef) {
  5082. c.Fatalf("failed to find arg default in image history output: %q expected: %q", outputTabs, envDef)
  5083. }
  5084. }
  5085. func (s *DockerSuite) TestBuildBuildTimeArgCacheHit(c *check.C) {
  5086. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5087. imgName := "bldargtest"
  5088. envKey := "foo"
  5089. envVal := "bar"
  5090. args := []string{
  5091. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5092. }
  5093. dockerfile := fmt.Sprintf(`FROM busybox
  5094. ARG %s
  5095. RUN echo $%s`, envKey, envKey)
  5096. origImgID := ""
  5097. var err error
  5098. if origImgID, err = buildImage(imgName, dockerfile, true, args...); err != nil {
  5099. c.Fatal(err)
  5100. }
  5101. imgNameCache := "bldargtestcachehit"
  5102. if newImgID, err := buildImage(imgNameCache, dockerfile, true, args...); err != nil || newImgID != origImgID {
  5103. if err != nil {
  5104. c.Fatal(err)
  5105. }
  5106. c.Fatalf("build didn't use cache! expected image id: %q built image id: %q", origImgID, newImgID)
  5107. }
  5108. }
  5109. func (s *DockerSuite) TestBuildBuildTimeArgCacheMissExtraArg(c *check.C) {
  5110. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5111. imgName := "bldargtest"
  5112. envKey := "foo"
  5113. envVal := "bar"
  5114. extraEnvKey := "foo1"
  5115. extraEnvVal := "bar1"
  5116. args := []string{
  5117. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5118. }
  5119. dockerfile := fmt.Sprintf(`FROM busybox
  5120. ARG %s
  5121. ARG %s
  5122. RUN echo $%s`, envKey, extraEnvKey, envKey)
  5123. origImgID := ""
  5124. var err error
  5125. if origImgID, err = buildImage(imgName, dockerfile, true, args...); err != nil {
  5126. c.Fatal(err)
  5127. }
  5128. imgNameCache := "bldargtestcachemiss"
  5129. args = append(args, "--build-arg", fmt.Sprintf("%s=%s", extraEnvKey, extraEnvVal))
  5130. if newImgID, err := buildImage(imgNameCache, dockerfile, true, args...); err != nil || newImgID == origImgID {
  5131. if err != nil {
  5132. c.Fatal(err)
  5133. }
  5134. c.Fatalf("build used cache, expected a miss!")
  5135. }
  5136. }
  5137. func (s *DockerSuite) TestBuildBuildTimeArgCacheMissSameArgDiffVal(c *check.C) {
  5138. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5139. imgName := "bldargtest"
  5140. envKey := "foo"
  5141. envVal := "bar"
  5142. newEnvVal := "bar1"
  5143. args := []string{
  5144. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5145. }
  5146. dockerfile := fmt.Sprintf(`FROM busybox
  5147. ARG %s
  5148. RUN echo $%s`, envKey, envKey)
  5149. origImgID := ""
  5150. var err error
  5151. if origImgID, err = buildImage(imgName, dockerfile, true, args...); err != nil {
  5152. c.Fatal(err)
  5153. }
  5154. imgNameCache := "bldargtestcachemiss"
  5155. args = []string{
  5156. "--build-arg", fmt.Sprintf("%s=%s", envKey, newEnvVal),
  5157. }
  5158. if newImgID, err := buildImage(imgNameCache, dockerfile, true, args...); err != nil || newImgID == origImgID {
  5159. if err != nil {
  5160. c.Fatal(err)
  5161. }
  5162. c.Fatalf("build used cache, expected a miss!")
  5163. }
  5164. }
  5165. func (s *DockerSuite) TestBuildBuildTimeArgOverrideArgDefinedBeforeEnv(c *check.C) {
  5166. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5167. imgName := "bldargtest"
  5168. envKey := "foo"
  5169. envVal := "bar"
  5170. envValOveride := "barOverride"
  5171. args := []string{
  5172. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5173. }
  5174. dockerfile := fmt.Sprintf(`FROM busybox
  5175. ARG %s
  5176. ENV %s %s
  5177. RUN echo $%s
  5178. CMD echo $%s
  5179. `, envKey, envKey, envValOveride, envKey, envKey)
  5180. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil || strings.Count(out, envValOveride) != 2 {
  5181. if err != nil {
  5182. c.Fatalf("build failed to complete: %q %q", out, err)
  5183. }
  5184. c.Fatalf("failed to access environment variable in output: %q expected: %q", out, envValOveride)
  5185. }
  5186. containerName := "bldargCont"
  5187. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOveride) {
  5188. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOveride)
  5189. }
  5190. }
  5191. func (s *DockerSuite) TestBuildBuildTimeArgOverrideEnvDefinedBeforeArg(c *check.C) {
  5192. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5193. imgName := "bldargtest"
  5194. envKey := "foo"
  5195. envVal := "bar"
  5196. envValOveride := "barOverride"
  5197. args := []string{
  5198. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5199. }
  5200. dockerfile := fmt.Sprintf(`FROM busybox
  5201. ENV %s %s
  5202. ARG %s
  5203. RUN echo $%s
  5204. CMD echo $%s
  5205. `, envKey, envValOveride, envKey, envKey, envKey)
  5206. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil || strings.Count(out, envValOveride) != 2 {
  5207. if err != nil {
  5208. c.Fatalf("build failed to complete: %q %q", out, err)
  5209. }
  5210. c.Fatalf("failed to access environment variable in output: %q expected: %q", out, envValOveride)
  5211. }
  5212. containerName := "bldargCont"
  5213. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOveride) {
  5214. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOveride)
  5215. }
  5216. }
  5217. func (s *DockerSuite) TestBuildBuildTimeArgExpansion(c *check.C) {
  5218. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5219. imgName := "bldvarstest"
  5220. wdVar := "WDIR"
  5221. wdVal := "/tmp/"
  5222. addVar := "AFILE"
  5223. addVal := "addFile"
  5224. copyVar := "CFILE"
  5225. copyVal := "copyFile"
  5226. envVar := "foo"
  5227. envVal := "bar"
  5228. exposeVar := "EPORT"
  5229. exposeVal := "9999"
  5230. userVar := "USER"
  5231. userVal := "testUser"
  5232. volVar := "VOL"
  5233. volVal := "/testVol/"
  5234. args := []string{
  5235. "--build-arg", fmt.Sprintf("%s=%s", wdVar, wdVal),
  5236. "--build-arg", fmt.Sprintf("%s=%s", addVar, addVal),
  5237. "--build-arg", fmt.Sprintf("%s=%s", copyVar, copyVal),
  5238. "--build-arg", fmt.Sprintf("%s=%s", envVar, envVal),
  5239. "--build-arg", fmt.Sprintf("%s=%s", exposeVar, exposeVal),
  5240. "--build-arg", fmt.Sprintf("%s=%s", userVar, userVal),
  5241. "--build-arg", fmt.Sprintf("%s=%s", volVar, volVal),
  5242. }
  5243. ctx, err := fakeContext(fmt.Sprintf(`FROM busybox
  5244. ARG %s
  5245. WORKDIR ${%s}
  5246. ARG %s
  5247. ADD ${%s} testDir/
  5248. ARG %s
  5249. COPY $%s testDir/
  5250. ARG %s
  5251. ENV %s=${%s}
  5252. ARG %s
  5253. EXPOSE $%s
  5254. ARG %s
  5255. USER $%s
  5256. ARG %s
  5257. VOLUME ${%s}`,
  5258. wdVar, wdVar, addVar, addVar, copyVar, copyVar, envVar, envVar,
  5259. envVar, exposeVar, exposeVar, userVar, userVar, volVar, volVar),
  5260. map[string]string{
  5261. addVal: "some stuff",
  5262. copyVal: "some stuff",
  5263. })
  5264. if err != nil {
  5265. c.Fatal(err)
  5266. }
  5267. defer ctx.Close()
  5268. if _, err := buildImageFromContext(imgName, ctx, true, args...); err != nil {
  5269. c.Fatal(err)
  5270. }
  5271. var resMap map[string]interface{}
  5272. var resArr []string
  5273. res := ""
  5274. res = inspectField(c, imgName, "Config.WorkingDir")
  5275. if res != filepath.ToSlash(filepath.Clean(wdVal)) {
  5276. c.Fatalf("Config.WorkingDir value mismatch. Expected: %s, got: %s", filepath.ToSlash(filepath.Clean(wdVal)), res)
  5277. }
  5278. inspectFieldAndMarshall(c, imgName, "Config.Env", &resArr)
  5279. found := false
  5280. for _, v := range resArr {
  5281. if fmt.Sprintf("%s=%s", envVar, envVal) == v {
  5282. found = true
  5283. break
  5284. }
  5285. }
  5286. if !found {
  5287. c.Fatalf("Config.Env value mismatch. Expected <key=value> to exist: %s=%s, got: %v",
  5288. envVar, envVal, resArr)
  5289. }
  5290. inspectFieldAndMarshall(c, imgName, "Config.ExposedPorts", &resMap)
  5291. if _, ok := resMap[fmt.Sprintf("%s/tcp", exposeVal)]; !ok {
  5292. c.Fatalf("Config.ExposedPorts value mismatch. Expected exposed port: %s/tcp, got: %v", exposeVal, resMap)
  5293. }
  5294. res = inspectField(c, imgName, "Config.User")
  5295. if res != userVal {
  5296. c.Fatalf("Config.User value mismatch. Expected: %s, got: %s", userVal, res)
  5297. }
  5298. inspectFieldAndMarshall(c, imgName, "Config.Volumes", &resMap)
  5299. if _, ok := resMap[volVal]; !ok {
  5300. c.Fatalf("Config.Volumes value mismatch. Expected volume: %s, got: %v", volVal, resMap)
  5301. }
  5302. }
  5303. func (s *DockerSuite) TestBuildBuildTimeArgExpansionOverride(c *check.C) {
  5304. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5305. imgName := "bldvarstest"
  5306. envKey := "foo"
  5307. envVal := "bar"
  5308. envKey1 := "foo1"
  5309. envValOveride := "barOverride"
  5310. args := []string{
  5311. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5312. }
  5313. dockerfile := fmt.Sprintf(`FROM busybox
  5314. ARG %s
  5315. ENV %s %s
  5316. ENV %s ${%s}
  5317. RUN echo $%s
  5318. CMD echo $%s`, envKey, envKey, envValOveride, envKey1, envKey, envKey1, envKey1)
  5319. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil || strings.Count(out, envValOveride) != 2 {
  5320. if err != nil {
  5321. c.Fatalf("build failed to complete: %q %q", out, err)
  5322. }
  5323. c.Fatalf("failed to access environment variable in output: %q expected: %q", out, envValOveride)
  5324. }
  5325. containerName := "bldargCont"
  5326. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOveride) {
  5327. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOveride)
  5328. }
  5329. }
  5330. func (s *DockerSuite) TestBuildBuildTimeArgUntrustedDefinedAfterUse(c *check.C) {
  5331. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5332. imgName := "bldargtest"
  5333. envKey := "foo"
  5334. envVal := "bar"
  5335. args := []string{
  5336. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5337. }
  5338. dockerfile := fmt.Sprintf(`FROM busybox
  5339. RUN echo $%s
  5340. ARG %s
  5341. CMD echo $%s`, envKey, envKey, envKey)
  5342. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil || strings.Contains(out, envVal) {
  5343. if err != nil {
  5344. c.Fatalf("build failed to complete: %q %q", out, err)
  5345. }
  5346. c.Fatalf("able to access environment variable in output: %q expected to be missing", out)
  5347. }
  5348. containerName := "bldargCont"
  5349. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); out != "\n" {
  5350. c.Fatalf("run produced invalid output: %q, expected empty string", out)
  5351. }
  5352. }
  5353. func (s *DockerSuite) TestBuildBuildTimeArgBuiltinArg(c *check.C) {
  5354. testRequires(c, DaemonIsLinux) // Windows does not support --build-arg
  5355. imgName := "bldargtest"
  5356. envKey := "HTTP_PROXY"
  5357. envVal := "bar"
  5358. args := []string{
  5359. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5360. }
  5361. dockerfile := fmt.Sprintf(`FROM busybox
  5362. RUN echo $%s
  5363. CMD echo $%s`, envKey, envKey)
  5364. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil || !strings.Contains(out, envVal) {
  5365. if err != nil {
  5366. c.Fatalf("build failed to complete: %q %q", out, err)
  5367. }
  5368. c.Fatalf("failed to access environment variable in output: %q expected: %q", out, envVal)
  5369. }
  5370. containerName := "bldargCont"
  5371. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); out != "\n" {
  5372. c.Fatalf("run produced invalid output: %q, expected empty string", out)
  5373. }
  5374. }
  5375. func (s *DockerSuite) TestBuildBuildTimeArgDefaultOverride(c *check.C) {
  5376. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5377. imgName := "bldargtest"
  5378. envKey := "foo"
  5379. envVal := "bar"
  5380. envValOveride := "barOverride"
  5381. args := []string{
  5382. "--build-arg", fmt.Sprintf("%s=%s", envKey, envValOveride),
  5383. }
  5384. dockerfile := fmt.Sprintf(`FROM busybox
  5385. ARG %s=%s
  5386. ENV %s $%s
  5387. RUN echo $%s
  5388. CMD echo $%s`, envKey, envVal, envKey, envKey, envKey, envKey)
  5389. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil || strings.Count(out, envValOveride) != 1 {
  5390. if err != nil {
  5391. c.Fatalf("build failed to complete: %q %q", out, err)
  5392. }
  5393. c.Fatalf("failed to access environment variable in output: %q expected: %q", out, envValOveride)
  5394. }
  5395. containerName := "bldargCont"
  5396. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOveride) {
  5397. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOveride)
  5398. }
  5399. }
  5400. func (s *DockerSuite) TestBuildBuildTimeArgMultiArgsSameLine(c *check.C) {
  5401. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5402. imgName := "bldargtest"
  5403. envKey := "foo"
  5404. envKey1 := "foo1"
  5405. args := []string{}
  5406. dockerfile := fmt.Sprintf(`FROM busybox
  5407. ARG %s %s`, envKey, envKey1)
  5408. errStr := "ARG requires exactly one argument definition"
  5409. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err == nil {
  5410. c.Fatalf("build succeeded, expected to fail. Output: %v", out)
  5411. } else if !strings.Contains(out, errStr) {
  5412. c.Fatalf("Unexpected error. output: %q, expected error: %q", out, errStr)
  5413. }
  5414. }
  5415. func (s *DockerSuite) TestBuildBuildTimeArgUnconsumedArg(c *check.C) {
  5416. testRequires(c, DaemonIsLinux) // Windows does not support --build-arg
  5417. imgName := "bldargtest"
  5418. envKey := "foo"
  5419. envVal := "bar"
  5420. args := []string{
  5421. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5422. }
  5423. dockerfile := fmt.Sprintf(`FROM busybox
  5424. RUN echo $%s
  5425. CMD echo $%s`, envKey, envKey)
  5426. errStr := "One or more build-args"
  5427. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err == nil {
  5428. c.Fatalf("build succeeded, expected to fail. Output: %v", out)
  5429. } else if !strings.Contains(out, errStr) {
  5430. c.Fatalf("Unexpected error. output: %q, expected error: %q", out, errStr)
  5431. }
  5432. }
  5433. func (s *DockerSuite) TestBuildBuildTimeArgQuotedValVariants(c *check.C) {
  5434. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5435. imgName := "bldargtest"
  5436. envKey := "foo"
  5437. envKey1 := "foo1"
  5438. envKey2 := "foo2"
  5439. envKey3 := "foo3"
  5440. args := []string{}
  5441. dockerfile := fmt.Sprintf(`FROM busybox
  5442. ARG %s=""
  5443. ARG %s=''
  5444. ARG %s="''"
  5445. ARG %s='""'
  5446. RUN [ "$%s" != "$%s" ]
  5447. RUN [ "$%s" != "$%s" ]
  5448. RUN [ "$%s" != "$%s" ]
  5449. RUN [ "$%s" != "$%s" ]
  5450. RUN [ "$%s" != "$%s" ]`, envKey, envKey1, envKey2, envKey3,
  5451. envKey, envKey2, envKey, envKey3, envKey1, envKey2, envKey1, envKey3,
  5452. envKey2, envKey3)
  5453. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil {
  5454. c.Fatalf("build failed to complete: %q %q", out, err)
  5455. }
  5456. }
  5457. func (s *DockerSuite) TestBuildBuildTimeArgEmptyValVariants(c *check.C) {
  5458. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5459. imgName := "bldargtest"
  5460. envKey := "foo"
  5461. envKey1 := "foo1"
  5462. envKey2 := "foo2"
  5463. args := []string{}
  5464. dockerfile := fmt.Sprintf(`FROM busybox
  5465. ARG %s=
  5466. ARG %s=""
  5467. ARG %s=''
  5468. RUN [ "$%s" == "$%s" ]
  5469. RUN [ "$%s" == "$%s" ]
  5470. RUN [ "$%s" == "$%s" ]`, envKey, envKey1, envKey2, envKey, envKey1, envKey1, envKey2, envKey, envKey2)
  5471. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil {
  5472. c.Fatalf("build failed to complete: %q %q", out, err)
  5473. }
  5474. }
  5475. func (s *DockerSuite) TestBuildBuildTimeArgDefintionWithNoEnvInjection(c *check.C) {
  5476. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5477. imgName := "bldargtest"
  5478. envKey := "foo"
  5479. args := []string{}
  5480. dockerfile := fmt.Sprintf(`FROM busybox
  5481. ARG %s
  5482. RUN env`, envKey)
  5483. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil || strings.Count(out, envKey) != 1 {
  5484. if err != nil {
  5485. c.Fatalf("build failed to complete: %q %q", out, err)
  5486. }
  5487. c.Fatalf("unexpected number of occurrences of the arg in output: %q expected: 1", out)
  5488. }
  5489. }
  5490. func (s *DockerSuite) TestBuildNoNamedVolume(c *check.C) {
  5491. volName := "testname:/foo"
  5492. if daemonPlatform == "windows" {
  5493. volName = "testname:C:\\foo"
  5494. }
  5495. dockerCmd(c, "run", "-v", volName, "busybox", "sh", "-c", "touch /foo/oops")
  5496. dockerFile := `FROM busybox
  5497. VOLUME ` + volName + `
  5498. RUN ls /foo/oops
  5499. `
  5500. _, err := buildImage("test", dockerFile, false)
  5501. c.Assert(err, check.NotNil, check.Commentf("image build should have failed"))
  5502. }
  5503. func (s *DockerSuite) TestBuildTagEvent(c *check.C) {
  5504. since := daemonTime(c).Unix()
  5505. dockerFile := `FROM busybox
  5506. RUN echo events
  5507. `
  5508. _, err := buildImage("test", dockerFile, false)
  5509. c.Assert(err, check.IsNil)
  5510. out, _ := dockerCmd(c, "events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()), "--filter", "type=image")
  5511. events := strings.Split(strings.TrimSpace(out), "\n")
  5512. actions := eventActionsByIDAndType(c, events, "test:latest", "image")
  5513. var foundTag bool
  5514. for _, a := range actions {
  5515. if a == "tag" {
  5516. foundTag = true
  5517. break
  5518. }
  5519. }
  5520. c.Assert(foundTag, checker.True, check.Commentf("No tag event found:\n%s", out))
  5521. }
  5522. // #15780
  5523. func (s *DockerSuite) TestBuildMultipleTags(c *check.C) {
  5524. dockerfile := `
  5525. FROM busybox
  5526. MAINTAINER test-15780
  5527. `
  5528. cmd := exec.Command(dockerBinary, "build", "-t", "tag1", "-t", "tag2:v2",
  5529. "-t", "tag1:latest", "-t", "tag1", "--no-cache", "-")
  5530. cmd.Stdin = strings.NewReader(dockerfile)
  5531. _, err := runCommand(cmd)
  5532. c.Assert(err, check.IsNil)
  5533. id1, err := getIDByName("tag1")
  5534. c.Assert(err, check.IsNil)
  5535. id2, err := getIDByName("tag2:v2")
  5536. c.Assert(err, check.IsNil)
  5537. c.Assert(id1, check.Equals, id2)
  5538. }
  5539. // #17290
  5540. func (s *DockerSuite) TestBuildCacheBrokenSymlink(c *check.C) {
  5541. testRequires(c, DaemonIsLinux)
  5542. name := "testbuildbrokensymlink"
  5543. ctx, err := fakeContext(`
  5544. FROM busybox
  5545. COPY . ./`,
  5546. map[string]string{
  5547. "foo": "bar",
  5548. })
  5549. c.Assert(err, checker.IsNil)
  5550. defer ctx.Close()
  5551. err = os.Symlink(filepath.Join(ctx.Dir, "nosuchfile"), filepath.Join(ctx.Dir, "asymlink"))
  5552. c.Assert(err, checker.IsNil)
  5553. // warm up cache
  5554. _, err = buildImageFromContext(name, ctx, true)
  5555. c.Assert(err, checker.IsNil)
  5556. // add new file to context, should invalidate cache
  5557. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "newfile"), []byte("foo"), 0644)
  5558. c.Assert(err, checker.IsNil)
  5559. _, out, err := buildImageFromContextWithOut(name, ctx, true)
  5560. c.Assert(err, checker.IsNil)
  5561. c.Assert(out, checker.Not(checker.Contains), "Using cache")
  5562. }
  5563. func (s *DockerSuite) TestBuildFollowSymlinkToFile(c *check.C) {
  5564. testRequires(c, DaemonIsLinux)
  5565. name := "testbuildbrokensymlink"
  5566. ctx, err := fakeContext(`
  5567. FROM busybox
  5568. COPY asymlink target`,
  5569. map[string]string{
  5570. "foo": "bar",
  5571. })
  5572. c.Assert(err, checker.IsNil)
  5573. defer ctx.Close()
  5574. err = os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink"))
  5575. c.Assert(err, checker.IsNil)
  5576. id, err := buildImageFromContext(name, ctx, true)
  5577. c.Assert(err, checker.IsNil)
  5578. out, _ := dockerCmd(c, "run", "--rm", id, "cat", "target")
  5579. c.Assert(out, checker.Matches, "bar")
  5580. // change target file should invalidate cache
  5581. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "foo"), []byte("baz"), 0644)
  5582. c.Assert(err, checker.IsNil)
  5583. id, out, err = buildImageFromContextWithOut(name, ctx, true)
  5584. c.Assert(err, checker.IsNil)
  5585. c.Assert(out, checker.Not(checker.Contains), "Using cache")
  5586. out, _ = dockerCmd(c, "run", "--rm", id, "cat", "target")
  5587. c.Assert(out, checker.Matches, "baz")
  5588. }
  5589. func (s *DockerSuite) TestBuildFollowSymlinkToDir(c *check.C) {
  5590. testRequires(c, DaemonIsLinux)
  5591. name := "testbuildbrokensymlink"
  5592. ctx, err := fakeContext(`
  5593. FROM busybox
  5594. COPY asymlink /`,
  5595. map[string]string{
  5596. "foo/abc": "bar",
  5597. "foo/def": "baz",
  5598. })
  5599. c.Assert(err, checker.IsNil)
  5600. defer ctx.Close()
  5601. err = os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink"))
  5602. c.Assert(err, checker.IsNil)
  5603. id, err := buildImageFromContext(name, ctx, true)
  5604. c.Assert(err, checker.IsNil)
  5605. out, _ := dockerCmd(c, "run", "--rm", id, "cat", "abc", "def")
  5606. c.Assert(out, checker.Matches, "barbaz")
  5607. // change target file should invalidate cache
  5608. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "foo/def"), []byte("bax"), 0644)
  5609. c.Assert(err, checker.IsNil)
  5610. id, out, err = buildImageFromContextWithOut(name, ctx, true)
  5611. c.Assert(err, checker.IsNil)
  5612. c.Assert(out, checker.Not(checker.Contains), "Using cache")
  5613. out, _ = dockerCmd(c, "run", "--rm", id, "cat", "abc", "def")
  5614. c.Assert(out, checker.Matches, "barbax")
  5615. }
  5616. // TestBuildSymlinkBasename tests that target file gets basename from symlink,
  5617. // not from the target file.
  5618. func (s *DockerSuite) TestBuildSymlinkBasename(c *check.C) {
  5619. testRequires(c, DaemonIsLinux)
  5620. name := "testbuildbrokensymlink"
  5621. ctx, err := fakeContext(`
  5622. FROM busybox
  5623. COPY asymlink /`,
  5624. map[string]string{
  5625. "foo": "bar",
  5626. })
  5627. c.Assert(err, checker.IsNil)
  5628. defer ctx.Close()
  5629. err = os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink"))
  5630. c.Assert(err, checker.IsNil)
  5631. id, err := buildImageFromContext(name, ctx, true)
  5632. c.Assert(err, checker.IsNil)
  5633. out, _ := dockerCmd(c, "run", "--rm", id, "cat", "asymlink")
  5634. c.Assert(out, checker.Matches, "bar")
  5635. }
  5636. // #17827
  5637. func (s *DockerSuite) TestBuildCacheRootSource(c *check.C) {
  5638. name := "testbuildrootsource"
  5639. ctx, err := fakeContext(`
  5640. FROM busybox
  5641. COPY / /data`,
  5642. map[string]string{
  5643. "foo": "bar",
  5644. })
  5645. c.Assert(err, checker.IsNil)
  5646. defer ctx.Close()
  5647. // warm up cache
  5648. _, err = buildImageFromContext(name, ctx, true)
  5649. c.Assert(err, checker.IsNil)
  5650. // change file, should invalidate cache
  5651. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "foo"), []byte("baz"), 0644)
  5652. c.Assert(err, checker.IsNil)
  5653. _, out, err := buildImageFromContextWithOut(name, ctx, true)
  5654. c.Assert(err, checker.IsNil)
  5655. c.Assert(out, checker.Not(checker.Contains), "Using cache")
  5656. }
  5657. // #19375
  5658. func (s *DockerSuite) TestBuildFailsGitNotCallable(c *check.C) {
  5659. cmd := exec.Command(dockerBinary, "build", "github.com/docker/v1.10-migrator.git")
  5660. cmd.Env = append(cmd.Env, "PATH=")
  5661. out, _, err := runCommandWithOutput(cmd)
  5662. c.Assert(err, checker.NotNil)
  5663. c.Assert(out, checker.Contains, "unable to prepare context: unable to find 'git': ")
  5664. cmd = exec.Command(dockerBinary, "build", "https://github.com/docker/v1.10-migrator.git")
  5665. cmd.Env = append(cmd.Env, "PATH=")
  5666. out, _, err = runCommandWithOutput(cmd)
  5667. c.Assert(err, checker.NotNil)
  5668. c.Assert(out, checker.Contains, "unable to prepare context: unable to find 'git': ")
  5669. }
  5670. // TestBuildWorkdirWindowsPath tests that a Windows style path works as a workdir
  5671. func (s *DockerSuite) TestBuildWorkdirWindowsPath(c *check.C) {
  5672. testRequires(c, DaemonIsWindows)
  5673. name := "testbuildworkdirwindowspath"
  5674. _, err := buildImage(name, `
  5675. FROM windowsservercore
  5676. RUN mkdir C:\\work
  5677. WORKDIR C:\\work
  5678. RUN if "%CD%" NEQ "C:\work" exit -1
  5679. `, true)
  5680. if err != nil {
  5681. c.Fatal(err)
  5682. }
  5683. }
  5684. func (s *DockerRegistryAuthSuite) TestBuildFromAuthenticatedRegistry(c *check.C) {
  5685. dockerCmd(c, "login", "-u", s.reg.username, "-p", s.reg.password, privateRegistryURL)
  5686. baseImage := privateRegistryURL + "/baseimage"
  5687. _, err := buildImage(baseImage, `
  5688. FROM busybox
  5689. ENV env1 val1
  5690. `, true)
  5691. c.Assert(err, checker.IsNil)
  5692. dockerCmd(c, "push", baseImage)
  5693. dockerCmd(c, "rmi", baseImage)
  5694. _, err = buildImage(baseImage, fmt.Sprintf(`
  5695. FROM %s
  5696. ENV env2 val2
  5697. `, baseImage), true)
  5698. c.Assert(err, checker.IsNil)
  5699. }
  5700. func (s *DockerRegistryAuthSuite) TestBuildWithExternalAuth(c *check.C) {
  5701. osPath := os.Getenv("PATH")
  5702. defer os.Setenv("PATH", osPath)
  5703. workingDir, err := os.Getwd()
  5704. c.Assert(err, checker.IsNil)
  5705. absolute, err := filepath.Abs(filepath.Join(workingDir, "fixtures", "auth"))
  5706. c.Assert(err, checker.IsNil)
  5707. testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute)
  5708. os.Setenv("PATH", testPath)
  5709. repoName := fmt.Sprintf("%v/dockercli/busybox:authtest", privateRegistryURL)
  5710. tmp, err := ioutil.TempDir("", "integration-cli-")
  5711. c.Assert(err, checker.IsNil)
  5712. externalAuthConfig := `{ "credsStore": "shell-test" }`
  5713. configPath := filepath.Join(tmp, "config.json")
  5714. err = ioutil.WriteFile(configPath, []byte(externalAuthConfig), 0644)
  5715. c.Assert(err, checker.IsNil)
  5716. dockerCmd(c, "--config", tmp, "login", "-u", s.reg.username, "-p", s.reg.password, privateRegistryURL)
  5717. b, err := ioutil.ReadFile(configPath)
  5718. c.Assert(err, checker.IsNil)
  5719. c.Assert(string(b), checker.Not(checker.Contains), "\"auth\":")
  5720. dockerCmd(c, "--config", tmp, "tag", "busybox", repoName)
  5721. dockerCmd(c, "--config", tmp, "push", repoName)
  5722. // make sure the image is pulled when building
  5723. dockerCmd(c, "rmi", repoName)
  5724. buildCmd := exec.Command(dockerBinary, "--config", tmp, "build", "-")
  5725. buildCmd.Stdin = strings.NewReader(fmt.Sprintf("FROM %s", repoName))
  5726. out, _, err := runCommandWithOutput(buildCmd)
  5727. c.Assert(err, check.IsNil, check.Commentf(out))
  5728. }