docker_cli_build_test.go 189 KB

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