docker_cli_build_test.go 185 KB

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