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