docker_cli_build_test.go 174 KB

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