docker_cli_build_test.go 186 KB

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