docker_cli_build_test.go 169 KB

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