docker_cli_build_test.go 174 KB

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