docker_cli_build_test.go 186 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912
  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. // TODO Windows: The expectedFinal needs fixing to match Windows
  1753. // filepath semantics. However, this is a non-trivial change. @jhowardmsft
  1754. // Short story - need to make the configuration file platform semantically
  1755. // consistent, so even if `WORKDIR /test2/test3` is specified in a Dockerfile,
  1756. // the configuration should be stored as C:\test2\test3. Something similar to
  1757. // if runtime.GOOS == "windows" && len(workdir) > 2 && string(workdir[0]) == `\` {
  1758. // workdir = "C:" + workdir
  1759. // }
  1760. // in builder\dockerfile\dispatchers.go, function workdir(), but also
  1761. // ironing out all other cases where this causes other failures.
  1762. if daemonPlatform == "windows" {
  1763. expected1 = `C:/`
  1764. expected2 = `C:/test1`
  1765. expected3 = `C:/test2`
  1766. expected4 = `C:/test2/test3`
  1767. expectedFinal = `\test2\test3`
  1768. } else {
  1769. expected1 = `/`
  1770. expected2 = `/test1`
  1771. expected3 = `/test2`
  1772. expected4 = `/test2/test3`
  1773. expectedFinal = `/test2/test3`
  1774. }
  1775. _, err := buildImage(name,
  1776. `FROM busybox
  1777. RUN sh -c "[ "$PWD" = "`+expected1+`" ]"
  1778. WORKDIR test1
  1779. RUN sh -c "[ "$PWD" = "`+expected2+`" ]"
  1780. WORKDIR /test2
  1781. RUN sh -c "[ "$PWD" = "`+expected3+`" ]"
  1782. WORKDIR test3
  1783. RUN sh -c "[ "$PWD" = "`+expected4+`" ]"`,
  1784. true)
  1785. if err != nil {
  1786. c.Fatal(err)
  1787. }
  1788. res := inspectField(c, name, "Config.WorkingDir")
  1789. if res != expectedFinal {
  1790. c.Fatalf("Workdir %s, expected %s", res, expectedFinal)
  1791. }
  1792. }
  1793. func (s *DockerSuite) TestBuildWorkdirWithEnvVariables(c *check.C) {
  1794. name := "testbuildworkdirwithenvvariables"
  1795. var expected string
  1796. if daemonPlatform == "windows" {
  1797. expected = `\test1\test2`
  1798. } else {
  1799. expected = `/test1/test2`
  1800. }
  1801. _, err := buildImage(name,
  1802. `FROM busybox
  1803. ENV DIRPATH /test1
  1804. ENV SUBDIRNAME test2
  1805. WORKDIR $DIRPATH
  1806. WORKDIR $SUBDIRNAME/$MISSING_VAR`,
  1807. true)
  1808. if err != nil {
  1809. c.Fatal(err)
  1810. }
  1811. res := inspectField(c, name, "Config.WorkingDir")
  1812. if res != expected {
  1813. c.Fatalf("Workdir %s, expected %s", res, expected)
  1814. }
  1815. }
  1816. func (s *DockerSuite) TestBuildRelativeCopy(c *check.C) {
  1817. // cat /test1/test2/foo gets permission denied for the user
  1818. testRequires(c, NotUserNamespace)
  1819. var expected string
  1820. if daemonPlatform == "windows" {
  1821. expected = `C:/test1/test2`
  1822. } else {
  1823. expected = `/test1/test2`
  1824. }
  1825. name := "testbuildrelativecopy"
  1826. dockerfile := `
  1827. FROM busybox
  1828. WORKDIR /test1
  1829. WORKDIR test2
  1830. RUN sh -c "[ "$PWD" = '` + expected + `' ]"
  1831. COPY foo ./
  1832. RUN sh -c "[ $(cat /test1/test2/foo) = 'hello' ]"
  1833. ADD foo ./bar/baz
  1834. RUN sh -c "[ $(cat /test1/test2/bar/baz) = 'hello' ]"
  1835. COPY foo ./bar/baz2
  1836. RUN sh -c "[ $(cat /test1/test2/bar/baz2) = 'hello' ]"
  1837. WORKDIR ..
  1838. COPY foo ./
  1839. RUN sh -c "[ $(cat /test1/foo) = 'hello' ]"
  1840. COPY foo /test3/
  1841. RUN sh -c "[ $(cat /test3/foo) = 'hello' ]"
  1842. WORKDIR /test4
  1843. COPY . .
  1844. RUN sh -c "[ $(cat /test4/foo) = 'hello' ]"
  1845. WORKDIR /test5/test6
  1846. COPY foo ../
  1847. RUN sh -c "[ $(cat /test5/foo) = 'hello' ]"
  1848. `
  1849. ctx, err := fakeContext(dockerfile, map[string]string{
  1850. "foo": "hello",
  1851. })
  1852. if err != nil {
  1853. c.Fatal(err)
  1854. }
  1855. defer ctx.Close()
  1856. _, err = buildImageFromContext(name, ctx, false)
  1857. if err != nil {
  1858. c.Fatal(err)
  1859. }
  1860. }
  1861. func (s *DockerSuite) TestBuildEnv(c *check.C) {
  1862. testRequires(c, DaemonIsLinux) // ENV expansion is different in Windows
  1863. name := "testbuildenv"
  1864. expected := "[PATH=/test:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin PORT=2375]"
  1865. _, err := buildImage(name,
  1866. `FROM busybox
  1867. ENV PATH /test:$PATH
  1868. ENV PORT 2375
  1869. RUN [ $(env | grep PORT) = 'PORT=2375' ]`,
  1870. true)
  1871. if err != nil {
  1872. c.Fatal(err)
  1873. }
  1874. res := inspectField(c, name, "Config.Env")
  1875. if res != expected {
  1876. c.Fatalf("Env %s, expected %s", res, expected)
  1877. }
  1878. }
  1879. func (s *DockerSuite) TestBuildPATH(c *check.C) {
  1880. testRequires(c, DaemonIsLinux) // ENV expansion is different in Windows
  1881. defPath := "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
  1882. fn := func(dockerfile string, exp string) {
  1883. _, err := buildImage("testbldpath", dockerfile, true)
  1884. c.Assert(err, check.IsNil)
  1885. res := inspectField(c, "testbldpath", "Config.Env")
  1886. if res != exp {
  1887. c.Fatalf("Env %q, expected %q for dockerfile:%q", res, exp, dockerfile)
  1888. }
  1889. }
  1890. tests := []struct{ dockerfile, exp string }{
  1891. {"FROM scratch\nMAINTAINER me", "[PATH=" + defPath + "]"},
  1892. {"FROM busybox\nMAINTAINER me", "[PATH=" + defPath + "]"},
  1893. {"FROM scratch\nENV FOO=bar", "[PATH=" + defPath + " FOO=bar]"},
  1894. {"FROM busybox\nENV FOO=bar", "[PATH=" + defPath + " FOO=bar]"},
  1895. {"FROM scratch\nENV PATH=/test", "[PATH=/test]"},
  1896. {"FROM busybox\nENV PATH=/test", "[PATH=/test]"},
  1897. {"FROM scratch\nENV PATH=''", "[PATH=]"},
  1898. {"FROM busybox\nENV PATH=''", "[PATH=]"},
  1899. }
  1900. for _, test := range tests {
  1901. fn(test.dockerfile, test.exp)
  1902. }
  1903. }
  1904. func (s *DockerSuite) TestBuildContextCleanup(c *check.C) {
  1905. testRequires(c, DaemonIsLinux)
  1906. testRequires(c, SameHostDaemon)
  1907. name := "testbuildcontextcleanup"
  1908. entries, err := ioutil.ReadDir(filepath.Join(dockerBasePath, "tmp"))
  1909. if err != nil {
  1910. c.Fatalf("failed to list contents of tmp dir: %s", err)
  1911. }
  1912. _, err = buildImage(name,
  1913. `FROM scratch
  1914. ENTRYPOINT ["/bin/echo"]`,
  1915. true)
  1916. if err != nil {
  1917. c.Fatal(err)
  1918. }
  1919. entriesFinal, err := ioutil.ReadDir(filepath.Join(dockerBasePath, "tmp"))
  1920. if err != nil {
  1921. c.Fatalf("failed to list contents of tmp dir: %s", err)
  1922. }
  1923. if err = compareDirectoryEntries(entries, entriesFinal); err != nil {
  1924. c.Fatalf("context should have been deleted, but wasn't")
  1925. }
  1926. }
  1927. func (s *DockerSuite) TestBuildContextCleanupFailedBuild(c *check.C) {
  1928. testRequires(c, DaemonIsLinux)
  1929. testRequires(c, SameHostDaemon)
  1930. name := "testbuildcontextcleanup"
  1931. entries, err := ioutil.ReadDir(filepath.Join(dockerBasePath, "tmp"))
  1932. if err != nil {
  1933. c.Fatalf("failed to list contents of tmp dir: %s", err)
  1934. }
  1935. _, err = buildImage(name,
  1936. `FROM scratch
  1937. RUN /non/existing/command`,
  1938. true)
  1939. if err == nil {
  1940. c.Fatalf("expected build to fail, but it didn't")
  1941. }
  1942. entriesFinal, err := ioutil.ReadDir(filepath.Join(dockerBasePath, "tmp"))
  1943. if err != nil {
  1944. c.Fatalf("failed to list contents of tmp dir: %s", err)
  1945. }
  1946. if err = compareDirectoryEntries(entries, entriesFinal); err != nil {
  1947. c.Fatalf("context should have been deleted, but wasn't")
  1948. }
  1949. }
  1950. func (s *DockerSuite) TestBuildCmd(c *check.C) {
  1951. name := "testbuildcmd"
  1952. expected := "[/bin/echo Hello World]"
  1953. _, err := buildImage(name,
  1954. `FROM `+minimalBaseImage()+`
  1955. CMD ["/bin/echo", "Hello World"]`,
  1956. true)
  1957. if err != nil {
  1958. c.Fatal(err)
  1959. }
  1960. res := inspectField(c, name, "Config.Cmd")
  1961. if res != expected {
  1962. c.Fatalf("Cmd %s, expected %s", res, expected)
  1963. }
  1964. }
  1965. func (s *DockerSuite) TestBuildExpose(c *check.C) {
  1966. testRequires(c, DaemonIsLinux) // Expose not implemented on Windows
  1967. name := "testbuildexpose"
  1968. expected := "map[2375/tcp:{}]"
  1969. _, err := buildImage(name,
  1970. `FROM scratch
  1971. EXPOSE 2375`,
  1972. true)
  1973. if err != nil {
  1974. c.Fatal(err)
  1975. }
  1976. res := inspectField(c, name, "Config.ExposedPorts")
  1977. if res != expected {
  1978. c.Fatalf("Exposed ports %s, expected %s", res, expected)
  1979. }
  1980. }
  1981. func (s *DockerSuite) TestBuildExposeMorePorts(c *check.C) {
  1982. testRequires(c, DaemonIsLinux) // Expose not implemented on Windows
  1983. // start building docker file with a large number of ports
  1984. portList := make([]string, 50)
  1985. line := make([]string, 100)
  1986. expectedPorts := make([]int, len(portList)*len(line))
  1987. for i := 0; i < len(portList); i++ {
  1988. for j := 0; j < len(line); j++ {
  1989. p := i*len(line) + j + 1
  1990. line[j] = strconv.Itoa(p)
  1991. expectedPorts[p-1] = p
  1992. }
  1993. if i == len(portList)-1 {
  1994. portList[i] = strings.Join(line, " ")
  1995. } else {
  1996. portList[i] = strings.Join(line, " ") + ` \`
  1997. }
  1998. }
  1999. dockerfile := `FROM scratch
  2000. EXPOSE {{range .}} {{.}}
  2001. {{end}}`
  2002. tmpl := template.Must(template.New("dockerfile").Parse(dockerfile))
  2003. buf := bytes.NewBuffer(nil)
  2004. tmpl.Execute(buf, portList)
  2005. name := "testbuildexpose"
  2006. _, err := buildImage(name, buf.String(), true)
  2007. if err != nil {
  2008. c.Fatal(err)
  2009. }
  2010. // check if all the ports are saved inside Config.ExposedPorts
  2011. res := inspectFieldJSON(c, name, "Config.ExposedPorts")
  2012. var exposedPorts map[string]interface{}
  2013. if err := json.Unmarshal([]byte(res), &exposedPorts); err != nil {
  2014. c.Fatal(err)
  2015. }
  2016. for _, p := range expectedPorts {
  2017. ep := fmt.Sprintf("%d/tcp", p)
  2018. if _, ok := exposedPorts[ep]; !ok {
  2019. c.Errorf("Port(%s) is not exposed", ep)
  2020. } else {
  2021. delete(exposedPorts, ep)
  2022. }
  2023. }
  2024. if len(exposedPorts) != 0 {
  2025. c.Errorf("Unexpected extra exposed ports %v", exposedPorts)
  2026. }
  2027. }
  2028. func (s *DockerSuite) TestBuildExposeOrder(c *check.C) {
  2029. testRequires(c, DaemonIsLinux) // Expose not implemented on Windows
  2030. buildID := func(name, exposed string) string {
  2031. _, err := buildImage(name, fmt.Sprintf(`FROM scratch
  2032. EXPOSE %s`, exposed), true)
  2033. if err != nil {
  2034. c.Fatal(err)
  2035. }
  2036. id := inspectField(c, name, "Id")
  2037. return id
  2038. }
  2039. id1 := buildID("testbuildexpose1", "80 2375")
  2040. id2 := buildID("testbuildexpose2", "2375 80")
  2041. if id1 != id2 {
  2042. c.Errorf("EXPOSE should invalidate the cache only when ports actually changed")
  2043. }
  2044. }
  2045. func (s *DockerSuite) TestBuildExposeUpperCaseProto(c *check.C) {
  2046. testRequires(c, DaemonIsLinux) // Expose not implemented on Windows
  2047. name := "testbuildexposeuppercaseproto"
  2048. expected := "map[5678/udp:{}]"
  2049. _, err := buildImage(name,
  2050. `FROM scratch
  2051. EXPOSE 5678/UDP`,
  2052. true)
  2053. if err != nil {
  2054. c.Fatal(err)
  2055. }
  2056. res := inspectField(c, name, "Config.ExposedPorts")
  2057. if res != expected {
  2058. c.Fatalf("Exposed ports %s, expected %s", res, expected)
  2059. }
  2060. }
  2061. func (s *DockerSuite) TestBuildEmptyEntrypointInheritance(c *check.C) {
  2062. name := "testbuildentrypointinheritance"
  2063. name2 := "testbuildentrypointinheritance2"
  2064. _, err := buildImage(name,
  2065. `FROM busybox
  2066. ENTRYPOINT ["/bin/echo"]`,
  2067. true)
  2068. if err != nil {
  2069. c.Fatal(err)
  2070. }
  2071. res := inspectField(c, name, "Config.Entrypoint")
  2072. expected := "[/bin/echo]"
  2073. if res != expected {
  2074. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  2075. }
  2076. _, err = buildImage(name2,
  2077. fmt.Sprintf(`FROM %s
  2078. ENTRYPOINT []`, name),
  2079. true)
  2080. if err != nil {
  2081. c.Fatal(err)
  2082. }
  2083. res = inspectField(c, name2, "Config.Entrypoint")
  2084. expected = "[]"
  2085. if res != expected {
  2086. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  2087. }
  2088. }
  2089. func (s *DockerSuite) TestBuildEmptyEntrypoint(c *check.C) {
  2090. name := "testbuildentrypoint"
  2091. expected := "[]"
  2092. _, err := buildImage(name,
  2093. `FROM busybox
  2094. ENTRYPOINT []`,
  2095. true)
  2096. if err != nil {
  2097. c.Fatal(err)
  2098. }
  2099. res := inspectField(c, name, "Config.Entrypoint")
  2100. if res != expected {
  2101. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  2102. }
  2103. }
  2104. func (s *DockerSuite) TestBuildEntrypoint(c *check.C) {
  2105. name := "testbuildentrypoint"
  2106. expected := "[/bin/echo]"
  2107. _, err := buildImage(name,
  2108. `FROM `+minimalBaseImage()+`
  2109. ENTRYPOINT ["/bin/echo"]`,
  2110. true)
  2111. if err != nil {
  2112. c.Fatal(err)
  2113. }
  2114. res := inspectField(c, name, "Config.Entrypoint")
  2115. if res != expected {
  2116. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  2117. }
  2118. }
  2119. // #6445 ensure ONBUILD triggers aren't committed to grandchildren
  2120. func (s *DockerSuite) TestBuildOnBuildLimitedInheritence(c *check.C) {
  2121. var (
  2122. out2, out3 string
  2123. )
  2124. {
  2125. name1 := "testonbuildtrigger1"
  2126. dockerfile1 := `
  2127. FROM busybox
  2128. RUN echo "GRANDPARENT"
  2129. ONBUILD RUN echo "ONBUILD PARENT"
  2130. `
  2131. ctx, err := fakeContext(dockerfile1, nil)
  2132. if err != nil {
  2133. c.Fatal(err)
  2134. }
  2135. defer ctx.Close()
  2136. out1, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", name1, ".")
  2137. if err != nil {
  2138. c.Fatalf("build failed to complete: %s, %v", out1, err)
  2139. }
  2140. }
  2141. {
  2142. name2 := "testonbuildtrigger2"
  2143. dockerfile2 := `
  2144. FROM testonbuildtrigger1
  2145. `
  2146. ctx, err := fakeContext(dockerfile2, nil)
  2147. if err != nil {
  2148. c.Fatal(err)
  2149. }
  2150. defer ctx.Close()
  2151. out2, _, err = dockerCmdInDir(c, ctx.Dir, "build", "-t", name2, ".")
  2152. if err != nil {
  2153. c.Fatalf("build failed to complete: %s, %v", out2, err)
  2154. }
  2155. }
  2156. {
  2157. name3 := "testonbuildtrigger3"
  2158. dockerfile3 := `
  2159. FROM testonbuildtrigger2
  2160. `
  2161. ctx, err := fakeContext(dockerfile3, nil)
  2162. if err != nil {
  2163. c.Fatal(err)
  2164. }
  2165. defer ctx.Close()
  2166. out3, _, err = dockerCmdInDir(c, ctx.Dir, "build", "-t", name3, ".")
  2167. if err != nil {
  2168. c.Fatalf("build failed to complete: %s, %v", out3, err)
  2169. }
  2170. }
  2171. // ONBUILD should be run in second build.
  2172. if !strings.Contains(out2, "ONBUILD PARENT") {
  2173. c.Fatalf("ONBUILD instruction did not run in child of ONBUILD parent")
  2174. }
  2175. // ONBUILD should *not* be run in third build.
  2176. if strings.Contains(out3, "ONBUILD PARENT") {
  2177. c.Fatalf("ONBUILD instruction ran in grandchild of ONBUILD parent")
  2178. }
  2179. }
  2180. func (s *DockerSuite) TestBuildWithCache(c *check.C) {
  2181. testRequires(c, DaemonIsLinux) // Expose not implemented on Windows
  2182. name := "testbuildwithcache"
  2183. id1, err := buildImage(name,
  2184. `FROM scratch
  2185. MAINTAINER dockerio
  2186. EXPOSE 5432
  2187. ENTRYPOINT ["/bin/echo"]`,
  2188. true)
  2189. if err != nil {
  2190. c.Fatal(err)
  2191. }
  2192. id2, err := buildImage(name,
  2193. `FROM scratch
  2194. MAINTAINER dockerio
  2195. EXPOSE 5432
  2196. ENTRYPOINT ["/bin/echo"]`,
  2197. true)
  2198. if err != nil {
  2199. c.Fatal(err)
  2200. }
  2201. if id1 != id2 {
  2202. c.Fatal("The cache should have been used but hasn't.")
  2203. }
  2204. }
  2205. func (s *DockerSuite) TestBuildWithoutCache(c *check.C) {
  2206. testRequires(c, DaemonIsLinux) // Expose not implemented on Windows
  2207. name := "testbuildwithoutcache"
  2208. name2 := "testbuildwithoutcache2"
  2209. id1, err := buildImage(name,
  2210. `FROM scratch
  2211. MAINTAINER dockerio
  2212. EXPOSE 5432
  2213. ENTRYPOINT ["/bin/echo"]`,
  2214. true)
  2215. if err != nil {
  2216. c.Fatal(err)
  2217. }
  2218. id2, err := buildImage(name2,
  2219. `FROM scratch
  2220. MAINTAINER dockerio
  2221. EXPOSE 5432
  2222. ENTRYPOINT ["/bin/echo"]`,
  2223. false)
  2224. if err != nil {
  2225. c.Fatal(err)
  2226. }
  2227. if id1 == id2 {
  2228. c.Fatal("The cache should have been invalided but hasn't.")
  2229. }
  2230. }
  2231. func (s *DockerSuite) TestBuildConditionalCache(c *check.C) {
  2232. name := "testbuildconditionalcache"
  2233. dockerfile := `
  2234. FROM busybox
  2235. ADD foo /tmp/`
  2236. ctx, err := fakeContext(dockerfile, map[string]string{
  2237. "foo": "hello",
  2238. })
  2239. if err != nil {
  2240. c.Fatal(err)
  2241. }
  2242. defer ctx.Close()
  2243. id1, err := buildImageFromContext(name, ctx, true)
  2244. if err != nil {
  2245. c.Fatalf("Error building #1: %s", err)
  2246. }
  2247. if err := ctx.Add("foo", "bye"); err != nil {
  2248. c.Fatalf("Error modifying foo: %s", err)
  2249. }
  2250. id2, err := buildImageFromContext(name, ctx, false)
  2251. if err != nil {
  2252. c.Fatalf("Error building #2: %s", err)
  2253. }
  2254. if id2 == id1 {
  2255. c.Fatal("Should not have used the cache")
  2256. }
  2257. id3, err := buildImageFromContext(name, ctx, true)
  2258. if err != nil {
  2259. c.Fatalf("Error building #3: %s", err)
  2260. }
  2261. if id3 != id2 {
  2262. c.Fatal("Should have used the cache")
  2263. }
  2264. }
  2265. func (s *DockerSuite) TestBuildAddLocalFileWithCache(c *check.C) {
  2266. // local files are not owned by the correct user
  2267. testRequires(c, NotUserNamespace)
  2268. name := "testbuildaddlocalfilewithcache"
  2269. name2 := "testbuildaddlocalfilewithcache2"
  2270. dockerfile := `
  2271. FROM busybox
  2272. MAINTAINER dockerio
  2273. ADD foo /usr/lib/bla/bar
  2274. RUN sh -c "[ $(cat /usr/lib/bla/bar) = "hello" ]"`
  2275. ctx, err := fakeContext(dockerfile, map[string]string{
  2276. "foo": "hello",
  2277. })
  2278. if err != nil {
  2279. c.Fatal(err)
  2280. }
  2281. defer ctx.Close()
  2282. id1, err := buildImageFromContext(name, ctx, true)
  2283. if err != nil {
  2284. c.Fatal(err)
  2285. }
  2286. id2, err := buildImageFromContext(name2, ctx, true)
  2287. if err != nil {
  2288. c.Fatal(err)
  2289. }
  2290. if id1 != id2 {
  2291. c.Fatal("The cache should have been used but hasn't.")
  2292. }
  2293. }
  2294. func (s *DockerSuite) TestBuildAddMultipleLocalFileWithCache(c *check.C) {
  2295. name := "testbuildaddmultiplelocalfilewithcache"
  2296. name2 := "testbuildaddmultiplelocalfilewithcache2"
  2297. dockerfile := `
  2298. FROM busybox
  2299. MAINTAINER dockerio
  2300. ADD foo Dockerfile /usr/lib/bla/
  2301. RUN sh -c "[ $(cat /usr/lib/bla/foo) = "hello" ]"`
  2302. ctx, err := fakeContext(dockerfile, map[string]string{
  2303. "foo": "hello",
  2304. })
  2305. if err != nil {
  2306. c.Fatal(err)
  2307. }
  2308. defer ctx.Close()
  2309. id1, err := buildImageFromContext(name, ctx, true)
  2310. if err != nil {
  2311. c.Fatal(err)
  2312. }
  2313. id2, err := buildImageFromContext(name2, ctx, true)
  2314. if err != nil {
  2315. c.Fatal(err)
  2316. }
  2317. if id1 != id2 {
  2318. c.Fatal("The cache should have been used but hasn't.")
  2319. }
  2320. }
  2321. func (s *DockerSuite) TestBuildAddLocalFileWithoutCache(c *check.C) {
  2322. // local files are not owned by the correct user
  2323. testRequires(c, NotUserNamespace)
  2324. name := "testbuildaddlocalfilewithoutcache"
  2325. name2 := "testbuildaddlocalfilewithoutcache2"
  2326. dockerfile := `
  2327. FROM busybox
  2328. MAINTAINER dockerio
  2329. ADD foo /usr/lib/bla/bar
  2330. RUN sh -c "[ $(cat /usr/lib/bla/bar) = "hello" ]"`
  2331. ctx, err := fakeContext(dockerfile, map[string]string{
  2332. "foo": "hello",
  2333. })
  2334. if err != nil {
  2335. c.Fatal(err)
  2336. }
  2337. defer ctx.Close()
  2338. id1, err := buildImageFromContext(name, ctx, true)
  2339. if err != nil {
  2340. c.Fatal(err)
  2341. }
  2342. id2, err := buildImageFromContext(name2, ctx, false)
  2343. if err != nil {
  2344. c.Fatal(err)
  2345. }
  2346. if id1 == id2 {
  2347. c.Fatal("The cache should have been invalided but hasn't.")
  2348. }
  2349. }
  2350. func (s *DockerSuite) TestBuildCopyDirButNotFile(c *check.C) {
  2351. name := "testbuildcopydirbutnotfile"
  2352. name2 := "testbuildcopydirbutnotfile2"
  2353. dockerfile := `
  2354. FROM ` + minimalBaseImage() + `
  2355. COPY dir /tmp/`
  2356. ctx, err := fakeContext(dockerfile, map[string]string{
  2357. "dir/foo": "hello",
  2358. })
  2359. if err != nil {
  2360. c.Fatal(err)
  2361. }
  2362. defer ctx.Close()
  2363. id1, err := buildImageFromContext(name, ctx, true)
  2364. if err != nil {
  2365. c.Fatal(err)
  2366. }
  2367. // Check that adding file with similar name doesn't mess with cache
  2368. if err := ctx.Add("dir_file", "hello2"); err != nil {
  2369. c.Fatal(err)
  2370. }
  2371. id2, err := buildImageFromContext(name2, ctx, true)
  2372. if err != nil {
  2373. c.Fatal(err)
  2374. }
  2375. if id1 != id2 {
  2376. c.Fatal("The cache should have been used but wasn't")
  2377. }
  2378. }
  2379. func (s *DockerSuite) TestBuildAddCurrentDirWithCache(c *check.C) {
  2380. name := "testbuildaddcurrentdirwithcache"
  2381. name2 := name + "2"
  2382. name3 := name + "3"
  2383. name4 := name + "4"
  2384. dockerfile := `
  2385. FROM ` + minimalBaseImage() + `
  2386. MAINTAINER dockerio
  2387. ADD . /usr/lib/bla`
  2388. ctx, err := fakeContext(dockerfile, map[string]string{
  2389. "foo": "hello",
  2390. })
  2391. if err != nil {
  2392. c.Fatal(err)
  2393. }
  2394. defer ctx.Close()
  2395. id1, err := buildImageFromContext(name, ctx, true)
  2396. if err != nil {
  2397. c.Fatal(err)
  2398. }
  2399. // Check that adding file invalidate cache of "ADD ."
  2400. if err := ctx.Add("bar", "hello2"); err != nil {
  2401. c.Fatal(err)
  2402. }
  2403. id2, err := buildImageFromContext(name2, ctx, true)
  2404. if err != nil {
  2405. c.Fatal(err)
  2406. }
  2407. if id1 == id2 {
  2408. c.Fatal("The cache should have been invalided but hasn't.")
  2409. }
  2410. // Check that changing file invalidate cache of "ADD ."
  2411. if err := ctx.Add("foo", "hello1"); err != nil {
  2412. c.Fatal(err)
  2413. }
  2414. id3, err := buildImageFromContext(name3, ctx, true)
  2415. if err != nil {
  2416. c.Fatal(err)
  2417. }
  2418. if id2 == id3 {
  2419. c.Fatal("The cache should have been invalided but hasn't.")
  2420. }
  2421. // Check that changing file to same content with different mtime does not
  2422. // invalidate cache of "ADD ."
  2423. time.Sleep(1 * time.Second) // wait second because of mtime precision
  2424. if err := ctx.Add("foo", "hello1"); err != nil {
  2425. c.Fatal(err)
  2426. }
  2427. id4, err := buildImageFromContext(name4, ctx, true)
  2428. if err != nil {
  2429. c.Fatal(err)
  2430. }
  2431. if id3 != id4 {
  2432. c.Fatal("The cache should have been used but hasn't.")
  2433. }
  2434. }
  2435. func (s *DockerSuite) TestBuildAddCurrentDirWithoutCache(c *check.C) {
  2436. name := "testbuildaddcurrentdirwithoutcache"
  2437. name2 := "testbuildaddcurrentdirwithoutcache2"
  2438. dockerfile := `
  2439. FROM ` + minimalBaseImage() + `
  2440. MAINTAINER dockerio
  2441. ADD . /usr/lib/bla`
  2442. ctx, err := fakeContext(dockerfile, map[string]string{
  2443. "foo": "hello",
  2444. })
  2445. if err != nil {
  2446. c.Fatal(err)
  2447. }
  2448. defer ctx.Close()
  2449. id1, err := buildImageFromContext(name, ctx, true)
  2450. if err != nil {
  2451. c.Fatal(err)
  2452. }
  2453. id2, err := buildImageFromContext(name2, ctx, false)
  2454. if err != nil {
  2455. c.Fatal(err)
  2456. }
  2457. if id1 == id2 {
  2458. c.Fatal("The cache should have been invalided but hasn't.")
  2459. }
  2460. }
  2461. func (s *DockerSuite) TestBuildAddRemoteFileWithCache(c *check.C) {
  2462. testRequires(c, DaemonIsLinux) // Windows doesn't have httpserver image yet
  2463. name := "testbuildaddremotefilewithcache"
  2464. server, err := fakeStorage(map[string]string{
  2465. "baz": "hello",
  2466. })
  2467. if err != nil {
  2468. c.Fatal(err)
  2469. }
  2470. defer server.Close()
  2471. id1, err := buildImage(name,
  2472. fmt.Sprintf(`FROM scratch
  2473. MAINTAINER dockerio
  2474. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2475. true)
  2476. if err != nil {
  2477. c.Fatal(err)
  2478. }
  2479. id2, err := buildImage(name,
  2480. fmt.Sprintf(`FROM scratch
  2481. MAINTAINER dockerio
  2482. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2483. true)
  2484. if err != nil {
  2485. c.Fatal(err)
  2486. }
  2487. if id1 != id2 {
  2488. c.Fatal("The cache should have been used but hasn't.")
  2489. }
  2490. }
  2491. func (s *DockerSuite) TestBuildAddRemoteFileWithoutCache(c *check.C) {
  2492. testRequires(c, DaemonIsLinux) // Windows doesn't have httpserver image yet
  2493. name := "testbuildaddremotefilewithoutcache"
  2494. name2 := "testbuildaddremotefilewithoutcache2"
  2495. server, err := fakeStorage(map[string]string{
  2496. "baz": "hello",
  2497. })
  2498. if err != nil {
  2499. c.Fatal(err)
  2500. }
  2501. defer server.Close()
  2502. id1, err := buildImage(name,
  2503. fmt.Sprintf(`FROM scratch
  2504. MAINTAINER dockerio
  2505. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2506. true)
  2507. if err != nil {
  2508. c.Fatal(err)
  2509. }
  2510. id2, err := buildImage(name2,
  2511. fmt.Sprintf(`FROM scratch
  2512. MAINTAINER dockerio
  2513. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2514. false)
  2515. if err != nil {
  2516. c.Fatal(err)
  2517. }
  2518. if id1 == id2 {
  2519. c.Fatal("The cache should have been invalided but hasn't.")
  2520. }
  2521. }
  2522. func (s *DockerSuite) TestBuildAddRemoteFileMTime(c *check.C) {
  2523. testRequires(c, DaemonIsLinux) // Windows doesn't have httpserver image yet
  2524. name := "testbuildaddremotefilemtime"
  2525. name2 := name + "2"
  2526. name3 := name + "3"
  2527. files := map[string]string{"baz": "hello"}
  2528. server, err := fakeStorage(files)
  2529. if err != nil {
  2530. c.Fatal(err)
  2531. }
  2532. defer server.Close()
  2533. ctx, err := fakeContext(fmt.Sprintf(`FROM scratch
  2534. MAINTAINER dockerio
  2535. ADD %s/baz /usr/lib/baz/quux`, server.URL()), nil)
  2536. if err != nil {
  2537. c.Fatal(err)
  2538. }
  2539. defer ctx.Close()
  2540. id1, err := buildImageFromContext(name, ctx, true)
  2541. if err != nil {
  2542. c.Fatal(err)
  2543. }
  2544. id2, err := buildImageFromContext(name2, ctx, true)
  2545. if err != nil {
  2546. c.Fatal(err)
  2547. }
  2548. if id1 != id2 {
  2549. c.Fatal("The cache should have been used but wasn't - #1")
  2550. }
  2551. // Now create a different server with same contents (causes different mtime)
  2552. // The cache should still be used
  2553. // allow some time for clock to pass as mtime precision is only 1s
  2554. time.Sleep(2 * time.Second)
  2555. server2, err := fakeStorage(files)
  2556. if err != nil {
  2557. c.Fatal(err)
  2558. }
  2559. defer server2.Close()
  2560. ctx2, err := fakeContext(fmt.Sprintf(`FROM scratch
  2561. MAINTAINER dockerio
  2562. ADD %s/baz /usr/lib/baz/quux`, server2.URL()), nil)
  2563. if err != nil {
  2564. c.Fatal(err)
  2565. }
  2566. defer ctx2.Close()
  2567. id3, err := buildImageFromContext(name3, ctx2, true)
  2568. if err != nil {
  2569. c.Fatal(err)
  2570. }
  2571. if id1 != id3 {
  2572. c.Fatal("The cache should have been used but wasn't")
  2573. }
  2574. }
  2575. func (s *DockerSuite) TestBuildAddLocalAndRemoteFilesWithCache(c *check.C) {
  2576. testRequires(c, DaemonIsLinux) // Windows doesn't have httpserver image yet
  2577. name := "testbuildaddlocalandremotefilewithcache"
  2578. server, err := fakeStorage(map[string]string{
  2579. "baz": "hello",
  2580. })
  2581. if err != nil {
  2582. c.Fatal(err)
  2583. }
  2584. defer server.Close()
  2585. ctx, err := fakeContext(fmt.Sprintf(`FROM scratch
  2586. MAINTAINER dockerio
  2587. ADD foo /usr/lib/bla/bar
  2588. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2589. map[string]string{
  2590. "foo": "hello world",
  2591. })
  2592. if err != nil {
  2593. c.Fatal(err)
  2594. }
  2595. defer ctx.Close()
  2596. id1, err := buildImageFromContext(name, ctx, true)
  2597. if err != nil {
  2598. c.Fatal(err)
  2599. }
  2600. id2, err := buildImageFromContext(name, ctx, true)
  2601. if err != nil {
  2602. c.Fatal(err)
  2603. }
  2604. if id1 != id2 {
  2605. c.Fatal("The cache should have been used but hasn't.")
  2606. }
  2607. }
  2608. func testContextTar(c *check.C, compression archive.Compression) {
  2609. ctx, err := fakeContext(
  2610. `FROM busybox
  2611. ADD foo /foo
  2612. CMD ["cat", "/foo"]`,
  2613. map[string]string{
  2614. "foo": "bar",
  2615. },
  2616. )
  2617. if err != nil {
  2618. c.Fatal(err)
  2619. }
  2620. defer ctx.Close()
  2621. context, err := archive.Tar(ctx.Dir, compression)
  2622. if err != nil {
  2623. c.Fatalf("failed to build context tar: %v", err)
  2624. }
  2625. name := "contexttar"
  2626. buildCmd := exec.Command(dockerBinary, "build", "-t", name, "-")
  2627. buildCmd.Stdin = context
  2628. if out, _, err := runCommandWithOutput(buildCmd); err != nil {
  2629. c.Fatalf("build failed to complete: %v %v", out, err)
  2630. }
  2631. }
  2632. func (s *DockerSuite) TestBuildContextTarGzip(c *check.C) {
  2633. testContextTar(c, archive.Gzip)
  2634. }
  2635. func (s *DockerSuite) TestBuildContextTarNoCompression(c *check.C) {
  2636. testContextTar(c, archive.Uncompressed)
  2637. }
  2638. func (s *DockerSuite) TestBuildNoContext(c *check.C) {
  2639. buildCmd := exec.Command(dockerBinary, "build", "-t", "nocontext", "-")
  2640. buildCmd.Stdin = strings.NewReader(
  2641. `FROM busybox
  2642. CMD ["echo", "ok"]`)
  2643. if out, _, err := runCommandWithOutput(buildCmd); err != nil {
  2644. c.Fatalf("build failed to complete: %v %v", out, err)
  2645. }
  2646. if out, _ := dockerCmd(c, "run", "--rm", "nocontext"); out != "ok\n" {
  2647. c.Fatalf("run produced invalid output: %q, expected %q", out, "ok")
  2648. }
  2649. }
  2650. // TODO: TestCaching
  2651. func (s *DockerSuite) TestBuildAddLocalAndRemoteFilesWithoutCache(c *check.C) {
  2652. testRequires(c, DaemonIsLinux) // Windows doesn't have httpserver image yet
  2653. name := "testbuildaddlocalandremotefilewithoutcache"
  2654. name2 := "testbuildaddlocalandremotefilewithoutcache2"
  2655. server, err := fakeStorage(map[string]string{
  2656. "baz": "hello",
  2657. })
  2658. if err != nil {
  2659. c.Fatal(err)
  2660. }
  2661. defer server.Close()
  2662. ctx, err := fakeContext(fmt.Sprintf(`FROM scratch
  2663. MAINTAINER dockerio
  2664. ADD foo /usr/lib/bla/bar
  2665. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2666. map[string]string{
  2667. "foo": "hello world",
  2668. })
  2669. if err != nil {
  2670. c.Fatal(err)
  2671. }
  2672. defer ctx.Close()
  2673. id1, err := buildImageFromContext(name, ctx, true)
  2674. if err != nil {
  2675. c.Fatal(err)
  2676. }
  2677. id2, err := buildImageFromContext(name2, ctx, false)
  2678. if err != nil {
  2679. c.Fatal(err)
  2680. }
  2681. if id1 == id2 {
  2682. c.Fatal("The cache should have been invalided but hasn't.")
  2683. }
  2684. }
  2685. func (s *DockerSuite) TestBuildWithVolumeOwnership(c *check.C) {
  2686. testRequires(c, DaemonIsLinux)
  2687. name := "testbuildimg"
  2688. _, err := buildImage(name,
  2689. `FROM busybox:latest
  2690. RUN mkdir /test && chown daemon:daemon /test && chmod 0600 /test
  2691. VOLUME /test`,
  2692. true)
  2693. if err != nil {
  2694. c.Fatal(err)
  2695. }
  2696. out, _ := dockerCmd(c, "run", "--rm", "testbuildimg", "ls", "-la", "/test")
  2697. if expected := "drw-------"; !strings.Contains(out, expected) {
  2698. c.Fatalf("expected %s received %s", expected, out)
  2699. }
  2700. if expected := "daemon daemon"; !strings.Contains(out, expected) {
  2701. c.Fatalf("expected %s received %s", expected, out)
  2702. }
  2703. }
  2704. // testing #1405 - config.Cmd does not get cleaned up if
  2705. // utilizing cache
  2706. func (s *DockerSuite) TestBuildEntrypointRunCleanup(c *check.C) {
  2707. name := "testbuildcmdcleanup"
  2708. if _, err := buildImage(name,
  2709. `FROM busybox
  2710. RUN echo "hello"`,
  2711. true); err != nil {
  2712. c.Fatal(err)
  2713. }
  2714. ctx, err := fakeContext(`FROM busybox
  2715. RUN echo "hello"
  2716. ADD foo /foo
  2717. ENTRYPOINT ["/bin/echo"]`,
  2718. map[string]string{
  2719. "foo": "hello",
  2720. })
  2721. if err != nil {
  2722. c.Fatal(err)
  2723. }
  2724. defer ctx.Close()
  2725. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2726. c.Fatal(err)
  2727. }
  2728. res := inspectField(c, name, "Config.Cmd")
  2729. // Cmd must be cleaned up
  2730. if res != "[]" {
  2731. c.Fatalf("Cmd %s, expected nil", res)
  2732. }
  2733. }
  2734. func (s *DockerSuite) TestBuildForbiddenContextPath(c *check.C) {
  2735. name := "testbuildforbidpath"
  2736. ctx, err := fakeContext(`FROM `+minimalBaseImage()+`
  2737. ADD ../../ test/
  2738. `,
  2739. map[string]string{
  2740. "test.txt": "test1",
  2741. "other.txt": "other",
  2742. })
  2743. if err != nil {
  2744. c.Fatal(err)
  2745. }
  2746. defer ctx.Close()
  2747. expected := "Forbidden path outside the build context: ../../ "
  2748. if daemonPlatform == "windows" {
  2749. expected = "Forbidden path outside the build context: ..\\..\\ "
  2750. }
  2751. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  2752. c.Fatalf("Wrong error: (should contain \"%s\") got:\n%v", expected, err)
  2753. }
  2754. }
  2755. func (s *DockerSuite) TestBuildAddFileNotFound(c *check.C) {
  2756. name := "testbuildaddnotfound"
  2757. expected := "foo: no such file or directory"
  2758. if daemonPlatform == "windows" {
  2759. expected = "foo: The system cannot find the file specified"
  2760. }
  2761. ctx, err := fakeContext(`FROM `+minimalBaseImage()+`
  2762. ADD foo /usr/local/bar`,
  2763. map[string]string{"bar": "hello"})
  2764. if err != nil {
  2765. c.Fatal(err)
  2766. }
  2767. defer ctx.Close()
  2768. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2769. if !strings.Contains(err.Error(), expected) {
  2770. c.Fatalf("Wrong error %v, must be about missing foo file or directory", err)
  2771. }
  2772. } else {
  2773. c.Fatal("Error must not be nil")
  2774. }
  2775. }
  2776. func (s *DockerSuite) TestBuildInheritance(c *check.C) {
  2777. testRequires(c, DaemonIsLinux)
  2778. name := "testbuildinheritance"
  2779. _, err := buildImage(name,
  2780. `FROM scratch
  2781. EXPOSE 2375`,
  2782. true)
  2783. if err != nil {
  2784. c.Fatal(err)
  2785. }
  2786. ports1 := inspectField(c, name, "Config.ExposedPorts")
  2787. _, err = buildImage(name,
  2788. fmt.Sprintf(`FROM %s
  2789. ENTRYPOINT ["/bin/echo"]`, name),
  2790. true)
  2791. if err != nil {
  2792. c.Fatal(err)
  2793. }
  2794. res := inspectField(c, name, "Config.Entrypoint")
  2795. if expected := "[/bin/echo]"; res != expected {
  2796. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  2797. }
  2798. ports2 := inspectField(c, name, "Config.ExposedPorts")
  2799. if ports1 != ports2 {
  2800. c.Fatalf("Ports must be same: %s != %s", ports1, ports2)
  2801. }
  2802. }
  2803. func (s *DockerSuite) TestBuildFails(c *check.C) {
  2804. name := "testbuildfails"
  2805. _, err := buildImage(name,
  2806. `FROM busybox
  2807. RUN sh -c "exit 23"`,
  2808. true)
  2809. if err != nil {
  2810. if !strings.Contains(err.Error(), "returned a non-zero code: 23") {
  2811. c.Fatalf("Wrong error %v, must be about non-zero code 23", err)
  2812. }
  2813. } else {
  2814. c.Fatal("Error must not be nil")
  2815. }
  2816. }
  2817. func (s *DockerSuite) TestBuildFailsDockerfileEmpty(c *check.C) {
  2818. name := "testbuildfails"
  2819. _, err := buildImage(name, ``, true)
  2820. if err != nil {
  2821. if !strings.Contains(err.Error(), "The Dockerfile (Dockerfile) cannot be empty") {
  2822. c.Fatalf("Wrong error %v, must be about empty Dockerfile", err)
  2823. }
  2824. } else {
  2825. c.Fatal("Error must not be nil")
  2826. }
  2827. }
  2828. func (s *DockerSuite) TestBuildOnBuild(c *check.C) {
  2829. name := "testbuildonbuild"
  2830. _, err := buildImage(name,
  2831. `FROM busybox
  2832. ONBUILD RUN touch foobar`,
  2833. true)
  2834. if err != nil {
  2835. c.Fatal(err)
  2836. }
  2837. _, err = buildImage(name,
  2838. fmt.Sprintf(`FROM %s
  2839. RUN [ -f foobar ]`, name),
  2840. true)
  2841. if err != nil {
  2842. c.Fatal(err)
  2843. }
  2844. }
  2845. func (s *DockerSuite) TestBuildOnBuildForbiddenChained(c *check.C) {
  2846. name := "testbuildonbuildforbiddenchained"
  2847. _, err := buildImage(name,
  2848. `FROM busybox
  2849. ONBUILD ONBUILD RUN touch foobar`,
  2850. true)
  2851. if err != nil {
  2852. if !strings.Contains(err.Error(), "Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed") {
  2853. c.Fatalf("Wrong error %v, must be about chaining ONBUILD", err)
  2854. }
  2855. } else {
  2856. c.Fatal("Error must not be nil")
  2857. }
  2858. }
  2859. func (s *DockerSuite) TestBuildOnBuildForbiddenFrom(c *check.C) {
  2860. name := "testbuildonbuildforbiddenfrom"
  2861. _, err := buildImage(name,
  2862. `FROM busybox
  2863. ONBUILD FROM scratch`,
  2864. true)
  2865. if err != nil {
  2866. if !strings.Contains(err.Error(), "FROM isn't allowed as an ONBUILD trigger") {
  2867. c.Fatalf("Wrong error %v, must be about FROM forbidden", err)
  2868. }
  2869. } else {
  2870. c.Fatal("Error must not be nil")
  2871. }
  2872. }
  2873. func (s *DockerSuite) TestBuildOnBuildForbiddenMaintainer(c *check.C) {
  2874. name := "testbuildonbuildforbiddenmaintainer"
  2875. _, err := buildImage(name,
  2876. `FROM busybox
  2877. ONBUILD MAINTAINER docker.io`,
  2878. true)
  2879. if err != nil {
  2880. if !strings.Contains(err.Error(), "MAINTAINER isn't allowed as an ONBUILD trigger") {
  2881. c.Fatalf("Wrong error %v, must be about MAINTAINER forbidden", err)
  2882. }
  2883. } else {
  2884. c.Fatal("Error must not be nil")
  2885. }
  2886. }
  2887. // gh #2446
  2888. func (s *DockerSuite) TestBuildAddToSymlinkDest(c *check.C) {
  2889. testRequires(c, DaemonIsLinux)
  2890. name := "testbuildaddtosymlinkdest"
  2891. ctx, err := fakeContext(`FROM busybox
  2892. RUN mkdir /foo
  2893. RUN ln -s /foo /bar
  2894. ADD foo /bar/
  2895. RUN [ -f /bar/foo ]
  2896. RUN [ -f /foo/foo ]`,
  2897. map[string]string{
  2898. "foo": "hello",
  2899. })
  2900. if err != nil {
  2901. c.Fatal(err)
  2902. }
  2903. defer ctx.Close()
  2904. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2905. c.Fatal(err)
  2906. }
  2907. }
  2908. func (s *DockerSuite) TestBuildEscapeWhitespace(c *check.C) {
  2909. name := "testbuildescaping"
  2910. _, err := buildImage(name, `
  2911. FROM busybox
  2912. MAINTAINER "Docker \
  2913. IO <io@\
  2914. docker.com>"
  2915. `, true)
  2916. if err != nil {
  2917. c.Fatal(err)
  2918. }
  2919. res := inspectField(c, name, "Author")
  2920. if res != "\"Docker IO <io@docker.com>\"" {
  2921. c.Fatalf("Parsed string did not match the escaped string. Got: %q", res)
  2922. }
  2923. }
  2924. func (s *DockerSuite) TestBuildVerifyIntString(c *check.C) {
  2925. // Verify that strings that look like ints are still passed as strings
  2926. name := "testbuildstringing"
  2927. _, err := buildImage(name, `
  2928. FROM busybox
  2929. MAINTAINER 123
  2930. `, true)
  2931. if err != nil {
  2932. c.Fatal(err)
  2933. }
  2934. out, _ := dockerCmd(c, "inspect", name)
  2935. if !strings.Contains(out, "\"123\"") {
  2936. c.Fatalf("Output does not contain the int as a string:\n%s", out)
  2937. }
  2938. }
  2939. func (s *DockerSuite) TestBuildDockerignore(c *check.C) {
  2940. testRequires(c, DaemonIsLinux) // TODO Windows: This test passes on Windows,
  2941. // but currently adds a disproportionate amount of time for the value it has.
  2942. // Removing it from Windows CI for now, but this will be revisited in the
  2943. // TP5 timeframe when perf is better.
  2944. name := "testbuilddockerignore"
  2945. dockerfile := `
  2946. FROM busybox
  2947. ADD . /bla
  2948. RUN sh -c "[[ -f /bla/src/x.go ]]"
  2949. RUN sh -c "[[ -f /bla/Makefile ]]"
  2950. RUN sh -c "[[ ! -e /bla/src/_vendor ]]"
  2951. RUN sh -c "[[ ! -e /bla/.gitignore ]]"
  2952. RUN sh -c "[[ ! -e /bla/README.md ]]"
  2953. RUN sh -c "[[ ! -e /bla/dir/foo ]]"
  2954. RUN sh -c "[[ ! -e /bla/foo ]]"
  2955. RUN sh -c "[[ ! -e /bla/.git ]]"
  2956. RUN sh -c "[[ ! -e v.cc ]]"
  2957. RUN sh -c "[[ ! -e src/v.cc ]]"
  2958. RUN sh -c "[[ ! -e src/_vendor/v.cc ]]"`
  2959. ctx, err := fakeContext(dockerfile, map[string]string{
  2960. "Makefile": "all:",
  2961. ".git/HEAD": "ref: foo",
  2962. "src/x.go": "package main",
  2963. "src/_vendor/v.go": "package main",
  2964. "src/_vendor/v.cc": "package main",
  2965. "src/v.cc": "package main",
  2966. "v.cc": "package main",
  2967. "dir/foo": "",
  2968. ".gitignore": "",
  2969. "README.md": "readme",
  2970. ".dockerignore": `
  2971. .git
  2972. pkg
  2973. .gitignore
  2974. src/_vendor
  2975. *.md
  2976. **/*.cc
  2977. dir`,
  2978. })
  2979. if err != nil {
  2980. c.Fatal(err)
  2981. }
  2982. defer ctx.Close()
  2983. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2984. c.Fatal(err)
  2985. }
  2986. }
  2987. func (s *DockerSuite) TestBuildDockerignoreCleanPaths(c *check.C) {
  2988. name := "testbuilddockerignorecleanpaths"
  2989. dockerfile := `
  2990. FROM busybox
  2991. ADD . /tmp/
  2992. RUN sh -c "(! ls /tmp/foo) && (! ls /tmp/foo2) && (! ls /tmp/dir1/foo)"`
  2993. ctx, err := fakeContext(dockerfile, map[string]string{
  2994. "foo": "foo",
  2995. "foo2": "foo2",
  2996. "dir1/foo": "foo in dir1",
  2997. ".dockerignore": "./foo\ndir1//foo\n./dir1/../foo2",
  2998. })
  2999. if err != nil {
  3000. c.Fatal(err)
  3001. }
  3002. defer ctx.Close()
  3003. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3004. c.Fatal(err)
  3005. }
  3006. }
  3007. func (s *DockerSuite) TestBuildDockerignoreExceptions(c *check.C) {
  3008. testRequires(c, DaemonIsLinux) // TODO Windows: This test passes on Windows,
  3009. // but currently adds a disproportionate amount of time for the value it has.
  3010. // Removing it from Windows CI for now, but this will be revisited in the
  3011. // TP5 timeframe when perf is better.
  3012. name := "testbuilddockerignoreexceptions"
  3013. dockerfile := `
  3014. FROM busybox
  3015. ADD . /bla
  3016. RUN sh -c "[[ -f /bla/src/x.go ]]"
  3017. RUN sh -c "[[ -f /bla/Makefile ]]"
  3018. RUN sh -c "[[ ! -e /bla/src/_vendor ]]"
  3019. RUN sh -c "[[ ! -e /bla/.gitignore ]]"
  3020. RUN sh -c "[[ ! -e /bla/README.md ]]"
  3021. RUN sh -c "[[ -e /bla/dir/dir/foo ]]"
  3022. RUN sh -c "[[ ! -e /bla/dir/foo1 ]]"
  3023. RUN sh -c "[[ -f /bla/dir/e ]]"
  3024. RUN sh -c "[[ -f /bla/dir/e-dir/foo ]]"
  3025. RUN sh -c "[[ ! -e /bla/foo ]]"
  3026. RUN sh -c "[[ ! -e /bla/.git ]]"
  3027. RUN sh -c "[[ -e /bla/dir/a.cc ]]"`
  3028. ctx, err := fakeContext(dockerfile, map[string]string{
  3029. "Makefile": "all:",
  3030. ".git/HEAD": "ref: foo",
  3031. "src/x.go": "package main",
  3032. "src/_vendor/v.go": "package main",
  3033. "dir/foo": "",
  3034. "dir/foo1": "",
  3035. "dir/dir/f1": "",
  3036. "dir/dir/foo": "",
  3037. "dir/e": "",
  3038. "dir/e-dir/foo": "",
  3039. ".gitignore": "",
  3040. "README.md": "readme",
  3041. "dir/a.cc": "hello",
  3042. ".dockerignore": `
  3043. .git
  3044. pkg
  3045. .gitignore
  3046. src/_vendor
  3047. *.md
  3048. dir
  3049. !dir/e*
  3050. !dir/dir/foo
  3051. **/*.cc
  3052. !**/*.cc`,
  3053. })
  3054. if err != nil {
  3055. c.Fatal(err)
  3056. }
  3057. defer ctx.Close()
  3058. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3059. c.Fatal(err)
  3060. }
  3061. }
  3062. func (s *DockerSuite) TestBuildDockerignoringDockerfile(c *check.C) {
  3063. name := "testbuilddockerignoredockerfile"
  3064. dockerfile := `
  3065. FROM busybox
  3066. ADD . /tmp/
  3067. RUN sh -c "! ls /tmp/Dockerfile"
  3068. RUN ls /tmp/.dockerignore`
  3069. ctx, err := fakeContext(dockerfile, map[string]string{
  3070. "Dockerfile": dockerfile,
  3071. ".dockerignore": "Dockerfile\n",
  3072. })
  3073. if err != nil {
  3074. c.Fatal(err)
  3075. }
  3076. defer ctx.Close()
  3077. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3078. c.Fatalf("Didn't ignore Dockerfile correctly:%s", err)
  3079. }
  3080. // now try it with ./Dockerfile
  3081. ctx.Add(".dockerignore", "./Dockerfile\n")
  3082. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3083. c.Fatalf("Didn't ignore ./Dockerfile correctly:%s", err)
  3084. }
  3085. }
  3086. func (s *DockerSuite) TestBuildDockerignoringRenamedDockerfile(c *check.C) {
  3087. name := "testbuilddockerignoredockerfile"
  3088. dockerfile := `
  3089. FROM busybox
  3090. ADD . /tmp/
  3091. RUN ls /tmp/Dockerfile
  3092. RUN sh -c "! ls /tmp/MyDockerfile"
  3093. RUN ls /tmp/.dockerignore`
  3094. ctx, err := fakeContext(dockerfile, map[string]string{
  3095. "Dockerfile": "Should not use me",
  3096. "MyDockerfile": dockerfile,
  3097. ".dockerignore": "MyDockerfile\n",
  3098. })
  3099. if err != nil {
  3100. c.Fatal(err)
  3101. }
  3102. defer ctx.Close()
  3103. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3104. c.Fatalf("Didn't ignore MyDockerfile correctly:%s", err)
  3105. }
  3106. // now try it with ./MyDockerfile
  3107. ctx.Add(".dockerignore", "./MyDockerfile\n")
  3108. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3109. c.Fatalf("Didn't ignore ./MyDockerfile correctly:%s", err)
  3110. }
  3111. }
  3112. func (s *DockerSuite) TestBuildDockerignoringDockerignore(c *check.C) {
  3113. name := "testbuilddockerignoredockerignore"
  3114. dockerfile := `
  3115. FROM busybox
  3116. ADD . /tmp/
  3117. RUN sh -c "! ls /tmp/.dockerignore"
  3118. RUN ls /tmp/Dockerfile`
  3119. ctx, err := fakeContext(dockerfile, map[string]string{
  3120. "Dockerfile": dockerfile,
  3121. ".dockerignore": ".dockerignore\n",
  3122. })
  3123. if err != nil {
  3124. c.Fatal(err)
  3125. }
  3126. defer ctx.Close()
  3127. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3128. c.Fatalf("Didn't ignore .dockerignore correctly:%s", err)
  3129. }
  3130. }
  3131. func (s *DockerSuite) TestBuildDockerignoreTouchDockerfile(c *check.C) {
  3132. var id1 string
  3133. var id2 string
  3134. name := "testbuilddockerignoretouchdockerfile"
  3135. dockerfile := `
  3136. FROM busybox
  3137. ADD . /tmp/`
  3138. ctx, err := fakeContext(dockerfile, map[string]string{
  3139. "Dockerfile": dockerfile,
  3140. ".dockerignore": "Dockerfile\n",
  3141. })
  3142. if err != nil {
  3143. c.Fatal(err)
  3144. }
  3145. defer ctx.Close()
  3146. if id1, err = buildImageFromContext(name, ctx, true); err != nil {
  3147. c.Fatalf("Didn't build it correctly:%s", err)
  3148. }
  3149. if id2, err = buildImageFromContext(name, ctx, true); err != nil {
  3150. c.Fatalf("Didn't build it correctly:%s", err)
  3151. }
  3152. if id1 != id2 {
  3153. c.Fatalf("Didn't use the cache - 1")
  3154. }
  3155. // Now make sure touching Dockerfile doesn't invalidate the cache
  3156. if err = ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil {
  3157. c.Fatalf("Didn't add Dockerfile: %s", err)
  3158. }
  3159. if id2, err = buildImageFromContext(name, ctx, true); err != nil {
  3160. c.Fatalf("Didn't build it correctly:%s", err)
  3161. }
  3162. if id1 != id2 {
  3163. c.Fatalf("Didn't use the cache - 2")
  3164. }
  3165. // One more time but just 'touch' it instead of changing the content
  3166. if err = ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil {
  3167. c.Fatalf("Didn't add Dockerfile: %s", err)
  3168. }
  3169. if id2, err = buildImageFromContext(name, ctx, true); err != nil {
  3170. c.Fatalf("Didn't build it correctly:%s", err)
  3171. }
  3172. if id1 != id2 {
  3173. c.Fatalf("Didn't use the cache - 3")
  3174. }
  3175. }
  3176. func (s *DockerSuite) TestBuildDockerignoringWholeDir(c *check.C) {
  3177. name := "testbuilddockerignorewholedir"
  3178. dockerfile := `
  3179. FROM busybox
  3180. COPY . /
  3181. RUN sh -c "[[ ! -e /.gitignore ]]"
  3182. RUN sh -c "[[ -f /Makefile ]]"`
  3183. ctx, err := fakeContext(dockerfile, map[string]string{
  3184. "Dockerfile": "FROM scratch",
  3185. "Makefile": "all:",
  3186. ".gitignore": "",
  3187. ".dockerignore": ".*\n",
  3188. })
  3189. c.Assert(err, check.IsNil)
  3190. defer ctx.Close()
  3191. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3192. c.Fatal(err)
  3193. }
  3194. c.Assert(ctx.Add(".dockerfile", "*"), check.IsNil)
  3195. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3196. c.Fatal(err)
  3197. }
  3198. c.Assert(ctx.Add(".dockerfile", "."), check.IsNil)
  3199. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3200. c.Fatal(err)
  3201. }
  3202. c.Assert(ctx.Add(".dockerfile", "?"), check.IsNil)
  3203. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3204. c.Fatal(err)
  3205. }
  3206. }
  3207. func (s *DockerSuite) TestBuildDockerignoringBadExclusion(c *check.C) {
  3208. name := "testbuilddockerignorebadexclusion"
  3209. dockerfile := `
  3210. FROM busybox
  3211. COPY . /
  3212. RUN sh -c "[[ ! -e /.gitignore ]]"
  3213. RUN sh -c "[[ -f /Makefile ]]"`
  3214. ctx, err := fakeContext(dockerfile, map[string]string{
  3215. "Dockerfile": "FROM scratch",
  3216. "Makefile": "all:",
  3217. ".gitignore": "",
  3218. ".dockerignore": "!\n",
  3219. })
  3220. c.Assert(err, check.IsNil)
  3221. defer ctx.Close()
  3222. if _, err = buildImageFromContext(name, ctx, true); err == nil {
  3223. c.Fatalf("Build was supposed to fail but didn't")
  3224. }
  3225. if err.Error() != "failed to build the image: Error checking context: 'Illegal exclusion pattern: !'.\n" {
  3226. c.Fatalf("Incorrect output, got:%q", err.Error())
  3227. }
  3228. }
  3229. func (s *DockerSuite) TestBuildDockerignoringWildTopDir(c *check.C) {
  3230. dockerfile := `
  3231. FROM busybox
  3232. COPY . /
  3233. RUN sh -c "[[ ! -e /.dockerignore ]]"
  3234. RUN sh -c "[[ ! -e /Dockerfile ]]"
  3235. RUN sh -c "[[ ! -e /file1 ]]"
  3236. RUN sh -c "[[ ! -e /dir ]]"`
  3237. ctx, err := fakeContext(dockerfile, map[string]string{
  3238. "Dockerfile": "FROM scratch",
  3239. "file1": "",
  3240. "dir/dfile1": "",
  3241. })
  3242. c.Assert(err, check.IsNil)
  3243. defer ctx.Close()
  3244. // All of these should result in ignoring all files
  3245. for _, variant := range []string{"**", "**/", "**/**", "*"} {
  3246. ctx.Add(".dockerignore", variant)
  3247. _, err = buildImageFromContext("noname", ctx, true)
  3248. c.Assert(err, check.IsNil, check.Commentf("variant: %s", variant))
  3249. }
  3250. }
  3251. func (s *DockerSuite) TestBuildDockerignoringWildDirs(c *check.C) {
  3252. testRequires(c, DaemonIsLinux) // TODO Windows: Fix this test; also perf
  3253. dockerfile := `
  3254. FROM busybox
  3255. COPY . /
  3256. #RUN sh -c "[[ -e /.dockerignore ]]"
  3257. RUN sh -c "[[ -e /Dockerfile ]] && \
  3258. [[ ! -e /file0 ]] && \
  3259. [[ ! -e /dir1/file0 ]] && \
  3260. [[ ! -e /dir2/file0 ]] && \
  3261. [[ ! -e /file1 ]] && \
  3262. [[ ! -e /dir1/file1 ]] && \
  3263. [[ ! -e /dir1/dir2/file1 ]] && \
  3264. [[ ! -e /dir1/file2 ]] && \
  3265. [[ -e /dir1/dir2/file2 ]] && \
  3266. [[ ! -e /dir1/dir2/file4 ]] && \
  3267. [[ ! -e /dir1/dir2/file5 ]] && \
  3268. [[ ! -e /dir1/dir2/file6 ]] && \
  3269. [[ ! -e /dir1/dir3/file7 ]] && \
  3270. [[ ! -e /dir1/dir3/file8 ]] && \
  3271. [[ -e /dir1/dir3 ]] && \
  3272. [[ -e /dir1/dir4 ]] && \
  3273. [[ ! -e 'dir1/dir5/fileAA' ]] && \
  3274. [[ -e 'dir1/dir5/fileAB' ]] && \
  3275. [[ -e 'dir1/dir5/fileB' ]]" # "." in pattern means nothing
  3276. RUN echo all done!`
  3277. ctx, err := fakeContext(dockerfile, map[string]string{
  3278. "Dockerfile": "FROM scratch",
  3279. "file0": "",
  3280. "dir1/file0": "",
  3281. "dir1/dir2/file0": "",
  3282. "file1": "",
  3283. "dir1/file1": "",
  3284. "dir1/dir2/file1": "",
  3285. "dir1/file2": "",
  3286. "dir1/dir2/file2": "", // remains
  3287. "dir1/dir2/file4": "",
  3288. "dir1/dir2/file5": "",
  3289. "dir1/dir2/file6": "",
  3290. "dir1/dir3/file7": "",
  3291. "dir1/dir3/file8": "",
  3292. "dir1/dir4/file9": "",
  3293. "dir1/dir5/fileAA": "",
  3294. "dir1/dir5/fileAB": "",
  3295. "dir1/dir5/fileB": "",
  3296. ".dockerignore": `
  3297. **/file0
  3298. **/*file1
  3299. **/dir1/file2
  3300. dir1/**/file4
  3301. **/dir2/file5
  3302. **/dir1/dir2/file6
  3303. dir1/dir3/**
  3304. **/dir4/**
  3305. **/file?A
  3306. **/file\?B
  3307. **/dir5/file.
  3308. `,
  3309. })
  3310. c.Assert(err, check.IsNil)
  3311. defer ctx.Close()
  3312. _, err = buildImageFromContext("noname", ctx, true)
  3313. c.Assert(err, check.IsNil)
  3314. }
  3315. func (s *DockerSuite) TestBuildLineBreak(c *check.C) {
  3316. testRequires(c, DaemonIsLinux)
  3317. name := "testbuildlinebreak"
  3318. _, err := buildImage(name,
  3319. `FROM busybox
  3320. RUN sh -c 'echo root:testpass \
  3321. > /tmp/passwd'
  3322. RUN mkdir -p /var/run/sshd
  3323. RUN sh -c "[ "$(cat /tmp/passwd)" = "root:testpass" ]"
  3324. RUN sh -c "[ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]"`,
  3325. true)
  3326. if err != nil {
  3327. c.Fatal(err)
  3328. }
  3329. }
  3330. func (s *DockerSuite) TestBuildEOLInLine(c *check.C) {
  3331. testRequires(c, DaemonIsLinux)
  3332. name := "testbuildeolinline"
  3333. _, err := buildImage(name,
  3334. `FROM busybox
  3335. RUN sh -c 'echo root:testpass > /tmp/passwd'
  3336. RUN echo "foo \n bar"; echo "baz"
  3337. RUN mkdir -p /var/run/sshd
  3338. RUN sh -c "[ "$(cat /tmp/passwd)" = "root:testpass" ]"
  3339. RUN sh -c "[ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]"`,
  3340. true)
  3341. if err != nil {
  3342. c.Fatal(err)
  3343. }
  3344. }
  3345. func (s *DockerSuite) TestBuildCommentsShebangs(c *check.C) {
  3346. testRequires(c, DaemonIsLinux)
  3347. name := "testbuildcomments"
  3348. _, err := buildImage(name,
  3349. `FROM busybox
  3350. # This is an ordinary comment.
  3351. RUN { echo '#!/bin/sh'; echo 'echo hello world'; } > /hello.sh
  3352. RUN [ ! -x /hello.sh ]
  3353. # comment with line break \
  3354. RUN chmod +x /hello.sh
  3355. RUN [ -x /hello.sh ]
  3356. RUN [ "$(cat /hello.sh)" = $'#!/bin/sh\necho hello world' ]
  3357. RUN [ "$(/hello.sh)" = "hello world" ]`,
  3358. true)
  3359. if err != nil {
  3360. c.Fatal(err)
  3361. }
  3362. }
  3363. func (s *DockerSuite) TestBuildUsersAndGroups(c *check.C) {
  3364. testRequires(c, DaemonIsLinux)
  3365. name := "testbuildusers"
  3366. _, err := buildImage(name,
  3367. `FROM busybox
  3368. # Make sure our defaults work
  3369. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)" = '0:0/root:root' ]
  3370. # 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)
  3371. USER root
  3372. RUN [ "$(id -G):$(id -Gn)" = '0 10:root wheel' ]
  3373. # Setup dockerio user and group
  3374. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd && \
  3375. echo 'dockerio:x:1001:' >> /etc/group
  3376. # Make sure we can switch to our user and all the information is exactly as we expect it to be
  3377. USER dockerio
  3378. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3379. # Switch back to root and double check that worked exactly as we might expect it to
  3380. USER root
  3381. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '0:0/root:root/0 10:root wheel' ] && \
  3382. # Add a "supplementary" group for our dockerio user \
  3383. echo 'supplementary:x:1002:dockerio' >> /etc/group
  3384. # ... and then go verify that we get it like we expect
  3385. USER dockerio
  3386. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  3387. USER 1001
  3388. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  3389. # super test the new "user:group" syntax
  3390. USER dockerio:dockerio
  3391. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3392. USER 1001:dockerio
  3393. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3394. USER dockerio:1001
  3395. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3396. USER 1001:1001
  3397. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3398. USER dockerio:supplementary
  3399. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3400. USER dockerio:1002
  3401. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3402. USER 1001:supplementary
  3403. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3404. USER 1001:1002
  3405. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3406. # make sure unknown uid/gid still works properly
  3407. USER 1042:1043
  3408. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1042:1043/1042:1043/1043:1043' ]`,
  3409. true)
  3410. if err != nil {
  3411. c.Fatal(err)
  3412. }
  3413. }
  3414. func (s *DockerSuite) TestBuildEnvUsage(c *check.C) {
  3415. // /docker/world/hello is not owned by the correct user
  3416. testRequires(c, NotUserNamespace)
  3417. testRequires(c, DaemonIsLinux)
  3418. name := "testbuildenvusage"
  3419. dockerfile := `FROM busybox
  3420. ENV HOME /root
  3421. ENV PATH $HOME/bin:$PATH
  3422. ENV PATH /tmp:$PATH
  3423. RUN [ "$PATH" = "/tmp:$HOME/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ]
  3424. ENV FOO /foo/baz
  3425. ENV BAR /bar
  3426. ENV BAZ $BAR
  3427. ENV FOOPATH $PATH:$FOO
  3428. RUN [ "$BAR" = "$BAZ" ]
  3429. RUN [ "$FOOPATH" = "$PATH:/foo/baz" ]
  3430. ENV FROM hello/docker/world
  3431. ENV TO /docker/world/hello
  3432. ADD $FROM $TO
  3433. RUN [ "$(cat $TO)" = "hello" ]
  3434. ENV abc=def
  3435. ENV ghi=$abc
  3436. RUN [ "$ghi" = "def" ]
  3437. `
  3438. ctx, err := fakeContext(dockerfile, map[string]string{
  3439. "hello/docker/world": "hello",
  3440. })
  3441. if err != nil {
  3442. c.Fatal(err)
  3443. }
  3444. defer ctx.Close()
  3445. _, err = buildImageFromContext(name, ctx, true)
  3446. if err != nil {
  3447. c.Fatal(err)
  3448. }
  3449. }
  3450. func (s *DockerSuite) TestBuildEnvUsage2(c *check.C) {
  3451. // /docker/world/hello is not owned by the correct user
  3452. testRequires(c, NotUserNamespace)
  3453. testRequires(c, DaemonIsLinux)
  3454. name := "testbuildenvusage2"
  3455. dockerfile := `FROM busybox
  3456. ENV abc=def def="hello world"
  3457. RUN [ "$abc,$def" = "def,hello world" ]
  3458. ENV def=hello\ world v1=abc v2="hi there" v3='boogie nights' v4="with'quotes too"
  3459. RUN [ "$def,$v1,$v2,$v3,$v4" = "hello world,abc,hi there,boogie nights,with'quotes too" ]
  3460. ENV abc=zzz FROM=hello/docker/world
  3461. ENV abc=zzz TO=/docker/world/hello
  3462. ADD $FROM $TO
  3463. RUN [ "$abc,$(cat $TO)" = "zzz,hello" ]
  3464. ENV abc 'yyy'
  3465. RUN [ $abc = 'yyy' ]
  3466. ENV abc=
  3467. RUN [ "$abc" = "" ]
  3468. # use grep to make sure if the builder substitutes \$foo by mistake
  3469. # we don't get a false positive
  3470. ENV abc=\$foo
  3471. RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep foo)
  3472. ENV abc \$foo
  3473. RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep foo)
  3474. ENV abc=\'foo\' abc2=\"foo\"
  3475. RUN [ "$abc,$abc2" = "'foo',\"foo\"" ]
  3476. ENV abc "foo"
  3477. RUN [ "$abc" = "foo" ]
  3478. ENV abc 'foo'
  3479. RUN [ "$abc" = 'foo' ]
  3480. ENV abc \'foo\'
  3481. RUN [ "$abc" = "'foo'" ]
  3482. ENV abc \"foo\"
  3483. RUN [ "$abc" = '"foo"' ]
  3484. ENV abc=ABC
  3485. RUN [ "$abc" = "ABC" ]
  3486. ENV def1=${abc:-DEF} def2=${ccc:-DEF}
  3487. ENV def3=${ccc:-${def2}xx} def4=${abc:+ALT} def5=${def2:+${abc}:} def6=${ccc:-\$abc:} def7=${ccc:-\${abc}:}
  3488. RUN [ "$def1,$def2,$def3,$def4,$def5,$def6,$def7" = 'ABC,DEF,DEFxx,ALT,ABC:,$abc:,${abc:}' ]
  3489. ENV mypath=${mypath:+$mypath:}/home
  3490. ENV mypath=${mypath:+$mypath:}/away
  3491. RUN [ "$mypath" = '/home:/away' ]
  3492. ENV e1=bar
  3493. ENV e2=$e1 e3=$e11 e4=\$e1 e5=\$e11
  3494. RUN [ "$e0,$e1,$e2,$e3,$e4,$e5" = ',bar,bar,,$e1,$e11' ]
  3495. ENV ee1 bar
  3496. ENV ee2 $ee1
  3497. ENV ee3 $ee11
  3498. ENV ee4 \$ee1
  3499. ENV ee5 \$ee11
  3500. RUN [ "$ee1,$ee2,$ee3,$ee4,$ee5" = 'bar,bar,,$ee1,$ee11' ]
  3501. ENV eee1="foo" eee2='foo'
  3502. ENV eee3 "foo"
  3503. ENV eee4 'foo'
  3504. RUN [ "$eee1,$eee2,$eee3,$eee4" = 'foo,foo,foo,foo' ]
  3505. `
  3506. ctx, err := fakeContext(dockerfile, map[string]string{
  3507. "hello/docker/world": "hello",
  3508. })
  3509. if err != nil {
  3510. c.Fatal(err)
  3511. }
  3512. defer ctx.Close()
  3513. _, err = buildImageFromContext(name, ctx, true)
  3514. if err != nil {
  3515. c.Fatal(err)
  3516. }
  3517. }
  3518. func (s *DockerSuite) TestBuildAddScript(c *check.C) {
  3519. testRequires(c, DaemonIsLinux)
  3520. name := "testbuildaddscript"
  3521. dockerfile := `
  3522. FROM busybox
  3523. ADD test /test
  3524. RUN ["chmod","+x","/test"]
  3525. RUN ["/test"]
  3526. RUN [ "$(cat /testfile)" = 'test!' ]`
  3527. ctx, err := fakeContext(dockerfile, map[string]string{
  3528. "test": "#!/bin/sh\necho 'test!' > /testfile",
  3529. })
  3530. if err != nil {
  3531. c.Fatal(err)
  3532. }
  3533. defer ctx.Close()
  3534. _, err = buildImageFromContext(name, ctx, true)
  3535. if err != nil {
  3536. c.Fatal(err)
  3537. }
  3538. }
  3539. func (s *DockerSuite) TestBuildAddTar(c *check.C) {
  3540. // /test/foo is not owned by the correct user
  3541. testRequires(c, NotUserNamespace)
  3542. name := "testbuildaddtar"
  3543. ctx := func() *FakeContext {
  3544. dockerfile := `
  3545. FROM busybox
  3546. ADD test.tar /
  3547. RUN cat /test/foo | grep Hi
  3548. ADD test.tar /test.tar
  3549. RUN cat /test.tar/test/foo | grep Hi
  3550. ADD test.tar /unlikely-to-exist
  3551. RUN cat /unlikely-to-exist/test/foo | grep Hi
  3552. ADD test.tar /unlikely-to-exist-trailing-slash/
  3553. RUN cat /unlikely-to-exist-trailing-slash/test/foo | grep Hi
  3554. RUN sh -c "mkdir /existing-directory" #sh -c is needed on Windows to use the correct mkdir
  3555. ADD test.tar /existing-directory
  3556. RUN cat /existing-directory/test/foo | grep Hi
  3557. ADD test.tar /existing-directory-trailing-slash/
  3558. RUN cat /existing-directory-trailing-slash/test/foo | grep Hi`
  3559. tmpDir, err := ioutil.TempDir("", "fake-context")
  3560. c.Assert(err, check.IsNil)
  3561. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3562. if err != nil {
  3563. c.Fatalf("failed to create test.tar archive: %v", err)
  3564. }
  3565. defer testTar.Close()
  3566. tw := tar.NewWriter(testTar)
  3567. if err := tw.WriteHeader(&tar.Header{
  3568. Name: "test/foo",
  3569. Size: 2,
  3570. }); err != nil {
  3571. c.Fatalf("failed to write tar file header: %v", err)
  3572. }
  3573. if _, err := tw.Write([]byte("Hi")); err != nil {
  3574. c.Fatalf("failed to write tar file content: %v", err)
  3575. }
  3576. if err := tw.Close(); err != nil {
  3577. c.Fatalf("failed to close tar archive: %v", err)
  3578. }
  3579. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3580. c.Fatalf("failed to open destination dockerfile: %v", err)
  3581. }
  3582. return fakeContextFromDir(tmpDir)
  3583. }()
  3584. defer ctx.Close()
  3585. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3586. c.Fatalf("build failed to complete for TestBuildAddTar: %v", err)
  3587. }
  3588. }
  3589. func (s *DockerSuite) TestBuildAddBrokenTar(c *check.C) {
  3590. name := "testbuildaddbrokentar"
  3591. ctx := func() *FakeContext {
  3592. dockerfile := `
  3593. FROM busybox
  3594. ADD test.tar /`
  3595. tmpDir, err := ioutil.TempDir("", "fake-context")
  3596. c.Assert(err, check.IsNil)
  3597. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3598. if err != nil {
  3599. c.Fatalf("failed to create test.tar archive: %v", err)
  3600. }
  3601. defer testTar.Close()
  3602. tw := tar.NewWriter(testTar)
  3603. if err := tw.WriteHeader(&tar.Header{
  3604. Name: "test/foo",
  3605. Size: 2,
  3606. }); err != nil {
  3607. c.Fatalf("failed to write tar file header: %v", err)
  3608. }
  3609. if _, err := tw.Write([]byte("Hi")); err != nil {
  3610. c.Fatalf("failed to write tar file content: %v", err)
  3611. }
  3612. if err := tw.Close(); err != nil {
  3613. c.Fatalf("failed to close tar archive: %v", err)
  3614. }
  3615. // Corrupt the tar by removing one byte off the end
  3616. stat, err := testTar.Stat()
  3617. if err != nil {
  3618. c.Fatalf("failed to stat tar archive: %v", err)
  3619. }
  3620. if err := testTar.Truncate(stat.Size() - 1); err != nil {
  3621. c.Fatalf("failed to truncate tar archive: %v", err)
  3622. }
  3623. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3624. c.Fatalf("failed to open destination dockerfile: %v", err)
  3625. }
  3626. return fakeContextFromDir(tmpDir)
  3627. }()
  3628. defer ctx.Close()
  3629. if _, err := buildImageFromContext(name, ctx, true); err == nil {
  3630. c.Fatalf("build should have failed for TestBuildAddBrokenTar")
  3631. }
  3632. }
  3633. func (s *DockerSuite) TestBuildAddNonTar(c *check.C) {
  3634. name := "testbuildaddnontar"
  3635. // Should not try to extract test.tar
  3636. ctx, err := fakeContext(`
  3637. FROM busybox
  3638. ADD test.tar /
  3639. RUN test -f /test.tar`,
  3640. map[string]string{"test.tar": "not_a_tar_file"})
  3641. if err != nil {
  3642. c.Fatal(err)
  3643. }
  3644. defer ctx.Close()
  3645. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3646. c.Fatalf("build failed for TestBuildAddNonTar")
  3647. }
  3648. }
  3649. func (s *DockerSuite) TestBuildAddTarXz(c *check.C) {
  3650. // /test/foo is not owned by the correct user
  3651. testRequires(c, NotUserNamespace)
  3652. testRequires(c, DaemonIsLinux)
  3653. name := "testbuildaddtarxz"
  3654. ctx := func() *FakeContext {
  3655. dockerfile := `
  3656. FROM busybox
  3657. ADD test.tar.xz /
  3658. RUN cat /test/foo | grep Hi`
  3659. tmpDir, err := ioutil.TempDir("", "fake-context")
  3660. c.Assert(err, check.IsNil)
  3661. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3662. if err != nil {
  3663. c.Fatalf("failed to create test.tar archive: %v", err)
  3664. }
  3665. defer testTar.Close()
  3666. tw := tar.NewWriter(testTar)
  3667. if err := tw.WriteHeader(&tar.Header{
  3668. Name: "test/foo",
  3669. Size: 2,
  3670. }); err != nil {
  3671. c.Fatalf("failed to write tar file header: %v", err)
  3672. }
  3673. if _, err := tw.Write([]byte("Hi")); err != nil {
  3674. c.Fatalf("failed to write tar file content: %v", err)
  3675. }
  3676. if err := tw.Close(); err != nil {
  3677. c.Fatalf("failed to close tar archive: %v", err)
  3678. }
  3679. xzCompressCmd := exec.Command("xz", "-k", "test.tar")
  3680. xzCompressCmd.Dir = tmpDir
  3681. out, _, err := runCommandWithOutput(xzCompressCmd)
  3682. if err != nil {
  3683. c.Fatal(err, out)
  3684. }
  3685. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3686. c.Fatalf("failed to open destination dockerfile: %v", err)
  3687. }
  3688. return fakeContextFromDir(tmpDir)
  3689. }()
  3690. defer ctx.Close()
  3691. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3692. c.Fatalf("build failed to complete for TestBuildAddTarXz: %v", err)
  3693. }
  3694. }
  3695. func (s *DockerSuite) TestBuildAddTarXzGz(c *check.C) {
  3696. testRequires(c, DaemonIsLinux)
  3697. name := "testbuildaddtarxzgz"
  3698. ctx := func() *FakeContext {
  3699. dockerfile := `
  3700. FROM busybox
  3701. ADD test.tar.xz.gz /
  3702. RUN ls /test.tar.xz.gz`
  3703. tmpDir, err := ioutil.TempDir("", "fake-context")
  3704. c.Assert(err, check.IsNil)
  3705. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3706. if err != nil {
  3707. c.Fatalf("failed to create test.tar archive: %v", err)
  3708. }
  3709. defer testTar.Close()
  3710. tw := tar.NewWriter(testTar)
  3711. if err := tw.WriteHeader(&tar.Header{
  3712. Name: "test/foo",
  3713. Size: 2,
  3714. }); err != nil {
  3715. c.Fatalf("failed to write tar file header: %v", err)
  3716. }
  3717. if _, err := tw.Write([]byte("Hi")); err != nil {
  3718. c.Fatalf("failed to write tar file content: %v", err)
  3719. }
  3720. if err := tw.Close(); err != nil {
  3721. c.Fatalf("failed to close tar archive: %v", err)
  3722. }
  3723. xzCompressCmd := exec.Command("xz", "-k", "test.tar")
  3724. xzCompressCmd.Dir = tmpDir
  3725. out, _, err := runCommandWithOutput(xzCompressCmd)
  3726. if err != nil {
  3727. c.Fatal(err, out)
  3728. }
  3729. gzipCompressCmd := exec.Command("gzip", "test.tar.xz")
  3730. gzipCompressCmd.Dir = tmpDir
  3731. out, _, err = runCommandWithOutput(gzipCompressCmd)
  3732. if err != nil {
  3733. c.Fatal(err, out)
  3734. }
  3735. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3736. c.Fatalf("failed to open destination dockerfile: %v", err)
  3737. }
  3738. return fakeContextFromDir(tmpDir)
  3739. }()
  3740. defer ctx.Close()
  3741. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3742. c.Fatalf("build failed to complete for TestBuildAddTarXz: %v", err)
  3743. }
  3744. }
  3745. func (s *DockerSuite) TestBuildFromGIT(c *check.C) {
  3746. name := "testbuildfromgit"
  3747. git, err := newFakeGit("repo", map[string]string{
  3748. "Dockerfile": `FROM busybox
  3749. ADD first /first
  3750. RUN [ -f /first ]
  3751. MAINTAINER docker`,
  3752. "first": "test git data",
  3753. }, true)
  3754. if err != nil {
  3755. c.Fatal(err)
  3756. }
  3757. defer git.Close()
  3758. _, err = buildImageFromPath(name, git.RepoURL, true)
  3759. if err != nil {
  3760. c.Fatal(err)
  3761. }
  3762. res := inspectField(c, name, "Author")
  3763. if res != "docker" {
  3764. c.Fatalf("Maintainer should be docker, got %s", res)
  3765. }
  3766. }
  3767. func (s *DockerSuite) TestBuildFromGITWithContext(c *check.C) {
  3768. name := "testbuildfromgit"
  3769. git, err := newFakeGit("repo", map[string]string{
  3770. "docker/Dockerfile": `FROM busybox
  3771. ADD first /first
  3772. RUN [ -f /first ]
  3773. MAINTAINER docker`,
  3774. "docker/first": "test git data",
  3775. }, true)
  3776. if err != nil {
  3777. c.Fatal(err)
  3778. }
  3779. defer git.Close()
  3780. u := fmt.Sprintf("%s#master:docker", git.RepoURL)
  3781. _, err = buildImageFromPath(name, u, true)
  3782. if err != nil {
  3783. c.Fatal(err)
  3784. }
  3785. res := inspectField(c, name, "Author")
  3786. if res != "docker" {
  3787. c.Fatalf("Maintainer should be docker, got %s", res)
  3788. }
  3789. }
  3790. func (s *DockerSuite) TestBuildFromGITwithF(c *check.C) {
  3791. name := "testbuildfromgitwithf"
  3792. git, err := newFakeGit("repo", map[string]string{
  3793. "myApp/myDockerfile": `FROM busybox
  3794. RUN echo hi from Dockerfile`,
  3795. }, true)
  3796. if err != nil {
  3797. c.Fatal(err)
  3798. }
  3799. defer git.Close()
  3800. out, _, err := dockerCmdWithError("build", "-t", name, "--no-cache", "-f", "myApp/myDockerfile", git.RepoURL)
  3801. if err != nil {
  3802. c.Fatalf("Error on build. Out: %s\nErr: %v", out, err)
  3803. }
  3804. if !strings.Contains(out, "hi from Dockerfile") {
  3805. c.Fatalf("Missing expected output, got:\n%s", out)
  3806. }
  3807. }
  3808. func (s *DockerSuite) TestBuildFromRemoteTarball(c *check.C) {
  3809. testRequires(c, DaemonIsLinux)
  3810. name := "testbuildfromremotetarball"
  3811. buffer := new(bytes.Buffer)
  3812. tw := tar.NewWriter(buffer)
  3813. defer tw.Close()
  3814. dockerfile := []byte(`FROM busybox
  3815. MAINTAINER docker`)
  3816. if err := tw.WriteHeader(&tar.Header{
  3817. Name: "Dockerfile",
  3818. Size: int64(len(dockerfile)),
  3819. }); err != nil {
  3820. c.Fatalf("failed to write tar file header: %v", err)
  3821. }
  3822. if _, err := tw.Write(dockerfile); err != nil {
  3823. c.Fatalf("failed to write tar file content: %v", err)
  3824. }
  3825. if err := tw.Close(); err != nil {
  3826. c.Fatalf("failed to close tar archive: %v", err)
  3827. }
  3828. server, err := fakeBinaryStorage(map[string]*bytes.Buffer{
  3829. "testT.tar": buffer,
  3830. })
  3831. c.Assert(err, check.IsNil)
  3832. defer server.Close()
  3833. _, err = buildImageFromPath(name, server.URL()+"/testT.tar", true)
  3834. c.Assert(err, check.IsNil)
  3835. res := inspectField(c, name, "Author")
  3836. if res != "docker" {
  3837. c.Fatalf("Maintainer should be docker, got %s", res)
  3838. }
  3839. }
  3840. func (s *DockerSuite) TestBuildCleanupCmdOnEntrypoint(c *check.C) {
  3841. name := "testbuildcmdcleanuponentrypoint"
  3842. if _, err := buildImage(name,
  3843. `FROM `+minimalBaseImage()+`
  3844. CMD ["test"]
  3845. ENTRYPOINT ["echo"]`,
  3846. true); err != nil {
  3847. c.Fatal(err)
  3848. }
  3849. if _, err := buildImage(name,
  3850. fmt.Sprintf(`FROM %s
  3851. ENTRYPOINT ["cat"]`, name),
  3852. true); err != nil {
  3853. c.Fatal(err)
  3854. }
  3855. res := inspectField(c, name, "Config.Cmd")
  3856. if res != "[]" {
  3857. c.Fatalf("Cmd %s, expected nil", res)
  3858. }
  3859. res = inspectField(c, name, "Config.Entrypoint")
  3860. if expected := "[cat]"; res != expected {
  3861. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  3862. }
  3863. }
  3864. func (s *DockerSuite) TestBuildClearCmd(c *check.C) {
  3865. name := "testbuildclearcmd"
  3866. _, err := buildImage(name,
  3867. `From `+minimalBaseImage()+`
  3868. ENTRYPOINT ["/bin/bash"]
  3869. CMD []`,
  3870. true)
  3871. if err != nil {
  3872. c.Fatal(err)
  3873. }
  3874. res := inspectFieldJSON(c, name, "Config.Cmd")
  3875. if res != "[]" {
  3876. c.Fatalf("Cmd %s, expected %s", res, "[]")
  3877. }
  3878. }
  3879. func (s *DockerSuite) TestBuildEmptyCmd(c *check.C) {
  3880. name := "testbuildemptycmd"
  3881. if _, err := buildImage(name, "FROM "+minimalBaseImage()+"\nMAINTAINER quux\n", true); err != nil {
  3882. c.Fatal(err)
  3883. }
  3884. res := inspectFieldJSON(c, name, "Config.Cmd")
  3885. if res != "null" {
  3886. c.Fatalf("Cmd %s, expected %s", res, "null")
  3887. }
  3888. }
  3889. func (s *DockerSuite) TestBuildOnBuildOutput(c *check.C) {
  3890. name := "testbuildonbuildparent"
  3891. if _, err := buildImage(name, "FROM busybox\nONBUILD RUN echo foo\n", true); err != nil {
  3892. c.Fatal(err)
  3893. }
  3894. _, out, err := buildImageWithOut(name, "FROM "+name+"\nMAINTAINER quux\n", true)
  3895. if err != nil {
  3896. c.Fatal(err)
  3897. }
  3898. if !strings.Contains(out, "# Executing 1 build trigger") {
  3899. c.Fatal("failed to find the build trigger output", out)
  3900. }
  3901. }
  3902. func (s *DockerSuite) TestBuildInvalidTag(c *check.C) {
  3903. name := "abcd:" + stringutils.GenerateRandomAlphaOnlyString(200)
  3904. _, out, err := buildImageWithOut(name, "FROM "+minimalBaseImage()+"\nMAINTAINER quux\n", true)
  3905. // if the error doesn't check for illegal tag name, or the image is built
  3906. // then this should fail
  3907. if !strings.Contains(out, "Error parsing reference") || strings.Contains(out, "Sending build context to Docker daemon") {
  3908. c.Fatalf("failed to stop before building. Error: %s, Output: %s", err, out)
  3909. }
  3910. }
  3911. func (s *DockerSuite) TestBuildCmdShDashC(c *check.C) {
  3912. name := "testbuildcmdshc"
  3913. if _, err := buildImage(name, "FROM busybox\nCMD echo cmd\n", true); err != nil {
  3914. c.Fatal(err)
  3915. }
  3916. res := inspectFieldJSON(c, name, "Config.Cmd")
  3917. expected := `["/bin/sh","-c","echo cmd"]`
  3918. if daemonPlatform == "windows" {
  3919. expected = `["cmd","/S","/C","echo cmd"]`
  3920. }
  3921. if res != expected {
  3922. c.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  3923. }
  3924. }
  3925. func (s *DockerSuite) TestBuildCmdSpaces(c *check.C) {
  3926. // Test to make sure that when we strcat arrays we take into account
  3927. // the arg separator to make sure ["echo","hi"] and ["echo hi"] don't
  3928. // look the same
  3929. name := "testbuildcmdspaces"
  3930. var id1 string
  3931. var id2 string
  3932. var err error
  3933. if id1, err = buildImage(name, "FROM busybox\nCMD [\"echo hi\"]\n", true); err != nil {
  3934. c.Fatal(err)
  3935. }
  3936. if id2, err = buildImage(name, "FROM busybox\nCMD [\"echo\", \"hi\"]\n", true); err != nil {
  3937. c.Fatal(err)
  3938. }
  3939. if id1 == id2 {
  3940. c.Fatal("Should not have resulted in the same CMD")
  3941. }
  3942. // Now do the same with ENTRYPOINT
  3943. if id1, err = buildImage(name, "FROM busybox\nENTRYPOINT [\"echo hi\"]\n", true); err != nil {
  3944. c.Fatal(err)
  3945. }
  3946. if id2, err = buildImage(name, "FROM busybox\nENTRYPOINT [\"echo\", \"hi\"]\n", true); err != nil {
  3947. c.Fatal(err)
  3948. }
  3949. if id1 == id2 {
  3950. c.Fatal("Should not have resulted in the same ENTRYPOINT")
  3951. }
  3952. }
  3953. func (s *DockerSuite) TestBuildCmdJSONNoShDashC(c *check.C) {
  3954. name := "testbuildcmdjson"
  3955. if _, err := buildImage(name, "FROM busybox\nCMD [\"echo\", \"cmd\"]", true); err != nil {
  3956. c.Fatal(err)
  3957. }
  3958. res := inspectFieldJSON(c, name, "Config.Cmd")
  3959. expected := `["echo","cmd"]`
  3960. if res != expected {
  3961. c.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  3962. }
  3963. }
  3964. func (s *DockerSuite) TestBuildErrorInvalidInstruction(c *check.C) {
  3965. name := "testbuildignoreinvalidinstruction"
  3966. out, _, err := buildImageWithOut(name, "FROM busybox\nfoo bar", true)
  3967. if err == nil {
  3968. c.Fatalf("Should have failed: %s", out)
  3969. }
  3970. }
  3971. func (s *DockerSuite) TestBuildEntrypointInheritance(c *check.C) {
  3972. if _, err := buildImage("parent", `
  3973. FROM busybox
  3974. ENTRYPOINT exit 130
  3975. `, true); err != nil {
  3976. c.Fatal(err)
  3977. }
  3978. if _, status, _ := dockerCmdWithError("run", "parent"); status != 130 {
  3979. c.Fatalf("expected exit code 130 but received %d", status)
  3980. }
  3981. if _, err := buildImage("child", `
  3982. FROM parent
  3983. ENTRYPOINT exit 5
  3984. `, true); err != nil {
  3985. c.Fatal(err)
  3986. }
  3987. if _, status, _ := dockerCmdWithError("run", "child"); status != 5 {
  3988. c.Fatalf("expected exit code 5 but received %d", status)
  3989. }
  3990. }
  3991. func (s *DockerSuite) TestBuildEntrypointInheritanceInspect(c *check.C) {
  3992. var (
  3993. name = "testbuildepinherit"
  3994. name2 = "testbuildepinherit2"
  3995. expected = `["/bin/sh","-c","echo quux"]`
  3996. )
  3997. if daemonPlatform == "windows" {
  3998. expected = `["cmd","/S","/C","echo quux"]`
  3999. }
  4000. if _, err := buildImage(name, "FROM busybox\nENTRYPOINT /foo/bar", true); err != nil {
  4001. c.Fatal(err)
  4002. }
  4003. if _, err := buildImage(name2, fmt.Sprintf("FROM %s\nENTRYPOINT echo quux", name), true); err != nil {
  4004. c.Fatal(err)
  4005. }
  4006. res := inspectFieldJSON(c, name2, "Config.Entrypoint")
  4007. if res != expected {
  4008. c.Fatalf("Expected value %s not in Config.Entrypoint: %s", expected, res)
  4009. }
  4010. out, _ := dockerCmd(c, "run", name2)
  4011. expected = "quux"
  4012. if strings.TrimSpace(out) != expected {
  4013. c.Fatalf("Expected output is %s, got %s", expected, out)
  4014. }
  4015. }
  4016. func (s *DockerSuite) TestBuildRunShEntrypoint(c *check.C) {
  4017. name := "testbuildentrypoint"
  4018. _, err := buildImage(name,
  4019. `FROM busybox
  4020. ENTRYPOINT echo`,
  4021. true)
  4022. if err != nil {
  4023. c.Fatal(err)
  4024. }
  4025. dockerCmd(c, "run", "--rm", name)
  4026. }
  4027. func (s *DockerSuite) TestBuildExoticShellInterpolation(c *check.C) {
  4028. testRequires(c, DaemonIsLinux)
  4029. name := "testbuildexoticshellinterpolation"
  4030. _, err := buildImage(name, `
  4031. FROM busybox
  4032. ENV SOME_VAR a.b.c
  4033. RUN [ "$SOME_VAR" = 'a.b.c' ]
  4034. RUN [ "${SOME_VAR}" = 'a.b.c' ]
  4035. RUN [ "${SOME_VAR%.*}" = 'a.b' ]
  4036. RUN [ "${SOME_VAR%%.*}" = 'a' ]
  4037. RUN [ "${SOME_VAR#*.}" = 'b.c' ]
  4038. RUN [ "${SOME_VAR##*.}" = 'c' ]
  4039. RUN [ "${SOME_VAR/c/d}" = 'a.b.d' ]
  4040. RUN [ "${#SOME_VAR}" = '5' ]
  4041. RUN [ "${SOME_UNSET_VAR:-$SOME_VAR}" = 'a.b.c' ]
  4042. RUN [ "${SOME_VAR:+Version: ${SOME_VAR}}" = 'Version: a.b.c' ]
  4043. RUN [ "${SOME_UNSET_VAR:+${SOME_VAR}}" = '' ]
  4044. RUN [ "${SOME_UNSET_VAR:-${SOME_VAR:-d.e.f}}" = 'a.b.c' ]
  4045. `, false)
  4046. if err != nil {
  4047. c.Fatal(err)
  4048. }
  4049. }
  4050. func (s *DockerSuite) TestBuildVerifySingleQuoteFails(c *check.C) {
  4051. // This testcase is supposed to generate an error because the
  4052. // JSON array we're passing in on the CMD uses single quotes instead
  4053. // of double quotes (per the JSON spec). This means we interpret it
  4054. // as a "string" instead of "JSON array" and pass it on to "sh -c" and
  4055. // it should barf on it.
  4056. name := "testbuildsinglequotefails"
  4057. if _, err := buildImage(name,
  4058. `FROM busybox
  4059. CMD [ '/bin/sh', '-c', 'echo hi' ]`,
  4060. true); err != nil {
  4061. c.Fatal(err)
  4062. }
  4063. if _, _, err := dockerCmdWithError("run", "--rm", name); err == nil {
  4064. c.Fatal("The image was not supposed to be able to run")
  4065. }
  4066. }
  4067. func (s *DockerSuite) TestBuildVerboseOut(c *check.C) {
  4068. name := "testbuildverboseout"
  4069. expected := "\n123\n"
  4070. if daemonPlatform == "windows" {
  4071. expected = "\n123\r\n"
  4072. }
  4073. _, out, err := buildImageWithOut(name,
  4074. `FROM busybox
  4075. RUN echo 123`,
  4076. false)
  4077. if err != nil {
  4078. c.Fatal(err)
  4079. }
  4080. if !strings.Contains(out, expected) {
  4081. c.Fatalf("Output should contain %q: %q", "123", out)
  4082. }
  4083. }
  4084. func (s *DockerSuite) TestBuildWithTabs(c *check.C) {
  4085. name := "testbuildwithtabs"
  4086. _, err := buildImage(name,
  4087. "FROM busybox\nRUN echo\tone\t\ttwo", true)
  4088. if err != nil {
  4089. c.Fatal(err)
  4090. }
  4091. res := inspectFieldJSON(c, name, "ContainerConfig.Cmd")
  4092. expected1 := `["/bin/sh","-c","echo\tone\t\ttwo"]`
  4093. expected2 := `["/bin/sh","-c","echo\u0009one\u0009\u0009two"]` // syntactically equivalent, and what Go 1.3 generates
  4094. if daemonPlatform == "windows" {
  4095. expected1 = `["cmd","/S","/C","echo\tone\t\ttwo"]`
  4096. expected2 = `["cmd","/S","/C","echo\u0009one\u0009\u0009two"]` // syntactically equivalent, and what Go 1.3 generates
  4097. }
  4098. if res != expected1 && res != expected2 {
  4099. c.Fatalf("Missing tabs.\nGot: %s\nExp: %s or %s", res, expected1, expected2)
  4100. }
  4101. }
  4102. func (s *DockerSuite) TestBuildLabels(c *check.C) {
  4103. name := "testbuildlabel"
  4104. expected := `{"License":"GPL","Vendor":"Acme"}`
  4105. _, err := buildImage(name,
  4106. `FROM busybox
  4107. LABEL Vendor=Acme
  4108. LABEL License GPL`,
  4109. true)
  4110. if err != nil {
  4111. c.Fatal(err)
  4112. }
  4113. res := inspectFieldJSON(c, name, "Config.Labels")
  4114. if res != expected {
  4115. c.Fatalf("Labels %s, expected %s", res, expected)
  4116. }
  4117. }
  4118. func (s *DockerSuite) TestBuildLabelsCache(c *check.C) {
  4119. name := "testbuildlabelcache"
  4120. id1, err := buildImage(name,
  4121. `FROM busybox
  4122. LABEL Vendor=Acme`, false)
  4123. if err != nil {
  4124. c.Fatalf("Build 1 should have worked: %v", err)
  4125. }
  4126. id2, err := buildImage(name,
  4127. `FROM busybox
  4128. LABEL Vendor=Acme`, true)
  4129. if err != nil || id1 != id2 {
  4130. c.Fatalf("Build 2 should have worked & used cache(%s,%s): %v", id1, id2, err)
  4131. }
  4132. id2, err = buildImage(name,
  4133. `FROM busybox
  4134. LABEL Vendor=Acme1`, true)
  4135. if err != nil || id1 == id2 {
  4136. c.Fatalf("Build 3 should have worked & NOT used cache(%s,%s): %v", id1, id2, err)
  4137. }
  4138. id2, err = buildImage(name,
  4139. `FROM busybox
  4140. LABEL Vendor Acme`, true) // Note: " " and "=" should be same
  4141. if err != nil || id1 != id2 {
  4142. c.Fatalf("Build 4 should have worked & used cache(%s,%s): %v", id1, id2, err)
  4143. }
  4144. // Now make sure the cache isn't used by mistake
  4145. id1, err = buildImage(name,
  4146. `FROM busybox
  4147. LABEL f1=b1 f2=b2`, false)
  4148. if err != nil {
  4149. c.Fatalf("Build 5 should have worked: %q", err)
  4150. }
  4151. id2, err = buildImage(name,
  4152. `FROM busybox
  4153. LABEL f1="b1 f2=b2"`, true)
  4154. if err != nil || id1 == id2 {
  4155. c.Fatalf("Build 6 should have worked & NOT used the cache(%s,%s): %q", id1, id2, err)
  4156. }
  4157. }
  4158. func (s *DockerSuite) TestBuildNotVerboseSuccess(c *check.C) {
  4159. // This test makes sure that -q works correctly when build is successful:
  4160. // stdout has only the image ID (long image ID) and stderr is empty.
  4161. var stdout, stderr string
  4162. var err error
  4163. outRegexp := regexp.MustCompile("^(sha256:|)[a-z0-9]{64}\\n$")
  4164. tt := []struct {
  4165. Name string
  4166. BuildFunc func(string)
  4167. }{
  4168. {
  4169. Name: "quiet_build_stdin_success",
  4170. BuildFunc: func(name string) {
  4171. _, stdout, stderr, err = buildImageWithStdoutStderr(name, "FROM busybox", true, "-q", "--force-rm", "--rm")
  4172. },
  4173. },
  4174. {
  4175. Name: "quiet_build_ctx_success",
  4176. BuildFunc: func(name string) {
  4177. ctx, err := fakeContext("FROM busybox", map[string]string{
  4178. "quiet_build_success_fctx": "test",
  4179. })
  4180. if err != nil {
  4181. c.Fatalf("Failed to create context: %s", err.Error())
  4182. }
  4183. defer ctx.Close()
  4184. _, stdout, stderr, err = buildImageFromContextWithStdoutStderr(name, ctx, true, "-q", "--force-rm", "--rm")
  4185. },
  4186. },
  4187. {
  4188. Name: "quiet_build_git_success",
  4189. BuildFunc: func(name string) {
  4190. git, err := newFakeGit("repo", map[string]string{
  4191. "Dockerfile": "FROM busybox",
  4192. }, true)
  4193. if err != nil {
  4194. c.Fatalf("Failed to create the git repo: %s", err.Error())
  4195. }
  4196. defer git.Close()
  4197. _, stdout, stderr, err = buildImageFromGitWithStdoutStderr(name, git, true, "-q", "--force-rm", "--rm")
  4198. },
  4199. },
  4200. }
  4201. for _, te := range tt {
  4202. te.BuildFunc(te.Name)
  4203. if err != nil {
  4204. c.Fatalf("Test %s shouldn't fail, but got the following error: %s", te.Name, err.Error())
  4205. }
  4206. if outRegexp.Find([]byte(stdout)) == nil {
  4207. c.Fatalf("Test %s expected stdout to match the [%v] regexp, but it is [%v]", te.Name, outRegexp, stdout)
  4208. }
  4209. if runtime.GOOS == "windows" {
  4210. // stderr contains a security warning on Windows if the daemon isn't Windows
  4211. lines := strings.Split(stderr, "\n")
  4212. warningCount := 0
  4213. for _, v := range lines {
  4214. warningText := "SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host."
  4215. if strings.Contains(v, warningText) {
  4216. warningCount++
  4217. }
  4218. if v != "" && !strings.Contains(v, warningText) {
  4219. c.Fatalf("Stderr contains unexpected output line: %q", v)
  4220. }
  4221. }
  4222. if warningCount != 1 && daemonPlatform != "windows" {
  4223. c.Fatalf("Test %s didn't get security warning running from Windows to non-Windows", te.Name)
  4224. }
  4225. } else {
  4226. if stderr != "" {
  4227. c.Fatalf("Test %s expected stderr to be empty, but it is [%#v]", te.Name, stderr)
  4228. }
  4229. }
  4230. }
  4231. }
  4232. func (s *DockerSuite) TestBuildNotVerboseFailureWithNonExistImage(c *check.C) {
  4233. // This test makes sure that -q works correctly when build fails by
  4234. // comparing between the stderr output in quiet mode and in stdout
  4235. // and stderr output in verbose mode
  4236. testRequires(c, Network)
  4237. testName := "quiet_build_not_exists_image"
  4238. buildCmd := "FROM busybox11"
  4239. _, _, qstderr, qerr := buildImageWithStdoutStderr(testName, buildCmd, false, "-q", "--force-rm", "--rm")
  4240. _, vstdout, vstderr, verr := buildImageWithStdoutStderr(testName, buildCmd, false, "--force-rm", "--rm")
  4241. if verr == nil || qerr == nil {
  4242. c.Fatal(fmt.Errorf("Test [%s] expected to fail but didn't", testName))
  4243. }
  4244. if qstderr != vstdout+vstderr {
  4245. c.Fatal(fmt.Errorf("Test[%s] expected that quiet stderr and verbose stdout are equal; quiet [%v], verbose [%v]", testName, qstderr, vstdout+vstderr))
  4246. }
  4247. }
  4248. func (s *DockerSuite) TestBuildNotVerboseFailure(c *check.C) {
  4249. // This test makes sure that -q works correctly when build fails by
  4250. // comparing between the stderr output in quiet mode and in stdout
  4251. // and stderr output in verbose mode
  4252. tt := []struct {
  4253. TestName string
  4254. BuildCmds string
  4255. }{
  4256. {"quiet_build_no_from_at_the_beginning", "RUN whoami"},
  4257. {"quiet_build_unknown_instr", "FROMD busybox"},
  4258. }
  4259. for _, te := range tt {
  4260. _, _, qstderr, qerr := buildImageWithStdoutStderr(te.TestName, te.BuildCmds, false, "-q", "--force-rm", "--rm")
  4261. _, vstdout, vstderr, verr := buildImageWithStdoutStderr(te.TestName, te.BuildCmds, false, "--force-rm", "--rm")
  4262. if verr == nil || qerr == nil {
  4263. c.Fatal(fmt.Errorf("Test [%s] expected to fail but didn't", te.TestName))
  4264. }
  4265. if qstderr != vstdout+vstderr {
  4266. c.Fatal(fmt.Errorf("Test[%s] expected that quiet stderr and verbose stdout are equal; quiet [%v], verbose [%v]", te.TestName, qstderr, vstdout+vstderr))
  4267. }
  4268. }
  4269. }
  4270. func (s *DockerSuite) TestBuildNotVerboseFailureRemote(c *check.C) {
  4271. // This test ensures that when given a wrong URL, stderr in quiet mode and
  4272. // stdout and stderr in verbose mode are identical.
  4273. URL := "http://bla.bla.com"
  4274. Name := "quiet_build_wrong_remote"
  4275. _, _, qstderr, qerr := buildImageWithStdoutStderr(Name, "", false, "-q", "--force-rm", "--rm", URL)
  4276. _, vstdout, vstderr, verr := buildImageWithStdoutStderr(Name, "", false, "--force-rm", "--rm", URL)
  4277. if qerr == nil || verr == nil {
  4278. c.Fatal(fmt.Errorf("Test [%s] expected to fail but didn't", Name))
  4279. }
  4280. if qstderr != vstdout+vstderr {
  4281. c.Fatal(fmt.Errorf("Test[%s] expected that quiet stderr and verbose stdout are equal; quiet [%v], verbose [%v]", Name, qstderr, vstdout))
  4282. }
  4283. }
  4284. func (s *DockerSuite) TestBuildStderr(c *check.C) {
  4285. // This test just makes sure that no non-error output goes
  4286. // to stderr
  4287. name := "testbuildstderr"
  4288. _, _, stderr, err := buildImageWithStdoutStderr(name,
  4289. "FROM busybox\nRUN echo one", true)
  4290. if err != nil {
  4291. c.Fatal(err)
  4292. }
  4293. if runtime.GOOS == "windows" {
  4294. // stderr might contain a security warning on windows
  4295. lines := strings.Split(stderr, "\n")
  4296. for _, v := range lines {
  4297. if v != "" && !strings.Contains(v, "SECURITY WARNING:") {
  4298. c.Fatalf("Stderr contains unexpected output line: %q", v)
  4299. }
  4300. }
  4301. } else {
  4302. if stderr != "" {
  4303. c.Fatalf("Stderr should have been empty, instead its: %q", stderr)
  4304. }
  4305. }
  4306. }
  4307. func (s *DockerSuite) TestBuildChownSingleFile(c *check.C) {
  4308. testRequires(c, UnixCli) // test uses chown: not available on windows
  4309. testRequires(c, DaemonIsLinux)
  4310. name := "testbuildchownsinglefile"
  4311. ctx, err := fakeContext(`
  4312. FROM busybox
  4313. COPY test /
  4314. RUN ls -l /test
  4315. RUN [ $(ls -l /test | awk '{print $3":"$4}') = 'root:root' ]
  4316. `, map[string]string{
  4317. "test": "test",
  4318. })
  4319. if err != nil {
  4320. c.Fatal(err)
  4321. }
  4322. defer ctx.Close()
  4323. if err := os.Chown(filepath.Join(ctx.Dir, "test"), 4242, 4242); err != nil {
  4324. c.Fatal(err)
  4325. }
  4326. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  4327. c.Fatal(err)
  4328. }
  4329. }
  4330. func (s *DockerSuite) TestBuildSymlinkBreakout(c *check.C) {
  4331. name := "testbuildsymlinkbreakout"
  4332. tmpdir, err := ioutil.TempDir("", name)
  4333. c.Assert(err, check.IsNil)
  4334. defer os.RemoveAll(tmpdir)
  4335. ctx := filepath.Join(tmpdir, "context")
  4336. if err := os.MkdirAll(ctx, 0755); err != nil {
  4337. c.Fatal(err)
  4338. }
  4339. if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte(`
  4340. from busybox
  4341. add symlink.tar /
  4342. add inject /symlink/
  4343. `), 0644); err != nil {
  4344. c.Fatal(err)
  4345. }
  4346. inject := filepath.Join(ctx, "inject")
  4347. if err := ioutil.WriteFile(inject, nil, 0644); err != nil {
  4348. c.Fatal(err)
  4349. }
  4350. f, err := os.Create(filepath.Join(ctx, "symlink.tar"))
  4351. if err != nil {
  4352. c.Fatal(err)
  4353. }
  4354. w := tar.NewWriter(f)
  4355. w.WriteHeader(&tar.Header{
  4356. Name: "symlink2",
  4357. Typeflag: tar.TypeSymlink,
  4358. Linkname: "/../../../../../../../../../../../../../../",
  4359. Uid: os.Getuid(),
  4360. Gid: os.Getgid(),
  4361. })
  4362. w.WriteHeader(&tar.Header{
  4363. Name: "symlink",
  4364. Typeflag: tar.TypeSymlink,
  4365. Linkname: filepath.Join("symlink2", tmpdir),
  4366. Uid: os.Getuid(),
  4367. Gid: os.Getgid(),
  4368. })
  4369. w.Close()
  4370. f.Close()
  4371. if _, err := buildImageFromContext(name, fakeContextFromDir(ctx), false); err != nil {
  4372. c.Fatal(err)
  4373. }
  4374. if _, err := os.Lstat(filepath.Join(tmpdir, "inject")); err == nil {
  4375. c.Fatal("symlink breakout - inject")
  4376. } else if !os.IsNotExist(err) {
  4377. c.Fatalf("unexpected error: %v", err)
  4378. }
  4379. }
  4380. func (s *DockerSuite) TestBuildXZHost(c *check.C) {
  4381. // /usr/local/sbin/xz gets permission denied for the user
  4382. testRequires(c, NotUserNamespace)
  4383. testRequires(c, DaemonIsLinux)
  4384. name := "testbuildxzhost"
  4385. ctx, err := fakeContext(`
  4386. FROM busybox
  4387. ADD xz /usr/local/sbin/
  4388. RUN chmod 755 /usr/local/sbin/xz
  4389. ADD test.xz /
  4390. RUN [ ! -e /injected ]`,
  4391. map[string]string{
  4392. "test.xz": "\xfd\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00" +
  4393. "\x21\x01\x16\x00\x00\x00\x74\x2f\xe5\xa3\x01\x00\x3f\xfd" +
  4394. "\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00\x21",
  4395. "xz": "#!/bin/sh\ntouch /injected",
  4396. })
  4397. if err != nil {
  4398. c.Fatal(err)
  4399. }
  4400. defer ctx.Close()
  4401. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  4402. c.Fatal(err)
  4403. }
  4404. }
  4405. func (s *DockerSuite) TestBuildVolumesRetainContents(c *check.C) {
  4406. // /foo/file gets permission denied for the user
  4407. testRequires(c, NotUserNamespace)
  4408. testRequires(c, DaemonIsLinux) // TODO Windows: Issue #20127
  4409. var (
  4410. name = "testbuildvolumescontent"
  4411. expected = "some text"
  4412. volName = "/foo"
  4413. )
  4414. if daemonPlatform == "windows" {
  4415. volName = "C:/foo"
  4416. }
  4417. ctx, err := fakeContext(`
  4418. FROM busybox
  4419. COPY content /foo/file
  4420. VOLUME `+volName+`
  4421. CMD cat /foo/file`,
  4422. map[string]string{
  4423. "content": expected,
  4424. })
  4425. if err != nil {
  4426. c.Fatal(err)
  4427. }
  4428. defer ctx.Close()
  4429. if _, err := buildImageFromContext(name, ctx, false); err != nil {
  4430. c.Fatal(err)
  4431. }
  4432. out, _ := dockerCmd(c, "run", "--rm", name)
  4433. if out != expected {
  4434. c.Fatalf("expected file contents for /foo/file to be %q but received %q", expected, out)
  4435. }
  4436. }
  4437. func (s *DockerSuite) TestBuildRenamedDockerfile(c *check.C) {
  4438. ctx, err := fakeContext(`FROM busybox
  4439. RUN echo from Dockerfile`,
  4440. map[string]string{
  4441. "Dockerfile": "FROM busybox\nRUN echo from Dockerfile",
  4442. "files/Dockerfile": "FROM busybox\nRUN echo from files/Dockerfile",
  4443. "files/dFile": "FROM busybox\nRUN echo from files/dFile",
  4444. "dFile": "FROM busybox\nRUN echo from dFile",
  4445. "files/dFile2": "FROM busybox\nRUN echo from files/dFile2",
  4446. })
  4447. if err != nil {
  4448. c.Fatal(err)
  4449. }
  4450. defer ctx.Close()
  4451. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", "test1", ".")
  4452. if err != nil {
  4453. c.Fatalf("Failed to build: %s\n%s", out, err)
  4454. }
  4455. if !strings.Contains(out, "from Dockerfile") {
  4456. c.Fatalf("test1 should have used Dockerfile, output:%s", out)
  4457. }
  4458. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", "-f", filepath.Join("files", "Dockerfile"), "-t", "test2", ".")
  4459. if err != nil {
  4460. c.Fatal(err)
  4461. }
  4462. if !strings.Contains(out, "from files/Dockerfile") {
  4463. c.Fatalf("test2 should have used files/Dockerfile, output:%s", out)
  4464. }
  4465. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", fmt.Sprintf("--file=%s", filepath.Join("files", "dFile")), "-t", "test3", ".")
  4466. if err != nil {
  4467. c.Fatal(err)
  4468. }
  4469. if !strings.Contains(out, "from files/dFile") {
  4470. c.Fatalf("test3 should have used files/dFile, output:%s", out)
  4471. }
  4472. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", "--file=dFile", "-t", "test4", ".")
  4473. if err != nil {
  4474. c.Fatal(err)
  4475. }
  4476. if !strings.Contains(out, "from dFile") {
  4477. c.Fatalf("test4 should have used dFile, output:%s", out)
  4478. }
  4479. dirWithNoDockerfile, err := ioutil.TempDir(os.TempDir(), "test5")
  4480. c.Assert(err, check.IsNil)
  4481. nonDockerfileFile := filepath.Join(dirWithNoDockerfile, "notDockerfile")
  4482. if _, err = os.Create(nonDockerfileFile); err != nil {
  4483. c.Fatal(err)
  4484. }
  4485. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", fmt.Sprintf("--file=%s", nonDockerfileFile), "-t", "test5", ".")
  4486. if err == nil {
  4487. c.Fatalf("test5 was supposed to fail to find passwd")
  4488. }
  4489. if expected := fmt.Sprintf("The Dockerfile (%s) must be within the build context (.)", nonDockerfileFile); !strings.Contains(out, expected) {
  4490. c.Fatalf("wrong error messsage:%v\nexpected to contain=%v", out, expected)
  4491. }
  4492. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join("..", "Dockerfile"), "-t", "test6", "..")
  4493. if err != nil {
  4494. c.Fatalf("test6 failed: %s", err)
  4495. }
  4496. if !strings.Contains(out, "from Dockerfile") {
  4497. c.Fatalf("test6 should have used root Dockerfile, output:%s", out)
  4498. }
  4499. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join(ctx.Dir, "files", "Dockerfile"), "-t", "test7", "..")
  4500. if err != nil {
  4501. c.Fatalf("test7 failed: %s", err)
  4502. }
  4503. if !strings.Contains(out, "from files/Dockerfile") {
  4504. c.Fatalf("test7 should have used files Dockerfile, output:%s", out)
  4505. }
  4506. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join("..", "Dockerfile"), "-t", "test8", ".")
  4507. if err == nil || !strings.Contains(out, "must be within the build context") {
  4508. c.Fatalf("test8 should have failed with Dockerfile out of context: %s", err)
  4509. }
  4510. tmpDir := os.TempDir()
  4511. out, _, err = dockerCmdInDir(c, tmpDir, "build", "-t", "test9", ctx.Dir)
  4512. if err != nil {
  4513. c.Fatalf("test9 - failed: %s", err)
  4514. }
  4515. if !strings.Contains(out, "from Dockerfile") {
  4516. c.Fatalf("test9 should have used root Dockerfile, output:%s", out)
  4517. }
  4518. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", "dFile2", "-t", "test10", ".")
  4519. if err != nil {
  4520. c.Fatalf("test10 should have worked: %s", err)
  4521. }
  4522. if !strings.Contains(out, "from files/dFile2") {
  4523. c.Fatalf("test10 should have used files/dFile2, output:%s", out)
  4524. }
  4525. }
  4526. func (s *DockerSuite) TestBuildFromMixedcaseDockerfile(c *check.C) {
  4527. testRequires(c, UnixCli) // Dockerfile overwrites dockerfile on windows
  4528. testRequires(c, DaemonIsLinux)
  4529. ctx, err := fakeContext(`FROM busybox
  4530. RUN echo from dockerfile`,
  4531. map[string]string{
  4532. "dockerfile": "FROM busybox\nRUN echo from dockerfile",
  4533. })
  4534. if err != nil {
  4535. c.Fatal(err)
  4536. }
  4537. defer ctx.Close()
  4538. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", "test1", ".")
  4539. if err != nil {
  4540. c.Fatalf("Failed to build: %s\n%s", out, err)
  4541. }
  4542. if !strings.Contains(out, "from dockerfile") {
  4543. c.Fatalf("Missing proper output: %s", out)
  4544. }
  4545. }
  4546. func (s *DockerSuite) TestBuildWithTwoDockerfiles(c *check.C) {
  4547. testRequires(c, UnixCli) // Dockerfile overwrites dockerfile on windows
  4548. testRequires(c, DaemonIsLinux)
  4549. ctx, err := fakeContext(`FROM busybox
  4550. RUN echo from Dockerfile`,
  4551. map[string]string{
  4552. "dockerfile": "FROM busybox\nRUN echo from dockerfile",
  4553. })
  4554. if err != nil {
  4555. c.Fatal(err)
  4556. }
  4557. defer ctx.Close()
  4558. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", "test1", ".")
  4559. if err != nil {
  4560. c.Fatalf("Failed to build: %s\n%s", out, err)
  4561. }
  4562. if !strings.Contains(out, "from Dockerfile") {
  4563. c.Fatalf("Missing proper output: %s", out)
  4564. }
  4565. }
  4566. func (s *DockerSuite) TestBuildFromURLWithF(c *check.C) {
  4567. testRequires(c, DaemonIsLinux)
  4568. server, err := fakeStorage(map[string]string{"baz": `FROM busybox
  4569. RUN echo from baz
  4570. COPY * /tmp/
  4571. RUN find /tmp/`})
  4572. if err != nil {
  4573. c.Fatal(err)
  4574. }
  4575. defer server.Close()
  4576. ctx, err := fakeContext(`FROM busybox
  4577. RUN echo from Dockerfile`,
  4578. map[string]string{})
  4579. if err != nil {
  4580. c.Fatal(err)
  4581. }
  4582. defer ctx.Close()
  4583. // Make sure that -f is ignored and that we don't use the Dockerfile
  4584. // that's in the current dir
  4585. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-f", "baz", "-t", "test1", server.URL()+"/baz")
  4586. if err != nil {
  4587. c.Fatalf("Failed to build: %s\n%s", out, err)
  4588. }
  4589. if !strings.Contains(out, "from baz") ||
  4590. strings.Contains(out, "/tmp/baz") ||
  4591. !strings.Contains(out, "/tmp/Dockerfile") {
  4592. c.Fatalf("Missing proper output: %s", out)
  4593. }
  4594. }
  4595. func (s *DockerSuite) TestBuildFromStdinWithF(c *check.C) {
  4596. testRequires(c, DaemonIsLinux) // TODO Windows: This test is flaky; no idea why
  4597. ctx, err := fakeContext(`FROM busybox
  4598. RUN echo "from Dockerfile"`,
  4599. map[string]string{})
  4600. if err != nil {
  4601. c.Fatal(err)
  4602. }
  4603. defer ctx.Close()
  4604. // Make sure that -f is ignored and that we don't use the Dockerfile
  4605. // that's in the current dir
  4606. dockerCommand := exec.Command(dockerBinary, "build", "-f", "baz", "-t", "test1", "-")
  4607. dockerCommand.Dir = ctx.Dir
  4608. dockerCommand.Stdin = strings.NewReader(`FROM busybox
  4609. RUN echo "from baz"
  4610. COPY * /tmp/
  4611. RUN sh -c "find /tmp/" # sh -c is needed on Windows to use the correct find`)
  4612. out, status, err := runCommandWithOutput(dockerCommand)
  4613. if err != nil || status != 0 {
  4614. c.Fatalf("Error building: %s", err)
  4615. }
  4616. if !strings.Contains(out, "from baz") ||
  4617. strings.Contains(out, "/tmp/baz") ||
  4618. !strings.Contains(out, "/tmp/Dockerfile") {
  4619. c.Fatalf("Missing proper output: %s", out)
  4620. }
  4621. }
  4622. func (s *DockerSuite) TestBuildFromOfficialNames(c *check.C) {
  4623. name := "testbuildfromofficial"
  4624. fromNames := []string{
  4625. "busybox",
  4626. "docker.io/busybox",
  4627. "index.docker.io/busybox",
  4628. "library/busybox",
  4629. "docker.io/library/busybox",
  4630. "index.docker.io/library/busybox",
  4631. }
  4632. for idx, fromName := range fromNames {
  4633. imgName := fmt.Sprintf("%s%d", name, idx)
  4634. _, err := buildImage(imgName, "FROM "+fromName, true)
  4635. if err != nil {
  4636. c.Errorf("Build failed using FROM %s: %s", fromName, err)
  4637. }
  4638. deleteImages(imgName)
  4639. }
  4640. }
  4641. func (s *DockerSuite) TestBuildDockerfileOutsideContext(c *check.C) {
  4642. testRequires(c, UnixCli) // uses os.Symlink: not implemented in windows at the time of writing (go-1.4.2)
  4643. testRequires(c, DaemonIsLinux)
  4644. name := "testbuilddockerfileoutsidecontext"
  4645. tmpdir, err := ioutil.TempDir("", name)
  4646. c.Assert(err, check.IsNil)
  4647. defer os.RemoveAll(tmpdir)
  4648. ctx := filepath.Join(tmpdir, "context")
  4649. if err := os.MkdirAll(ctx, 0755); err != nil {
  4650. c.Fatal(err)
  4651. }
  4652. if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte("FROM scratch\nENV X Y"), 0644); err != nil {
  4653. c.Fatal(err)
  4654. }
  4655. wd, err := os.Getwd()
  4656. if err != nil {
  4657. c.Fatal(err)
  4658. }
  4659. defer os.Chdir(wd)
  4660. if err := os.Chdir(ctx); err != nil {
  4661. c.Fatal(err)
  4662. }
  4663. if err := ioutil.WriteFile(filepath.Join(tmpdir, "outsideDockerfile"), []byte("FROM scratch\nENV x y"), 0644); err != nil {
  4664. c.Fatal(err)
  4665. }
  4666. if err := os.Symlink(filepath.Join("..", "outsideDockerfile"), filepath.Join(ctx, "dockerfile1")); err != nil {
  4667. c.Fatal(err)
  4668. }
  4669. if err := os.Symlink(filepath.Join(tmpdir, "outsideDockerfile"), filepath.Join(ctx, "dockerfile2")); err != nil {
  4670. c.Fatal(err)
  4671. }
  4672. for _, dockerfilePath := range []string{
  4673. filepath.Join("..", "outsideDockerfile"),
  4674. filepath.Join(ctx, "dockerfile1"),
  4675. filepath.Join(ctx, "dockerfile2"),
  4676. } {
  4677. out, _, err := dockerCmdWithError("build", "-t", name, "--no-cache", "-f", dockerfilePath, ".")
  4678. if err == nil {
  4679. c.Fatalf("Expected error with %s. Out: %s", dockerfilePath, out)
  4680. }
  4681. if !strings.Contains(out, "must be within the build context") && !strings.Contains(out, "Cannot locate Dockerfile") {
  4682. c.Fatalf("Unexpected error with %s. Out: %s", dockerfilePath, out)
  4683. }
  4684. deleteImages(name)
  4685. }
  4686. os.Chdir(tmpdir)
  4687. // Path to Dockerfile should be resolved relative to working directory, not relative to context.
  4688. // There is a Dockerfile in the context, but since there is no Dockerfile in the current directory, the following should fail
  4689. out, _, err := dockerCmdWithError("build", "-t", name, "--no-cache", "-f", "Dockerfile", ctx)
  4690. if err == nil {
  4691. c.Fatalf("Expected error. Out: %s", out)
  4692. }
  4693. }
  4694. func (s *DockerSuite) TestBuildSpaces(c *check.C) {
  4695. // Test to make sure that leading/trailing spaces on a command
  4696. // doesn't change the error msg we get
  4697. var (
  4698. err1 error
  4699. err2 error
  4700. )
  4701. name := "testspaces"
  4702. ctx, err := fakeContext("FROM busybox\nCOPY\n",
  4703. map[string]string{
  4704. "Dockerfile": "FROM busybox\nCOPY\n",
  4705. })
  4706. if err != nil {
  4707. c.Fatal(err)
  4708. }
  4709. defer ctx.Close()
  4710. if _, err1 = buildImageFromContext(name, ctx, false); err1 == nil {
  4711. c.Fatal("Build 1 was supposed to fail, but didn't")
  4712. }
  4713. ctx.Add("Dockerfile", "FROM busybox\nCOPY ")
  4714. if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil {
  4715. c.Fatal("Build 2 was supposed to fail, but didn't")
  4716. }
  4717. removeLogTimestamps := func(s string) string {
  4718. return regexp.MustCompile(`time="(.*?)"`).ReplaceAllString(s, `time=[TIMESTAMP]`)
  4719. }
  4720. // Skip over the times
  4721. e1 := removeLogTimestamps(err1.Error())
  4722. e2 := removeLogTimestamps(err2.Error())
  4723. // Ignore whitespace since that's what were verifying doesn't change stuff
  4724. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  4725. c.Fatalf("Build 2's error wasn't the same as build 1's\n1:%s\n2:%s", err1, err2)
  4726. }
  4727. ctx.Add("Dockerfile", "FROM busybox\n COPY")
  4728. if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil {
  4729. c.Fatal("Build 3 was supposed to fail, but didn't")
  4730. }
  4731. // Skip over the times
  4732. e1 = removeLogTimestamps(err1.Error())
  4733. e2 = removeLogTimestamps(err2.Error())
  4734. // Ignore whitespace since that's what were verifying doesn't change stuff
  4735. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  4736. c.Fatalf("Build 3's error wasn't the same as build 1's\n1:%s\n3:%s", err1, err2)
  4737. }
  4738. ctx.Add("Dockerfile", "FROM busybox\n COPY ")
  4739. if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil {
  4740. c.Fatal("Build 4 was supposed to fail, but didn't")
  4741. }
  4742. // Skip over the times
  4743. e1 = removeLogTimestamps(err1.Error())
  4744. e2 = removeLogTimestamps(err2.Error())
  4745. // Ignore whitespace since that's what were verifying doesn't change stuff
  4746. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  4747. c.Fatalf("Build 4's error wasn't the same as build 1's\n1:%s\n4:%s", err1, err2)
  4748. }
  4749. }
  4750. func (s *DockerSuite) TestBuildSpacesWithQuotes(c *check.C) {
  4751. testRequires(c, DaemonIsLinux)
  4752. // Test to make sure that spaces in quotes aren't lost
  4753. name := "testspacesquotes"
  4754. dockerfile := `FROM busybox
  4755. RUN echo " \
  4756. foo "`
  4757. _, out, err := buildImageWithOut(name, dockerfile, false)
  4758. if err != nil {
  4759. c.Fatal("Build failed:", err)
  4760. }
  4761. expecting := "\n foo \n"
  4762. if !strings.Contains(out, expecting) {
  4763. c.Fatalf("Bad output: %q expecting to contain %q", out, expecting)
  4764. }
  4765. }
  4766. // #4393
  4767. func (s *DockerSuite) TestBuildVolumeFileExistsinContainer(c *check.C) {
  4768. testRequires(c, DaemonIsLinux) // TODO Windows: This should error out
  4769. buildCmd := exec.Command(dockerBinary, "build", "-t", "docker-test-errcreatevolumewithfile", "-")
  4770. buildCmd.Stdin = strings.NewReader(`
  4771. FROM busybox
  4772. RUN touch /foo
  4773. VOLUME /foo
  4774. `)
  4775. out, _, err := runCommandWithOutput(buildCmd)
  4776. if err == nil || !strings.Contains(out, "file exists") {
  4777. c.Fatalf("expected build to fail when file exists in container at requested volume path")
  4778. }
  4779. }
  4780. func (s *DockerSuite) TestBuildMissingArgs(c *check.C) {
  4781. // Test to make sure that all Dockerfile commands (except the ones listed
  4782. // in skipCmds) will generate an error if no args are provided.
  4783. // Note: INSERT is deprecated so we exclude it because of that.
  4784. skipCmds := map[string]struct{}{
  4785. "CMD": {},
  4786. "RUN": {},
  4787. "ENTRYPOINT": {},
  4788. "INSERT": {},
  4789. }
  4790. if daemonPlatform == "windows" {
  4791. skipCmds = map[string]struct{}{
  4792. "CMD": {},
  4793. "RUN": {},
  4794. "ENTRYPOINT": {},
  4795. "INSERT": {},
  4796. "STOPSIGNAL": {},
  4797. "ARG": {},
  4798. "USER": {},
  4799. "EXPOSE": {},
  4800. }
  4801. }
  4802. for cmd := range command.Commands {
  4803. cmd = strings.ToUpper(cmd)
  4804. if _, ok := skipCmds[cmd]; ok {
  4805. continue
  4806. }
  4807. var dockerfile string
  4808. if cmd == "FROM" {
  4809. dockerfile = cmd
  4810. } else {
  4811. // Add FROM to make sure we don't complain about it missing
  4812. dockerfile = "FROM busybox\n" + cmd
  4813. }
  4814. ctx, err := fakeContext(dockerfile, map[string]string{})
  4815. if err != nil {
  4816. c.Fatal(err)
  4817. }
  4818. defer ctx.Close()
  4819. var out string
  4820. if out, err = buildImageFromContext("args", ctx, true); err == nil {
  4821. c.Fatalf("%s was supposed to fail. Out:%s", cmd, out)
  4822. }
  4823. if !strings.Contains(err.Error(), cmd+" requires") {
  4824. c.Fatalf("%s returned the wrong type of error:%s", cmd, err)
  4825. }
  4826. }
  4827. }
  4828. func (s *DockerSuite) TestBuildEmptyScratch(c *check.C) {
  4829. testRequires(c, DaemonIsLinux)
  4830. _, out, err := buildImageWithOut("sc", "FROM scratch", true)
  4831. if err == nil {
  4832. c.Fatalf("Build was supposed to fail")
  4833. }
  4834. if !strings.Contains(out, "No image was generated") {
  4835. c.Fatalf("Wrong error message: %v", out)
  4836. }
  4837. }
  4838. func (s *DockerSuite) TestBuildDotDotFile(c *check.C) {
  4839. ctx, err := fakeContext("FROM busybox\n",
  4840. map[string]string{
  4841. "..gitme": "",
  4842. })
  4843. if err != nil {
  4844. c.Fatal(err)
  4845. }
  4846. defer ctx.Close()
  4847. if _, err = buildImageFromContext("sc", ctx, false); err != nil {
  4848. c.Fatalf("Build was supposed to work: %s", err)
  4849. }
  4850. }
  4851. func (s *DockerSuite) TestBuildRUNoneJSON(c *check.C) {
  4852. testRequires(c, DaemonIsLinux) // No hello-world Windows image
  4853. name := "testbuildrunonejson"
  4854. ctx, err := fakeContext(`FROM hello-world:frozen
  4855. RUN [ "/hello" ]`, map[string]string{})
  4856. if err != nil {
  4857. c.Fatal(err)
  4858. }
  4859. defer ctx.Close()
  4860. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "--no-cache", "-t", name, ".")
  4861. if err != nil {
  4862. c.Fatalf("failed to build the image: %s, %v", out, err)
  4863. }
  4864. if !strings.Contains(out, "Hello from Docker") {
  4865. c.Fatalf("bad output: %s", out)
  4866. }
  4867. }
  4868. func (s *DockerSuite) TestBuildEmptyStringVolume(c *check.C) {
  4869. name := "testbuildemptystringvolume"
  4870. _, err := buildImage(name, `
  4871. FROM busybox
  4872. ENV foo=""
  4873. VOLUME $foo
  4874. `, false)
  4875. if err == nil {
  4876. c.Fatal("Should have failed to build")
  4877. }
  4878. }
  4879. func (s *DockerSuite) TestBuildContainerWithCgroupParent(c *check.C) {
  4880. testRequires(c, SameHostDaemon)
  4881. testRequires(c, DaemonIsLinux)
  4882. cgroupParent := "test"
  4883. data, err := ioutil.ReadFile("/proc/self/cgroup")
  4884. if err != nil {
  4885. c.Fatalf("failed to read '/proc/self/cgroup - %v", err)
  4886. }
  4887. selfCgroupPaths := parseCgroupPaths(string(data))
  4888. _, found := selfCgroupPaths["memory"]
  4889. if !found {
  4890. c.Fatalf("unable to find self memory cgroup path. CgroupsPath: %v", selfCgroupPaths)
  4891. }
  4892. cmd := exec.Command(dockerBinary, "build", "--cgroup-parent", cgroupParent, "-")
  4893. cmd.Stdin = strings.NewReader(`
  4894. FROM busybox
  4895. RUN cat /proc/self/cgroup
  4896. `)
  4897. out, _, err := runCommandWithOutput(cmd)
  4898. if err != nil {
  4899. c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err)
  4900. }
  4901. m, err := regexp.MatchString(fmt.Sprintf("memory:.*/%s/.*", cgroupParent), out)
  4902. c.Assert(err, check.IsNil)
  4903. if !m {
  4904. c.Fatalf("There is no expected memory cgroup with parent /%s/: %s", cgroupParent, out)
  4905. }
  4906. }
  4907. func (s *DockerSuite) TestBuildNoDupOutput(c *check.C) {
  4908. // Check to make sure our build output prints the Dockerfile cmd
  4909. // property - there was a bug that caused it to be duplicated on the
  4910. // Step X line
  4911. name := "testbuildnodupoutput"
  4912. _, out, err := buildImageWithOut(name, `
  4913. FROM busybox
  4914. RUN env`, false)
  4915. if err != nil {
  4916. c.Fatalf("Build should have worked: %q", err)
  4917. }
  4918. exp := "\nStep 2 : RUN env\n"
  4919. if !strings.Contains(out, exp) {
  4920. c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", out, exp)
  4921. }
  4922. }
  4923. // GH15826
  4924. func (s *DockerSuite) TestBuildStartsFromOne(c *check.C) {
  4925. // Explicit check to ensure that build starts from step 1 rather than 0
  4926. name := "testbuildstartsfromone"
  4927. _, out, err := buildImageWithOut(name, `
  4928. FROM busybox`, false)
  4929. if err != nil {
  4930. c.Fatalf("Build should have worked: %q", err)
  4931. }
  4932. exp := "\nStep 1 : FROM busybox\n"
  4933. if !strings.Contains(out, exp) {
  4934. c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", out, exp)
  4935. }
  4936. }
  4937. func (s *DockerSuite) TestBuildBadCmdFlag(c *check.C) {
  4938. name := "testbuildbadcmdflag"
  4939. _, out, err := buildImageWithOut(name, `
  4940. FROM busybox
  4941. MAINTAINER --boo joe@example.com`, false)
  4942. if err == nil {
  4943. c.Fatal("Build should have failed")
  4944. }
  4945. exp := "\nUnknown flag: boo\n"
  4946. if !strings.Contains(out, exp) {
  4947. c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", out, exp)
  4948. }
  4949. }
  4950. func (s *DockerSuite) TestBuildRUNErrMsg(c *check.C) {
  4951. // Test to make sure the bad command is quoted with just "s and
  4952. // not as a Go []string
  4953. name := "testbuildbadrunerrmsg"
  4954. _, out, err := buildImageWithOut(name, `
  4955. FROM busybox
  4956. RUN badEXE a1 \& a2 a3`, false) // tab between a2 and a3
  4957. if err == nil {
  4958. c.Fatal("Should have failed to build")
  4959. }
  4960. shell := "/bin/sh -c"
  4961. exitCode := "127"
  4962. if daemonPlatform == "windows" {
  4963. shell = "cmd /S /C"
  4964. // architectural - Windows has to start the container to determine the exe is bad, Linux does not
  4965. exitCode = "1"
  4966. }
  4967. exp := `The command '` + shell + ` badEXE a1 \& a2 a3' returned a non-zero code: ` + exitCode
  4968. if !strings.Contains(out, exp) {
  4969. c.Fatalf("RUN doesn't have the correct output:\nGot:%s\nExpected:%s", out, exp)
  4970. }
  4971. }
  4972. func (s *DockerTrustSuite) TestTrustedBuild(c *check.C) {
  4973. repoName := s.setupTrustedImage(c, "trusted-build")
  4974. dockerFile := fmt.Sprintf(`
  4975. FROM %s
  4976. RUN []
  4977. `, repoName)
  4978. name := "testtrustedbuild"
  4979. buildCmd := buildImageCmd(name, dockerFile, true)
  4980. s.trustedCmd(buildCmd)
  4981. out, _, err := runCommandWithOutput(buildCmd)
  4982. if err != nil {
  4983. c.Fatalf("Error running trusted build: %s\n%s", err, out)
  4984. }
  4985. if !strings.Contains(out, fmt.Sprintf("FROM %s@sha", repoName[:len(repoName)-7])) {
  4986. c.Fatalf("Unexpected output on trusted build:\n%s", out)
  4987. }
  4988. // We should also have a tag reference for the image.
  4989. if out, exitCode := dockerCmd(c, "inspect", repoName); exitCode != 0 {
  4990. c.Fatalf("unexpected exit code inspecting image %q: %d: %s", repoName, exitCode, out)
  4991. }
  4992. // We should now be able to remove the tag reference.
  4993. if out, exitCode := dockerCmd(c, "rmi", repoName); exitCode != 0 {
  4994. c.Fatalf("unexpected exit code inspecting image %q: %d: %s", repoName, exitCode, out)
  4995. }
  4996. }
  4997. func (s *DockerTrustSuite) TestTrustedBuildUntrustedTag(c *check.C) {
  4998. repoName := fmt.Sprintf("%v/dockercli/build-untrusted-tag:latest", privateRegistryURL)
  4999. dockerFile := fmt.Sprintf(`
  5000. FROM %s
  5001. RUN []
  5002. `, repoName)
  5003. name := "testtrustedbuilduntrustedtag"
  5004. buildCmd := buildImageCmd(name, dockerFile, true)
  5005. s.trustedCmd(buildCmd)
  5006. out, _, err := runCommandWithOutput(buildCmd)
  5007. if err == nil {
  5008. c.Fatalf("Expected error on trusted build with untrusted tag: %s\n%s", err, out)
  5009. }
  5010. if !strings.Contains(out, "does not have trust data for") {
  5011. c.Fatalf("Unexpected output on trusted build with untrusted tag:\n%s", out)
  5012. }
  5013. }
  5014. func (s *DockerTrustSuite) TestBuildContextDirIsSymlink(c *check.C) {
  5015. testRequires(c, DaemonIsLinux)
  5016. tempDir, err := ioutil.TempDir("", "test-build-dir-is-symlink-")
  5017. c.Assert(err, check.IsNil)
  5018. defer os.RemoveAll(tempDir)
  5019. // Make a real context directory in this temp directory with a simple
  5020. // Dockerfile.
  5021. realContextDirname := filepath.Join(tempDir, "context")
  5022. if err := os.Mkdir(realContextDirname, os.FileMode(0755)); err != nil {
  5023. c.Fatal(err)
  5024. }
  5025. if err = ioutil.WriteFile(
  5026. filepath.Join(realContextDirname, "Dockerfile"),
  5027. []byte(`
  5028. FROM busybox
  5029. RUN echo hello world
  5030. `),
  5031. os.FileMode(0644),
  5032. ); err != nil {
  5033. c.Fatal(err)
  5034. }
  5035. // Make a symlink to the real context directory.
  5036. contextSymlinkName := filepath.Join(tempDir, "context_link")
  5037. if err := os.Symlink(realContextDirname, contextSymlinkName); err != nil {
  5038. c.Fatal(err)
  5039. }
  5040. // Executing the build with the symlink as the specified context should
  5041. // *not* fail.
  5042. if out, exitStatus := dockerCmd(c, "build", contextSymlinkName); exitStatus != 0 {
  5043. c.Fatalf("build failed with exit status %d: %s", exitStatus, out)
  5044. }
  5045. }
  5046. func (s *DockerTrustSuite) TestTrustedBuildTagFromReleasesRole(c *check.C) {
  5047. testRequires(c, NotaryHosting)
  5048. latestTag := s.setupTrustedImage(c, "trusted-build-releases-role")
  5049. repoName := strings.TrimSuffix(latestTag, ":latest")
  5050. // Now create the releases role
  5051. s.notaryCreateDelegation(c, repoName, "targets/releases", s.not.keys[0].Public)
  5052. s.notaryImportKey(c, repoName, "targets/releases", s.not.keys[0].Private)
  5053. s.notaryPublish(c, repoName)
  5054. // push a different tag to the releases role
  5055. otherTag := fmt.Sprintf("%s:other", repoName)
  5056. dockerCmd(c, "tag", "busybox", otherTag)
  5057. pushCmd := exec.Command(dockerBinary, "push", otherTag)
  5058. s.trustedCmd(pushCmd)
  5059. out, _, err := runCommandWithOutput(pushCmd)
  5060. c.Assert(err, check.IsNil, check.Commentf("Trusted push failed: %s", out))
  5061. s.assertTargetInRoles(c, repoName, "other", "targets/releases")
  5062. s.assertTargetNotInRoles(c, repoName, "other", "targets")
  5063. out, status := dockerCmd(c, "rmi", otherTag)
  5064. c.Assert(status, check.Equals, 0, check.Commentf("docker rmi failed: %s", out))
  5065. dockerFile := fmt.Sprintf(`
  5066. FROM %s
  5067. RUN []
  5068. `, otherTag)
  5069. name := "testtrustedbuildreleasesrole"
  5070. buildCmd := buildImageCmd(name, dockerFile, true)
  5071. s.trustedCmd(buildCmd)
  5072. out, _, err = runCommandWithOutput(buildCmd)
  5073. c.Assert(err, check.IsNil, check.Commentf("Trusted build failed: %s", out))
  5074. c.Assert(out, checker.Contains, fmt.Sprintf("FROM %s@sha", repoName))
  5075. }
  5076. func (s *DockerTrustSuite) TestTrustedBuildTagIgnoresOtherDelegationRoles(c *check.C) {
  5077. testRequires(c, NotaryHosting)
  5078. latestTag := s.setupTrustedImage(c, "trusted-build-releases-role")
  5079. repoName := strings.TrimSuffix(latestTag, ":latest")
  5080. // Now create a non-releases delegation role
  5081. s.notaryCreateDelegation(c, repoName, "targets/other", s.not.keys[0].Public)
  5082. s.notaryImportKey(c, repoName, "targets/other", s.not.keys[0].Private)
  5083. s.notaryPublish(c, repoName)
  5084. // push a different tag to the other role
  5085. otherTag := fmt.Sprintf("%s:other", repoName)
  5086. dockerCmd(c, "tag", "busybox", otherTag)
  5087. pushCmd := exec.Command(dockerBinary, "push", otherTag)
  5088. s.trustedCmd(pushCmd)
  5089. out, _, err := runCommandWithOutput(pushCmd)
  5090. c.Assert(err, check.IsNil, check.Commentf("Trusted push failed: %s", out))
  5091. s.assertTargetInRoles(c, repoName, "other", "targets/other")
  5092. s.assertTargetNotInRoles(c, repoName, "other", "targets")
  5093. out, status := dockerCmd(c, "rmi", otherTag)
  5094. c.Assert(status, check.Equals, 0, check.Commentf("docker rmi failed: %s", out))
  5095. dockerFile := fmt.Sprintf(`
  5096. FROM %s
  5097. RUN []
  5098. `, otherTag)
  5099. name := "testtrustedbuildotherrole"
  5100. buildCmd := buildImageCmd(name, dockerFile, true)
  5101. s.trustedCmd(buildCmd)
  5102. out, _, err = runCommandWithOutput(buildCmd)
  5103. c.Assert(err, check.NotNil, check.Commentf("Trusted build expected to fail: %s", out))
  5104. }
  5105. // Issue #15634: COPY fails when path starts with "null"
  5106. func (s *DockerSuite) TestBuildNullStringInAddCopyVolume(c *check.C) {
  5107. name := "testbuildnullstringinaddcopyvolume"
  5108. volName := "nullvolume"
  5109. if daemonPlatform == "windows" {
  5110. volName = `C:\\nullvolume`
  5111. }
  5112. ctx, err := fakeContext(`
  5113. FROM busybox
  5114. ADD null /
  5115. COPY nullfile /
  5116. VOLUME `+volName+`
  5117. `,
  5118. map[string]string{
  5119. "null": "test1",
  5120. "nullfile": "test2",
  5121. },
  5122. )
  5123. c.Assert(err, check.IsNil)
  5124. defer ctx.Close()
  5125. _, err = buildImageFromContext(name, ctx, true)
  5126. c.Assert(err, check.IsNil)
  5127. }
  5128. func (s *DockerSuite) TestBuildStopSignal(c *check.C) {
  5129. testRequires(c, DaemonIsLinux) // Windows does not support STOPSIGNAL yet
  5130. imgName := "test_build_stop_signal"
  5131. _, err := buildImage(imgName,
  5132. `FROM busybox
  5133. STOPSIGNAL SIGKILL`,
  5134. true)
  5135. c.Assert(err, check.IsNil)
  5136. res := inspectFieldJSON(c, imgName, "Config.StopSignal")
  5137. if res != `"SIGKILL"` {
  5138. c.Fatalf("Signal %s, expected SIGKILL", res)
  5139. }
  5140. containerName := "test-container-stop-signal"
  5141. dockerCmd(c, "run", "-d", "--name", containerName, imgName, "top")
  5142. res = inspectFieldJSON(c, containerName, "Config.StopSignal")
  5143. if res != `"SIGKILL"` {
  5144. c.Fatalf("Signal %s, expected SIGKILL", res)
  5145. }
  5146. }
  5147. func (s *DockerSuite) TestBuildBuildTimeArg(c *check.C) {
  5148. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5149. imgName := "bldargtest"
  5150. envKey := "foo"
  5151. envVal := "bar"
  5152. args := []string{
  5153. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5154. }
  5155. dockerfile := fmt.Sprintf(`FROM busybox
  5156. ARG %s
  5157. RUN echo $%s
  5158. CMD echo $%s`, envKey, envKey, envKey)
  5159. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil || !strings.Contains(out, envVal) {
  5160. if err != nil {
  5161. c.Fatalf("build failed to complete: %q %q", out, err)
  5162. }
  5163. c.Fatalf("failed to access environment variable in output: %q expected: %q", out, envVal)
  5164. }
  5165. containerName := "bldargCont"
  5166. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); out != "\n" {
  5167. c.Fatalf("run produced invalid output: %q, expected empty string", out)
  5168. }
  5169. }
  5170. func (s *DockerSuite) TestBuildBuildTimeArgHistory(c *check.C) {
  5171. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5172. imgName := "bldargtest"
  5173. envKey := "foo"
  5174. envVal := "bar"
  5175. envDef := "bar1"
  5176. args := []string{
  5177. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5178. }
  5179. dockerfile := fmt.Sprintf(`FROM busybox
  5180. ARG %s=%s`, envKey, envDef)
  5181. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil || !strings.Contains(out, envVal) {
  5182. if err != nil {
  5183. c.Fatalf("build failed to complete: %q %q", out, err)
  5184. }
  5185. c.Fatalf("failed to access environment variable in output: %q expected: %q", out, envVal)
  5186. }
  5187. out, _ := dockerCmd(c, "history", "--no-trunc", imgName)
  5188. outputTabs := strings.Split(out, "\n")[1]
  5189. if !strings.Contains(outputTabs, envDef) {
  5190. c.Fatalf("failed to find arg default in image history output: %q expected: %q", outputTabs, envDef)
  5191. }
  5192. }
  5193. func (s *DockerSuite) TestBuildBuildTimeArgCacheHit(c *check.C) {
  5194. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5195. imgName := "bldargtest"
  5196. envKey := "foo"
  5197. envVal := "bar"
  5198. args := []string{
  5199. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5200. }
  5201. dockerfile := fmt.Sprintf(`FROM busybox
  5202. ARG %s
  5203. RUN echo $%s`, envKey, envKey)
  5204. origImgID := ""
  5205. var err error
  5206. if origImgID, err = buildImage(imgName, dockerfile, true, args...); err != nil {
  5207. c.Fatal(err)
  5208. }
  5209. imgNameCache := "bldargtestcachehit"
  5210. if newImgID, err := buildImage(imgNameCache, dockerfile, true, args...); err != nil || newImgID != origImgID {
  5211. if err != nil {
  5212. c.Fatal(err)
  5213. }
  5214. c.Fatalf("build didn't use cache! expected image id: %q built image id: %q", origImgID, newImgID)
  5215. }
  5216. }
  5217. func (s *DockerSuite) TestBuildBuildTimeArgCacheMissExtraArg(c *check.C) {
  5218. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5219. imgName := "bldargtest"
  5220. envKey := "foo"
  5221. envVal := "bar"
  5222. extraEnvKey := "foo1"
  5223. extraEnvVal := "bar1"
  5224. args := []string{
  5225. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5226. }
  5227. dockerfile := fmt.Sprintf(`FROM busybox
  5228. ARG %s
  5229. ARG %s
  5230. RUN echo $%s`, envKey, extraEnvKey, envKey)
  5231. origImgID := ""
  5232. var err error
  5233. if origImgID, err = buildImage(imgName, dockerfile, true, args...); err != nil {
  5234. c.Fatal(err)
  5235. }
  5236. imgNameCache := "bldargtestcachemiss"
  5237. args = append(args, "--build-arg", fmt.Sprintf("%s=%s", extraEnvKey, extraEnvVal))
  5238. if newImgID, err := buildImage(imgNameCache, dockerfile, true, args...); err != nil || newImgID == origImgID {
  5239. if err != nil {
  5240. c.Fatal(err)
  5241. }
  5242. c.Fatalf("build used cache, expected a miss!")
  5243. }
  5244. }
  5245. func (s *DockerSuite) TestBuildBuildTimeArgCacheMissSameArgDiffVal(c *check.C) {
  5246. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5247. imgName := "bldargtest"
  5248. envKey := "foo"
  5249. envVal := "bar"
  5250. newEnvVal := "bar1"
  5251. args := []string{
  5252. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5253. }
  5254. dockerfile := fmt.Sprintf(`FROM busybox
  5255. ARG %s
  5256. RUN echo $%s`, envKey, envKey)
  5257. origImgID := ""
  5258. var err error
  5259. if origImgID, err = buildImage(imgName, dockerfile, true, args...); err != nil {
  5260. c.Fatal(err)
  5261. }
  5262. imgNameCache := "bldargtestcachemiss"
  5263. args = []string{
  5264. "--build-arg", fmt.Sprintf("%s=%s", envKey, newEnvVal),
  5265. }
  5266. if newImgID, err := buildImage(imgNameCache, dockerfile, true, args...); err != nil || newImgID == origImgID {
  5267. if err != nil {
  5268. c.Fatal(err)
  5269. }
  5270. c.Fatalf("build used cache, expected a miss!")
  5271. }
  5272. }
  5273. func (s *DockerSuite) TestBuildBuildTimeArgOverrideArgDefinedBeforeEnv(c *check.C) {
  5274. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5275. imgName := "bldargtest"
  5276. envKey := "foo"
  5277. envVal := "bar"
  5278. envValOveride := "barOverride"
  5279. args := []string{
  5280. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5281. }
  5282. dockerfile := fmt.Sprintf(`FROM busybox
  5283. ARG %s
  5284. ENV %s %s
  5285. RUN echo $%s
  5286. CMD echo $%s
  5287. `, envKey, envKey, envValOveride, envKey, envKey)
  5288. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil || strings.Count(out, envValOveride) != 2 {
  5289. if err != nil {
  5290. c.Fatalf("build failed to complete: %q %q", out, err)
  5291. }
  5292. c.Fatalf("failed to access environment variable in output: %q expected: %q", out, envValOveride)
  5293. }
  5294. containerName := "bldargCont"
  5295. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOveride) {
  5296. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOveride)
  5297. }
  5298. }
  5299. func (s *DockerSuite) TestBuildBuildTimeArgOverrideEnvDefinedBeforeArg(c *check.C) {
  5300. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5301. imgName := "bldargtest"
  5302. envKey := "foo"
  5303. envVal := "bar"
  5304. envValOveride := "barOverride"
  5305. args := []string{
  5306. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5307. }
  5308. dockerfile := fmt.Sprintf(`FROM busybox
  5309. ENV %s %s
  5310. ARG %s
  5311. RUN echo $%s
  5312. CMD echo $%s
  5313. `, envKey, envValOveride, envKey, envKey, envKey)
  5314. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil || strings.Count(out, envValOveride) != 2 {
  5315. if err != nil {
  5316. c.Fatalf("build failed to complete: %q %q", out, err)
  5317. }
  5318. c.Fatalf("failed to access environment variable in output: %q expected: %q", out, envValOveride)
  5319. }
  5320. containerName := "bldargCont"
  5321. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOveride) {
  5322. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOveride)
  5323. }
  5324. }
  5325. func (s *DockerSuite) TestBuildBuildTimeArgExpansion(c *check.C) {
  5326. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5327. imgName := "bldvarstest"
  5328. wdVar := "WDIR"
  5329. wdVal := "/tmp/"
  5330. addVar := "AFILE"
  5331. addVal := "addFile"
  5332. copyVar := "CFILE"
  5333. copyVal := "copyFile"
  5334. envVar := "foo"
  5335. envVal := "bar"
  5336. exposeVar := "EPORT"
  5337. exposeVal := "9999"
  5338. userVar := "USER"
  5339. userVal := "testUser"
  5340. volVar := "VOL"
  5341. volVal := "/testVol/"
  5342. args := []string{
  5343. "--build-arg", fmt.Sprintf("%s=%s", wdVar, wdVal),
  5344. "--build-arg", fmt.Sprintf("%s=%s", addVar, addVal),
  5345. "--build-arg", fmt.Sprintf("%s=%s", copyVar, copyVal),
  5346. "--build-arg", fmt.Sprintf("%s=%s", envVar, envVal),
  5347. "--build-arg", fmt.Sprintf("%s=%s", exposeVar, exposeVal),
  5348. "--build-arg", fmt.Sprintf("%s=%s", userVar, userVal),
  5349. "--build-arg", fmt.Sprintf("%s=%s", volVar, volVal),
  5350. }
  5351. ctx, err := fakeContext(fmt.Sprintf(`FROM busybox
  5352. ARG %s
  5353. WORKDIR ${%s}
  5354. ARG %s
  5355. ADD ${%s} testDir/
  5356. ARG %s
  5357. COPY $%s testDir/
  5358. ARG %s
  5359. ENV %s=${%s}
  5360. ARG %s
  5361. EXPOSE $%s
  5362. ARG %s
  5363. USER $%s
  5364. ARG %s
  5365. VOLUME ${%s}`,
  5366. wdVar, wdVar, addVar, addVar, copyVar, copyVar, envVar, envVar,
  5367. envVar, exposeVar, exposeVar, userVar, userVar, volVar, volVar),
  5368. map[string]string{
  5369. addVal: "some stuff",
  5370. copyVal: "some stuff",
  5371. })
  5372. if err != nil {
  5373. c.Fatal(err)
  5374. }
  5375. defer ctx.Close()
  5376. if _, err := buildImageFromContext(imgName, ctx, true, args...); err != nil {
  5377. c.Fatal(err)
  5378. }
  5379. var resMap map[string]interface{}
  5380. var resArr []string
  5381. res := ""
  5382. res = inspectField(c, imgName, "Config.WorkingDir")
  5383. if res != filepath.ToSlash(filepath.Clean(wdVal)) {
  5384. c.Fatalf("Config.WorkingDir value mismatch. Expected: %s, got: %s", filepath.ToSlash(filepath.Clean(wdVal)), res)
  5385. }
  5386. inspectFieldAndMarshall(c, imgName, "Config.Env", &resArr)
  5387. found := false
  5388. for _, v := range resArr {
  5389. if fmt.Sprintf("%s=%s", envVar, envVal) == v {
  5390. found = true
  5391. break
  5392. }
  5393. }
  5394. if !found {
  5395. c.Fatalf("Config.Env value mismatch. Expected <key=value> to exist: %s=%s, got: %v",
  5396. envVar, envVal, resArr)
  5397. }
  5398. inspectFieldAndMarshall(c, imgName, "Config.ExposedPorts", &resMap)
  5399. if _, ok := resMap[fmt.Sprintf("%s/tcp", exposeVal)]; !ok {
  5400. c.Fatalf("Config.ExposedPorts value mismatch. Expected exposed port: %s/tcp, got: %v", exposeVal, resMap)
  5401. }
  5402. res = inspectField(c, imgName, "Config.User")
  5403. if res != userVal {
  5404. c.Fatalf("Config.User value mismatch. Expected: %s, got: %s", userVal, res)
  5405. }
  5406. inspectFieldAndMarshall(c, imgName, "Config.Volumes", &resMap)
  5407. if _, ok := resMap[volVal]; !ok {
  5408. c.Fatalf("Config.Volumes value mismatch. Expected volume: %s, got: %v", volVal, resMap)
  5409. }
  5410. }
  5411. func (s *DockerSuite) TestBuildBuildTimeArgExpansionOverride(c *check.C) {
  5412. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5413. imgName := "bldvarstest"
  5414. envKey := "foo"
  5415. envVal := "bar"
  5416. envKey1 := "foo1"
  5417. envValOveride := "barOverride"
  5418. args := []string{
  5419. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5420. }
  5421. dockerfile := fmt.Sprintf(`FROM busybox
  5422. ARG %s
  5423. ENV %s %s
  5424. ENV %s ${%s}
  5425. RUN echo $%s
  5426. CMD echo $%s`, envKey, envKey, envValOveride, envKey1, envKey, envKey1, envKey1)
  5427. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil || strings.Count(out, envValOveride) != 2 {
  5428. if err != nil {
  5429. c.Fatalf("build failed to complete: %q %q", out, err)
  5430. }
  5431. c.Fatalf("failed to access environment variable in output: %q expected: %q", out, envValOveride)
  5432. }
  5433. containerName := "bldargCont"
  5434. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOveride) {
  5435. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOveride)
  5436. }
  5437. }
  5438. func (s *DockerSuite) TestBuildBuildTimeArgUntrustedDefinedAfterUse(c *check.C) {
  5439. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5440. imgName := "bldargtest"
  5441. envKey := "foo"
  5442. envVal := "bar"
  5443. args := []string{
  5444. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5445. }
  5446. dockerfile := fmt.Sprintf(`FROM busybox
  5447. RUN echo $%s
  5448. ARG %s
  5449. CMD echo $%s`, envKey, envKey, envKey)
  5450. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil || strings.Contains(out, envVal) {
  5451. if err != nil {
  5452. c.Fatalf("build failed to complete: %q %q", out, err)
  5453. }
  5454. c.Fatalf("able to access environment variable in output: %q expected to be missing", out)
  5455. }
  5456. containerName := "bldargCont"
  5457. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); out != "\n" {
  5458. c.Fatalf("run produced invalid output: %q, expected empty string", out)
  5459. }
  5460. }
  5461. func (s *DockerSuite) TestBuildBuildTimeArgBuiltinArg(c *check.C) {
  5462. testRequires(c, DaemonIsLinux) // Windows does not support --build-arg
  5463. imgName := "bldargtest"
  5464. envKey := "HTTP_PROXY"
  5465. envVal := "bar"
  5466. args := []string{
  5467. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5468. }
  5469. dockerfile := fmt.Sprintf(`FROM busybox
  5470. RUN echo $%s
  5471. CMD echo $%s`, envKey, envKey)
  5472. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil || !strings.Contains(out, envVal) {
  5473. if err != nil {
  5474. c.Fatalf("build failed to complete: %q %q", out, err)
  5475. }
  5476. c.Fatalf("failed to access environment variable in output: %q expected: %q", out, envVal)
  5477. }
  5478. containerName := "bldargCont"
  5479. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); out != "\n" {
  5480. c.Fatalf("run produced invalid output: %q, expected empty string", out)
  5481. }
  5482. }
  5483. func (s *DockerSuite) TestBuildBuildTimeArgDefaultOverride(c *check.C) {
  5484. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5485. imgName := "bldargtest"
  5486. envKey := "foo"
  5487. envVal := "bar"
  5488. envValOveride := "barOverride"
  5489. args := []string{
  5490. "--build-arg", fmt.Sprintf("%s=%s", envKey, envValOveride),
  5491. }
  5492. dockerfile := fmt.Sprintf(`FROM busybox
  5493. ARG %s=%s
  5494. ENV %s $%s
  5495. RUN echo $%s
  5496. CMD echo $%s`, envKey, envVal, envKey, envKey, envKey, envKey)
  5497. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil || strings.Count(out, envValOveride) != 1 {
  5498. if err != nil {
  5499. c.Fatalf("build failed to complete: %q %q", out, err)
  5500. }
  5501. c.Fatalf("failed to access environment variable in output: %q expected: %q", out, envValOveride)
  5502. }
  5503. containerName := "bldargCont"
  5504. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOveride) {
  5505. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOveride)
  5506. }
  5507. }
  5508. func (s *DockerSuite) TestBuildBuildTimeArgMultiArgsSameLine(c *check.C) {
  5509. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5510. imgName := "bldargtest"
  5511. envKey := "foo"
  5512. envKey1 := "foo1"
  5513. args := []string{}
  5514. dockerfile := fmt.Sprintf(`FROM busybox
  5515. ARG %s %s`, envKey, envKey1)
  5516. errStr := "ARG requires exactly one argument definition"
  5517. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err == nil {
  5518. c.Fatalf("build succeeded, expected to fail. Output: %v", out)
  5519. } else if !strings.Contains(out, errStr) {
  5520. c.Fatalf("Unexpected error. output: %q, expected error: %q", out, errStr)
  5521. }
  5522. }
  5523. func (s *DockerSuite) TestBuildBuildTimeArgUnconsumedArg(c *check.C) {
  5524. testRequires(c, DaemonIsLinux) // Windows does not support --build-arg
  5525. imgName := "bldargtest"
  5526. envKey := "foo"
  5527. envVal := "bar"
  5528. args := []string{
  5529. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5530. }
  5531. dockerfile := fmt.Sprintf(`FROM busybox
  5532. RUN echo $%s
  5533. CMD echo $%s`, envKey, envKey)
  5534. errStr := "One or more build-args"
  5535. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err == nil {
  5536. c.Fatalf("build succeeded, expected to fail. Output: %v", out)
  5537. } else if !strings.Contains(out, errStr) {
  5538. c.Fatalf("Unexpected error. output: %q, expected error: %q", out, errStr)
  5539. }
  5540. }
  5541. func (s *DockerSuite) TestBuildBuildTimeArgQuotedValVariants(c *check.C) {
  5542. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5543. imgName := "bldargtest"
  5544. envKey := "foo"
  5545. envKey1 := "foo1"
  5546. envKey2 := "foo2"
  5547. envKey3 := "foo3"
  5548. args := []string{}
  5549. dockerfile := fmt.Sprintf(`FROM busybox
  5550. ARG %s=""
  5551. ARG %s=''
  5552. ARG %s="''"
  5553. ARG %s='""'
  5554. RUN [ "$%s" != "$%s" ]
  5555. RUN [ "$%s" != "$%s" ]
  5556. RUN [ "$%s" != "$%s" ]
  5557. RUN [ "$%s" != "$%s" ]
  5558. RUN [ "$%s" != "$%s" ]`, envKey, envKey1, envKey2, envKey3,
  5559. envKey, envKey2, envKey, envKey3, envKey1, envKey2, envKey1, envKey3,
  5560. envKey2, envKey3)
  5561. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil {
  5562. c.Fatalf("build failed to complete: %q %q", out, err)
  5563. }
  5564. }
  5565. func (s *DockerSuite) TestBuildBuildTimeArgEmptyValVariants(c *check.C) {
  5566. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5567. imgName := "bldargtest"
  5568. envKey := "foo"
  5569. envKey1 := "foo1"
  5570. envKey2 := "foo2"
  5571. args := []string{}
  5572. dockerfile := fmt.Sprintf(`FROM busybox
  5573. ARG %s=
  5574. ARG %s=""
  5575. ARG %s=''
  5576. RUN [ "$%s" == "$%s" ]
  5577. RUN [ "$%s" == "$%s" ]
  5578. RUN [ "$%s" == "$%s" ]`, envKey, envKey1, envKey2, envKey, envKey1, envKey1, envKey2, envKey, envKey2)
  5579. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil {
  5580. c.Fatalf("build failed to complete: %q %q", out, err)
  5581. }
  5582. }
  5583. func (s *DockerSuite) TestBuildBuildTimeArgDefintionWithNoEnvInjection(c *check.C) {
  5584. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  5585. imgName := "bldargtest"
  5586. envKey := "foo"
  5587. args := []string{}
  5588. dockerfile := fmt.Sprintf(`FROM busybox
  5589. ARG %s
  5590. RUN env`, envKey)
  5591. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil || strings.Count(out, envKey) != 1 {
  5592. if err != nil {
  5593. c.Fatalf("build failed to complete: %q %q", out, err)
  5594. }
  5595. c.Fatalf("unexpected number of occurrences of the arg in output: %q expected: 1", out)
  5596. }
  5597. }
  5598. func (s *DockerSuite) TestBuildNoNamedVolume(c *check.C) {
  5599. volName := "testname:/foo"
  5600. if daemonPlatform == "windows" {
  5601. volName = "testname:C:\\foo"
  5602. }
  5603. dockerCmd(c, "run", "-v", volName, "busybox", "sh", "-c", "touch /foo/oops")
  5604. dockerFile := `FROM busybox
  5605. VOLUME ` + volName + `
  5606. RUN ls /foo/oops
  5607. `
  5608. _, err := buildImage("test", dockerFile, false)
  5609. c.Assert(err, check.NotNil, check.Commentf("image build should have failed"))
  5610. }
  5611. func (s *DockerSuite) TestBuildTagEvent(c *check.C) {
  5612. since := daemonUnixTime(c)
  5613. dockerFile := `FROM busybox
  5614. RUN echo events
  5615. `
  5616. _, err := buildImage("test", dockerFile, false)
  5617. c.Assert(err, check.IsNil)
  5618. until := daemonUnixTime(c)
  5619. out, _ := dockerCmd(c, "events", "--since", since, "--until", until, "--filter", "type=image")
  5620. events := strings.Split(strings.TrimSpace(out), "\n")
  5621. actions := eventActionsByIDAndType(c, events, "test:latest", "image")
  5622. var foundTag bool
  5623. for _, a := range actions {
  5624. if a == "tag" {
  5625. foundTag = true
  5626. break
  5627. }
  5628. }
  5629. c.Assert(foundTag, checker.True, check.Commentf("No tag event found:\n%s", out))
  5630. }
  5631. // #15780
  5632. func (s *DockerSuite) TestBuildMultipleTags(c *check.C) {
  5633. dockerfile := `
  5634. FROM busybox
  5635. MAINTAINER test-15780
  5636. `
  5637. cmd := exec.Command(dockerBinary, "build", "-t", "tag1", "-t", "tag2:v2",
  5638. "-t", "tag1:latest", "-t", "tag1", "--no-cache", "-")
  5639. cmd.Stdin = strings.NewReader(dockerfile)
  5640. _, err := runCommand(cmd)
  5641. c.Assert(err, check.IsNil)
  5642. id1, err := getIDByName("tag1")
  5643. c.Assert(err, check.IsNil)
  5644. id2, err := getIDByName("tag2:v2")
  5645. c.Assert(err, check.IsNil)
  5646. c.Assert(id1, check.Equals, id2)
  5647. }
  5648. // #17290
  5649. func (s *DockerSuite) TestBuildCacheBrokenSymlink(c *check.C) {
  5650. testRequires(c, DaemonIsLinux)
  5651. name := "testbuildbrokensymlink"
  5652. ctx, err := fakeContext(`
  5653. FROM busybox
  5654. COPY . ./`,
  5655. map[string]string{
  5656. "foo": "bar",
  5657. })
  5658. c.Assert(err, checker.IsNil)
  5659. defer ctx.Close()
  5660. err = os.Symlink(filepath.Join(ctx.Dir, "nosuchfile"), filepath.Join(ctx.Dir, "asymlink"))
  5661. c.Assert(err, checker.IsNil)
  5662. // warm up cache
  5663. _, err = buildImageFromContext(name, ctx, true)
  5664. c.Assert(err, checker.IsNil)
  5665. // add new file to context, should invalidate cache
  5666. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "newfile"), []byte("foo"), 0644)
  5667. c.Assert(err, checker.IsNil)
  5668. _, out, err := buildImageFromContextWithOut(name, ctx, true)
  5669. c.Assert(err, checker.IsNil)
  5670. c.Assert(out, checker.Not(checker.Contains), "Using cache")
  5671. }
  5672. func (s *DockerSuite) TestBuildFollowSymlinkToFile(c *check.C) {
  5673. testRequires(c, DaemonIsLinux)
  5674. name := "testbuildbrokensymlink"
  5675. ctx, err := fakeContext(`
  5676. FROM busybox
  5677. COPY asymlink target`,
  5678. map[string]string{
  5679. "foo": "bar",
  5680. })
  5681. c.Assert(err, checker.IsNil)
  5682. defer ctx.Close()
  5683. err = os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink"))
  5684. c.Assert(err, checker.IsNil)
  5685. id, err := buildImageFromContext(name, ctx, true)
  5686. c.Assert(err, checker.IsNil)
  5687. out, _ := dockerCmd(c, "run", "--rm", id, "cat", "target")
  5688. c.Assert(out, checker.Matches, "bar")
  5689. // change target file should invalidate cache
  5690. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "foo"), []byte("baz"), 0644)
  5691. c.Assert(err, checker.IsNil)
  5692. id, out, err = buildImageFromContextWithOut(name, ctx, true)
  5693. c.Assert(err, checker.IsNil)
  5694. c.Assert(out, checker.Not(checker.Contains), "Using cache")
  5695. out, _ = dockerCmd(c, "run", "--rm", id, "cat", "target")
  5696. c.Assert(out, checker.Matches, "baz")
  5697. }
  5698. func (s *DockerSuite) TestBuildFollowSymlinkToDir(c *check.C) {
  5699. testRequires(c, DaemonIsLinux)
  5700. name := "testbuildbrokensymlink"
  5701. ctx, err := fakeContext(`
  5702. FROM busybox
  5703. COPY asymlink /`,
  5704. map[string]string{
  5705. "foo/abc": "bar",
  5706. "foo/def": "baz",
  5707. })
  5708. c.Assert(err, checker.IsNil)
  5709. defer ctx.Close()
  5710. err = os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink"))
  5711. c.Assert(err, checker.IsNil)
  5712. id, err := buildImageFromContext(name, ctx, true)
  5713. c.Assert(err, checker.IsNil)
  5714. out, _ := dockerCmd(c, "run", "--rm", id, "cat", "abc", "def")
  5715. c.Assert(out, checker.Matches, "barbaz")
  5716. // change target file should invalidate cache
  5717. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "foo/def"), []byte("bax"), 0644)
  5718. c.Assert(err, checker.IsNil)
  5719. id, out, err = buildImageFromContextWithOut(name, ctx, true)
  5720. c.Assert(err, checker.IsNil)
  5721. c.Assert(out, checker.Not(checker.Contains), "Using cache")
  5722. out, _ = dockerCmd(c, "run", "--rm", id, "cat", "abc", "def")
  5723. c.Assert(out, checker.Matches, "barbax")
  5724. }
  5725. // TestBuildSymlinkBasename tests that target file gets basename from symlink,
  5726. // not from the target file.
  5727. func (s *DockerSuite) TestBuildSymlinkBasename(c *check.C) {
  5728. testRequires(c, DaemonIsLinux)
  5729. name := "testbuildbrokensymlink"
  5730. ctx, err := fakeContext(`
  5731. FROM busybox
  5732. COPY asymlink /`,
  5733. map[string]string{
  5734. "foo": "bar",
  5735. })
  5736. c.Assert(err, checker.IsNil)
  5737. defer ctx.Close()
  5738. err = os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink"))
  5739. c.Assert(err, checker.IsNil)
  5740. id, err := buildImageFromContext(name, ctx, true)
  5741. c.Assert(err, checker.IsNil)
  5742. out, _ := dockerCmd(c, "run", "--rm", id, "cat", "asymlink")
  5743. c.Assert(out, checker.Matches, "bar")
  5744. }
  5745. // #17827
  5746. func (s *DockerSuite) TestBuildCacheRootSource(c *check.C) {
  5747. name := "testbuildrootsource"
  5748. ctx, err := fakeContext(`
  5749. FROM busybox
  5750. COPY / /data`,
  5751. map[string]string{
  5752. "foo": "bar",
  5753. })
  5754. c.Assert(err, checker.IsNil)
  5755. defer ctx.Close()
  5756. // warm up cache
  5757. _, err = buildImageFromContext(name, ctx, true)
  5758. c.Assert(err, checker.IsNil)
  5759. // change file, should invalidate cache
  5760. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "foo"), []byte("baz"), 0644)
  5761. c.Assert(err, checker.IsNil)
  5762. _, out, err := buildImageFromContextWithOut(name, ctx, true)
  5763. c.Assert(err, checker.IsNil)
  5764. c.Assert(out, checker.Not(checker.Contains), "Using cache")
  5765. }
  5766. // #19375
  5767. func (s *DockerSuite) TestBuildFailsGitNotCallable(c *check.C) {
  5768. cmd := exec.Command(dockerBinary, "build", "github.com/docker/v1.10-migrator.git")
  5769. cmd.Env = append(cmd.Env, "PATH=")
  5770. out, _, err := runCommandWithOutput(cmd)
  5771. c.Assert(err, checker.NotNil)
  5772. c.Assert(out, checker.Contains, "unable to prepare context: unable to find 'git': ")
  5773. cmd = exec.Command(dockerBinary, "build", "https://github.com/docker/v1.10-migrator.git")
  5774. cmd.Env = append(cmd.Env, "PATH=")
  5775. out, _, err = runCommandWithOutput(cmd)
  5776. c.Assert(err, checker.NotNil)
  5777. c.Assert(out, checker.Contains, "unable to prepare context: unable to find 'git': ")
  5778. }
  5779. // TestBuildWorkdirWindowsPath tests that a Windows style path works as a workdir
  5780. func (s *DockerSuite) TestBuildWorkdirWindowsPath(c *check.C) {
  5781. testRequires(c, DaemonIsWindows)
  5782. name := "testbuildworkdirwindowspath"
  5783. _, err := buildImage(name, `
  5784. FROM windowsservercore
  5785. RUN mkdir C:\\work
  5786. WORKDIR C:\\work
  5787. RUN if "%CD%" NEQ "C:\work" exit -1
  5788. `, true)
  5789. if err != nil {
  5790. c.Fatal(err)
  5791. }
  5792. }
  5793. func (s *DockerSuite) TestBuildLabel(c *check.C) {
  5794. name := "testbuildlabel"
  5795. testLabel := "foo"
  5796. _, err := buildImage(name, `
  5797. FROM `+minimalBaseImage()+`
  5798. LABEL default foo
  5799. `, false, "--label", testLabel)
  5800. c.Assert(err, checker.IsNil)
  5801. res := inspectFieldJSON(c, name, "Config.Labels")
  5802. var labels map[string]string
  5803. if err := json.Unmarshal([]byte(res), &labels); err != nil {
  5804. c.Fatal(err)
  5805. }
  5806. if _, ok := labels[testLabel]; !ok {
  5807. c.Fatal("label not found in image")
  5808. }
  5809. }
  5810. func (s *DockerSuite) TestBuildLabelOneNode(c *check.C) {
  5811. name := "testbuildlabel"
  5812. _, err := buildImage(name, "FROM busybox", false, "--label", "foo=bar")
  5813. c.Assert(err, checker.IsNil)
  5814. res, err := inspectImage(name, "json .Config.Labels")
  5815. c.Assert(err, checker.IsNil)
  5816. var labels map[string]string
  5817. if err := json.Unmarshal([]byte(res), &labels); err != nil {
  5818. c.Fatal(err)
  5819. }
  5820. v, ok := labels["foo"]
  5821. if !ok {
  5822. c.Fatal("label `foo` not found in image")
  5823. }
  5824. c.Assert(v, checker.Equals, "bar")
  5825. }
  5826. func (s *DockerSuite) TestBuildLabelCacheCommit(c *check.C) {
  5827. name := "testbuildlabelcachecommit"
  5828. testLabel := "foo"
  5829. if _, err := buildImage(name, `
  5830. FROM `+minimalBaseImage()+`
  5831. LABEL default foo
  5832. `, false); err != nil {
  5833. c.Fatal(err)
  5834. }
  5835. _, err := buildImage(name, `
  5836. FROM `+minimalBaseImage()+`
  5837. LABEL default foo
  5838. `, true, "--label", testLabel)
  5839. c.Assert(err, checker.IsNil)
  5840. res := inspectFieldJSON(c, name, "Config.Labels")
  5841. var labels map[string]string
  5842. if err := json.Unmarshal([]byte(res), &labels); err != nil {
  5843. c.Fatal(err)
  5844. }
  5845. if _, ok := labels[testLabel]; !ok {
  5846. c.Fatal("label not found in image")
  5847. }
  5848. }
  5849. func (s *DockerSuite) TestBuildLabelMultiple(c *check.C) {
  5850. name := "testbuildlabelmultiple"
  5851. testLabels := map[string]string{
  5852. "foo": "bar",
  5853. "123": "456",
  5854. }
  5855. labelArgs := []string{}
  5856. for k, v := range testLabels {
  5857. labelArgs = append(labelArgs, "--label", k+"="+v)
  5858. }
  5859. _, err := buildImage(name, `
  5860. FROM `+minimalBaseImage()+`
  5861. LABEL default foo
  5862. `, false, labelArgs...)
  5863. if err != nil {
  5864. c.Fatal("error building image with labels", err)
  5865. }
  5866. res := inspectFieldJSON(c, name, "Config.Labels")
  5867. var labels map[string]string
  5868. if err := json.Unmarshal([]byte(res), &labels); err != nil {
  5869. c.Fatal(err)
  5870. }
  5871. for k, v := range testLabels {
  5872. if x, ok := labels[k]; !ok || x != v {
  5873. c.Fatalf("label %s=%s not found in image", k, v)
  5874. }
  5875. }
  5876. }
  5877. func (s *DockerSuite) TestBuildLabelOverwrite(c *check.C) {
  5878. name := "testbuildlabeloverwrite"
  5879. testLabel := "foo"
  5880. testValue := "bar"
  5881. _, err := buildImage(name, `
  5882. FROM `+minimalBaseImage()+`
  5883. LABEL `+testLabel+`+ foo
  5884. `, false, []string{"--label", testLabel + "=" + testValue}...)
  5885. if err != nil {
  5886. c.Fatal("error building image with labels", err)
  5887. }
  5888. res := inspectFieldJSON(c, name, "Config.Labels")
  5889. var labels map[string]string
  5890. if err := json.Unmarshal([]byte(res), &labels); err != nil {
  5891. c.Fatal(err)
  5892. }
  5893. v, ok := labels[testLabel]
  5894. if !ok {
  5895. c.Fatal("label not found in image")
  5896. }
  5897. if v != testValue {
  5898. c.Fatal("label not overwritten")
  5899. }
  5900. }
  5901. func (s *DockerRegistryAuthHtpasswdSuite) TestBuildFromAuthenticatedRegistry(c *check.C) {
  5902. dockerCmd(c, "login", "-u", s.reg.username, "-p", s.reg.password, privateRegistryURL)
  5903. baseImage := privateRegistryURL + "/baseimage"
  5904. _, err := buildImage(baseImage, `
  5905. FROM busybox
  5906. ENV env1 val1
  5907. `, true)
  5908. c.Assert(err, checker.IsNil)
  5909. dockerCmd(c, "push", baseImage)
  5910. dockerCmd(c, "rmi", baseImage)
  5911. _, err = buildImage(baseImage, fmt.Sprintf(`
  5912. FROM %s
  5913. ENV env2 val2
  5914. `, baseImage), true)
  5915. c.Assert(err, checker.IsNil)
  5916. }
  5917. func (s *DockerRegistryAuthHtpasswdSuite) TestBuildWithExternalAuth(c *check.C) {
  5918. osPath := os.Getenv("PATH")
  5919. defer os.Setenv("PATH", osPath)
  5920. workingDir, err := os.Getwd()
  5921. c.Assert(err, checker.IsNil)
  5922. absolute, err := filepath.Abs(filepath.Join(workingDir, "fixtures", "auth"))
  5923. c.Assert(err, checker.IsNil)
  5924. testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute)
  5925. os.Setenv("PATH", testPath)
  5926. repoName := fmt.Sprintf("%v/dockercli/busybox:authtest", privateRegistryURL)
  5927. tmp, err := ioutil.TempDir("", "integration-cli-")
  5928. c.Assert(err, checker.IsNil)
  5929. externalAuthConfig := `{ "credsStore": "shell-test" }`
  5930. configPath := filepath.Join(tmp, "config.json")
  5931. err = ioutil.WriteFile(configPath, []byte(externalAuthConfig), 0644)
  5932. c.Assert(err, checker.IsNil)
  5933. dockerCmd(c, "--config", tmp, "login", "-u", s.reg.username, "-p", s.reg.password, privateRegistryURL)
  5934. b, err := ioutil.ReadFile(configPath)
  5935. c.Assert(err, checker.IsNil)
  5936. c.Assert(string(b), checker.Not(checker.Contains), "\"auth\":")
  5937. dockerCmd(c, "--config", tmp, "tag", "busybox", repoName)
  5938. dockerCmd(c, "--config", tmp, "push", repoName)
  5939. // make sure the image is pulled when building
  5940. dockerCmd(c, "rmi", repoName)
  5941. buildCmd := exec.Command(dockerBinary, "--config", tmp, "build", "-")
  5942. buildCmd.Stdin = strings.NewReader(fmt.Sprintf("FROM %s", repoName))
  5943. out, _, err := runCommandWithOutput(buildCmd)
  5944. c.Assert(err, check.IsNil, check.Commentf(out))
  5945. }