docker_cli_build_test.go 166 KB

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