docker_cli_build_test.go 199 KB

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