docker_cli_build_test.go 185 KB

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