docker_cli_build_test.go 166 KB

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