docker_cli_build_test.go 172 KB

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