docker_cli_build_test.go 174 KB

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