docker_cli_build_test.go 181 KB

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