docker_cli_build_test.go 173 KB

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