docker_cli_build_test.go 173 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668
  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. observer, err := newEventObserver(c)
  1597. c.Assert(err, checker.IsNil)
  1598. err = observer.Start()
  1599. c.Assert(err, checker.IsNil)
  1600. defer observer.Stop()
  1601. // (Note: one year, will never finish)
  1602. ctx, err := fakeContext("FROM busybox\nRUN sleep 31536000", nil)
  1603. if err != nil {
  1604. c.Fatal(err)
  1605. }
  1606. defer ctx.Close()
  1607. buildCmd := exec.Command(dockerBinary, "build", "-t", name, ".")
  1608. buildCmd.Dir = ctx.Dir
  1609. stdoutBuild, err := buildCmd.StdoutPipe()
  1610. if err := buildCmd.Start(); err != nil {
  1611. c.Fatalf("failed to run build: %s", err)
  1612. }
  1613. matchCID := regexp.MustCompile("Running in (.+)")
  1614. scanner := bufio.NewScanner(stdoutBuild)
  1615. outputBuffer := new(bytes.Buffer)
  1616. var buildID string
  1617. for scanner.Scan() {
  1618. line := scanner.Text()
  1619. outputBuffer.WriteString(line)
  1620. outputBuffer.WriteString("\n")
  1621. if matches := matchCID.FindStringSubmatch(line); len(matches) > 0 {
  1622. buildID = matches[1]
  1623. break
  1624. }
  1625. }
  1626. if buildID == "" {
  1627. c.Fatalf("Unable to find build container id in build output:\n%s", outputBuffer.String())
  1628. }
  1629. testActions := map[string]chan bool{
  1630. "start": make(chan bool),
  1631. "die": make(chan bool),
  1632. }
  1633. go observer.Match(matchEventLine(buildID, "container", testActions))
  1634. select {
  1635. case <-time.After(10 * time.Second):
  1636. c.Fatal(observer.TimeoutError(buildID, "start"))
  1637. case <-testActions["start"]:
  1638. // ignore, done
  1639. }
  1640. // Send a kill to the `docker build` command.
  1641. // Causes the underlying build to be cancelled due to socket close.
  1642. if err := buildCmd.Process.Kill(); err != nil {
  1643. c.Fatalf("error killing build command: %s", err)
  1644. }
  1645. // Get the exit status of `docker build`, check it exited because killed.
  1646. if err := buildCmd.Wait(); err != nil && !isKilled(err) {
  1647. c.Fatalf("wait failed during build run: %T %s", err, err)
  1648. }
  1649. select {
  1650. case <-time.After(10 * time.Second):
  1651. c.Fatal(observer.TimeoutError(buildID, "die"))
  1652. case <-testActions["die"]:
  1653. // ignore, done
  1654. }
  1655. }
  1656. func (s *DockerSuite) TestBuildRm(c *check.C) {
  1657. testRequires(c, DaemonIsLinux)
  1658. name := "testbuildrm"
  1659. ctx, err := fakeContext("FROM scratch\nADD foo /\nADD foo /", map[string]string{"foo": "bar"})
  1660. if err != nil {
  1661. c.Fatal(err)
  1662. }
  1663. defer ctx.Close()
  1664. {
  1665. containerCountBefore, err := getContainerCount()
  1666. if err != nil {
  1667. c.Fatalf("failed to get the container count: %s", err)
  1668. }
  1669. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "--rm", "-t", name, ".")
  1670. if err != nil {
  1671. c.Fatal("failed to build the image", out)
  1672. }
  1673. containerCountAfter, err := getContainerCount()
  1674. if err != nil {
  1675. c.Fatalf("failed to get the container count: %s", err)
  1676. }
  1677. if containerCountBefore != containerCountAfter {
  1678. c.Fatalf("-rm shouldn't have left containers behind")
  1679. }
  1680. deleteImages(name)
  1681. }
  1682. {
  1683. containerCountBefore, err := getContainerCount()
  1684. if err != nil {
  1685. c.Fatalf("failed to get the container count: %s", err)
  1686. }
  1687. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", name, ".")
  1688. if err != nil {
  1689. c.Fatal("failed to build the image", out)
  1690. }
  1691. containerCountAfter, err := getContainerCount()
  1692. if err != nil {
  1693. c.Fatalf("failed to get the container count: %s", err)
  1694. }
  1695. if containerCountBefore != containerCountAfter {
  1696. c.Fatalf("--rm shouldn't have left containers behind")
  1697. }
  1698. deleteImages(name)
  1699. }
  1700. {
  1701. containerCountBefore, err := getContainerCount()
  1702. if err != nil {
  1703. c.Fatalf("failed to get the container count: %s", err)
  1704. }
  1705. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "--rm=false", "-t", name, ".")
  1706. if err != nil {
  1707. c.Fatal("failed to build the image", out)
  1708. }
  1709. containerCountAfter, err := getContainerCount()
  1710. if err != nil {
  1711. c.Fatalf("failed to get the container count: %s", err)
  1712. }
  1713. if containerCountBefore == containerCountAfter {
  1714. c.Fatalf("--rm=false should have left containers behind")
  1715. }
  1716. deleteImages(name)
  1717. }
  1718. }
  1719. func (s *DockerSuite) TestBuildWithVolumes(c *check.C) {
  1720. testRequires(c, DaemonIsLinux)
  1721. var (
  1722. result map[string]map[string]struct{}
  1723. name = "testbuildvolumes"
  1724. emptyMap = make(map[string]struct{})
  1725. expected = map[string]map[string]struct{}{
  1726. "/test1": emptyMap,
  1727. "/test2": emptyMap,
  1728. "/test3": emptyMap,
  1729. "/test4": emptyMap,
  1730. "/test5": emptyMap,
  1731. "/test6": emptyMap,
  1732. "[/test7": emptyMap,
  1733. "/test8]": emptyMap,
  1734. }
  1735. )
  1736. _, err := buildImage(name,
  1737. `FROM scratch
  1738. VOLUME /test1
  1739. VOLUME /test2
  1740. VOLUME /test3 /test4
  1741. VOLUME ["/test5", "/test6"]
  1742. VOLUME [/test7 /test8]
  1743. `,
  1744. true)
  1745. if err != nil {
  1746. c.Fatal(err)
  1747. }
  1748. res, err := inspectFieldJSON(name, "Config.Volumes")
  1749. if err != nil {
  1750. c.Fatal(err)
  1751. }
  1752. err = unmarshalJSON([]byte(res), &result)
  1753. if err != nil {
  1754. c.Fatal(err)
  1755. }
  1756. equal := reflect.DeepEqual(&result, &expected)
  1757. if !equal {
  1758. c.Fatalf("Volumes %s, expected %s", result, expected)
  1759. }
  1760. }
  1761. func (s *DockerSuite) TestBuildMaintainer(c *check.C) {
  1762. testRequires(c, DaemonIsLinux)
  1763. name := "testbuildmaintainer"
  1764. expected := "dockerio"
  1765. _, err := buildImage(name,
  1766. `FROM scratch
  1767. MAINTAINER dockerio`,
  1768. true)
  1769. if err != nil {
  1770. c.Fatal(err)
  1771. }
  1772. res, err := inspectField(name, "Author")
  1773. if err != nil {
  1774. c.Fatal(err)
  1775. }
  1776. if res != expected {
  1777. c.Fatalf("Maintainer %s, expected %s", res, expected)
  1778. }
  1779. }
  1780. func (s *DockerSuite) TestBuildUser(c *check.C) {
  1781. testRequires(c, DaemonIsLinux)
  1782. name := "testbuilduser"
  1783. expected := "dockerio"
  1784. _, err := buildImage(name,
  1785. `FROM busybox
  1786. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1787. USER dockerio
  1788. RUN [ $(whoami) = 'dockerio' ]`,
  1789. true)
  1790. if err != nil {
  1791. c.Fatal(err)
  1792. }
  1793. res, err := inspectField(name, "Config.User")
  1794. if err != nil {
  1795. c.Fatal(err)
  1796. }
  1797. if res != expected {
  1798. c.Fatalf("User %s, expected %s", res, expected)
  1799. }
  1800. }
  1801. func (s *DockerSuite) TestBuildRelativeWorkdir(c *check.C) {
  1802. testRequires(c, DaemonIsLinux)
  1803. name := "testbuildrelativeworkdir"
  1804. expected := "/test2/test3"
  1805. _, err := buildImage(name,
  1806. `FROM busybox
  1807. RUN [ "$PWD" = '/' ]
  1808. WORKDIR test1
  1809. RUN [ "$PWD" = '/test1' ]
  1810. WORKDIR /test2
  1811. RUN [ "$PWD" = '/test2' ]
  1812. WORKDIR test3
  1813. RUN [ "$PWD" = '/test2/test3' ]`,
  1814. true)
  1815. if err != nil {
  1816. c.Fatal(err)
  1817. }
  1818. res, err := inspectField(name, "Config.WorkingDir")
  1819. if err != nil {
  1820. c.Fatal(err)
  1821. }
  1822. if res != expected {
  1823. c.Fatalf("Workdir %s, expected %s", res, expected)
  1824. }
  1825. }
  1826. func (s *DockerSuite) TestBuildWorkdirWithEnvVariables(c *check.C) {
  1827. testRequires(c, DaemonIsLinux)
  1828. name := "testbuildworkdirwithenvvariables"
  1829. expected := "/test1/test2"
  1830. _, err := buildImage(name,
  1831. `FROM busybox
  1832. ENV DIRPATH /test1
  1833. ENV SUBDIRNAME test2
  1834. WORKDIR $DIRPATH
  1835. WORKDIR $SUBDIRNAME/$MISSING_VAR`,
  1836. true)
  1837. if err != nil {
  1838. c.Fatal(err)
  1839. }
  1840. res, err := inspectField(name, "Config.WorkingDir")
  1841. if err != nil {
  1842. c.Fatal(err)
  1843. }
  1844. if res != expected {
  1845. c.Fatalf("Workdir %s, expected %s", res, expected)
  1846. }
  1847. }
  1848. func (s *DockerSuite) TestBuildRelativeCopy(c *check.C) {
  1849. // cat /test1/test2/foo gets permission denied for the user
  1850. testRequires(c, NotUserNamespace)
  1851. testRequires(c, DaemonIsLinux)
  1852. name := "testbuildrelativecopy"
  1853. dockerfile := `
  1854. FROM busybox
  1855. WORKDIR /test1
  1856. WORKDIR test2
  1857. RUN [ "$PWD" = '/test1/test2' ]
  1858. COPY foo ./
  1859. RUN [ "$(cat /test1/test2/foo)" = 'hello' ]
  1860. ADD foo ./bar/baz
  1861. RUN [ "$(cat /test1/test2/bar/baz)" = 'hello' ]
  1862. COPY foo ./bar/baz2
  1863. RUN [ "$(cat /test1/test2/bar/baz2)" = 'hello' ]
  1864. WORKDIR ..
  1865. COPY foo ./
  1866. RUN [ "$(cat /test1/foo)" = 'hello' ]
  1867. COPY foo /test3/
  1868. RUN [ "$(cat /test3/foo)" = 'hello' ]
  1869. WORKDIR /test4
  1870. COPY . .
  1871. RUN [ "$(cat /test4/foo)" = 'hello' ]
  1872. WORKDIR /test5/test6
  1873. COPY foo ../
  1874. RUN [ "$(cat /test5/foo)" = 'hello' ]
  1875. `
  1876. ctx, err := fakeContext(dockerfile, map[string]string{
  1877. "foo": "hello",
  1878. })
  1879. if err != nil {
  1880. c.Fatal(err)
  1881. }
  1882. defer ctx.Close()
  1883. _, err = buildImageFromContext(name, ctx, false)
  1884. if err != nil {
  1885. c.Fatal(err)
  1886. }
  1887. }
  1888. func (s *DockerSuite) TestBuildEnv(c *check.C) {
  1889. testRequires(c, DaemonIsLinux)
  1890. name := "testbuildenv"
  1891. expected := "[PATH=/test:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin PORT=2375]"
  1892. _, err := buildImage(name,
  1893. `FROM busybox
  1894. ENV PATH /test:$PATH
  1895. ENV PORT 2375
  1896. RUN [ $(env | grep PORT) = 'PORT=2375' ]`,
  1897. true)
  1898. if err != nil {
  1899. c.Fatal(err)
  1900. }
  1901. res, err := inspectField(name, "Config.Env")
  1902. if err != nil {
  1903. c.Fatal(err)
  1904. }
  1905. if res != expected {
  1906. c.Fatalf("Env %s, expected %s", res, expected)
  1907. }
  1908. }
  1909. func (s *DockerSuite) TestBuildContextCleanup(c *check.C) {
  1910. testRequires(c, DaemonIsLinux)
  1911. testRequires(c, SameHostDaemon)
  1912. name := "testbuildcontextcleanup"
  1913. entries, err := ioutil.ReadDir(filepath.Join(dockerBasePath, "tmp"))
  1914. if err != nil {
  1915. c.Fatalf("failed to list contents of tmp dir: %s", err)
  1916. }
  1917. _, err = buildImage(name,
  1918. `FROM scratch
  1919. ENTRYPOINT ["/bin/echo"]`,
  1920. true)
  1921. if err != nil {
  1922. c.Fatal(err)
  1923. }
  1924. entriesFinal, err := ioutil.ReadDir(filepath.Join(dockerBasePath, "tmp"))
  1925. if err != nil {
  1926. c.Fatalf("failed to list contents of tmp dir: %s", err)
  1927. }
  1928. if err = compareDirectoryEntries(entries, entriesFinal); err != nil {
  1929. c.Fatalf("context should have been deleted, but wasn't")
  1930. }
  1931. }
  1932. func (s *DockerSuite) TestBuildContextCleanupFailedBuild(c *check.C) {
  1933. testRequires(c, DaemonIsLinux)
  1934. testRequires(c, SameHostDaemon)
  1935. name := "testbuildcontextcleanup"
  1936. entries, 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. _, err = buildImage(name,
  1941. `FROM scratch
  1942. RUN /non/existing/command`,
  1943. true)
  1944. if err == nil {
  1945. c.Fatalf("expected build to fail, but it didn't")
  1946. }
  1947. entriesFinal, err := ioutil.ReadDir(filepath.Join(dockerBasePath, "tmp"))
  1948. if err != nil {
  1949. c.Fatalf("failed to list contents of tmp dir: %s", err)
  1950. }
  1951. if err = compareDirectoryEntries(entries, entriesFinal); err != nil {
  1952. c.Fatalf("context should have been deleted, but wasn't")
  1953. }
  1954. }
  1955. func (s *DockerSuite) TestBuildCmd(c *check.C) {
  1956. testRequires(c, DaemonIsLinux)
  1957. name := "testbuildcmd"
  1958. expected := "{[/bin/echo Hello World]}"
  1959. _, err := buildImage(name,
  1960. `FROM scratch
  1961. CMD ["/bin/echo", "Hello World"]`,
  1962. true)
  1963. if err != nil {
  1964. c.Fatal(err)
  1965. }
  1966. res, err := inspectField(name, "Config.Cmd")
  1967. if err != nil {
  1968. c.Fatal(err)
  1969. }
  1970. if res != expected {
  1971. c.Fatalf("Cmd %s, expected %s", res, expected)
  1972. }
  1973. }
  1974. func (s *DockerSuite) TestBuildExpose(c *check.C) {
  1975. testRequires(c, DaemonIsLinux)
  1976. name := "testbuildexpose"
  1977. expected := "map[2375/tcp:{}]"
  1978. _, err := buildImage(name,
  1979. `FROM scratch
  1980. EXPOSE 2375`,
  1981. true)
  1982. if err != nil {
  1983. c.Fatal(err)
  1984. }
  1985. res, err := inspectField(name, "Config.ExposedPorts")
  1986. if err != nil {
  1987. c.Fatal(err)
  1988. }
  1989. if res != expected {
  1990. c.Fatalf("Exposed ports %s, expected %s", res, expected)
  1991. }
  1992. }
  1993. func (s *DockerSuite) TestBuildExposeMorePorts(c *check.C) {
  1994. testRequires(c, DaemonIsLinux)
  1995. // start building docker file with a large number of ports
  1996. portList := make([]string, 50)
  1997. line := make([]string, 100)
  1998. expectedPorts := make([]int, len(portList)*len(line))
  1999. for i := 0; i < len(portList); i++ {
  2000. for j := 0; j < len(line); j++ {
  2001. p := i*len(line) + j + 1
  2002. line[j] = strconv.Itoa(p)
  2003. expectedPorts[p-1] = p
  2004. }
  2005. if i == len(portList)-1 {
  2006. portList[i] = strings.Join(line, " ")
  2007. } else {
  2008. portList[i] = strings.Join(line, " ") + ` \`
  2009. }
  2010. }
  2011. dockerfile := `FROM scratch
  2012. EXPOSE {{range .}} {{.}}
  2013. {{end}}`
  2014. tmpl := template.Must(template.New("dockerfile").Parse(dockerfile))
  2015. buf := bytes.NewBuffer(nil)
  2016. tmpl.Execute(buf, portList)
  2017. name := "testbuildexpose"
  2018. _, err := buildImage(name, buf.String(), true)
  2019. if err != nil {
  2020. c.Fatal(err)
  2021. }
  2022. // check if all the ports are saved inside Config.ExposedPorts
  2023. res, err := inspectFieldJSON(name, "Config.ExposedPorts")
  2024. if err != nil {
  2025. c.Fatal(err)
  2026. }
  2027. var exposedPorts map[string]interface{}
  2028. if err := json.Unmarshal([]byte(res), &exposedPorts); err != nil {
  2029. c.Fatal(err)
  2030. }
  2031. for _, p := range expectedPorts {
  2032. ep := fmt.Sprintf("%d/tcp", p)
  2033. if _, ok := exposedPorts[ep]; !ok {
  2034. c.Errorf("Port(%s) is not exposed", ep)
  2035. } else {
  2036. delete(exposedPorts, ep)
  2037. }
  2038. }
  2039. if len(exposedPorts) != 0 {
  2040. c.Errorf("Unexpected extra exposed ports %v", exposedPorts)
  2041. }
  2042. }
  2043. func (s *DockerSuite) TestBuildExposeOrder(c *check.C) {
  2044. testRequires(c, DaemonIsLinux)
  2045. buildID := func(name, exposed string) string {
  2046. _, err := buildImage(name, fmt.Sprintf(`FROM scratch
  2047. EXPOSE %s`, exposed), true)
  2048. if err != nil {
  2049. c.Fatal(err)
  2050. }
  2051. id, err := inspectField(name, "Id")
  2052. if err != nil {
  2053. c.Fatal(err)
  2054. }
  2055. return id
  2056. }
  2057. id1 := buildID("testbuildexpose1", "80 2375")
  2058. id2 := buildID("testbuildexpose2", "2375 80")
  2059. if id1 != id2 {
  2060. c.Errorf("EXPOSE should invalidate the cache only when ports actually changed")
  2061. }
  2062. }
  2063. func (s *DockerSuite) TestBuildExposeUpperCaseProto(c *check.C) {
  2064. testRequires(c, DaemonIsLinux)
  2065. name := "testbuildexposeuppercaseproto"
  2066. expected := "map[5678/udp:{}]"
  2067. _, err := buildImage(name,
  2068. `FROM scratch
  2069. EXPOSE 5678/UDP`,
  2070. true)
  2071. if err != nil {
  2072. c.Fatal(err)
  2073. }
  2074. res, err := inspectField(name, "Config.ExposedPorts")
  2075. if err != nil {
  2076. c.Fatal(err)
  2077. }
  2078. if res != expected {
  2079. c.Fatalf("Exposed ports %s, expected %s", res, expected)
  2080. }
  2081. }
  2082. func (s *DockerSuite) TestBuildEmptyEntrypointInheritance(c *check.C) {
  2083. testRequires(c, DaemonIsLinux)
  2084. name := "testbuildentrypointinheritance"
  2085. name2 := "testbuildentrypointinheritance2"
  2086. _, err := buildImage(name,
  2087. `FROM busybox
  2088. ENTRYPOINT ["/bin/echo"]`,
  2089. true)
  2090. if err != nil {
  2091. c.Fatal(err)
  2092. }
  2093. res, err := inspectField(name, "Config.Entrypoint")
  2094. if err != nil {
  2095. c.Fatal(err)
  2096. }
  2097. expected := "{[/bin/echo]}"
  2098. if res != expected {
  2099. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  2100. }
  2101. _, err = buildImage(name2,
  2102. fmt.Sprintf(`FROM %s
  2103. ENTRYPOINT []`, name),
  2104. true)
  2105. if err != nil {
  2106. c.Fatal(err)
  2107. }
  2108. res, err = inspectField(name2, "Config.Entrypoint")
  2109. if err != nil {
  2110. c.Fatal(err)
  2111. }
  2112. expected = "{[]}"
  2113. if res != expected {
  2114. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  2115. }
  2116. }
  2117. func (s *DockerSuite) TestBuildEmptyEntrypoint(c *check.C) {
  2118. testRequires(c, DaemonIsLinux)
  2119. name := "testbuildentrypoint"
  2120. expected := "{[]}"
  2121. _, err := buildImage(name,
  2122. `FROM busybox
  2123. ENTRYPOINT []`,
  2124. true)
  2125. if err != nil {
  2126. c.Fatal(err)
  2127. }
  2128. res, err := inspectField(name, "Config.Entrypoint")
  2129. if err != nil {
  2130. c.Fatal(err)
  2131. }
  2132. if res != expected {
  2133. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  2134. }
  2135. }
  2136. func (s *DockerSuite) TestBuildEntrypoint(c *check.C) {
  2137. testRequires(c, DaemonIsLinux)
  2138. name := "testbuildentrypoint"
  2139. expected := "{[/bin/echo]}"
  2140. _, err := buildImage(name,
  2141. `FROM scratch
  2142. ENTRYPOINT ["/bin/echo"]`,
  2143. true)
  2144. if err != nil {
  2145. c.Fatal(err)
  2146. }
  2147. res, err := inspectField(name, "Config.Entrypoint")
  2148. if err != nil {
  2149. c.Fatal(err)
  2150. }
  2151. if res != expected {
  2152. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  2153. }
  2154. }
  2155. // #6445 ensure ONBUILD triggers aren't committed to grandchildren
  2156. func (s *DockerSuite) TestBuildOnBuildLimitedInheritence(c *check.C) {
  2157. testRequires(c, DaemonIsLinux)
  2158. var (
  2159. out2, out3 string
  2160. )
  2161. {
  2162. name1 := "testonbuildtrigger1"
  2163. dockerfile1 := `
  2164. FROM busybox
  2165. RUN echo "GRANDPARENT"
  2166. ONBUILD RUN echo "ONBUILD PARENT"
  2167. `
  2168. ctx, err := fakeContext(dockerfile1, nil)
  2169. if err != nil {
  2170. c.Fatal(err)
  2171. }
  2172. defer ctx.Close()
  2173. out1, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", name1, ".")
  2174. if err != nil {
  2175. c.Fatalf("build failed to complete: %s, %v", out1, err)
  2176. }
  2177. }
  2178. {
  2179. name2 := "testonbuildtrigger2"
  2180. dockerfile2 := `
  2181. FROM testonbuildtrigger1
  2182. `
  2183. ctx, err := fakeContext(dockerfile2, nil)
  2184. if err != nil {
  2185. c.Fatal(err)
  2186. }
  2187. defer ctx.Close()
  2188. out2, _, err = dockerCmdInDir(c, ctx.Dir, "build", "-t", name2, ".")
  2189. if err != nil {
  2190. c.Fatalf("build failed to complete: %s, %v", out2, err)
  2191. }
  2192. }
  2193. {
  2194. name3 := "testonbuildtrigger3"
  2195. dockerfile3 := `
  2196. FROM testonbuildtrigger2
  2197. `
  2198. ctx, err := fakeContext(dockerfile3, nil)
  2199. if err != nil {
  2200. c.Fatal(err)
  2201. }
  2202. defer ctx.Close()
  2203. out3, _, err = dockerCmdInDir(c, ctx.Dir, "build", "-t", name3, ".")
  2204. if err != nil {
  2205. c.Fatalf("build failed to complete: %s, %v", out3, err)
  2206. }
  2207. }
  2208. // ONBUILD should be run in second build.
  2209. if !strings.Contains(out2, "ONBUILD PARENT") {
  2210. c.Fatalf("ONBUILD instruction did not run in child of ONBUILD parent")
  2211. }
  2212. // ONBUILD should *not* be run in third build.
  2213. if strings.Contains(out3, "ONBUILD PARENT") {
  2214. c.Fatalf("ONBUILD instruction ran in grandchild of ONBUILD parent")
  2215. }
  2216. }
  2217. func (s *DockerSuite) TestBuildWithCache(c *check.C) {
  2218. testRequires(c, DaemonIsLinux)
  2219. name := "testbuildwithcache"
  2220. id1, err := buildImage(name,
  2221. `FROM scratch
  2222. MAINTAINER dockerio
  2223. EXPOSE 5432
  2224. ENTRYPOINT ["/bin/echo"]`,
  2225. true)
  2226. if err != nil {
  2227. c.Fatal(err)
  2228. }
  2229. id2, err := buildImage(name,
  2230. `FROM scratch
  2231. MAINTAINER dockerio
  2232. EXPOSE 5432
  2233. ENTRYPOINT ["/bin/echo"]`,
  2234. true)
  2235. if err != nil {
  2236. c.Fatal(err)
  2237. }
  2238. if id1 != id2 {
  2239. c.Fatal("The cache should have been used but hasn't.")
  2240. }
  2241. }
  2242. func (s *DockerSuite) TestBuildWithoutCache(c *check.C) {
  2243. testRequires(c, DaemonIsLinux)
  2244. name := "testbuildwithoutcache"
  2245. name2 := "testbuildwithoutcache2"
  2246. id1, err := buildImage(name,
  2247. `FROM scratch
  2248. MAINTAINER dockerio
  2249. EXPOSE 5432
  2250. ENTRYPOINT ["/bin/echo"]`,
  2251. true)
  2252. if err != nil {
  2253. c.Fatal(err)
  2254. }
  2255. id2, err := buildImage(name2,
  2256. `FROM scratch
  2257. MAINTAINER dockerio
  2258. EXPOSE 5432
  2259. ENTRYPOINT ["/bin/echo"]`,
  2260. false)
  2261. if err != nil {
  2262. c.Fatal(err)
  2263. }
  2264. if id1 == id2 {
  2265. c.Fatal("The cache should have been invalided but hasn't.")
  2266. }
  2267. }
  2268. func (s *DockerSuite) TestBuildConditionalCache(c *check.C) {
  2269. testRequires(c, DaemonIsLinux)
  2270. name := "testbuildconditionalcache"
  2271. dockerfile := `
  2272. FROM busybox
  2273. ADD foo /tmp/`
  2274. ctx, err := fakeContext(dockerfile, map[string]string{
  2275. "foo": "hello",
  2276. })
  2277. if err != nil {
  2278. c.Fatal(err)
  2279. }
  2280. defer ctx.Close()
  2281. id1, err := buildImageFromContext(name, ctx, true)
  2282. if err != nil {
  2283. c.Fatalf("Error building #1: %s", err)
  2284. }
  2285. if err := ctx.Add("foo", "bye"); err != nil {
  2286. c.Fatalf("Error modifying foo: %s", err)
  2287. }
  2288. id2, err := buildImageFromContext(name, ctx, false)
  2289. if err != nil {
  2290. c.Fatalf("Error building #2: %s", err)
  2291. }
  2292. if id2 == id1 {
  2293. c.Fatal("Should not have used the cache")
  2294. }
  2295. id3, err := buildImageFromContext(name, ctx, true)
  2296. if err != nil {
  2297. c.Fatalf("Error building #3: %s", err)
  2298. }
  2299. if id3 != id2 {
  2300. c.Fatal("Should have used the cache")
  2301. }
  2302. }
  2303. func (s *DockerSuite) TestBuildAddLocalFileWithCache(c *check.C) {
  2304. // local files are not owned by the correct user
  2305. testRequires(c, NotUserNamespace)
  2306. testRequires(c, DaemonIsLinux)
  2307. name := "testbuildaddlocalfilewithcache"
  2308. name2 := "testbuildaddlocalfilewithcache2"
  2309. dockerfile := `
  2310. FROM busybox
  2311. MAINTAINER dockerio
  2312. ADD foo /usr/lib/bla/bar
  2313. RUN [ "$(cat /usr/lib/bla/bar)" = "hello" ]`
  2314. ctx, err := fakeContext(dockerfile, map[string]string{
  2315. "foo": "hello",
  2316. })
  2317. if err != nil {
  2318. c.Fatal(err)
  2319. }
  2320. defer ctx.Close()
  2321. id1, err := buildImageFromContext(name, ctx, true)
  2322. if err != nil {
  2323. c.Fatal(err)
  2324. }
  2325. id2, err := buildImageFromContext(name2, ctx, true)
  2326. if err != nil {
  2327. c.Fatal(err)
  2328. }
  2329. if id1 != id2 {
  2330. c.Fatal("The cache should have been used but hasn't.")
  2331. }
  2332. }
  2333. func (s *DockerSuite) TestBuildAddMultipleLocalFileWithCache(c *check.C) {
  2334. testRequires(c, DaemonIsLinux)
  2335. name := "testbuildaddmultiplelocalfilewithcache"
  2336. name2 := "testbuildaddmultiplelocalfilewithcache2"
  2337. dockerfile := `
  2338. FROM busybox
  2339. MAINTAINER dockerio
  2340. ADD foo Dockerfile /usr/lib/bla/
  2341. RUN [ "$(cat /usr/lib/bla/foo)" = "hello" ]`
  2342. ctx, err := fakeContext(dockerfile, map[string]string{
  2343. "foo": "hello",
  2344. })
  2345. if err != nil {
  2346. c.Fatal(err)
  2347. }
  2348. defer ctx.Close()
  2349. id1, err := buildImageFromContext(name, ctx, true)
  2350. if err != nil {
  2351. c.Fatal(err)
  2352. }
  2353. id2, err := buildImageFromContext(name2, ctx, true)
  2354. if err != nil {
  2355. c.Fatal(err)
  2356. }
  2357. if id1 != id2 {
  2358. c.Fatal("The cache should have been used but hasn't.")
  2359. }
  2360. }
  2361. func (s *DockerSuite) TestBuildAddLocalFileWithoutCache(c *check.C) {
  2362. // local files are not owned by the correct user
  2363. testRequires(c, NotUserNamespace)
  2364. testRequires(c, DaemonIsLinux)
  2365. name := "testbuildaddlocalfilewithoutcache"
  2366. name2 := "testbuildaddlocalfilewithoutcache2"
  2367. dockerfile := `
  2368. FROM busybox
  2369. MAINTAINER dockerio
  2370. ADD foo /usr/lib/bla/bar
  2371. RUN [ "$(cat /usr/lib/bla/bar)" = "hello" ]`
  2372. ctx, err := fakeContext(dockerfile, map[string]string{
  2373. "foo": "hello",
  2374. })
  2375. if err != nil {
  2376. c.Fatal(err)
  2377. }
  2378. defer ctx.Close()
  2379. id1, err := buildImageFromContext(name, ctx, true)
  2380. if err != nil {
  2381. c.Fatal(err)
  2382. }
  2383. id2, err := buildImageFromContext(name2, ctx, false)
  2384. if err != nil {
  2385. c.Fatal(err)
  2386. }
  2387. if id1 == id2 {
  2388. c.Fatal("The cache should have been invalided but hasn't.")
  2389. }
  2390. }
  2391. func (s *DockerSuite) TestBuildCopyDirButNotFile(c *check.C) {
  2392. testRequires(c, DaemonIsLinux)
  2393. name := "testbuildcopydirbutnotfile"
  2394. name2 := "testbuildcopydirbutnotfile2"
  2395. dockerfile := `
  2396. FROM scratch
  2397. COPY dir /tmp/`
  2398. ctx, err := fakeContext(dockerfile, map[string]string{
  2399. "dir/foo": "hello",
  2400. })
  2401. if err != nil {
  2402. c.Fatal(err)
  2403. }
  2404. defer ctx.Close()
  2405. id1, err := buildImageFromContext(name, ctx, true)
  2406. if err != nil {
  2407. c.Fatal(err)
  2408. }
  2409. // Check that adding file with similar name doesn't mess with cache
  2410. if err := ctx.Add("dir_file", "hello2"); err != nil {
  2411. c.Fatal(err)
  2412. }
  2413. id2, err := buildImageFromContext(name2, ctx, true)
  2414. if err != nil {
  2415. c.Fatal(err)
  2416. }
  2417. if id1 != id2 {
  2418. c.Fatal("The cache should have been used but wasn't")
  2419. }
  2420. }
  2421. func (s *DockerSuite) TestBuildAddCurrentDirWithCache(c *check.C) {
  2422. testRequires(c, DaemonIsLinux)
  2423. name := "testbuildaddcurrentdirwithcache"
  2424. name2 := name + "2"
  2425. name3 := name + "3"
  2426. name4 := name + "4"
  2427. dockerfile := `
  2428. FROM scratch
  2429. MAINTAINER dockerio
  2430. ADD . /usr/lib/bla`
  2431. ctx, err := fakeContext(dockerfile, map[string]string{
  2432. "foo": "hello",
  2433. })
  2434. if err != nil {
  2435. c.Fatal(err)
  2436. }
  2437. defer ctx.Close()
  2438. id1, err := buildImageFromContext(name, ctx, true)
  2439. if err != nil {
  2440. c.Fatal(err)
  2441. }
  2442. // Check that adding file invalidate cache of "ADD ."
  2443. if err := ctx.Add("bar", "hello2"); err != nil {
  2444. c.Fatal(err)
  2445. }
  2446. id2, err := buildImageFromContext(name2, ctx, true)
  2447. if err != nil {
  2448. c.Fatal(err)
  2449. }
  2450. if id1 == id2 {
  2451. c.Fatal("The cache should have been invalided but hasn't.")
  2452. }
  2453. // Check that changing file invalidate cache of "ADD ."
  2454. if err := ctx.Add("foo", "hello1"); err != nil {
  2455. c.Fatal(err)
  2456. }
  2457. id3, err := buildImageFromContext(name3, ctx, true)
  2458. if err != nil {
  2459. c.Fatal(err)
  2460. }
  2461. if id2 == id3 {
  2462. c.Fatal("The cache should have been invalided but hasn't.")
  2463. }
  2464. // Check that changing file to same content with different mtime does not
  2465. // invalidate cache of "ADD ."
  2466. time.Sleep(1 * time.Second) // wait second because of mtime precision
  2467. if err := ctx.Add("foo", "hello1"); err != nil {
  2468. c.Fatal(err)
  2469. }
  2470. id4, err := buildImageFromContext(name4, ctx, true)
  2471. if err != nil {
  2472. c.Fatal(err)
  2473. }
  2474. if id3 != id4 {
  2475. c.Fatal("The cache should have been used but hasn't.")
  2476. }
  2477. }
  2478. func (s *DockerSuite) TestBuildAddCurrentDirWithoutCache(c *check.C) {
  2479. testRequires(c, DaemonIsLinux)
  2480. name := "testbuildaddcurrentdirwithoutcache"
  2481. name2 := "testbuildaddcurrentdirwithoutcache2"
  2482. dockerfile := `
  2483. FROM scratch
  2484. MAINTAINER dockerio
  2485. ADD . /usr/lib/bla`
  2486. ctx, err := fakeContext(dockerfile, map[string]string{
  2487. "foo": "hello",
  2488. })
  2489. if err != nil {
  2490. c.Fatal(err)
  2491. }
  2492. defer ctx.Close()
  2493. id1, err := buildImageFromContext(name, ctx, true)
  2494. if err != nil {
  2495. c.Fatal(err)
  2496. }
  2497. id2, err := buildImageFromContext(name2, ctx, false)
  2498. if err != nil {
  2499. c.Fatal(err)
  2500. }
  2501. if id1 == id2 {
  2502. c.Fatal("The cache should have been invalided but hasn't.")
  2503. }
  2504. }
  2505. func (s *DockerSuite) TestBuildAddRemoteFileWithCache(c *check.C) {
  2506. testRequires(c, DaemonIsLinux)
  2507. name := "testbuildaddremotefilewithcache"
  2508. server, err := fakeStorage(map[string]string{
  2509. "baz": "hello",
  2510. })
  2511. if err != nil {
  2512. c.Fatal(err)
  2513. }
  2514. defer server.Close()
  2515. id1, err := buildImage(name,
  2516. fmt.Sprintf(`FROM scratch
  2517. MAINTAINER dockerio
  2518. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2519. true)
  2520. if err != nil {
  2521. c.Fatal(err)
  2522. }
  2523. id2, err := buildImage(name,
  2524. fmt.Sprintf(`FROM scratch
  2525. MAINTAINER dockerio
  2526. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2527. true)
  2528. if err != nil {
  2529. c.Fatal(err)
  2530. }
  2531. if id1 != id2 {
  2532. c.Fatal("The cache should have been used but hasn't.")
  2533. }
  2534. }
  2535. func (s *DockerSuite) TestBuildAddRemoteFileWithoutCache(c *check.C) {
  2536. testRequires(c, DaemonIsLinux)
  2537. name := "testbuildaddremotefilewithoutcache"
  2538. name2 := "testbuildaddremotefilewithoutcache2"
  2539. server, err := fakeStorage(map[string]string{
  2540. "baz": "hello",
  2541. })
  2542. if err != nil {
  2543. c.Fatal(err)
  2544. }
  2545. defer server.Close()
  2546. id1, err := buildImage(name,
  2547. fmt.Sprintf(`FROM scratch
  2548. MAINTAINER dockerio
  2549. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2550. true)
  2551. if err != nil {
  2552. c.Fatal(err)
  2553. }
  2554. id2, err := buildImage(name2,
  2555. fmt.Sprintf(`FROM scratch
  2556. MAINTAINER dockerio
  2557. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2558. false)
  2559. if err != nil {
  2560. c.Fatal(err)
  2561. }
  2562. if id1 == id2 {
  2563. c.Fatal("The cache should have been invalided but hasn't.")
  2564. }
  2565. }
  2566. func (s *DockerSuite) TestBuildAddRemoteFileMTime(c *check.C) {
  2567. testRequires(c, DaemonIsLinux)
  2568. name := "testbuildaddremotefilemtime"
  2569. name2 := name + "2"
  2570. name3 := name + "3"
  2571. files := map[string]string{"baz": "hello"}
  2572. server, err := fakeStorage(files)
  2573. if err != nil {
  2574. c.Fatal(err)
  2575. }
  2576. defer server.Close()
  2577. ctx, err := fakeContext(fmt.Sprintf(`FROM scratch
  2578. MAINTAINER dockerio
  2579. ADD %s/baz /usr/lib/baz/quux`, server.URL()), nil)
  2580. if err != nil {
  2581. c.Fatal(err)
  2582. }
  2583. defer ctx.Close()
  2584. id1, err := buildImageFromContext(name, ctx, true)
  2585. if err != nil {
  2586. c.Fatal(err)
  2587. }
  2588. id2, err := buildImageFromContext(name2, ctx, true)
  2589. if err != nil {
  2590. c.Fatal(err)
  2591. }
  2592. if id1 != id2 {
  2593. c.Fatal("The cache should have been used but wasn't - #1")
  2594. }
  2595. // Now create a different server with same contents (causes different mtime)
  2596. // The cache should still be used
  2597. // allow some time for clock to pass as mtime precision is only 1s
  2598. time.Sleep(2 * time.Second)
  2599. server2, err := fakeStorage(files)
  2600. if err != nil {
  2601. c.Fatal(err)
  2602. }
  2603. defer server2.Close()
  2604. ctx2, err := fakeContext(fmt.Sprintf(`FROM scratch
  2605. MAINTAINER dockerio
  2606. ADD %s/baz /usr/lib/baz/quux`, server2.URL()), nil)
  2607. if err != nil {
  2608. c.Fatal(err)
  2609. }
  2610. defer ctx2.Close()
  2611. id3, err := buildImageFromContext(name3, ctx2, true)
  2612. if err != nil {
  2613. c.Fatal(err)
  2614. }
  2615. if id1 != id3 {
  2616. c.Fatal("The cache should have been used but wasn't")
  2617. }
  2618. }
  2619. func (s *DockerSuite) TestBuildAddLocalAndRemoteFilesWithCache(c *check.C) {
  2620. testRequires(c, DaemonIsLinux)
  2621. name := "testbuildaddlocalandremotefilewithcache"
  2622. server, err := fakeStorage(map[string]string{
  2623. "baz": "hello",
  2624. })
  2625. if err != nil {
  2626. c.Fatal(err)
  2627. }
  2628. defer server.Close()
  2629. ctx, err := fakeContext(fmt.Sprintf(`FROM scratch
  2630. MAINTAINER dockerio
  2631. ADD foo /usr/lib/bla/bar
  2632. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2633. map[string]string{
  2634. "foo": "hello world",
  2635. })
  2636. if err != nil {
  2637. c.Fatal(err)
  2638. }
  2639. defer ctx.Close()
  2640. id1, err := buildImageFromContext(name, ctx, true)
  2641. if err != nil {
  2642. c.Fatal(err)
  2643. }
  2644. id2, err := buildImageFromContext(name, ctx, true)
  2645. if err != nil {
  2646. c.Fatal(err)
  2647. }
  2648. if id1 != id2 {
  2649. c.Fatal("The cache should have been used but hasn't.")
  2650. }
  2651. }
  2652. func testContextTar(c *check.C, compression archive.Compression) {
  2653. testRequires(c, DaemonIsLinux)
  2654. ctx, err := fakeContext(
  2655. `FROM busybox
  2656. ADD foo /foo
  2657. CMD ["cat", "/foo"]`,
  2658. map[string]string{
  2659. "foo": "bar",
  2660. },
  2661. )
  2662. if err != nil {
  2663. c.Fatal(err)
  2664. }
  2665. defer ctx.Close()
  2666. context, err := archive.Tar(ctx.Dir, compression)
  2667. if err != nil {
  2668. c.Fatalf("failed to build context tar: %v", err)
  2669. }
  2670. name := "contexttar"
  2671. buildCmd := exec.Command(dockerBinary, "build", "-t", name, "-")
  2672. buildCmd.Stdin = context
  2673. if out, _, err := runCommandWithOutput(buildCmd); err != nil {
  2674. c.Fatalf("build failed to complete: %v %v", out, err)
  2675. }
  2676. }
  2677. func (s *DockerSuite) TestBuildContextTarGzip(c *check.C) {
  2678. testContextTar(c, archive.Gzip)
  2679. }
  2680. func (s *DockerSuite) TestBuildContextTarNoCompression(c *check.C) {
  2681. testContextTar(c, archive.Uncompressed)
  2682. }
  2683. func (s *DockerSuite) TestBuildNoContext(c *check.C) {
  2684. testRequires(c, DaemonIsLinux)
  2685. buildCmd := exec.Command(dockerBinary, "build", "-t", "nocontext", "-")
  2686. buildCmd.Stdin = strings.NewReader("FROM busybox\nCMD echo ok\n")
  2687. if out, _, err := runCommandWithOutput(buildCmd); err != nil {
  2688. c.Fatalf("build failed to complete: %v %v", out, err)
  2689. }
  2690. if out, _ := dockerCmd(c, "run", "--rm", "nocontext"); out != "ok\n" {
  2691. c.Fatalf("run produced invalid output: %q, expected %q", out, "ok")
  2692. }
  2693. }
  2694. // TODO: TestCaching
  2695. func (s *DockerSuite) TestBuildAddLocalAndRemoteFilesWithoutCache(c *check.C) {
  2696. testRequires(c, DaemonIsLinux)
  2697. name := "testbuildaddlocalandremotefilewithoutcache"
  2698. name2 := "testbuildaddlocalandremotefilewithoutcache2"
  2699. server, err := fakeStorage(map[string]string{
  2700. "baz": "hello",
  2701. })
  2702. if err != nil {
  2703. c.Fatal(err)
  2704. }
  2705. defer server.Close()
  2706. ctx, err := fakeContext(fmt.Sprintf(`FROM scratch
  2707. MAINTAINER dockerio
  2708. ADD foo /usr/lib/bla/bar
  2709. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2710. map[string]string{
  2711. "foo": "hello world",
  2712. })
  2713. if err != nil {
  2714. c.Fatal(err)
  2715. }
  2716. defer ctx.Close()
  2717. id1, err := buildImageFromContext(name, ctx, true)
  2718. if err != nil {
  2719. c.Fatal(err)
  2720. }
  2721. id2, err := buildImageFromContext(name2, ctx, false)
  2722. if err != nil {
  2723. c.Fatal(err)
  2724. }
  2725. if id1 == id2 {
  2726. c.Fatal("The cache should have been invalided but hasn't.")
  2727. }
  2728. }
  2729. func (s *DockerSuite) TestBuildWithVolumeOwnership(c *check.C) {
  2730. testRequires(c, DaemonIsLinux)
  2731. name := "testbuildimg"
  2732. _, err := buildImage(name,
  2733. `FROM busybox:latest
  2734. RUN mkdir /test && chown daemon:daemon /test && chmod 0600 /test
  2735. VOLUME /test`,
  2736. true)
  2737. if err != nil {
  2738. c.Fatal(err)
  2739. }
  2740. out, _ := dockerCmd(c, "run", "--rm", "testbuildimg", "ls", "-la", "/test")
  2741. if expected := "drw-------"; !strings.Contains(out, expected) {
  2742. c.Fatalf("expected %s received %s", expected, out)
  2743. }
  2744. if expected := "daemon daemon"; !strings.Contains(out, expected) {
  2745. c.Fatalf("expected %s received %s", expected, out)
  2746. }
  2747. }
  2748. // testing #1405 - config.Cmd does not get cleaned up if
  2749. // utilizing cache
  2750. func (s *DockerSuite) TestBuildEntrypointRunCleanup(c *check.C) {
  2751. testRequires(c, DaemonIsLinux)
  2752. name := "testbuildcmdcleanup"
  2753. if _, err := buildImage(name,
  2754. `FROM busybox
  2755. RUN echo "hello"`,
  2756. true); err != nil {
  2757. c.Fatal(err)
  2758. }
  2759. ctx, err := fakeContext(`FROM busybox
  2760. RUN echo "hello"
  2761. ADD foo /foo
  2762. ENTRYPOINT ["/bin/echo"]`,
  2763. map[string]string{
  2764. "foo": "hello",
  2765. })
  2766. if err != nil {
  2767. c.Fatal(err)
  2768. }
  2769. defer ctx.Close()
  2770. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2771. c.Fatal(err)
  2772. }
  2773. res, err := inspectField(name, "Config.Cmd")
  2774. if err != nil {
  2775. c.Fatal(err)
  2776. }
  2777. // Cmd must be cleaned up
  2778. if res != "<nil>" {
  2779. c.Fatalf("Cmd %s, expected nil", res)
  2780. }
  2781. }
  2782. func (s *DockerSuite) TestBuildForbiddenContextPath(c *check.C) {
  2783. testRequires(c, DaemonIsLinux)
  2784. name := "testbuildforbidpath"
  2785. ctx, err := fakeContext(`FROM scratch
  2786. ADD ../../ test/
  2787. `,
  2788. map[string]string{
  2789. "test.txt": "test1",
  2790. "other.txt": "other",
  2791. })
  2792. if err != nil {
  2793. c.Fatal(err)
  2794. }
  2795. defer ctx.Close()
  2796. expected := "Forbidden path outside the build context: ../../ "
  2797. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  2798. c.Fatalf("Wrong error: (should contain \"%s\") got:\n%v", expected, err)
  2799. }
  2800. }
  2801. func (s *DockerSuite) TestBuildAddFileNotFound(c *check.C) {
  2802. testRequires(c, DaemonIsLinux)
  2803. name := "testbuildaddnotfound"
  2804. ctx, err := fakeContext(`FROM scratch
  2805. ADD foo /usr/local/bar`,
  2806. map[string]string{"bar": "hello"})
  2807. if err != nil {
  2808. c.Fatal(err)
  2809. }
  2810. defer ctx.Close()
  2811. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2812. if !strings.Contains(err.Error(), "foo: no such file or directory") {
  2813. c.Fatalf("Wrong error %v, must be about missing foo file or directory", err)
  2814. }
  2815. } else {
  2816. c.Fatal("Error must not be nil")
  2817. }
  2818. }
  2819. func (s *DockerSuite) TestBuildInheritance(c *check.C) {
  2820. testRequires(c, DaemonIsLinux)
  2821. name := "testbuildinheritance"
  2822. _, err := buildImage(name,
  2823. `FROM scratch
  2824. EXPOSE 2375`,
  2825. true)
  2826. if err != nil {
  2827. c.Fatal(err)
  2828. }
  2829. ports1, err := inspectField(name, "Config.ExposedPorts")
  2830. if err != nil {
  2831. c.Fatal(err)
  2832. }
  2833. _, err = buildImage(name,
  2834. fmt.Sprintf(`FROM %s
  2835. ENTRYPOINT ["/bin/echo"]`, name),
  2836. true)
  2837. if err != nil {
  2838. c.Fatal(err)
  2839. }
  2840. res, err := inspectField(name, "Config.Entrypoint")
  2841. if err != nil {
  2842. c.Fatal(err)
  2843. }
  2844. if expected := "{[/bin/echo]}"; res != expected {
  2845. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  2846. }
  2847. ports2, err := inspectField(name, "Config.ExposedPorts")
  2848. if err != nil {
  2849. c.Fatal(err)
  2850. }
  2851. if ports1 != ports2 {
  2852. c.Fatalf("Ports must be same: %s != %s", ports1, ports2)
  2853. }
  2854. }
  2855. func (s *DockerSuite) TestBuildFails(c *check.C) {
  2856. testRequires(c, DaemonIsLinux)
  2857. name := "testbuildfails"
  2858. _, err := buildImage(name,
  2859. `FROM busybox
  2860. RUN sh -c "exit 23"`,
  2861. true)
  2862. if err != nil {
  2863. if !strings.Contains(err.Error(), "returned a non-zero code: 23") {
  2864. c.Fatalf("Wrong error %v, must be about non-zero code 23", err)
  2865. }
  2866. } else {
  2867. c.Fatal("Error must not be nil")
  2868. }
  2869. }
  2870. func (s *DockerSuite) TestBuildFailsDockerfileEmpty(c *check.C) {
  2871. name := "testbuildfails"
  2872. _, err := buildImage(name, ``, true)
  2873. if err != nil {
  2874. if !strings.Contains(err.Error(), "The Dockerfile (Dockerfile) cannot be empty") {
  2875. c.Fatalf("Wrong error %v, must be about empty Dockerfile", err)
  2876. }
  2877. } else {
  2878. c.Fatal("Error must not be nil")
  2879. }
  2880. }
  2881. func (s *DockerSuite) TestBuildOnBuild(c *check.C) {
  2882. testRequires(c, DaemonIsLinux)
  2883. name := "testbuildonbuild"
  2884. _, err := buildImage(name,
  2885. `FROM busybox
  2886. ONBUILD RUN touch foobar`,
  2887. true)
  2888. if err != nil {
  2889. c.Fatal(err)
  2890. }
  2891. _, err = buildImage(name,
  2892. fmt.Sprintf(`FROM %s
  2893. RUN [ -f foobar ]`, name),
  2894. true)
  2895. if err != nil {
  2896. c.Fatal(err)
  2897. }
  2898. }
  2899. func (s *DockerSuite) TestBuildOnBuildForbiddenChained(c *check.C) {
  2900. testRequires(c, DaemonIsLinux)
  2901. name := "testbuildonbuildforbiddenchained"
  2902. _, err := buildImage(name,
  2903. `FROM busybox
  2904. ONBUILD ONBUILD RUN touch foobar`,
  2905. true)
  2906. if err != nil {
  2907. if !strings.Contains(err.Error(), "Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed") {
  2908. c.Fatalf("Wrong error %v, must be about chaining ONBUILD", err)
  2909. }
  2910. } else {
  2911. c.Fatal("Error must not be nil")
  2912. }
  2913. }
  2914. func (s *DockerSuite) TestBuildOnBuildForbiddenFrom(c *check.C) {
  2915. testRequires(c, DaemonIsLinux)
  2916. name := "testbuildonbuildforbiddenfrom"
  2917. _, err := buildImage(name,
  2918. `FROM busybox
  2919. ONBUILD FROM scratch`,
  2920. true)
  2921. if err != nil {
  2922. if !strings.Contains(err.Error(), "FROM isn't allowed as an ONBUILD trigger") {
  2923. c.Fatalf("Wrong error %v, must be about FROM forbidden", err)
  2924. }
  2925. } else {
  2926. c.Fatal("Error must not be nil")
  2927. }
  2928. }
  2929. func (s *DockerSuite) TestBuildOnBuildForbiddenMaintainer(c *check.C) {
  2930. testRequires(c, DaemonIsLinux)
  2931. name := "testbuildonbuildforbiddenmaintainer"
  2932. _, err := buildImage(name,
  2933. `FROM busybox
  2934. ONBUILD MAINTAINER docker.io`,
  2935. true)
  2936. if err != nil {
  2937. if !strings.Contains(err.Error(), "MAINTAINER isn't allowed as an ONBUILD trigger") {
  2938. c.Fatalf("Wrong error %v, must be about MAINTAINER forbidden", err)
  2939. }
  2940. } else {
  2941. c.Fatal("Error must not be nil")
  2942. }
  2943. }
  2944. // gh #2446
  2945. func (s *DockerSuite) TestBuildAddToSymlinkDest(c *check.C) {
  2946. testRequires(c, DaemonIsLinux)
  2947. name := "testbuildaddtosymlinkdest"
  2948. ctx, err := fakeContext(`FROM busybox
  2949. RUN mkdir /foo
  2950. RUN ln -s /foo /bar
  2951. ADD foo /bar/
  2952. RUN [ -f /bar/foo ]
  2953. RUN [ -f /foo/foo ]`,
  2954. map[string]string{
  2955. "foo": "hello",
  2956. })
  2957. if err != nil {
  2958. c.Fatal(err)
  2959. }
  2960. defer ctx.Close()
  2961. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2962. c.Fatal(err)
  2963. }
  2964. }
  2965. func (s *DockerSuite) TestBuildEscapeWhitespace(c *check.C) {
  2966. testRequires(c, DaemonIsLinux)
  2967. name := "testbuildescaping"
  2968. _, err := buildImage(name, `
  2969. FROM busybox
  2970. MAINTAINER "Docker \
  2971. IO <io@\
  2972. docker.com>"
  2973. `, true)
  2974. if err != nil {
  2975. c.Fatal(err)
  2976. }
  2977. res, err := inspectField(name, "Author")
  2978. if err != nil {
  2979. c.Fatal(err)
  2980. }
  2981. if res != "\"Docker IO <io@docker.com>\"" {
  2982. c.Fatalf("Parsed string did not match the escaped string. Got: %q", res)
  2983. }
  2984. }
  2985. func (s *DockerSuite) TestBuildVerifyIntString(c *check.C) {
  2986. testRequires(c, DaemonIsLinux)
  2987. // Verify that strings that look like ints are still passed as strings
  2988. name := "testbuildstringing"
  2989. _, err := buildImage(name, `
  2990. FROM busybox
  2991. MAINTAINER 123
  2992. `, true)
  2993. if err != nil {
  2994. c.Fatal(err)
  2995. }
  2996. out, _ := dockerCmd(c, "inspect", name)
  2997. if !strings.Contains(out, "\"123\"") {
  2998. c.Fatalf("Output does not contain the int as a string:\n%s", out)
  2999. }
  3000. }
  3001. func (s *DockerSuite) TestBuildDockerignore(c *check.C) {
  3002. testRequires(c, DaemonIsLinux)
  3003. name := "testbuilddockerignore"
  3004. dockerfile := `
  3005. FROM busybox
  3006. ADD . /bla
  3007. RUN [[ -f /bla/src/x.go ]]
  3008. RUN [[ -f /bla/Makefile ]]
  3009. RUN [[ ! -e /bla/src/_vendor ]]
  3010. RUN [[ ! -e /bla/.gitignore ]]
  3011. RUN [[ ! -e /bla/README.md ]]
  3012. RUN [[ ! -e /bla/dir/foo ]]
  3013. RUN [[ ! -e /bla/foo ]]
  3014. RUN [[ ! -e /bla/.git ]]
  3015. RUN [[ ! -e v.cc ]]
  3016. RUN [[ ! -e src/v.cc ]]
  3017. RUN [[ ! -e src/_vendor/v.cc ]]`
  3018. ctx, err := fakeContext(dockerfile, map[string]string{
  3019. "Makefile": "all:",
  3020. ".git/HEAD": "ref: foo",
  3021. "src/x.go": "package main",
  3022. "src/_vendor/v.go": "package main",
  3023. "src/_vendor/v.cc": "package main",
  3024. "src/v.cc": "package main",
  3025. "v.cc": "package main",
  3026. "dir/foo": "",
  3027. ".gitignore": "",
  3028. "README.md": "readme",
  3029. ".dockerignore": `
  3030. .git
  3031. pkg
  3032. .gitignore
  3033. src/_vendor
  3034. *.md
  3035. **/*.cc
  3036. dir`,
  3037. })
  3038. if err != nil {
  3039. c.Fatal(err)
  3040. }
  3041. defer ctx.Close()
  3042. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3043. c.Fatal(err)
  3044. }
  3045. }
  3046. func (s *DockerSuite) TestBuildDockerignoreCleanPaths(c *check.C) {
  3047. testRequires(c, DaemonIsLinux)
  3048. name := "testbuilddockerignorecleanpaths"
  3049. dockerfile := `
  3050. FROM busybox
  3051. ADD . /tmp/
  3052. RUN (! ls /tmp/foo) && (! ls /tmp/foo2) && (! ls /tmp/dir1/foo)`
  3053. ctx, err := fakeContext(dockerfile, map[string]string{
  3054. "foo": "foo",
  3055. "foo2": "foo2",
  3056. "dir1/foo": "foo in dir1",
  3057. ".dockerignore": "./foo\ndir1//foo\n./dir1/../foo2",
  3058. })
  3059. if err != nil {
  3060. c.Fatal(err)
  3061. }
  3062. defer ctx.Close()
  3063. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3064. c.Fatal(err)
  3065. }
  3066. }
  3067. func (s *DockerSuite) TestBuildDockerignoreExceptions(c *check.C) {
  3068. testRequires(c, DaemonIsLinux)
  3069. name := "testbuilddockerignoreexceptions"
  3070. dockerfile := `
  3071. FROM busybox
  3072. ADD . /bla
  3073. RUN [[ -f /bla/src/x.go ]]
  3074. RUN [[ -f /bla/Makefile ]]
  3075. RUN [[ ! -e /bla/src/_vendor ]]
  3076. RUN [[ ! -e /bla/.gitignore ]]
  3077. RUN [[ ! -e /bla/README.md ]]
  3078. RUN [[ -e /bla/dir/dir/foo ]]
  3079. RUN [[ ! -e /bla/dir/foo1 ]]
  3080. RUN [[ -f /bla/dir/e ]]
  3081. RUN [[ -f /bla/dir/e-dir/foo ]]
  3082. RUN [[ ! -e /bla/foo ]]
  3083. RUN [[ ! -e /bla/.git ]]
  3084. RUN [[ -e /bla/dir/a.cc ]]`
  3085. ctx, err := fakeContext(dockerfile, map[string]string{
  3086. "Makefile": "all:",
  3087. ".git/HEAD": "ref: foo",
  3088. "src/x.go": "package main",
  3089. "src/_vendor/v.go": "package main",
  3090. "dir/foo": "",
  3091. "dir/foo1": "",
  3092. "dir/dir/f1": "",
  3093. "dir/dir/foo": "",
  3094. "dir/e": "",
  3095. "dir/e-dir/foo": "",
  3096. ".gitignore": "",
  3097. "README.md": "readme",
  3098. "dir/a.cc": "hello",
  3099. ".dockerignore": `
  3100. .git
  3101. pkg
  3102. .gitignore
  3103. src/_vendor
  3104. *.md
  3105. dir
  3106. !dir/e*
  3107. !dir/dir/foo
  3108. **/*.cc
  3109. !**/*.cc`,
  3110. })
  3111. if err != nil {
  3112. c.Fatal(err)
  3113. }
  3114. defer ctx.Close()
  3115. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3116. c.Fatal(err)
  3117. }
  3118. }
  3119. func (s *DockerSuite) TestBuildDockerignoringDockerfile(c *check.C) {
  3120. testRequires(c, DaemonIsLinux)
  3121. name := "testbuilddockerignoredockerfile"
  3122. dockerfile := `
  3123. FROM busybox
  3124. ADD . /tmp/
  3125. RUN ! ls /tmp/Dockerfile
  3126. RUN ls /tmp/.dockerignore`
  3127. ctx, err := fakeContext(dockerfile, map[string]string{
  3128. "Dockerfile": dockerfile,
  3129. ".dockerignore": "Dockerfile\n",
  3130. })
  3131. if err != nil {
  3132. c.Fatal(err)
  3133. }
  3134. defer ctx.Close()
  3135. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3136. c.Fatalf("Didn't ignore Dockerfile correctly:%s", err)
  3137. }
  3138. // now try it with ./Dockerfile
  3139. ctx.Add(".dockerignore", "./Dockerfile\n")
  3140. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3141. c.Fatalf("Didn't ignore ./Dockerfile correctly:%s", err)
  3142. }
  3143. }
  3144. func (s *DockerSuite) TestBuildDockerignoringRenamedDockerfile(c *check.C) {
  3145. testRequires(c, DaemonIsLinux)
  3146. name := "testbuilddockerignoredockerfile"
  3147. dockerfile := `
  3148. FROM busybox
  3149. ADD . /tmp/
  3150. RUN ls /tmp/Dockerfile
  3151. RUN ! ls /tmp/MyDockerfile
  3152. RUN ls /tmp/.dockerignore`
  3153. ctx, err := fakeContext(dockerfile, map[string]string{
  3154. "Dockerfile": "Should not use me",
  3155. "MyDockerfile": dockerfile,
  3156. ".dockerignore": "MyDockerfile\n",
  3157. })
  3158. if err != nil {
  3159. c.Fatal(err)
  3160. }
  3161. defer ctx.Close()
  3162. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3163. c.Fatalf("Didn't ignore MyDockerfile correctly:%s", err)
  3164. }
  3165. // now try it with ./MyDockerfile
  3166. ctx.Add(".dockerignore", "./MyDockerfile\n")
  3167. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3168. c.Fatalf("Didn't ignore ./MyDockerfile correctly:%s", err)
  3169. }
  3170. }
  3171. func (s *DockerSuite) TestBuildDockerignoringDockerignore(c *check.C) {
  3172. testRequires(c, DaemonIsLinux)
  3173. name := "testbuilddockerignoredockerignore"
  3174. dockerfile := `
  3175. FROM busybox
  3176. ADD . /tmp/
  3177. RUN ! ls /tmp/.dockerignore
  3178. RUN ls /tmp/Dockerfile`
  3179. ctx, err := fakeContext(dockerfile, map[string]string{
  3180. "Dockerfile": dockerfile,
  3181. ".dockerignore": ".dockerignore\n",
  3182. })
  3183. if err != nil {
  3184. c.Fatal(err)
  3185. }
  3186. defer ctx.Close()
  3187. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3188. c.Fatalf("Didn't ignore .dockerignore correctly:%s", err)
  3189. }
  3190. }
  3191. func (s *DockerSuite) TestBuildDockerignoreTouchDockerfile(c *check.C) {
  3192. testRequires(c, DaemonIsLinux)
  3193. var id1 string
  3194. var id2 string
  3195. name := "testbuilddockerignoretouchdockerfile"
  3196. dockerfile := `
  3197. FROM busybox
  3198. ADD . /tmp/`
  3199. ctx, err := fakeContext(dockerfile, map[string]string{
  3200. "Dockerfile": dockerfile,
  3201. ".dockerignore": "Dockerfile\n",
  3202. })
  3203. if err != nil {
  3204. c.Fatal(err)
  3205. }
  3206. defer ctx.Close()
  3207. if id1, err = buildImageFromContext(name, ctx, true); err != nil {
  3208. c.Fatalf("Didn't build it correctly:%s", err)
  3209. }
  3210. if id2, err = buildImageFromContext(name, ctx, true); err != nil {
  3211. c.Fatalf("Didn't build it correctly:%s", err)
  3212. }
  3213. if id1 != id2 {
  3214. c.Fatalf("Didn't use the cache - 1")
  3215. }
  3216. // Now make sure touching Dockerfile doesn't invalidate the cache
  3217. if err = ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil {
  3218. c.Fatalf("Didn't add Dockerfile: %s", err)
  3219. }
  3220. if id2, err = buildImageFromContext(name, ctx, true); err != nil {
  3221. c.Fatalf("Didn't build it correctly:%s", err)
  3222. }
  3223. if id1 != id2 {
  3224. c.Fatalf("Didn't use the cache - 2")
  3225. }
  3226. // One more time but just 'touch' it instead of changing the content
  3227. if err = ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil {
  3228. c.Fatalf("Didn't add Dockerfile: %s", err)
  3229. }
  3230. if id2, err = buildImageFromContext(name, ctx, true); err != nil {
  3231. c.Fatalf("Didn't build it correctly:%s", err)
  3232. }
  3233. if id1 != id2 {
  3234. c.Fatalf("Didn't use the cache - 3")
  3235. }
  3236. }
  3237. func (s *DockerSuite) TestBuildDockerignoringWholeDir(c *check.C) {
  3238. testRequires(c, DaemonIsLinux)
  3239. name := "testbuilddockerignorewholedir"
  3240. dockerfile := `
  3241. FROM busybox
  3242. COPY . /
  3243. RUN [[ ! -e /.gitignore ]]
  3244. RUN [[ -f /Makefile ]]`
  3245. ctx, err := fakeContext(dockerfile, map[string]string{
  3246. "Dockerfile": "FROM scratch",
  3247. "Makefile": "all:",
  3248. ".gitignore": "",
  3249. ".dockerignore": ".*\n",
  3250. })
  3251. c.Assert(err, check.IsNil)
  3252. defer ctx.Close()
  3253. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3254. c.Fatal(err)
  3255. }
  3256. c.Assert(ctx.Add(".dockerfile", "*"), check.IsNil)
  3257. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3258. c.Fatal(err)
  3259. }
  3260. c.Assert(ctx.Add(".dockerfile", "."), check.IsNil)
  3261. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3262. c.Fatal(err)
  3263. }
  3264. c.Assert(ctx.Add(".dockerfile", "?"), check.IsNil)
  3265. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3266. c.Fatal(err)
  3267. }
  3268. }
  3269. func (s *DockerSuite) TestBuildDockerignoringBadExclusion(c *check.C) {
  3270. testRequires(c, DaemonIsLinux)
  3271. name := "testbuilddockerignorebadexclusion"
  3272. dockerfile := `
  3273. FROM busybox
  3274. COPY . /
  3275. RUN [[ ! -e /.gitignore ]]
  3276. RUN [[ -f /Makefile ]]`
  3277. ctx, err := fakeContext(dockerfile, map[string]string{
  3278. "Dockerfile": "FROM scratch",
  3279. "Makefile": "all:",
  3280. ".gitignore": "",
  3281. ".dockerignore": "!\n",
  3282. })
  3283. c.Assert(err, check.IsNil)
  3284. defer ctx.Close()
  3285. if _, err = buildImageFromContext(name, ctx, true); err == nil {
  3286. c.Fatalf("Build was supposed to fail but didn't")
  3287. }
  3288. if err.Error() != "failed to build the image: Error checking context: 'Illegal exclusion pattern: !'.\n" {
  3289. c.Fatalf("Incorrect output, got:%q", err.Error())
  3290. }
  3291. }
  3292. func (s *DockerSuite) TestBuildDockerignoringWildTopDir(c *check.C) {
  3293. testRequires(c, DaemonIsLinux)
  3294. dockerfile := `
  3295. FROM busybox
  3296. COPY . /
  3297. RUN [[ ! -e /.dockerignore ]]
  3298. RUN [[ ! -e /Dockerfile ]]
  3299. RUN [[ ! -e /file1 ]]
  3300. RUN [[ ! -e /dir ]]`
  3301. ctx, err := fakeContext(dockerfile, map[string]string{
  3302. "Dockerfile": "FROM scratch",
  3303. "file1": "",
  3304. "dir/dfile1": "",
  3305. })
  3306. c.Assert(err, check.IsNil)
  3307. defer ctx.Close()
  3308. // All of these should result in ignoring all files
  3309. for _, variant := range []string{"**", "**/", "**/**", "*"} {
  3310. ctx.Add(".dockerignore", variant)
  3311. _, err = buildImageFromContext("noname", ctx, true)
  3312. c.Assert(err, check.IsNil, check.Commentf("variant: %s", variant))
  3313. }
  3314. }
  3315. func (s *DockerSuite) TestBuildDockerignoringWildDirs(c *check.C) {
  3316. testRequires(c, DaemonIsLinux)
  3317. dockerfile := `
  3318. FROM busybox
  3319. COPY . /
  3320. RUN [[ -e /.dockerignore ]]
  3321. RUN [[ -e /Dockerfile ]]
  3322. RUN [[ ! -e /file0 ]]
  3323. RUN [[ ! -e /dir1/file0 ]]
  3324. RUN [[ ! -e /dir2/file0 ]]
  3325. RUN [[ ! -e /file1 ]]
  3326. RUN [[ ! -e /dir1/file1 ]]
  3327. RUN [[ ! -e /dir1/dir2/file1 ]]
  3328. RUN [[ ! -e /dir1/file2 ]]
  3329. RUN [[ -e /dir1/dir2/file2 ]]
  3330. RUN [[ ! -e /dir1/dir2/file4 ]]
  3331. RUN [[ ! -e /dir1/dir2/file5 ]]
  3332. RUN [[ ! -e /dir1/dir2/file6 ]]
  3333. RUN [[ ! -e /dir1/dir3/file7 ]]
  3334. RUN [[ ! -e /dir1/dir3/file8 ]]
  3335. RUN [[ -e /dir1/dir3 ]]
  3336. RUN [[ -e /dir1/dir4 ]]
  3337. RUN [[ ! -e 'dir1/dir5/fileAA' ]]
  3338. RUN [[ -e 'dir1/dir5/fileAB' ]]
  3339. RUN [[ -e 'dir1/dir5/fileB' ]] # "." in pattern means nothing
  3340. RUN echo all done!`
  3341. ctx, err := fakeContext(dockerfile, map[string]string{
  3342. "Dockerfile": "FROM scratch",
  3343. "file0": "",
  3344. "dir1/file0": "",
  3345. "dir1/dir2/file0": "",
  3346. "file1": "",
  3347. "dir1/file1": "",
  3348. "dir1/dir2/file1": "",
  3349. "dir1/file2": "",
  3350. "dir1/dir2/file2": "", // remains
  3351. "dir1/dir2/file4": "",
  3352. "dir1/dir2/file5": "",
  3353. "dir1/dir2/file6": "",
  3354. "dir1/dir3/file7": "",
  3355. "dir1/dir3/file8": "",
  3356. "dir1/dir4/file9": "",
  3357. "dir1/dir5/fileAA": "",
  3358. "dir1/dir5/fileAB": "",
  3359. "dir1/dir5/fileB": "",
  3360. ".dockerignore": `
  3361. **/file0
  3362. **/*file1
  3363. **/dir1/file2
  3364. dir1/**/file4
  3365. **/dir2/file5
  3366. **/dir1/dir2/file6
  3367. dir1/dir3/**
  3368. **/dir4/**
  3369. **/file?A
  3370. **/file\?B
  3371. **/dir5/file.
  3372. `,
  3373. })
  3374. c.Assert(err, check.IsNil)
  3375. defer ctx.Close()
  3376. _, err = buildImageFromContext("noname", ctx, true)
  3377. c.Assert(err, check.IsNil)
  3378. }
  3379. func (s *DockerSuite) TestBuildLineBreak(c *check.C) {
  3380. testRequires(c, DaemonIsLinux)
  3381. name := "testbuildlinebreak"
  3382. _, err := buildImage(name,
  3383. `FROM busybox
  3384. RUN sh -c 'echo root:testpass \
  3385. > /tmp/passwd'
  3386. RUN mkdir -p /var/run/sshd
  3387. RUN [ "$(cat /tmp/passwd)" = "root:testpass" ]
  3388. RUN [ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]`,
  3389. true)
  3390. if err != nil {
  3391. c.Fatal(err)
  3392. }
  3393. }
  3394. func (s *DockerSuite) TestBuildEOLInLine(c *check.C) {
  3395. testRequires(c, DaemonIsLinux)
  3396. name := "testbuildeolinline"
  3397. _, err := buildImage(name,
  3398. `FROM busybox
  3399. RUN sh -c 'echo root:testpass > /tmp/passwd'
  3400. RUN echo "foo \n bar"; echo "baz"
  3401. RUN mkdir -p /var/run/sshd
  3402. RUN [ "$(cat /tmp/passwd)" = "root:testpass" ]
  3403. RUN [ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]`,
  3404. true)
  3405. if err != nil {
  3406. c.Fatal(err)
  3407. }
  3408. }
  3409. func (s *DockerSuite) TestBuildCommentsShebangs(c *check.C) {
  3410. testRequires(c, DaemonIsLinux)
  3411. name := "testbuildcomments"
  3412. _, err := buildImage(name,
  3413. `FROM busybox
  3414. # This is an ordinary comment.
  3415. RUN { echo '#!/bin/sh'; echo 'echo hello world'; } > /hello.sh
  3416. RUN [ ! -x /hello.sh ]
  3417. # comment with line break \
  3418. RUN chmod +x /hello.sh
  3419. RUN [ -x /hello.sh ]
  3420. RUN [ "$(cat /hello.sh)" = $'#!/bin/sh\necho hello world' ]
  3421. RUN [ "$(/hello.sh)" = "hello world" ]`,
  3422. true)
  3423. if err != nil {
  3424. c.Fatal(err)
  3425. }
  3426. }
  3427. func (s *DockerSuite) TestBuildUsersAndGroups(c *check.C) {
  3428. testRequires(c, DaemonIsLinux)
  3429. name := "testbuildusers"
  3430. _, err := buildImage(name,
  3431. `FROM busybox
  3432. # Make sure our defaults work
  3433. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)" = '0:0/root:root' ]
  3434. # 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)
  3435. USER root
  3436. RUN [ "$(id -G):$(id -Gn)" = '0 10:root wheel' ]
  3437. # Setup dockerio user and group
  3438. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  3439. RUN echo 'dockerio:x:1001:' >> /etc/group
  3440. # Make sure we can switch to our user and all the information is exactly as we expect it to be
  3441. USER dockerio
  3442. RUN id -G
  3443. RUN id -Gn
  3444. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3445. # Switch back to root and double check that worked exactly as we might expect it to
  3446. USER root
  3447. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '0:0/root:root/0 10:root wheel' ]
  3448. # Add a "supplementary" group for our dockerio user
  3449. RUN echo 'supplementary:x:1002:dockerio' >> /etc/group
  3450. # ... and then go verify that we get it like we expect
  3451. USER dockerio
  3452. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  3453. USER 1001
  3454. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  3455. # super test the new "user:group" syntax
  3456. USER dockerio:dockerio
  3457. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3458. USER 1001:dockerio
  3459. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3460. USER dockerio:1001
  3461. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3462. USER 1001:1001
  3463. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3464. USER dockerio:supplementary
  3465. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3466. USER dockerio:1002
  3467. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3468. USER 1001:supplementary
  3469. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3470. USER 1001:1002
  3471. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3472. # make sure unknown uid/gid still works properly
  3473. USER 1042:1043
  3474. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1042:1043/1042:1043/1043:1043' ]`,
  3475. true)
  3476. if err != nil {
  3477. c.Fatal(err)
  3478. }
  3479. }
  3480. func (s *DockerSuite) TestBuildEnvUsage(c *check.C) {
  3481. // /docker/world/hello is not owned by the correct user
  3482. testRequires(c, NotUserNamespace)
  3483. testRequires(c, DaemonIsLinux)
  3484. name := "testbuildenvusage"
  3485. dockerfile := `FROM busybox
  3486. ENV HOME /root
  3487. ENV PATH $HOME/bin:$PATH
  3488. ENV PATH /tmp:$PATH
  3489. RUN [ "$PATH" = "/tmp:$HOME/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ]
  3490. ENV FOO /foo/baz
  3491. ENV BAR /bar
  3492. ENV BAZ $BAR
  3493. ENV FOOPATH $PATH:$FOO
  3494. RUN [ "$BAR" = "$BAZ" ]
  3495. RUN [ "$FOOPATH" = "$PATH:/foo/baz" ]
  3496. ENV FROM hello/docker/world
  3497. ENV TO /docker/world/hello
  3498. ADD $FROM $TO
  3499. RUN [ "$(cat $TO)" = "hello" ]
  3500. ENV abc=def
  3501. ENV ghi=$abc
  3502. RUN [ "$ghi" = "def" ]
  3503. `
  3504. ctx, err := fakeContext(dockerfile, map[string]string{
  3505. "hello/docker/world": "hello",
  3506. })
  3507. if err != nil {
  3508. c.Fatal(err)
  3509. }
  3510. defer ctx.Close()
  3511. _, err = buildImageFromContext(name, ctx, true)
  3512. if err != nil {
  3513. c.Fatal(err)
  3514. }
  3515. }
  3516. func (s *DockerSuite) TestBuildEnvUsage2(c *check.C) {
  3517. // /docker/world/hello is not owned by the correct user
  3518. testRequires(c, NotUserNamespace)
  3519. testRequires(c, DaemonIsLinux)
  3520. name := "testbuildenvusage2"
  3521. dockerfile := `FROM busybox
  3522. ENV abc=def
  3523. RUN [ "$abc" = "def" ]
  3524. ENV def="hello world"
  3525. RUN [ "$def" = "hello world" ]
  3526. ENV def=hello\ world
  3527. RUN [ "$def" = "hello world" ]
  3528. ENV v1=abc v2="hi there"
  3529. RUN [ "$v1" = "abc" ]
  3530. RUN [ "$v2" = "hi there" ]
  3531. ENV v3='boogie nights' v4="with'quotes too"
  3532. RUN [ "$v3" = "boogie nights" ]
  3533. RUN [ "$v4" = "with'quotes too" ]
  3534. ENV abc=zzz FROM=hello/docker/world
  3535. ENV abc=zzz TO=/docker/world/hello
  3536. ADD $FROM $TO
  3537. RUN [ "$(cat $TO)" = "hello" ]
  3538. ENV abc "zzz"
  3539. RUN [ $abc = "zzz" ]
  3540. ENV abc 'yyy'
  3541. RUN [ $abc = 'yyy' ]
  3542. ENV abc=
  3543. RUN [ "$abc" = "" ]
  3544. # use grep to make sure if the builder substitutes \$foo by mistake
  3545. # we don't get a false positive
  3546. ENV abc=\$foo
  3547. RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep foo)
  3548. ENV abc \$foo
  3549. RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep foo)
  3550. ENV abc=\'foo\'
  3551. RUN [ "$abc" = "'foo'" ]
  3552. ENV abc=\"foo\"
  3553. RUN [ "$abc" = "\"foo\"" ]
  3554. ENV abc "foo"
  3555. RUN [ "$abc" = "foo" ]
  3556. ENV abc 'foo'
  3557. RUN [ "$abc" = 'foo' ]
  3558. ENV abc \'foo\'
  3559. RUN [ "$abc" = "'foo'" ]
  3560. ENV abc \"foo\"
  3561. RUN [ "$abc" = '"foo"' ]
  3562. ENV abc=ABC
  3563. RUN [ "$abc" = "ABC" ]
  3564. ENV def=${abc:-DEF}
  3565. RUN [ "$def" = "ABC" ]
  3566. ENV def=${ccc:-DEF}
  3567. RUN [ "$def" = "DEF" ]
  3568. ENV def=${ccc:-${def}xx}
  3569. RUN [ "$def" = "DEFxx" ]
  3570. ENV def=${def:+ALT}
  3571. RUN [ "$def" = "ALT" ]
  3572. ENV def=${def:+${abc}:}
  3573. RUN [ "$def" = "ABC:" ]
  3574. ENV def=${ccc:-\$abc:}
  3575. RUN [ "$def" = '$abc:' ]
  3576. ENV def=${ccc:-\${abc}:}
  3577. RUN [ "$def" = '${abc:}' ]
  3578. ENV mypath=${mypath:+$mypath:}/home
  3579. RUN [ "$mypath" = '/home' ]
  3580. ENV mypath=${mypath:+$mypath:}/away
  3581. RUN [ "$mypath" = '/home:/away' ]
  3582. ENV e1=bar
  3583. ENV e2=$e1
  3584. ENV e3=$e11
  3585. ENV e4=\$e1
  3586. ENV e5=\$e11
  3587. RUN [ "$e0,$e1,$e2,$e3,$e4,$e5" = ',bar,bar,,$e1,$e11' ]
  3588. ENV ee1 bar
  3589. ENV ee2 $ee1
  3590. ENV ee3 $ee11
  3591. ENV ee4 \$ee1
  3592. ENV ee5 \$ee11
  3593. RUN [ "$ee1,$ee2,$ee3,$ee4,$ee5" = 'bar,bar,,$ee1,$ee11' ]
  3594. ENV eee1="foo"
  3595. ENV eee2='foo'
  3596. ENV eee3 "foo"
  3597. ENV eee4 'foo'
  3598. RUN [ "$eee1,$eee2,$eee3,$eee4" = 'foo,foo,foo,foo' ]
  3599. `
  3600. ctx, err := fakeContext(dockerfile, map[string]string{
  3601. "hello/docker/world": "hello",
  3602. })
  3603. if err != nil {
  3604. c.Fatal(err)
  3605. }
  3606. defer ctx.Close()
  3607. _, err = buildImageFromContext(name, ctx, true)
  3608. if err != nil {
  3609. c.Fatal(err)
  3610. }
  3611. }
  3612. func (s *DockerSuite) TestBuildAddScript(c *check.C) {
  3613. testRequires(c, DaemonIsLinux)
  3614. name := "testbuildaddscript"
  3615. dockerfile := `
  3616. FROM busybox
  3617. ADD test /test
  3618. RUN ["chmod","+x","/test"]
  3619. RUN ["/test"]
  3620. RUN [ "$(cat /testfile)" = 'test!' ]`
  3621. ctx, err := fakeContext(dockerfile, map[string]string{
  3622. "test": "#!/bin/sh\necho 'test!' > /testfile",
  3623. })
  3624. if err != nil {
  3625. c.Fatal(err)
  3626. }
  3627. defer ctx.Close()
  3628. _, err = buildImageFromContext(name, ctx, true)
  3629. if err != nil {
  3630. c.Fatal(err)
  3631. }
  3632. }
  3633. func (s *DockerSuite) TestBuildAddTar(c *check.C) {
  3634. // /test/foo is not owned by the correct user
  3635. testRequires(c, NotUserNamespace)
  3636. testRequires(c, DaemonIsLinux)
  3637. name := "testbuildaddtar"
  3638. ctx := func() *FakeContext {
  3639. dockerfile := `
  3640. FROM busybox
  3641. ADD test.tar /
  3642. RUN cat /test/foo | grep Hi
  3643. ADD test.tar /test.tar
  3644. RUN cat /test.tar/test/foo | grep Hi
  3645. ADD test.tar /unlikely-to-exist
  3646. RUN cat /unlikely-to-exist/test/foo | grep Hi
  3647. ADD test.tar /unlikely-to-exist-trailing-slash/
  3648. RUN cat /unlikely-to-exist-trailing-slash/test/foo | grep Hi
  3649. RUN mkdir /existing-directory
  3650. ADD test.tar /existing-directory
  3651. RUN cat /existing-directory/test/foo | grep Hi
  3652. ADD test.tar /existing-directory-trailing-slash/
  3653. RUN cat /existing-directory-trailing-slash/test/foo | grep Hi`
  3654. tmpDir, err := ioutil.TempDir("", "fake-context")
  3655. c.Assert(err, check.IsNil)
  3656. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3657. if err != nil {
  3658. c.Fatalf("failed to create test.tar archive: %v", err)
  3659. }
  3660. defer testTar.Close()
  3661. tw := tar.NewWriter(testTar)
  3662. if err := tw.WriteHeader(&tar.Header{
  3663. Name: "test/foo",
  3664. Size: 2,
  3665. }); err != nil {
  3666. c.Fatalf("failed to write tar file header: %v", err)
  3667. }
  3668. if _, err := tw.Write([]byte("Hi")); err != nil {
  3669. c.Fatalf("failed to write tar file content: %v", err)
  3670. }
  3671. if err := tw.Close(); err != nil {
  3672. c.Fatalf("failed to close tar archive: %v", err)
  3673. }
  3674. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3675. c.Fatalf("failed to open destination dockerfile: %v", err)
  3676. }
  3677. return fakeContextFromDir(tmpDir)
  3678. }()
  3679. defer ctx.Close()
  3680. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3681. c.Fatalf("build failed to complete for TestBuildAddTar: %v", err)
  3682. }
  3683. }
  3684. func (s *DockerSuite) TestBuildAddBrokenTar(c *check.C) {
  3685. testRequires(c, DaemonIsLinux)
  3686. name := "testbuildaddbrokentar"
  3687. ctx := func() *FakeContext {
  3688. dockerfile := `
  3689. FROM busybox
  3690. ADD test.tar /`
  3691. tmpDir, err := ioutil.TempDir("", "fake-context")
  3692. c.Assert(err, check.IsNil)
  3693. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3694. if err != nil {
  3695. c.Fatalf("failed to create test.tar archive: %v", err)
  3696. }
  3697. defer testTar.Close()
  3698. tw := tar.NewWriter(testTar)
  3699. if err := tw.WriteHeader(&tar.Header{
  3700. Name: "test/foo",
  3701. Size: 2,
  3702. }); err != nil {
  3703. c.Fatalf("failed to write tar file header: %v", err)
  3704. }
  3705. if _, err := tw.Write([]byte("Hi")); err != nil {
  3706. c.Fatalf("failed to write tar file content: %v", err)
  3707. }
  3708. if err := tw.Close(); err != nil {
  3709. c.Fatalf("failed to close tar archive: %v", err)
  3710. }
  3711. // Corrupt the tar by removing one byte off the end
  3712. stat, err := testTar.Stat()
  3713. if err != nil {
  3714. c.Fatalf("failed to stat tar archive: %v", err)
  3715. }
  3716. if err := testTar.Truncate(stat.Size() - 1); err != nil {
  3717. c.Fatalf("failed to truncate tar archive: %v", err)
  3718. }
  3719. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3720. c.Fatalf("failed to open destination dockerfile: %v", err)
  3721. }
  3722. return fakeContextFromDir(tmpDir)
  3723. }()
  3724. defer ctx.Close()
  3725. if _, err := buildImageFromContext(name, ctx, true); err == nil {
  3726. c.Fatalf("build should have failed for TestBuildAddBrokenTar")
  3727. }
  3728. }
  3729. func (s *DockerSuite) TestBuildAddNonTar(c *check.C) {
  3730. testRequires(c, DaemonIsLinux)
  3731. name := "testbuildaddnontar"
  3732. // Should not try to extract test.tar
  3733. ctx, err := fakeContext(`
  3734. FROM busybox
  3735. ADD test.tar /
  3736. RUN test -f /test.tar`,
  3737. map[string]string{"test.tar": "not_a_tar_file"})
  3738. if err != nil {
  3739. c.Fatal(err)
  3740. }
  3741. defer ctx.Close()
  3742. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3743. c.Fatalf("build failed for TestBuildAddNonTar")
  3744. }
  3745. }
  3746. func (s *DockerSuite) TestBuildAddTarXz(c *check.C) {
  3747. // /test/foo is not owned by the correct user
  3748. testRequires(c, NotUserNamespace)
  3749. testRequires(c, DaemonIsLinux)
  3750. name := "testbuildaddtarxz"
  3751. ctx := func() *FakeContext {
  3752. dockerfile := `
  3753. FROM busybox
  3754. ADD test.tar.xz /
  3755. RUN cat /test/foo | grep Hi`
  3756. tmpDir, err := ioutil.TempDir("", "fake-context")
  3757. c.Assert(err, check.IsNil)
  3758. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3759. if err != nil {
  3760. c.Fatalf("failed to create test.tar archive: %v", err)
  3761. }
  3762. defer testTar.Close()
  3763. tw := tar.NewWriter(testTar)
  3764. if err := tw.WriteHeader(&tar.Header{
  3765. Name: "test/foo",
  3766. Size: 2,
  3767. }); err != nil {
  3768. c.Fatalf("failed to write tar file header: %v", err)
  3769. }
  3770. if _, err := tw.Write([]byte("Hi")); err != nil {
  3771. c.Fatalf("failed to write tar file content: %v", err)
  3772. }
  3773. if err := tw.Close(); err != nil {
  3774. c.Fatalf("failed to close tar archive: %v", err)
  3775. }
  3776. xzCompressCmd := exec.Command("xz", "-k", "test.tar")
  3777. xzCompressCmd.Dir = tmpDir
  3778. out, _, err := runCommandWithOutput(xzCompressCmd)
  3779. if err != nil {
  3780. c.Fatal(err, out)
  3781. }
  3782. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3783. c.Fatalf("failed to open destination dockerfile: %v", err)
  3784. }
  3785. return fakeContextFromDir(tmpDir)
  3786. }()
  3787. defer ctx.Close()
  3788. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3789. c.Fatalf("build failed to complete for TestBuildAddTarXz: %v", err)
  3790. }
  3791. }
  3792. func (s *DockerSuite) TestBuildAddTarXzGz(c *check.C) {
  3793. testRequires(c, DaemonIsLinux)
  3794. name := "testbuildaddtarxzgz"
  3795. ctx := func() *FakeContext {
  3796. dockerfile := `
  3797. FROM busybox
  3798. ADD test.tar.xz.gz /
  3799. RUN ls /test.tar.xz.gz`
  3800. tmpDir, err := ioutil.TempDir("", "fake-context")
  3801. c.Assert(err, check.IsNil)
  3802. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3803. if err != nil {
  3804. c.Fatalf("failed to create test.tar archive: %v", err)
  3805. }
  3806. defer testTar.Close()
  3807. tw := tar.NewWriter(testTar)
  3808. if err := tw.WriteHeader(&tar.Header{
  3809. Name: "test/foo",
  3810. Size: 2,
  3811. }); err != nil {
  3812. c.Fatalf("failed to write tar file header: %v", err)
  3813. }
  3814. if _, err := tw.Write([]byte("Hi")); err != nil {
  3815. c.Fatalf("failed to write tar file content: %v", err)
  3816. }
  3817. if err := tw.Close(); err != nil {
  3818. c.Fatalf("failed to close tar archive: %v", err)
  3819. }
  3820. xzCompressCmd := exec.Command("xz", "-k", "test.tar")
  3821. xzCompressCmd.Dir = tmpDir
  3822. out, _, err := runCommandWithOutput(xzCompressCmd)
  3823. if err != nil {
  3824. c.Fatal(err, out)
  3825. }
  3826. gzipCompressCmd := exec.Command("gzip", "test.tar.xz")
  3827. gzipCompressCmd.Dir = tmpDir
  3828. out, _, err = runCommandWithOutput(gzipCompressCmd)
  3829. if err != nil {
  3830. c.Fatal(err, out)
  3831. }
  3832. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3833. c.Fatalf("failed to open destination dockerfile: %v", err)
  3834. }
  3835. return fakeContextFromDir(tmpDir)
  3836. }()
  3837. defer ctx.Close()
  3838. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3839. c.Fatalf("build failed to complete for TestBuildAddTarXz: %v", err)
  3840. }
  3841. }
  3842. func (s *DockerSuite) TestBuildFromGIT(c *check.C) {
  3843. testRequires(c, DaemonIsLinux)
  3844. name := "testbuildfromgit"
  3845. git, err := newFakeGit("repo", map[string]string{
  3846. "Dockerfile": `FROM busybox
  3847. ADD first /first
  3848. RUN [ -f /first ]
  3849. MAINTAINER docker`,
  3850. "first": "test git data",
  3851. }, true)
  3852. if err != nil {
  3853. c.Fatal(err)
  3854. }
  3855. defer git.Close()
  3856. _, err = buildImageFromPath(name, git.RepoURL, true)
  3857. if err != nil {
  3858. c.Fatal(err)
  3859. }
  3860. res, err := inspectField(name, "Author")
  3861. if err != nil {
  3862. c.Fatal(err)
  3863. }
  3864. if res != "docker" {
  3865. c.Fatalf("Maintainer should be docker, got %s", res)
  3866. }
  3867. }
  3868. func (s *DockerSuite) TestBuildFromGITWithContext(c *check.C) {
  3869. testRequires(c, DaemonIsLinux)
  3870. name := "testbuildfromgit"
  3871. git, err := newFakeGit("repo", map[string]string{
  3872. "docker/Dockerfile": `FROM busybox
  3873. ADD first /first
  3874. RUN [ -f /first ]
  3875. MAINTAINER docker`,
  3876. "docker/first": "test git data",
  3877. }, true)
  3878. if err != nil {
  3879. c.Fatal(err)
  3880. }
  3881. defer git.Close()
  3882. u := fmt.Sprintf("%s#master:docker", git.RepoURL)
  3883. _, err = buildImageFromPath(name, u, true)
  3884. if err != nil {
  3885. c.Fatal(err)
  3886. }
  3887. res, err := inspectField(name, "Author")
  3888. if err != nil {
  3889. c.Fatal(err)
  3890. }
  3891. if res != "docker" {
  3892. c.Fatalf("Maintainer should be docker, got %s", res)
  3893. }
  3894. }
  3895. func (s *DockerSuite) TestBuildFromGITwithF(c *check.C) {
  3896. testRequires(c, DaemonIsLinux)
  3897. name := "testbuildfromgitwithf"
  3898. git, err := newFakeGit("repo", map[string]string{
  3899. "myApp/myDockerfile": `FROM busybox
  3900. RUN echo hi from Dockerfile`,
  3901. }, true)
  3902. if err != nil {
  3903. c.Fatal(err)
  3904. }
  3905. defer git.Close()
  3906. out, _, err := dockerCmdWithError("build", "-t", name, "--no-cache", "-f", "myApp/myDockerfile", git.RepoURL)
  3907. if err != nil {
  3908. c.Fatalf("Error on build. Out: %s\nErr: %v", out, err)
  3909. }
  3910. if !strings.Contains(out, "hi from Dockerfile") {
  3911. c.Fatalf("Missing expected output, got:\n%s", out)
  3912. }
  3913. }
  3914. func (s *DockerSuite) TestBuildFromRemoteTarball(c *check.C) {
  3915. testRequires(c, DaemonIsLinux)
  3916. name := "testbuildfromremotetarball"
  3917. buffer := new(bytes.Buffer)
  3918. tw := tar.NewWriter(buffer)
  3919. defer tw.Close()
  3920. dockerfile := []byte(`FROM busybox
  3921. MAINTAINER docker`)
  3922. if err := tw.WriteHeader(&tar.Header{
  3923. Name: "Dockerfile",
  3924. Size: int64(len(dockerfile)),
  3925. }); err != nil {
  3926. c.Fatalf("failed to write tar file header: %v", err)
  3927. }
  3928. if _, err := tw.Write(dockerfile); err != nil {
  3929. c.Fatalf("failed to write tar file content: %v", err)
  3930. }
  3931. if err := tw.Close(); err != nil {
  3932. c.Fatalf("failed to close tar archive: %v", err)
  3933. }
  3934. server, err := fakeBinaryStorage(map[string]*bytes.Buffer{
  3935. "testT.tar": buffer,
  3936. })
  3937. c.Assert(err, check.IsNil)
  3938. defer server.Close()
  3939. _, err = buildImageFromPath(name, server.URL()+"/testT.tar", true)
  3940. c.Assert(err, check.IsNil)
  3941. res, err := inspectField(name, "Author")
  3942. c.Assert(err, check.IsNil)
  3943. if res != "docker" {
  3944. c.Fatalf("Maintainer should be docker, got %s", res)
  3945. }
  3946. }
  3947. func (s *DockerSuite) TestBuildCleanupCmdOnEntrypoint(c *check.C) {
  3948. testRequires(c, DaemonIsLinux)
  3949. name := "testbuildcmdcleanuponentrypoint"
  3950. if _, err := buildImage(name,
  3951. `FROM scratch
  3952. CMD ["test"]
  3953. ENTRYPOINT ["echo"]`,
  3954. true); err != nil {
  3955. c.Fatal(err)
  3956. }
  3957. if _, err := buildImage(name,
  3958. fmt.Sprintf(`FROM %s
  3959. ENTRYPOINT ["cat"]`, name),
  3960. true); err != nil {
  3961. c.Fatal(err)
  3962. }
  3963. res, err := inspectField(name, "Config.Cmd")
  3964. if err != nil {
  3965. c.Fatal(err)
  3966. }
  3967. if res != "<nil>" {
  3968. c.Fatalf("Cmd %s, expected nil", res)
  3969. }
  3970. res, err = inspectField(name, "Config.Entrypoint")
  3971. if err != nil {
  3972. c.Fatal(err)
  3973. }
  3974. if expected := "{[cat]}"; res != expected {
  3975. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  3976. }
  3977. }
  3978. func (s *DockerSuite) TestBuildClearCmd(c *check.C) {
  3979. testRequires(c, DaemonIsLinux)
  3980. name := "testbuildclearcmd"
  3981. _, err := buildImage(name,
  3982. `From scratch
  3983. ENTRYPOINT ["/bin/bash"]
  3984. CMD []`,
  3985. true)
  3986. if err != nil {
  3987. c.Fatal(err)
  3988. }
  3989. res, err := inspectFieldJSON(name, "Config.Cmd")
  3990. if err != nil {
  3991. c.Fatal(err)
  3992. }
  3993. if res != "[]" {
  3994. c.Fatalf("Cmd %s, expected %s", res, "[]")
  3995. }
  3996. }
  3997. func (s *DockerSuite) TestBuildEmptyCmd(c *check.C) {
  3998. testRequires(c, DaemonIsLinux)
  3999. name := "testbuildemptycmd"
  4000. if _, err := buildImage(name, "FROM scratch\nMAINTAINER quux\n", true); err != nil {
  4001. c.Fatal(err)
  4002. }
  4003. res, err := inspectFieldJSON(name, "Config.Cmd")
  4004. if err != nil {
  4005. c.Fatal(err)
  4006. }
  4007. if res != "null" {
  4008. c.Fatalf("Cmd %s, expected %s", res, "null")
  4009. }
  4010. }
  4011. func (s *DockerSuite) TestBuildOnBuildOutput(c *check.C) {
  4012. testRequires(c, DaemonIsLinux)
  4013. name := "testbuildonbuildparent"
  4014. if _, err := buildImage(name, "FROM busybox\nONBUILD RUN echo foo\n", true); err != nil {
  4015. c.Fatal(err)
  4016. }
  4017. _, out, err := buildImageWithOut(name, "FROM "+name+"\nMAINTAINER quux\n", true)
  4018. if err != nil {
  4019. c.Fatal(err)
  4020. }
  4021. if !strings.Contains(out, "# Executing 1 build trigger") {
  4022. c.Fatal("failed to find the build trigger output", out)
  4023. }
  4024. }
  4025. func (s *DockerSuite) TestBuildInvalidTag(c *check.C) {
  4026. testRequires(c, DaemonIsLinux)
  4027. name := "abcd:" + stringutils.GenerateRandomAlphaOnlyString(200)
  4028. _, out, err := buildImageWithOut(name, "FROM scratch\nMAINTAINER quux\n", true)
  4029. // if the error doesn't check for illegal tag name, or the image is built
  4030. // then this should fail
  4031. if !strings.Contains(out, "Error parsing reference") || strings.Contains(out, "Sending build context to Docker daemon") {
  4032. c.Fatalf("failed to stop before building. Error: %s, Output: %s", err, out)
  4033. }
  4034. }
  4035. func (s *DockerSuite) TestBuildCmdShDashC(c *check.C) {
  4036. testRequires(c, DaemonIsLinux)
  4037. name := "testbuildcmdshc"
  4038. if _, err := buildImage(name, "FROM busybox\nCMD echo cmd\n", true); err != nil {
  4039. c.Fatal(err)
  4040. }
  4041. res, err := inspectFieldJSON(name, "Config.Cmd")
  4042. if err != nil {
  4043. c.Fatal(err, res)
  4044. }
  4045. expected := `["/bin/sh","-c","echo cmd"]`
  4046. if res != expected {
  4047. c.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  4048. }
  4049. }
  4050. func (s *DockerSuite) TestBuildCmdSpaces(c *check.C) {
  4051. testRequires(c, DaemonIsLinux)
  4052. // Test to make sure that when we strcat arrays we take into account
  4053. // the arg separator to make sure ["echo","hi"] and ["echo hi"] don't
  4054. // look the same
  4055. name := "testbuildcmdspaces"
  4056. var id1 string
  4057. var id2 string
  4058. var err error
  4059. if id1, err = buildImage(name, "FROM busybox\nCMD [\"echo hi\"]\n", true); err != nil {
  4060. c.Fatal(err)
  4061. }
  4062. if id2, err = buildImage(name, "FROM busybox\nCMD [\"echo\", \"hi\"]\n", true); err != nil {
  4063. c.Fatal(err)
  4064. }
  4065. if id1 == id2 {
  4066. c.Fatal("Should not have resulted in the same CMD")
  4067. }
  4068. // Now do the same with ENTRYPOINT
  4069. if id1, err = buildImage(name, "FROM busybox\nENTRYPOINT [\"echo hi\"]\n", true); err != nil {
  4070. c.Fatal(err)
  4071. }
  4072. if id2, err = buildImage(name, "FROM busybox\nENTRYPOINT [\"echo\", \"hi\"]\n", true); err != nil {
  4073. c.Fatal(err)
  4074. }
  4075. if id1 == id2 {
  4076. c.Fatal("Should not have resulted in the same ENTRYPOINT")
  4077. }
  4078. }
  4079. func (s *DockerSuite) TestBuildCmdJSONNoShDashC(c *check.C) {
  4080. testRequires(c, DaemonIsLinux)
  4081. name := "testbuildcmdjson"
  4082. if _, err := buildImage(name, "FROM busybox\nCMD [\"echo\", \"cmd\"]", true); err != nil {
  4083. c.Fatal(err)
  4084. }
  4085. res, err := inspectFieldJSON(name, "Config.Cmd")
  4086. if err != nil {
  4087. c.Fatal(err, res)
  4088. }
  4089. expected := `["echo","cmd"]`
  4090. if res != expected {
  4091. c.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  4092. }
  4093. }
  4094. func (s *DockerSuite) TestBuildErrorInvalidInstruction(c *check.C) {
  4095. testRequires(c, DaemonIsLinux)
  4096. name := "testbuildignoreinvalidinstruction"
  4097. out, _, err := buildImageWithOut(name, "FROM busybox\nfoo bar", true)
  4098. if err == nil {
  4099. c.Fatalf("Should have failed: %s", out)
  4100. }
  4101. }
  4102. func (s *DockerSuite) TestBuildEntrypointInheritance(c *check.C) {
  4103. testRequires(c, DaemonIsLinux)
  4104. if _, err := buildImage("parent", `
  4105. FROM busybox
  4106. ENTRYPOINT exit 130
  4107. `, true); err != nil {
  4108. c.Fatal(err)
  4109. }
  4110. if _, status, _ := dockerCmdWithError("run", "parent"); status != 130 {
  4111. c.Fatalf("expected exit code 130 but received %d", status)
  4112. }
  4113. if _, err := buildImage("child", `
  4114. FROM parent
  4115. ENTRYPOINT exit 5
  4116. `, true); err != nil {
  4117. c.Fatal(err)
  4118. }
  4119. if _, status, _ := dockerCmdWithError("run", "child"); status != 5 {
  4120. c.Fatalf("expected exit code 5 but received %d", status)
  4121. }
  4122. }
  4123. func (s *DockerSuite) TestBuildEntrypointInheritanceInspect(c *check.C) {
  4124. testRequires(c, DaemonIsLinux)
  4125. var (
  4126. name = "testbuildepinherit"
  4127. name2 = "testbuildepinherit2"
  4128. expected = `["/bin/sh","-c","echo quux"]`
  4129. )
  4130. if _, err := buildImage(name, "FROM busybox\nENTRYPOINT /foo/bar", true); err != nil {
  4131. c.Fatal(err)
  4132. }
  4133. if _, err := buildImage(name2, fmt.Sprintf("FROM %s\nENTRYPOINT echo quux", name), true); err != nil {
  4134. c.Fatal(err)
  4135. }
  4136. res, err := inspectFieldJSON(name2, "Config.Entrypoint")
  4137. if err != nil {
  4138. c.Fatal(err, res)
  4139. }
  4140. if res != expected {
  4141. c.Fatalf("Expected value %s not in Config.Entrypoint: %s", expected, res)
  4142. }
  4143. out, _ := dockerCmd(c, "run", "-t", name2)
  4144. expected = "quux"
  4145. if strings.TrimSpace(out) != expected {
  4146. c.Fatalf("Expected output is %s, got %s", expected, out)
  4147. }
  4148. }
  4149. func (s *DockerSuite) TestBuildRunShEntrypoint(c *check.C) {
  4150. testRequires(c, DaemonIsLinux)
  4151. name := "testbuildentrypoint"
  4152. _, err := buildImage(name,
  4153. `FROM busybox
  4154. ENTRYPOINT /bin/echo`,
  4155. true)
  4156. if err != nil {
  4157. c.Fatal(err)
  4158. }
  4159. dockerCmd(c, "run", "--rm", name)
  4160. }
  4161. func (s *DockerSuite) TestBuildExoticShellInterpolation(c *check.C) {
  4162. testRequires(c, DaemonIsLinux)
  4163. name := "testbuildexoticshellinterpolation"
  4164. _, err := buildImage(name, `
  4165. FROM busybox
  4166. ENV SOME_VAR a.b.c
  4167. RUN [ "$SOME_VAR" = 'a.b.c' ]
  4168. RUN [ "${SOME_VAR}" = 'a.b.c' ]
  4169. RUN [ "${SOME_VAR%.*}" = 'a.b' ]
  4170. RUN [ "${SOME_VAR%%.*}" = 'a' ]
  4171. RUN [ "${SOME_VAR#*.}" = 'b.c' ]
  4172. RUN [ "${SOME_VAR##*.}" = 'c' ]
  4173. RUN [ "${SOME_VAR/c/d}" = 'a.b.d' ]
  4174. RUN [ "${#SOME_VAR}" = '5' ]
  4175. RUN [ "${SOME_UNSET_VAR:-$SOME_VAR}" = 'a.b.c' ]
  4176. RUN [ "${SOME_VAR:+Version: ${SOME_VAR}}" = 'Version: a.b.c' ]
  4177. RUN [ "${SOME_UNSET_VAR:+${SOME_VAR}}" = '' ]
  4178. RUN [ "${SOME_UNSET_VAR:-${SOME_VAR:-d.e.f}}" = 'a.b.c' ]
  4179. `, false)
  4180. if err != nil {
  4181. c.Fatal(err)
  4182. }
  4183. }
  4184. func (s *DockerSuite) TestBuildVerifySingleQuoteFails(c *check.C) {
  4185. testRequires(c, DaemonIsLinux)
  4186. // This testcase is supposed to generate an error because the
  4187. // JSON array we're passing in on the CMD uses single quotes instead
  4188. // of double quotes (per the JSON spec). This means we interpret it
  4189. // as a "string" instead of "JSON array" and pass it on to "sh -c" and
  4190. // it should barf on it.
  4191. name := "testbuildsinglequotefails"
  4192. if _, err := buildImage(name,
  4193. `FROM busybox
  4194. CMD [ '/bin/sh', '-c', 'echo hi' ]`,
  4195. true); err != nil {
  4196. c.Fatal(err)
  4197. }
  4198. if _, _, err := dockerCmdWithError("run", "--rm", name); err == nil {
  4199. c.Fatal("The image was not supposed to be able to run")
  4200. }
  4201. }
  4202. func (s *DockerSuite) TestBuildVerboseOut(c *check.C) {
  4203. testRequires(c, DaemonIsLinux)
  4204. name := "testbuildverboseout"
  4205. _, out, err := buildImageWithOut(name,
  4206. `FROM busybox
  4207. RUN echo 123`,
  4208. false)
  4209. if err != nil {
  4210. c.Fatal(err)
  4211. }
  4212. if !strings.Contains(out, "\n123\n") {
  4213. c.Fatalf("Output should contain %q: %q", "123", out)
  4214. }
  4215. }
  4216. func (s *DockerSuite) TestBuildWithTabs(c *check.C) {
  4217. testRequires(c, DaemonIsLinux)
  4218. name := "testbuildwithtabs"
  4219. _, err := buildImage(name,
  4220. "FROM busybox\nRUN echo\tone\t\ttwo", true)
  4221. if err != nil {
  4222. c.Fatal(err)
  4223. }
  4224. res, err := inspectFieldJSON(name, "ContainerConfig.Cmd")
  4225. if err != nil {
  4226. c.Fatal(err)
  4227. }
  4228. expected1 := `["/bin/sh","-c","echo\tone\t\ttwo"]`
  4229. expected2 := `["/bin/sh","-c","echo\u0009one\u0009\u0009two"]` // syntactically equivalent, and what Go 1.3 generates
  4230. if res != expected1 && res != expected2 {
  4231. c.Fatalf("Missing tabs.\nGot: %s\nExp: %s or %s", res, expected1, expected2)
  4232. }
  4233. }
  4234. func (s *DockerSuite) TestBuildLabels(c *check.C) {
  4235. testRequires(c, DaemonIsLinux)
  4236. name := "testbuildlabel"
  4237. expected := `{"License":"GPL","Vendor":"Acme"}`
  4238. _, err := buildImage(name,
  4239. `FROM busybox
  4240. LABEL Vendor=Acme
  4241. LABEL License GPL`,
  4242. true)
  4243. if err != nil {
  4244. c.Fatal(err)
  4245. }
  4246. res, err := inspectFieldJSON(name, "Config.Labels")
  4247. if err != nil {
  4248. c.Fatal(err)
  4249. }
  4250. if res != expected {
  4251. c.Fatalf("Labels %s, expected %s", res, expected)
  4252. }
  4253. }
  4254. func (s *DockerSuite) TestBuildLabelsCache(c *check.C) {
  4255. testRequires(c, DaemonIsLinux)
  4256. name := "testbuildlabelcache"
  4257. id1, err := buildImage(name,
  4258. `FROM busybox
  4259. LABEL Vendor=Acme`, false)
  4260. if err != nil {
  4261. c.Fatalf("Build 1 should have worked: %v", err)
  4262. }
  4263. id2, err := buildImage(name,
  4264. `FROM busybox
  4265. LABEL Vendor=Acme`, true)
  4266. if err != nil || id1 != id2 {
  4267. c.Fatalf("Build 2 should have worked & used cache(%s,%s): %v", id1, id2, err)
  4268. }
  4269. id2, err = buildImage(name,
  4270. `FROM busybox
  4271. LABEL Vendor=Acme1`, true)
  4272. if err != nil || id1 == id2 {
  4273. c.Fatalf("Build 3 should have worked & NOT used cache(%s,%s): %v", id1, id2, err)
  4274. }
  4275. id2, err = buildImage(name,
  4276. `FROM busybox
  4277. LABEL Vendor Acme`, true) // Note: " " and "=" should be same
  4278. if err != nil || id1 != id2 {
  4279. c.Fatalf("Build 4 should have worked & used cache(%s,%s): %v", id1, id2, err)
  4280. }
  4281. // Now make sure the cache isn't used by mistake
  4282. id1, err = buildImage(name,
  4283. `FROM busybox
  4284. LABEL f1=b1 f2=b2`, false)
  4285. if err != nil {
  4286. c.Fatalf("Build 5 should have worked: %q", err)
  4287. }
  4288. id2, err = buildImage(name,
  4289. `FROM busybox
  4290. LABEL f1="b1 f2=b2"`, true)
  4291. if err != nil || id1 == id2 {
  4292. c.Fatalf("Build 6 should have worked & NOT used the cache(%s,%s): %q", id1, id2, err)
  4293. }
  4294. }
  4295. func (s *DockerSuite) TestBuildNotVerboseSuccess(c *check.C) {
  4296. testRequires(c, DaemonIsLinux)
  4297. // This test makes sure that -q works correctly when build is successful:
  4298. // stdout has only the image ID (long image ID) and stderr is empty.
  4299. var stdout, stderr string
  4300. var err error
  4301. outRegexp := regexp.MustCompile("^(sha256:|)[a-z0-9]{64}\\n$")
  4302. tt := []struct {
  4303. Name string
  4304. BuildFunc func(string)
  4305. }{
  4306. {
  4307. Name: "quiet_build_stdin_success",
  4308. BuildFunc: func(name string) {
  4309. _, stdout, stderr, err = buildImageWithStdoutStderr(name, "FROM busybox", true, "-q", "--force-rm", "--rm")
  4310. },
  4311. },
  4312. {
  4313. Name: "quiet_build_ctx_success",
  4314. BuildFunc: func(name string) {
  4315. ctx, err := fakeContext("FROM busybox", map[string]string{
  4316. "quiet_build_success_fctx": "test",
  4317. })
  4318. if err != nil {
  4319. c.Fatalf("Failed to create context: %s", err.Error())
  4320. }
  4321. defer ctx.Close()
  4322. _, stdout, stderr, err = buildImageFromContextWithStdoutStderr(name, ctx, true, "-q", "--force-rm", "--rm")
  4323. },
  4324. },
  4325. {
  4326. Name: "quiet_build_git_success",
  4327. BuildFunc: func(name string) {
  4328. git, err := newFakeGit("repo", map[string]string{
  4329. "Dockerfile": "FROM busybox",
  4330. }, true)
  4331. if err != nil {
  4332. c.Fatalf("Failed to create the git repo: %s", err.Error())
  4333. }
  4334. defer git.Close()
  4335. _, stdout, stderr, err = buildImageFromGitWithStdoutStderr(name, git, true, "-q", "--force-rm", "--rm")
  4336. },
  4337. },
  4338. }
  4339. for _, te := range tt {
  4340. te.BuildFunc(te.Name)
  4341. if err != nil {
  4342. c.Fatalf("Test %s shouldn't fail, but got the following error: %s", te.Name, err.Error())
  4343. }
  4344. if outRegexp.Find([]byte(stdout)) == nil {
  4345. c.Fatalf("Test %s expected stdout to match the [%v] regexp, but it is [%v]", te.Name, outRegexp, stdout)
  4346. }
  4347. if stderr != "" {
  4348. c.Fatalf("Test %s expected stderr to be empty, but it is [%#v]", te.Name, stderr)
  4349. }
  4350. }
  4351. }
  4352. func (s *DockerSuite) TestBuildNotVerboseFailure(c *check.C) {
  4353. testRequires(c, DaemonIsLinux)
  4354. // This test makes sure that -q works correctly when build fails by
  4355. // comparing between the stderr output in quiet mode and in stdout
  4356. // and stderr output in verbose mode
  4357. tt := []struct {
  4358. TestName string
  4359. BuildCmds string
  4360. }{
  4361. {"quiet_build_no_from_at_the_beginning", "RUN whoami"},
  4362. {"quiet_build_unknown_instr", "FROMD busybox"},
  4363. {"quiet_build_not_exists_image", "FROM busybox11"},
  4364. }
  4365. for _, te := range tt {
  4366. _, _, qstderr, qerr := buildImageWithStdoutStderr(te.TestName, te.BuildCmds, false, "-q", "--force-rm", "--rm")
  4367. _, vstdout, vstderr, verr := buildImageWithStdoutStderr(te.TestName, te.BuildCmds, false, "--force-rm", "--rm")
  4368. if verr == nil || qerr == nil {
  4369. c.Fatal(fmt.Errorf("Test [%s] expected to fail but didn't", te.TestName))
  4370. }
  4371. if qstderr != vstdout+vstderr {
  4372. c.Fatal(fmt.Errorf("Test[%s] expected that quiet stderr and verbose stdout are equal; quiet [%v], verbose [%v]", te.TestName, qstderr, vstdout))
  4373. }
  4374. }
  4375. }
  4376. func (s *DockerSuite) TestBuildNotVerboseFailureRemote(c *check.C) {
  4377. testRequires(c, DaemonIsLinux)
  4378. // This test ensures that when given a wrong URL, stderr in quiet mode and
  4379. // stdout and stderr in verbose mode are identical.
  4380. URL := "http://bla.bla.com"
  4381. Name := "quiet_build_wrong_remote"
  4382. _, _, qstderr, qerr := buildImageWithStdoutStderr(Name, "", false, "-q", "--force-rm", "--rm", URL)
  4383. _, vstdout, vstderr, verr := buildImageWithStdoutStderr(Name, "", false, "--force-rm", "--rm", URL)
  4384. if qerr == nil || verr == nil {
  4385. c.Fatal(fmt.Errorf("Test [%s] expected to fail but didn't", Name))
  4386. }
  4387. if qstderr != vstdout+vstderr {
  4388. c.Fatal(fmt.Errorf("Test[%s] expected that quiet stderr and verbose stdout are equal; quiet [%v], verbose [%v]", Name, qstderr, vstdout))
  4389. }
  4390. }
  4391. func (s *DockerSuite) TestBuildStderr(c *check.C) {
  4392. testRequires(c, DaemonIsLinux)
  4393. // This test just makes sure that no non-error output goes
  4394. // to stderr
  4395. name := "testbuildstderr"
  4396. _, _, stderr, err := buildImageWithStdoutStderr(name,
  4397. "FROM busybox\nRUN echo one", true)
  4398. if err != nil {
  4399. c.Fatal(err)
  4400. }
  4401. if runtime.GOOS == "windows" {
  4402. // stderr might contain a security warning on windows
  4403. lines := strings.Split(stderr, "\n")
  4404. for _, v := range lines {
  4405. if v != "" && !strings.Contains(v, "SECURITY WARNING:") {
  4406. c.Fatalf("Stderr contains unexpected output line: %q", v)
  4407. }
  4408. }
  4409. } else {
  4410. if stderr != "" {
  4411. c.Fatalf("Stderr should have been empty, instead its: %q", stderr)
  4412. }
  4413. }
  4414. }
  4415. func (s *DockerSuite) TestBuildChownSingleFile(c *check.C) {
  4416. testRequires(c, UnixCli) // test uses chown: not available on windows
  4417. testRequires(c, DaemonIsLinux)
  4418. name := "testbuildchownsinglefile"
  4419. ctx, err := fakeContext(`
  4420. FROM busybox
  4421. COPY test /
  4422. RUN ls -l /test
  4423. RUN [ $(ls -l /test | awk '{print $3":"$4}') = 'root:root' ]
  4424. `, map[string]string{
  4425. "test": "test",
  4426. })
  4427. if err != nil {
  4428. c.Fatal(err)
  4429. }
  4430. defer ctx.Close()
  4431. if err := os.Chown(filepath.Join(ctx.Dir, "test"), 4242, 4242); err != nil {
  4432. c.Fatal(err)
  4433. }
  4434. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  4435. c.Fatal(err)
  4436. }
  4437. }
  4438. func (s *DockerSuite) TestBuildSymlinkBreakout(c *check.C) {
  4439. testRequires(c, DaemonIsLinux)
  4440. name := "testbuildsymlinkbreakout"
  4441. tmpdir, err := ioutil.TempDir("", name)
  4442. c.Assert(err, check.IsNil)
  4443. defer os.RemoveAll(tmpdir)
  4444. ctx := filepath.Join(tmpdir, "context")
  4445. if err := os.MkdirAll(ctx, 0755); err != nil {
  4446. c.Fatal(err)
  4447. }
  4448. if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte(`
  4449. from busybox
  4450. add symlink.tar /
  4451. add inject /symlink/
  4452. `), 0644); err != nil {
  4453. c.Fatal(err)
  4454. }
  4455. inject := filepath.Join(ctx, "inject")
  4456. if err := ioutil.WriteFile(inject, nil, 0644); err != nil {
  4457. c.Fatal(err)
  4458. }
  4459. f, err := os.Create(filepath.Join(ctx, "symlink.tar"))
  4460. if err != nil {
  4461. c.Fatal(err)
  4462. }
  4463. w := tar.NewWriter(f)
  4464. w.WriteHeader(&tar.Header{
  4465. Name: "symlink2",
  4466. Typeflag: tar.TypeSymlink,
  4467. Linkname: "/../../../../../../../../../../../../../../",
  4468. Uid: os.Getuid(),
  4469. Gid: os.Getgid(),
  4470. })
  4471. w.WriteHeader(&tar.Header{
  4472. Name: "symlink",
  4473. Typeflag: tar.TypeSymlink,
  4474. Linkname: filepath.Join("symlink2", tmpdir),
  4475. Uid: os.Getuid(),
  4476. Gid: os.Getgid(),
  4477. })
  4478. w.Close()
  4479. f.Close()
  4480. if _, err := buildImageFromContext(name, fakeContextFromDir(ctx), false); err != nil {
  4481. c.Fatal(err)
  4482. }
  4483. if _, err := os.Lstat(filepath.Join(tmpdir, "inject")); err == nil {
  4484. c.Fatal("symlink breakout - inject")
  4485. } else if !os.IsNotExist(err) {
  4486. c.Fatalf("unexpected error: %v", err)
  4487. }
  4488. }
  4489. func (s *DockerSuite) TestBuildXZHost(c *check.C) {
  4490. // /usr/local/sbin/xz gets permission denied for the user
  4491. testRequires(c, NotUserNamespace)
  4492. testRequires(c, DaemonIsLinux)
  4493. name := "testbuildxzhost"
  4494. ctx, err := fakeContext(`
  4495. FROM busybox
  4496. ADD xz /usr/local/sbin/
  4497. RUN chmod 755 /usr/local/sbin/xz
  4498. ADD test.xz /
  4499. RUN [ ! -e /injected ]`,
  4500. map[string]string{
  4501. "test.xz": "\xfd\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00" +
  4502. "\x21\x01\x16\x00\x00\x00\x74\x2f\xe5\xa3\x01\x00\x3f\xfd" +
  4503. "\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00\x21",
  4504. "xz": "#!/bin/sh\ntouch /injected",
  4505. })
  4506. if err != nil {
  4507. c.Fatal(err)
  4508. }
  4509. defer ctx.Close()
  4510. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  4511. c.Fatal(err)
  4512. }
  4513. }
  4514. func (s *DockerSuite) TestBuildVolumesRetainContents(c *check.C) {
  4515. // /foo/file gets permission denied for the user
  4516. testRequires(c, NotUserNamespace)
  4517. testRequires(c, DaemonIsLinux)
  4518. var (
  4519. name = "testbuildvolumescontent"
  4520. expected = "some text"
  4521. )
  4522. ctx, err := fakeContext(`
  4523. FROM busybox
  4524. COPY content /foo/file
  4525. VOLUME /foo
  4526. CMD cat /foo/file`,
  4527. map[string]string{
  4528. "content": expected,
  4529. })
  4530. if err != nil {
  4531. c.Fatal(err)
  4532. }
  4533. defer ctx.Close()
  4534. if _, err := buildImageFromContext(name, ctx, false); err != nil {
  4535. c.Fatal(err)
  4536. }
  4537. out, _ := dockerCmd(c, "run", "--rm", name)
  4538. if out != expected {
  4539. c.Fatalf("expected file contents for /foo/file to be %q but received %q", expected, out)
  4540. }
  4541. }
  4542. func (s *DockerSuite) TestBuildRenamedDockerfile(c *check.C) {
  4543. testRequires(c, DaemonIsLinux)
  4544. ctx, err := fakeContext(`FROM busybox
  4545. RUN echo from Dockerfile`,
  4546. map[string]string{
  4547. "Dockerfile": "FROM busybox\nRUN echo from Dockerfile",
  4548. "files/Dockerfile": "FROM busybox\nRUN echo from files/Dockerfile",
  4549. "files/dFile": "FROM busybox\nRUN echo from files/dFile",
  4550. "dFile": "FROM busybox\nRUN echo from dFile",
  4551. "files/dFile2": "FROM busybox\nRUN echo from files/dFile2",
  4552. })
  4553. if err != nil {
  4554. c.Fatal(err)
  4555. }
  4556. defer ctx.Close()
  4557. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", "test1", ".")
  4558. if err != nil {
  4559. c.Fatalf("Failed to build: %s\n%s", out, err)
  4560. }
  4561. if !strings.Contains(out, "from Dockerfile") {
  4562. c.Fatalf("test1 should have used Dockerfile, output:%s", out)
  4563. }
  4564. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", "-f", filepath.Join("files", "Dockerfile"), "-t", "test2", ".")
  4565. if err != nil {
  4566. c.Fatal(err)
  4567. }
  4568. if !strings.Contains(out, "from files/Dockerfile") {
  4569. c.Fatalf("test2 should have used files/Dockerfile, output:%s", out)
  4570. }
  4571. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", fmt.Sprintf("--file=%s", filepath.Join("files", "dFile")), "-t", "test3", ".")
  4572. if err != nil {
  4573. c.Fatal(err)
  4574. }
  4575. if !strings.Contains(out, "from files/dFile") {
  4576. c.Fatalf("test3 should have used files/dFile, output:%s", out)
  4577. }
  4578. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", "--file=dFile", "-t", "test4", ".")
  4579. if err != nil {
  4580. c.Fatal(err)
  4581. }
  4582. if !strings.Contains(out, "from dFile") {
  4583. c.Fatalf("test4 should have used dFile, output:%s", out)
  4584. }
  4585. dirWithNoDockerfile, err := ioutil.TempDir(os.TempDir(), "test5")
  4586. c.Assert(err, check.IsNil)
  4587. nonDockerfileFile := filepath.Join(dirWithNoDockerfile, "notDockerfile")
  4588. if _, err = os.Create(nonDockerfileFile); err != nil {
  4589. c.Fatal(err)
  4590. }
  4591. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", fmt.Sprintf("--file=%s", nonDockerfileFile), "-t", "test5", ".")
  4592. if err == nil {
  4593. c.Fatalf("test5 was supposed to fail to find passwd")
  4594. }
  4595. if expected := fmt.Sprintf("The Dockerfile (%s) must be within the build context (.)", nonDockerfileFile); !strings.Contains(out, expected) {
  4596. c.Fatalf("wrong error messsage:%v\nexpected to contain=%v", out, expected)
  4597. }
  4598. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join("..", "Dockerfile"), "-t", "test6", "..")
  4599. if err != nil {
  4600. c.Fatalf("test6 failed: %s", err)
  4601. }
  4602. if !strings.Contains(out, "from Dockerfile") {
  4603. c.Fatalf("test6 should have used root Dockerfile, output:%s", out)
  4604. }
  4605. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join(ctx.Dir, "files", "Dockerfile"), "-t", "test7", "..")
  4606. if err != nil {
  4607. c.Fatalf("test7 failed: %s", err)
  4608. }
  4609. if !strings.Contains(out, "from files/Dockerfile") {
  4610. c.Fatalf("test7 should have used files Dockerfile, output:%s", out)
  4611. }
  4612. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join("..", "Dockerfile"), "-t", "test8", ".")
  4613. if err == nil || !strings.Contains(out, "must be within the build context") {
  4614. c.Fatalf("test8 should have failed with Dockerfile out of context: %s", err)
  4615. }
  4616. tmpDir := os.TempDir()
  4617. out, _, err = dockerCmdInDir(c, tmpDir, "build", "-t", "test9", ctx.Dir)
  4618. if err != nil {
  4619. c.Fatalf("test9 - failed: %s", err)
  4620. }
  4621. if !strings.Contains(out, "from Dockerfile") {
  4622. c.Fatalf("test9 should have used root Dockerfile, output:%s", out)
  4623. }
  4624. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", "dFile2", "-t", "test10", ".")
  4625. if err != nil {
  4626. c.Fatalf("test10 should have worked: %s", err)
  4627. }
  4628. if !strings.Contains(out, "from files/dFile2") {
  4629. c.Fatalf("test10 should have used files/dFile2, output:%s", out)
  4630. }
  4631. }
  4632. func (s *DockerSuite) TestBuildFromMixedcaseDockerfile(c *check.C) {
  4633. testRequires(c, UnixCli) // Dockerfile overwrites dockerfile on windows
  4634. testRequires(c, DaemonIsLinux)
  4635. ctx, err := fakeContext(`FROM busybox
  4636. RUN echo from dockerfile`,
  4637. map[string]string{
  4638. "dockerfile": "FROM busybox\nRUN echo from dockerfile",
  4639. })
  4640. if err != nil {
  4641. c.Fatal(err)
  4642. }
  4643. defer ctx.Close()
  4644. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", "test1", ".")
  4645. if err != nil {
  4646. c.Fatalf("Failed to build: %s\n%s", out, err)
  4647. }
  4648. if !strings.Contains(out, "from dockerfile") {
  4649. c.Fatalf("Missing proper output: %s", out)
  4650. }
  4651. }
  4652. func (s *DockerSuite) TestBuildWithTwoDockerfiles(c *check.C) {
  4653. testRequires(c, UnixCli) // Dockerfile overwrites dockerfile on windows
  4654. testRequires(c, DaemonIsLinux)
  4655. ctx, err := fakeContext(`FROM busybox
  4656. RUN echo from Dockerfile`,
  4657. map[string]string{
  4658. "dockerfile": "FROM busybox\nRUN echo from dockerfile",
  4659. })
  4660. if err != nil {
  4661. c.Fatal(err)
  4662. }
  4663. defer ctx.Close()
  4664. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", "test1", ".")
  4665. if err != nil {
  4666. c.Fatalf("Failed to build: %s\n%s", out, err)
  4667. }
  4668. if !strings.Contains(out, "from Dockerfile") {
  4669. c.Fatalf("Missing proper output: %s", out)
  4670. }
  4671. }
  4672. func (s *DockerSuite) TestBuildFromURLWithF(c *check.C) {
  4673. testRequires(c, DaemonIsLinux)
  4674. server, err := fakeStorage(map[string]string{"baz": `FROM busybox
  4675. RUN echo from baz
  4676. COPY * /tmp/
  4677. RUN find /tmp/`})
  4678. if err != nil {
  4679. c.Fatal(err)
  4680. }
  4681. defer server.Close()
  4682. ctx, err := fakeContext(`FROM busybox
  4683. RUN echo from Dockerfile`,
  4684. map[string]string{})
  4685. if err != nil {
  4686. c.Fatal(err)
  4687. }
  4688. defer ctx.Close()
  4689. // Make sure that -f is ignored and that we don't use the Dockerfile
  4690. // that's in the current dir
  4691. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-f", "baz", "-t", "test1", server.URL()+"/baz")
  4692. if err != nil {
  4693. c.Fatalf("Failed to build: %s\n%s", out, err)
  4694. }
  4695. if !strings.Contains(out, "from baz") ||
  4696. strings.Contains(out, "/tmp/baz") ||
  4697. !strings.Contains(out, "/tmp/Dockerfile") {
  4698. c.Fatalf("Missing proper output: %s", out)
  4699. }
  4700. }
  4701. func (s *DockerSuite) TestBuildFromStdinWithF(c *check.C) {
  4702. testRequires(c, DaemonIsLinux)
  4703. ctx, err := fakeContext(`FROM busybox
  4704. RUN echo from Dockerfile`,
  4705. map[string]string{})
  4706. if err != nil {
  4707. c.Fatal(err)
  4708. }
  4709. defer ctx.Close()
  4710. // Make sure that -f is ignored and that we don't use the Dockerfile
  4711. // that's in the current dir
  4712. dockerCommand := exec.Command(dockerBinary, "build", "-f", "baz", "-t", "test1", "-")
  4713. dockerCommand.Dir = ctx.Dir
  4714. dockerCommand.Stdin = strings.NewReader(`FROM busybox
  4715. RUN echo from baz
  4716. COPY * /tmp/
  4717. RUN find /tmp/`)
  4718. out, status, err := runCommandWithOutput(dockerCommand)
  4719. if err != nil || status != 0 {
  4720. c.Fatalf("Error building: %s", err)
  4721. }
  4722. if !strings.Contains(out, "from baz") ||
  4723. strings.Contains(out, "/tmp/baz") ||
  4724. !strings.Contains(out, "/tmp/Dockerfile") {
  4725. c.Fatalf("Missing proper output: %s", out)
  4726. }
  4727. }
  4728. func (s *DockerSuite) TestBuildFromOfficialNames(c *check.C) {
  4729. testRequires(c, DaemonIsLinux)
  4730. name := "testbuildfromofficial"
  4731. fromNames := []string{
  4732. "busybox",
  4733. "docker.io/busybox",
  4734. "index.docker.io/busybox",
  4735. "library/busybox",
  4736. "docker.io/library/busybox",
  4737. "index.docker.io/library/busybox",
  4738. }
  4739. for idx, fromName := range fromNames {
  4740. imgName := fmt.Sprintf("%s%d", name, idx)
  4741. _, err := buildImage(imgName, "FROM "+fromName, true)
  4742. if err != nil {
  4743. c.Errorf("Build failed using FROM %s: %s", fromName, err)
  4744. }
  4745. deleteImages(imgName)
  4746. }
  4747. }
  4748. func (s *DockerSuite) TestBuildDockerfileOutsideContext(c *check.C) {
  4749. testRequires(c, UnixCli) // uses os.Symlink: not implemented in windows at the time of writing (go-1.4.2)
  4750. testRequires(c, DaemonIsLinux)
  4751. name := "testbuilddockerfileoutsidecontext"
  4752. tmpdir, err := ioutil.TempDir("", name)
  4753. c.Assert(err, check.IsNil)
  4754. defer os.RemoveAll(tmpdir)
  4755. ctx := filepath.Join(tmpdir, "context")
  4756. if err := os.MkdirAll(ctx, 0755); err != nil {
  4757. c.Fatal(err)
  4758. }
  4759. if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte("FROM scratch\nENV X Y"), 0644); err != nil {
  4760. c.Fatal(err)
  4761. }
  4762. wd, err := os.Getwd()
  4763. if err != nil {
  4764. c.Fatal(err)
  4765. }
  4766. defer os.Chdir(wd)
  4767. if err := os.Chdir(ctx); err != nil {
  4768. c.Fatal(err)
  4769. }
  4770. if err := ioutil.WriteFile(filepath.Join(tmpdir, "outsideDockerfile"), []byte("FROM scratch\nENV x y"), 0644); err != nil {
  4771. c.Fatal(err)
  4772. }
  4773. if err := os.Symlink(filepath.Join("..", "outsideDockerfile"), filepath.Join(ctx, "dockerfile1")); err != nil {
  4774. c.Fatal(err)
  4775. }
  4776. if err := os.Symlink(filepath.Join(tmpdir, "outsideDockerfile"), filepath.Join(ctx, "dockerfile2")); err != nil {
  4777. c.Fatal(err)
  4778. }
  4779. for _, dockerfilePath := range []string{
  4780. filepath.Join("..", "outsideDockerfile"),
  4781. filepath.Join(ctx, "dockerfile1"),
  4782. filepath.Join(ctx, "dockerfile2"),
  4783. } {
  4784. out, _, err := dockerCmdWithError("build", "-t", name, "--no-cache", "-f", dockerfilePath, ".")
  4785. if err == nil {
  4786. c.Fatalf("Expected error with %s. Out: %s", dockerfilePath, out)
  4787. }
  4788. if !strings.Contains(out, "must be within the build context") && !strings.Contains(out, "Cannot locate Dockerfile") {
  4789. c.Fatalf("Unexpected error with %s. Out: %s", dockerfilePath, out)
  4790. }
  4791. deleteImages(name)
  4792. }
  4793. os.Chdir(tmpdir)
  4794. // Path to Dockerfile should be resolved relative to working directory, not relative to context.
  4795. // There is a Dockerfile in the context, but since there is no Dockerfile in the current directory, the following should fail
  4796. out, _, err := dockerCmdWithError("build", "-t", name, "--no-cache", "-f", "Dockerfile", ctx)
  4797. if err == nil {
  4798. c.Fatalf("Expected error. Out: %s", out)
  4799. }
  4800. }
  4801. func (s *DockerSuite) TestBuildSpaces(c *check.C) {
  4802. testRequires(c, DaemonIsLinux)
  4803. // Test to make sure that leading/trailing spaces on a command
  4804. // doesn't change the error msg we get
  4805. var (
  4806. err1 error
  4807. err2 error
  4808. )
  4809. name := "testspaces"
  4810. ctx, err := fakeContext("FROM busybox\nCOPY\n",
  4811. map[string]string{
  4812. "Dockerfile": "FROM busybox\nCOPY\n",
  4813. })
  4814. if err != nil {
  4815. c.Fatal(err)
  4816. }
  4817. defer ctx.Close()
  4818. if _, err1 = buildImageFromContext(name, ctx, false); err1 == nil {
  4819. c.Fatal("Build 1 was supposed to fail, but didn't")
  4820. }
  4821. ctx.Add("Dockerfile", "FROM busybox\nCOPY ")
  4822. if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil {
  4823. c.Fatal("Build 2 was supposed to fail, but didn't")
  4824. }
  4825. removeLogTimestamps := func(s string) string {
  4826. return regexp.MustCompile(`time="(.*?)"`).ReplaceAllString(s, `time=[TIMESTAMP]`)
  4827. }
  4828. // Skip over the times
  4829. e1 := removeLogTimestamps(err1.Error())
  4830. e2 := removeLogTimestamps(err2.Error())
  4831. // Ignore whitespace since that's what were verifying doesn't change stuff
  4832. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  4833. c.Fatalf("Build 2's error wasn't the same as build 1's\n1:%s\n2:%s", err1, err2)
  4834. }
  4835. ctx.Add("Dockerfile", "FROM busybox\n COPY")
  4836. if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil {
  4837. c.Fatal("Build 3 was supposed to fail, but didn't")
  4838. }
  4839. // Skip over the times
  4840. e1 = removeLogTimestamps(err1.Error())
  4841. e2 = removeLogTimestamps(err2.Error())
  4842. // Ignore whitespace since that's what were verifying doesn't change stuff
  4843. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  4844. c.Fatalf("Build 3's error wasn't the same as build 1's\n1:%s\n3:%s", err1, err2)
  4845. }
  4846. ctx.Add("Dockerfile", "FROM busybox\n COPY ")
  4847. if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil {
  4848. c.Fatal("Build 4 was supposed to fail, but didn't")
  4849. }
  4850. // Skip over the times
  4851. e1 = removeLogTimestamps(err1.Error())
  4852. e2 = removeLogTimestamps(err2.Error())
  4853. // Ignore whitespace since that's what were verifying doesn't change stuff
  4854. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  4855. c.Fatalf("Build 4's error wasn't the same as build 1's\n1:%s\n4:%s", err1, err2)
  4856. }
  4857. }
  4858. func (s *DockerSuite) TestBuildSpacesWithQuotes(c *check.C) {
  4859. testRequires(c, DaemonIsLinux)
  4860. // Test to make sure that spaces in quotes aren't lost
  4861. name := "testspacesquotes"
  4862. dockerfile := `FROM busybox
  4863. RUN echo " \
  4864. foo "`
  4865. _, out, err := buildImageWithOut(name, dockerfile, false)
  4866. if err != nil {
  4867. c.Fatal("Build failed:", err)
  4868. }
  4869. expecting := "\n foo \n"
  4870. if !strings.Contains(out, expecting) {
  4871. c.Fatalf("Bad output: %q expecting to contain %q", out, expecting)
  4872. }
  4873. }
  4874. // #4393
  4875. func (s *DockerSuite) TestBuildVolumeFileExistsinContainer(c *check.C) {
  4876. testRequires(c, DaemonIsLinux)
  4877. buildCmd := exec.Command(dockerBinary, "build", "-t", "docker-test-errcreatevolumewithfile", "-")
  4878. buildCmd.Stdin = strings.NewReader(`
  4879. FROM busybox
  4880. RUN touch /foo
  4881. VOLUME /foo
  4882. `)
  4883. out, _, err := runCommandWithOutput(buildCmd)
  4884. if err == nil || !strings.Contains(out, "file exists") {
  4885. c.Fatalf("expected build to fail when file exists in container at requested volume path")
  4886. }
  4887. }
  4888. func (s *DockerSuite) TestBuildMissingArgs(c *check.C) {
  4889. testRequires(c, DaemonIsLinux)
  4890. // Test to make sure that all Dockerfile commands (except the ones listed
  4891. // in skipCmds) will generate an error if no args are provided.
  4892. // Note: INSERT is deprecated so we exclude it because of that.
  4893. skipCmds := map[string]struct{}{
  4894. "CMD": {},
  4895. "RUN": {},
  4896. "ENTRYPOINT": {},
  4897. "INSERT": {},
  4898. }
  4899. for cmd := range command.Commands {
  4900. cmd = strings.ToUpper(cmd)
  4901. if _, ok := skipCmds[cmd]; ok {
  4902. continue
  4903. }
  4904. var dockerfile string
  4905. if cmd == "FROM" {
  4906. dockerfile = cmd
  4907. } else {
  4908. // Add FROM to make sure we don't complain about it missing
  4909. dockerfile = "FROM busybox\n" + cmd
  4910. }
  4911. ctx, err := fakeContext(dockerfile, map[string]string{})
  4912. if err != nil {
  4913. c.Fatal(err)
  4914. }
  4915. defer ctx.Close()
  4916. var out string
  4917. if out, err = buildImageFromContext("args", ctx, true); err == nil {
  4918. c.Fatalf("%s was supposed to fail. Out:%s", cmd, out)
  4919. }
  4920. if !strings.Contains(err.Error(), cmd+" requires") {
  4921. c.Fatalf("%s returned the wrong type of error:%s", cmd, err)
  4922. }
  4923. }
  4924. }
  4925. func (s *DockerSuite) TestBuildEmptyScratch(c *check.C) {
  4926. testRequires(c, DaemonIsLinux)
  4927. _, out, err := buildImageWithOut("sc", "FROM scratch", true)
  4928. if err == nil {
  4929. c.Fatalf("Build was supposed to fail")
  4930. }
  4931. if !strings.Contains(out, "No image was generated") {
  4932. c.Fatalf("Wrong error message: %v", out)
  4933. }
  4934. }
  4935. func (s *DockerSuite) TestBuildDotDotFile(c *check.C) {
  4936. testRequires(c, DaemonIsLinux)
  4937. ctx, err := fakeContext("FROM busybox\n",
  4938. map[string]string{
  4939. "..gitme": "",
  4940. })
  4941. if err != nil {
  4942. c.Fatal(err)
  4943. }
  4944. defer ctx.Close()
  4945. if _, err = buildImageFromContext("sc", ctx, false); err != nil {
  4946. c.Fatalf("Build was supposed to work: %s", err)
  4947. }
  4948. }
  4949. func (s *DockerSuite) TestBuildRUNoneJSON(c *check.C) {
  4950. testRequires(c, DaemonIsLinux)
  4951. name := "testbuildrunonejson"
  4952. ctx, err := fakeContext(`FROM hello-world:frozen
  4953. RUN [ "/hello" ]`, map[string]string{})
  4954. if err != nil {
  4955. c.Fatal(err)
  4956. }
  4957. defer ctx.Close()
  4958. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "--no-cache", "-t", name, ".")
  4959. if err != nil {
  4960. c.Fatalf("failed to build the image: %s, %v", out, err)
  4961. }
  4962. if !strings.Contains(out, "Hello from Docker") {
  4963. c.Fatalf("bad output: %s", out)
  4964. }
  4965. }
  4966. func (s *DockerSuite) TestBuildEmptyStringVolume(c *check.C) {
  4967. testRequires(c, DaemonIsLinux)
  4968. name := "testbuildemptystringvolume"
  4969. _, err := buildImage(name, `
  4970. FROM busybox
  4971. ENV foo=""
  4972. VOLUME $foo
  4973. `, false)
  4974. if err == nil {
  4975. c.Fatal("Should have failed to build")
  4976. }
  4977. }
  4978. func (s *DockerSuite) TestBuildContainerWithCgroupParent(c *check.C) {
  4979. testRequires(c, SameHostDaemon)
  4980. testRequires(c, DaemonIsLinux)
  4981. cgroupParent := "test"
  4982. data, err := ioutil.ReadFile("/proc/self/cgroup")
  4983. if err != nil {
  4984. c.Fatalf("failed to read '/proc/self/cgroup - %v", err)
  4985. }
  4986. selfCgroupPaths := parseCgroupPaths(string(data))
  4987. _, found := selfCgroupPaths["memory"]
  4988. if !found {
  4989. c.Fatalf("unable to find self memory cgroup path. CgroupsPath: %v", selfCgroupPaths)
  4990. }
  4991. cmd := exec.Command(dockerBinary, "build", "--cgroup-parent", cgroupParent, "-")
  4992. cmd.Stdin = strings.NewReader(`
  4993. FROM busybox
  4994. RUN cat /proc/self/cgroup
  4995. `)
  4996. out, _, err := runCommandWithOutput(cmd)
  4997. if err != nil {
  4998. c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err)
  4999. }
  5000. m, err := regexp.MatchString(fmt.Sprintf("memory:.*/%s/.*", cgroupParent), out)
  5001. c.Assert(err, check.IsNil)
  5002. if !m {
  5003. c.Fatalf("There is no expected memory cgroup with parent /%s/: %s", cgroupParent, out)
  5004. }
  5005. }
  5006. func (s *DockerSuite) TestBuildNoDupOutput(c *check.C) {
  5007. testRequires(c, DaemonIsLinux)
  5008. // Check to make sure our build output prints the Dockerfile cmd
  5009. // property - there was a bug that caused it to be duplicated on the
  5010. // Step X line
  5011. name := "testbuildnodupoutput"
  5012. _, out, err := buildImageWithOut(name, `
  5013. FROM busybox
  5014. RUN env`, false)
  5015. if err != nil {
  5016. c.Fatalf("Build should have worked: %q", err)
  5017. }
  5018. exp := "\nStep 2 : RUN env\n"
  5019. if !strings.Contains(out, exp) {
  5020. c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", out, exp)
  5021. }
  5022. }
  5023. // GH15826
  5024. func (s *DockerSuite) TestBuildStartsFromOne(c *check.C) {
  5025. testRequires(c, DaemonIsLinux)
  5026. // Explicit check to ensure that build starts from step 1 rather than 0
  5027. name := "testbuildstartsfromone"
  5028. _, out, err := buildImageWithOut(name, `
  5029. FROM busybox`, false)
  5030. if err != nil {
  5031. c.Fatalf("Build should have worked: %q", err)
  5032. }
  5033. exp := "\nStep 1 : FROM busybox\n"
  5034. if !strings.Contains(out, exp) {
  5035. c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", out, exp)
  5036. }
  5037. }
  5038. func (s *DockerSuite) TestBuildBadCmdFlag(c *check.C) {
  5039. testRequires(c, DaemonIsLinux)
  5040. name := "testbuildbadcmdflag"
  5041. _, out, err := buildImageWithOut(name, `
  5042. FROM busybox
  5043. MAINTAINER --boo joe@example.com`, false)
  5044. if err == nil {
  5045. c.Fatal("Build should have failed")
  5046. }
  5047. exp := "\nUnknown flag: boo\n"
  5048. if !strings.Contains(out, exp) {
  5049. c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", out, exp)
  5050. }
  5051. }
  5052. func (s *DockerSuite) TestBuildRUNErrMsg(c *check.C) {
  5053. testRequires(c, DaemonIsLinux)
  5054. // Test to make sure the bad command is quoted with just "s and
  5055. // not as a Go []string
  5056. name := "testbuildbadrunerrmsg"
  5057. _, out, err := buildImageWithOut(name, `
  5058. FROM busybox
  5059. RUN badEXE a1 \& a2 a3`, false) // tab between a2 and a3
  5060. if err == nil {
  5061. c.Fatal("Should have failed to build")
  5062. }
  5063. exp := `The command '/bin/sh -c badEXE a1 \& a2 a3' returned a non-zero code: 127`
  5064. if !strings.Contains(out, exp) {
  5065. c.Fatalf("RUN doesn't have the correct output:\nGot:%s\nExpected:%s", out, exp)
  5066. }
  5067. }
  5068. func (s *DockerTrustSuite) TestTrustedBuild(c *check.C) {
  5069. repoName := s.setupTrustedImage(c, "trusted-build")
  5070. dockerFile := fmt.Sprintf(`
  5071. FROM %s
  5072. RUN []
  5073. `, repoName)
  5074. name := "testtrustedbuild"
  5075. buildCmd := buildImageCmd(name, dockerFile, true)
  5076. s.trustedCmd(buildCmd)
  5077. out, _, err := runCommandWithOutput(buildCmd)
  5078. if err != nil {
  5079. c.Fatalf("Error running trusted build: %s\n%s", err, out)
  5080. }
  5081. if !strings.Contains(out, fmt.Sprintf("FROM %s@sha", repoName[:len(repoName)-7])) {
  5082. c.Fatalf("Unexpected output on trusted build:\n%s", out)
  5083. }
  5084. // We should also have a tag reference for the image.
  5085. if out, exitCode := dockerCmd(c, "inspect", repoName); exitCode != 0 {
  5086. c.Fatalf("unexpected exit code inspecting image %q: %d: %s", repoName, exitCode, out)
  5087. }
  5088. // We should now be able to remove the tag reference.
  5089. if out, exitCode := dockerCmd(c, "rmi", repoName); exitCode != 0 {
  5090. c.Fatalf("unexpected exit code inspecting image %q: %d: %s", repoName, exitCode, out)
  5091. }
  5092. }
  5093. func (s *DockerTrustSuite) TestTrustedBuildUntrustedTag(c *check.C) {
  5094. repoName := fmt.Sprintf("%v/dockercli/build-untrusted-tag:latest", privateRegistryURL)
  5095. dockerFile := fmt.Sprintf(`
  5096. FROM %s
  5097. RUN []
  5098. `, repoName)
  5099. name := "testtrustedbuilduntrustedtag"
  5100. buildCmd := buildImageCmd(name, dockerFile, true)
  5101. s.trustedCmd(buildCmd)
  5102. out, _, err := runCommandWithOutput(buildCmd)
  5103. if err == nil {
  5104. c.Fatalf("Expected error on trusted build with untrusted tag: %s\n%s", err, out)
  5105. }
  5106. if !strings.Contains(out, fmt.Sprintf("no trust data available")) {
  5107. c.Fatalf("Unexpected output on trusted build with untrusted tag:\n%s", out)
  5108. }
  5109. }
  5110. func (s *DockerTrustSuite) TestBuildContextDirIsSymlink(c *check.C) {
  5111. testRequires(c, DaemonIsLinux)
  5112. tempDir, err := ioutil.TempDir("", "test-build-dir-is-symlink-")
  5113. c.Assert(err, check.IsNil)
  5114. defer os.RemoveAll(tempDir)
  5115. // Make a real context directory in this temp directory with a simple
  5116. // Dockerfile.
  5117. realContextDirname := filepath.Join(tempDir, "context")
  5118. if err := os.Mkdir(realContextDirname, os.FileMode(0755)); err != nil {
  5119. c.Fatal(err)
  5120. }
  5121. if err = ioutil.WriteFile(
  5122. filepath.Join(realContextDirname, "Dockerfile"),
  5123. []byte(`
  5124. FROM busybox
  5125. RUN echo hello world
  5126. `),
  5127. os.FileMode(0644),
  5128. ); err != nil {
  5129. c.Fatal(err)
  5130. }
  5131. // Make a symlink to the real context directory.
  5132. contextSymlinkName := filepath.Join(tempDir, "context_link")
  5133. if err := os.Symlink(realContextDirname, contextSymlinkName); err != nil {
  5134. c.Fatal(err)
  5135. }
  5136. // Executing the build with the symlink as the specified context should
  5137. // *not* fail.
  5138. if out, exitStatus := dockerCmd(c, "build", contextSymlinkName); exitStatus != 0 {
  5139. c.Fatalf("build failed with exit status %d: %s", exitStatus, out)
  5140. }
  5141. }
  5142. // Issue #15634: COPY fails when path starts with "null"
  5143. func (s *DockerSuite) TestBuildNullStringInAddCopyVolume(c *check.C) {
  5144. testRequires(c, DaemonIsLinux)
  5145. name := "testbuildnullstringinaddcopyvolume"
  5146. ctx, err := fakeContext(`
  5147. FROM busybox
  5148. ADD null /
  5149. COPY nullfile /
  5150. VOLUME nullvolume
  5151. `,
  5152. map[string]string{
  5153. "null": "test1",
  5154. "nullfile": "test2",
  5155. },
  5156. )
  5157. c.Assert(err, check.IsNil)
  5158. defer ctx.Close()
  5159. _, err = buildImageFromContext(name, ctx, true)
  5160. c.Assert(err, check.IsNil)
  5161. }
  5162. func (s *DockerSuite) TestBuildStopSignal(c *check.C) {
  5163. testRequires(c, DaemonIsLinux)
  5164. name := "test_build_stop_signal"
  5165. _, err := buildImage(name,
  5166. `FROM busybox
  5167. STOPSIGNAL SIGKILL`,
  5168. true)
  5169. c.Assert(err, check.IsNil)
  5170. res, err := inspectFieldJSON(name, "Config.StopSignal")
  5171. c.Assert(err, check.IsNil)
  5172. if res != `"SIGKILL"` {
  5173. c.Fatalf("Signal %s, expected SIGKILL", res)
  5174. }
  5175. }
  5176. func (s *DockerSuite) TestBuildBuildTimeArg(c *check.C) {
  5177. testRequires(c, DaemonIsLinux)
  5178. imgName := "bldargtest"
  5179. envKey := "foo"
  5180. envVal := "bar"
  5181. args := []string{
  5182. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5183. }
  5184. dockerfile := fmt.Sprintf(`FROM busybox
  5185. ARG %s
  5186. RUN echo $%s
  5187. CMD echo $%s`, envKey, envKey, envKey)
  5188. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil || !strings.Contains(out, envVal) {
  5189. if err != nil {
  5190. c.Fatalf("build failed to complete: %q %q", out, err)
  5191. }
  5192. c.Fatalf("failed to access environment variable in output: %q expected: %q", out, envVal)
  5193. }
  5194. containerName := "bldargCont"
  5195. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); out != "\n" {
  5196. c.Fatalf("run produced invalid output: %q, expected empty string", out)
  5197. }
  5198. }
  5199. func (s *DockerSuite) TestBuildBuildTimeArgHistory(c *check.C) {
  5200. testRequires(c, DaemonIsLinux)
  5201. imgName := "bldargtest"
  5202. envKey := "foo"
  5203. envVal := "bar"
  5204. envDef := "bar1"
  5205. args := []string{
  5206. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5207. }
  5208. dockerfile := fmt.Sprintf(`FROM busybox
  5209. ARG %s=%s`, envKey, envDef)
  5210. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil || !strings.Contains(out, envVal) {
  5211. if err != nil {
  5212. c.Fatalf("build failed to complete: %q %q", out, err)
  5213. }
  5214. c.Fatalf("failed to access environment variable in output: %q expected: %q", out, envVal)
  5215. }
  5216. out, _ := dockerCmd(c, "history", "--no-trunc", imgName)
  5217. outputTabs := strings.Split(out, "\n")[1]
  5218. if !strings.Contains(outputTabs, envDef) {
  5219. c.Fatalf("failed to find arg default in image history output: %q expected: %q", outputTabs, envDef)
  5220. }
  5221. }
  5222. func (s *DockerSuite) TestBuildBuildTimeArgCacheHit(c *check.C) {
  5223. testRequires(c, DaemonIsLinux)
  5224. imgName := "bldargtest"
  5225. envKey := "foo"
  5226. envVal := "bar"
  5227. args := []string{
  5228. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5229. }
  5230. dockerfile := fmt.Sprintf(`FROM busybox
  5231. ARG %s
  5232. RUN echo $%s`, envKey, envKey)
  5233. origImgID := ""
  5234. var err error
  5235. if origImgID, err = buildImage(imgName, dockerfile, true, args...); err != nil {
  5236. c.Fatal(err)
  5237. }
  5238. imgNameCache := "bldargtestcachehit"
  5239. if newImgID, err := buildImage(imgNameCache, dockerfile, true, args...); err != nil || newImgID != origImgID {
  5240. if err != nil {
  5241. c.Fatal(err)
  5242. }
  5243. c.Fatalf("build didn't use cache! expected image id: %q built image id: %q", origImgID, newImgID)
  5244. }
  5245. }
  5246. func (s *DockerSuite) TestBuildBuildTimeArgCacheMissExtraArg(c *check.C) {
  5247. testRequires(c, DaemonIsLinux)
  5248. imgName := "bldargtest"
  5249. envKey := "foo"
  5250. envVal := "bar"
  5251. extraEnvKey := "foo1"
  5252. extraEnvVal := "bar1"
  5253. args := []string{
  5254. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5255. }
  5256. dockerfile := fmt.Sprintf(`FROM busybox
  5257. ARG %s
  5258. ARG %s
  5259. RUN echo $%s`, envKey, extraEnvKey, envKey)
  5260. origImgID := ""
  5261. var err error
  5262. if origImgID, err = buildImage(imgName, dockerfile, true, args...); err != nil {
  5263. c.Fatal(err)
  5264. }
  5265. imgNameCache := "bldargtestcachemiss"
  5266. args = append(args, "--build-arg", fmt.Sprintf("%s=%s", extraEnvKey, extraEnvVal))
  5267. if newImgID, err := buildImage(imgNameCache, dockerfile, true, args...); err != nil || newImgID == origImgID {
  5268. if err != nil {
  5269. c.Fatal(err)
  5270. }
  5271. c.Fatalf("build used cache, expected a miss!")
  5272. }
  5273. }
  5274. func (s *DockerSuite) TestBuildBuildTimeArgCacheMissSameArgDiffVal(c *check.C) {
  5275. testRequires(c, DaemonIsLinux)
  5276. imgName := "bldargtest"
  5277. envKey := "foo"
  5278. envVal := "bar"
  5279. newEnvVal := "bar1"
  5280. args := []string{
  5281. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5282. }
  5283. dockerfile := fmt.Sprintf(`FROM busybox
  5284. ARG %s
  5285. RUN echo $%s`, envKey, envKey)
  5286. origImgID := ""
  5287. var err error
  5288. if origImgID, err = buildImage(imgName, dockerfile, true, args...); err != nil {
  5289. c.Fatal(err)
  5290. }
  5291. imgNameCache := "bldargtestcachemiss"
  5292. args = []string{
  5293. "--build-arg", fmt.Sprintf("%s=%s", envKey, newEnvVal),
  5294. }
  5295. if newImgID, err := buildImage(imgNameCache, dockerfile, true, args...); err != nil || newImgID == origImgID {
  5296. if err != nil {
  5297. c.Fatal(err)
  5298. }
  5299. c.Fatalf("build used cache, expected a miss!")
  5300. }
  5301. }
  5302. func (s *DockerSuite) TestBuildBuildTimeArgOverrideArgDefinedBeforeEnv(c *check.C) {
  5303. testRequires(c, DaemonIsLinux)
  5304. imgName := "bldargtest"
  5305. envKey := "foo"
  5306. envVal := "bar"
  5307. envValOveride := "barOverride"
  5308. args := []string{
  5309. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5310. }
  5311. dockerfile := fmt.Sprintf(`FROM busybox
  5312. ARG %s
  5313. ENV %s %s
  5314. RUN echo $%s
  5315. CMD echo $%s
  5316. `, envKey, envKey, envValOveride, envKey, envKey)
  5317. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil || strings.Count(out, envValOveride) != 2 {
  5318. if err != nil {
  5319. c.Fatalf("build failed to complete: %q %q", out, err)
  5320. }
  5321. c.Fatalf("failed to access environment variable in output: %q expected: %q", out, envValOveride)
  5322. }
  5323. containerName := "bldargCont"
  5324. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOveride) {
  5325. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOveride)
  5326. }
  5327. }
  5328. func (s *DockerSuite) TestBuildBuildTimeArgOverrideEnvDefinedBeforeArg(c *check.C) {
  5329. testRequires(c, DaemonIsLinux)
  5330. imgName := "bldargtest"
  5331. envKey := "foo"
  5332. envVal := "bar"
  5333. envValOveride := "barOverride"
  5334. args := []string{
  5335. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5336. }
  5337. dockerfile := fmt.Sprintf(`FROM busybox
  5338. ENV %s %s
  5339. ARG %s
  5340. RUN echo $%s
  5341. CMD echo $%s
  5342. `, envKey, envValOveride, envKey, envKey, envKey)
  5343. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil || strings.Count(out, envValOveride) != 2 {
  5344. if err != nil {
  5345. c.Fatalf("build failed to complete: %q %q", out, err)
  5346. }
  5347. c.Fatalf("failed to access environment variable in output: %q expected: %q", out, envValOveride)
  5348. }
  5349. containerName := "bldargCont"
  5350. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOveride) {
  5351. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOveride)
  5352. }
  5353. }
  5354. func (s *DockerSuite) TestBuildBuildTimeArgExpansion(c *check.C) {
  5355. testRequires(c, DaemonIsLinux)
  5356. imgName := "bldvarstest"
  5357. wdVar := "WDIR"
  5358. wdVal := "/tmp/"
  5359. addVar := "AFILE"
  5360. addVal := "addFile"
  5361. copyVar := "CFILE"
  5362. copyVal := "copyFile"
  5363. envVar := "foo"
  5364. envVal := "bar"
  5365. exposeVar := "EPORT"
  5366. exposeVal := "9999"
  5367. userVar := "USER"
  5368. userVal := "testUser"
  5369. volVar := "VOL"
  5370. volVal := "/testVol/"
  5371. args := []string{
  5372. "--build-arg", fmt.Sprintf("%s=%s", wdVar, wdVal),
  5373. "--build-arg", fmt.Sprintf("%s=%s", addVar, addVal),
  5374. "--build-arg", fmt.Sprintf("%s=%s", copyVar, copyVal),
  5375. "--build-arg", fmt.Sprintf("%s=%s", envVar, envVal),
  5376. "--build-arg", fmt.Sprintf("%s=%s", exposeVar, exposeVal),
  5377. "--build-arg", fmt.Sprintf("%s=%s", userVar, userVal),
  5378. "--build-arg", fmt.Sprintf("%s=%s", volVar, volVal),
  5379. }
  5380. ctx, err := fakeContext(fmt.Sprintf(`FROM busybox
  5381. ARG %s
  5382. WORKDIR ${%s}
  5383. ARG %s
  5384. ADD ${%s} testDir/
  5385. ARG %s
  5386. COPY $%s testDir/
  5387. ARG %s
  5388. ENV %s=${%s}
  5389. ARG %s
  5390. EXPOSE $%s
  5391. ARG %s
  5392. USER $%s
  5393. ARG %s
  5394. VOLUME ${%s}`,
  5395. wdVar, wdVar, addVar, addVar, copyVar, copyVar, envVar, envVar,
  5396. envVar, exposeVar, exposeVar, userVar, userVar, volVar, volVar),
  5397. map[string]string{
  5398. addVal: "some stuff",
  5399. copyVal: "some stuff",
  5400. })
  5401. if err != nil {
  5402. c.Fatal(err)
  5403. }
  5404. defer ctx.Close()
  5405. if _, err := buildImageFromContext(imgName, ctx, true, args...); err != nil {
  5406. c.Fatal(err)
  5407. }
  5408. var resMap map[string]interface{}
  5409. var resArr []string
  5410. res := ""
  5411. res, err = inspectField(imgName, "Config.WorkingDir")
  5412. if err != nil {
  5413. c.Fatal(err)
  5414. }
  5415. if res != wdVal {
  5416. c.Fatalf("Config.WorkingDir value mismatch. Expected: %s, got: %s", wdVal, res)
  5417. }
  5418. err = inspectFieldAndMarshall(imgName, "Config.Env", &resArr)
  5419. if err != nil {
  5420. c.Fatal(err)
  5421. }
  5422. found := false
  5423. for _, v := range resArr {
  5424. if fmt.Sprintf("%s=%s", envVar, envVal) == v {
  5425. found = true
  5426. break
  5427. }
  5428. }
  5429. if !found {
  5430. c.Fatalf("Config.Env value mismatch. Expected <key=value> to exist: %s=%s, got: %v",
  5431. envVar, envVal, resArr)
  5432. }
  5433. err = inspectFieldAndMarshall(imgName, "Config.ExposedPorts", &resMap)
  5434. if err != nil {
  5435. c.Fatal(err)
  5436. }
  5437. if _, ok := resMap[fmt.Sprintf("%s/tcp", exposeVal)]; !ok {
  5438. c.Fatalf("Config.ExposedPorts value mismatch. Expected exposed port: %s/tcp, got: %v", exposeVal, resMap)
  5439. }
  5440. res, err = inspectField(imgName, "Config.User")
  5441. if err != nil {
  5442. c.Fatal(err)
  5443. }
  5444. if res != userVal {
  5445. c.Fatalf("Config.User value mismatch. Expected: %s, got: %s", userVal, res)
  5446. }
  5447. err = inspectFieldAndMarshall(imgName, "Config.Volumes", &resMap)
  5448. if err != nil {
  5449. c.Fatal(err)
  5450. }
  5451. if _, ok := resMap[volVal]; !ok {
  5452. c.Fatalf("Config.Volumes value mismatch. Expected volume: %s, got: %v", volVal, resMap)
  5453. }
  5454. }
  5455. func (s *DockerSuite) TestBuildBuildTimeArgExpansionOverride(c *check.C) {
  5456. testRequires(c, DaemonIsLinux)
  5457. imgName := "bldvarstest"
  5458. envKey := "foo"
  5459. envVal := "bar"
  5460. envKey1 := "foo1"
  5461. envValOveride := "barOverride"
  5462. args := []string{
  5463. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5464. }
  5465. dockerfile := fmt.Sprintf(`FROM busybox
  5466. ARG %s
  5467. ENV %s %s
  5468. ENV %s ${%s}
  5469. RUN echo $%s
  5470. CMD echo $%s`, envKey, envKey, envValOveride, envKey1, envKey, envKey1, envKey1)
  5471. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil || strings.Count(out, envValOveride) != 2 {
  5472. if err != nil {
  5473. c.Fatalf("build failed to complete: %q %q", out, err)
  5474. }
  5475. c.Fatalf("failed to access environment variable in output: %q expected: %q", out, envValOveride)
  5476. }
  5477. containerName := "bldargCont"
  5478. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOveride) {
  5479. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOveride)
  5480. }
  5481. }
  5482. func (s *DockerSuite) TestBuildBuildTimeArgUntrustedDefinedAfterUse(c *check.C) {
  5483. testRequires(c, DaemonIsLinux)
  5484. imgName := "bldargtest"
  5485. envKey := "foo"
  5486. envVal := "bar"
  5487. args := []string{
  5488. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5489. }
  5490. dockerfile := fmt.Sprintf(`FROM busybox
  5491. RUN echo $%s
  5492. ARG %s
  5493. CMD echo $%s`, envKey, envKey, envKey)
  5494. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil || strings.Contains(out, envVal) {
  5495. if err != nil {
  5496. c.Fatalf("build failed to complete: %q %q", out, err)
  5497. }
  5498. c.Fatalf("able to access environment variable in output: %q expected to be missing", out)
  5499. }
  5500. containerName := "bldargCont"
  5501. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); out != "\n" {
  5502. c.Fatalf("run produced invalid output: %q, expected empty string", out)
  5503. }
  5504. }
  5505. func (s *DockerSuite) TestBuildBuildTimeArgBuiltinArg(c *check.C) {
  5506. testRequires(c, DaemonIsLinux)
  5507. imgName := "bldargtest"
  5508. envKey := "HTTP_PROXY"
  5509. envVal := "bar"
  5510. args := []string{
  5511. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5512. }
  5513. dockerfile := fmt.Sprintf(`FROM busybox
  5514. RUN echo $%s
  5515. CMD echo $%s`, envKey, envKey)
  5516. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil || !strings.Contains(out, envVal) {
  5517. if err != nil {
  5518. c.Fatalf("build failed to complete: %q %q", out, err)
  5519. }
  5520. c.Fatalf("failed to access environment variable in output: %q expected: %q", out, envVal)
  5521. }
  5522. containerName := "bldargCont"
  5523. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); out != "\n" {
  5524. c.Fatalf("run produced invalid output: %q, expected empty string", out)
  5525. }
  5526. }
  5527. func (s *DockerSuite) TestBuildBuildTimeArgDefaultOverride(c *check.C) {
  5528. testRequires(c, DaemonIsLinux)
  5529. imgName := "bldargtest"
  5530. envKey := "foo"
  5531. envVal := "bar"
  5532. envValOveride := "barOverride"
  5533. args := []string{
  5534. "--build-arg", fmt.Sprintf("%s=%s", envKey, envValOveride),
  5535. }
  5536. dockerfile := fmt.Sprintf(`FROM busybox
  5537. ARG %s=%s
  5538. ENV %s $%s
  5539. RUN echo $%s
  5540. CMD echo $%s`, envKey, envVal, envKey, envKey, envKey, envKey)
  5541. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil || strings.Count(out, envValOveride) != 1 {
  5542. if err != nil {
  5543. c.Fatalf("build failed to complete: %q %q", out, err)
  5544. }
  5545. c.Fatalf("failed to access environment variable in output: %q expected: %q", out, envValOveride)
  5546. }
  5547. containerName := "bldargCont"
  5548. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOveride) {
  5549. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOveride)
  5550. }
  5551. }
  5552. func (s *DockerSuite) TestBuildBuildTimeArgMultiArgsSameLine(c *check.C) {
  5553. testRequires(c, DaemonIsLinux)
  5554. imgName := "bldargtest"
  5555. envKey := "foo"
  5556. envKey1 := "foo1"
  5557. args := []string{}
  5558. dockerfile := fmt.Sprintf(`FROM busybox
  5559. ARG %s %s`, envKey, envKey1)
  5560. errStr := "ARG requires exactly one argument definition"
  5561. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err == nil {
  5562. c.Fatalf("build succeeded, expected to fail. Output: %v", out)
  5563. } else if !strings.Contains(out, errStr) {
  5564. c.Fatalf("Unexpected error. output: %q, expected error: %q", out, errStr)
  5565. }
  5566. }
  5567. func (s *DockerSuite) TestBuildBuildTimeArgUnconsumedArg(c *check.C) {
  5568. testRequires(c, DaemonIsLinux)
  5569. imgName := "bldargtest"
  5570. envKey := "foo"
  5571. envVal := "bar"
  5572. args := []string{
  5573. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  5574. }
  5575. dockerfile := fmt.Sprintf(`FROM busybox
  5576. RUN echo $%s
  5577. CMD echo $%s`, envKey, envKey)
  5578. errStr := "One or more build-args"
  5579. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err == nil {
  5580. c.Fatalf("build succeeded, expected to fail. Output: %v", out)
  5581. } else if !strings.Contains(out, errStr) {
  5582. c.Fatalf("Unexpected error. output: %q, expected error: %q", out, errStr)
  5583. }
  5584. }
  5585. func (s *DockerSuite) TestBuildBuildTimeArgQuotedValVariants(c *check.C) {
  5586. testRequires(c, DaemonIsLinux)
  5587. imgName := "bldargtest"
  5588. envKey := "foo"
  5589. envKey1 := "foo1"
  5590. envKey2 := "foo2"
  5591. envKey3 := "foo3"
  5592. args := []string{}
  5593. dockerfile := fmt.Sprintf(`FROM busybox
  5594. ARG %s=""
  5595. ARG %s=''
  5596. ARG %s="''"
  5597. ARG %s='""'
  5598. RUN [ "$%s" != "$%s" ]
  5599. RUN [ "$%s" != "$%s" ]
  5600. RUN [ "$%s" != "$%s" ]
  5601. RUN [ "$%s" != "$%s" ]
  5602. RUN [ "$%s" != "$%s" ]`, envKey, envKey1, envKey2, envKey3,
  5603. envKey, envKey2, envKey, envKey3, envKey1, envKey2, envKey1, envKey3,
  5604. envKey2, envKey3)
  5605. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil {
  5606. c.Fatalf("build failed to complete: %q %q", out, err)
  5607. }
  5608. }
  5609. func (s *DockerSuite) TestBuildBuildTimeArgEmptyValVariants(c *check.C) {
  5610. testRequires(c, DaemonIsLinux)
  5611. imgName := "bldargtest"
  5612. envKey := "foo"
  5613. envKey1 := "foo1"
  5614. envKey2 := "foo2"
  5615. args := []string{}
  5616. dockerfile := fmt.Sprintf(`FROM busybox
  5617. ARG %s=
  5618. ARG %s=""
  5619. ARG %s=''
  5620. RUN [ "$%s" == "$%s" ]
  5621. RUN [ "$%s" == "$%s" ]
  5622. RUN [ "$%s" == "$%s" ]`, envKey, envKey1, envKey2, envKey, envKey1, envKey1, envKey2, envKey, envKey2)
  5623. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil {
  5624. c.Fatalf("build failed to complete: %q %q", out, err)
  5625. }
  5626. }
  5627. func (s *DockerSuite) TestBuildBuildTimeArgDefintionWithNoEnvInjection(c *check.C) {
  5628. testRequires(c, DaemonIsLinux)
  5629. imgName := "bldargtest"
  5630. envKey := "foo"
  5631. args := []string{}
  5632. dockerfile := fmt.Sprintf(`FROM busybox
  5633. ARG %s
  5634. RUN env`, envKey)
  5635. if _, out, err := buildImageWithOut(imgName, dockerfile, true, args...); err != nil || strings.Count(out, envKey) != 1 {
  5636. if err != nil {
  5637. c.Fatalf("build failed to complete: %q %q", out, err)
  5638. }
  5639. c.Fatalf("unexpected number of occurrences of the arg in output: %q expected: 1", out)
  5640. }
  5641. }
  5642. func (s *DockerSuite) TestBuildNoNamedVolume(c *check.C) {
  5643. testRequires(c, DaemonIsLinux)
  5644. dockerCmd(c, "run", "-v", "testname:/foo", "busybox", "sh", "-c", "touch /foo/oops")
  5645. dockerFile := `FROM busybox
  5646. VOLUME testname:/foo
  5647. RUN ls /foo/oops
  5648. `
  5649. _, err := buildImage("test", dockerFile, false)
  5650. c.Assert(err, check.NotNil, check.Commentf("image build should have failed"))
  5651. }
  5652. func (s *DockerSuite) TestBuildTagEvent(c *check.C) {
  5653. testRequires(c, DaemonIsLinux)
  5654. since := daemonTime(c).Unix()
  5655. dockerFile := `FROM busybox
  5656. RUN echo events
  5657. `
  5658. _, err := buildImage("test", dockerFile, false)
  5659. c.Assert(err, check.IsNil)
  5660. out, _ := dockerCmd(c, "events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()), "--filter", "type=image")
  5661. events := strings.Split(strings.TrimSpace(out), "\n")
  5662. actions := eventActionsByIDAndType(c, events, "test:latest", "image")
  5663. var foundTag bool
  5664. for _, a := range actions {
  5665. if a == "tag" {
  5666. foundTag = true
  5667. break
  5668. }
  5669. }
  5670. c.Assert(foundTag, checker.True, check.Commentf("No tag event found:\n%s", out))
  5671. }
  5672. // #15780
  5673. func (s *DockerSuite) TestBuildMultipleTags(c *check.C) {
  5674. dockerfile := `
  5675. FROM busybox
  5676. MAINTAINER test-15780
  5677. `
  5678. cmd := exec.Command(dockerBinary, "build", "-t", "tag1", "-t", "tag2:v2",
  5679. "-t", "tag1:latest", "-t", "tag1", "--no-cache", "-")
  5680. cmd.Stdin = strings.NewReader(dockerfile)
  5681. _, err := runCommand(cmd)
  5682. c.Assert(err, check.IsNil)
  5683. id1, err := getIDByName("tag1")
  5684. c.Assert(err, check.IsNil)
  5685. id2, err := getIDByName("tag2:v2")
  5686. c.Assert(err, check.IsNil)
  5687. c.Assert(id1, check.Equals, id2)
  5688. }
  5689. // #17290
  5690. func (s *DockerSuite) TestBuildCacheBrokenSymlink(c *check.C) {
  5691. testRequires(c, DaemonIsLinux)
  5692. name := "testbuildbrokensymlink"
  5693. ctx, err := fakeContext(`
  5694. FROM busybox
  5695. COPY . ./`,
  5696. map[string]string{
  5697. "foo": "bar",
  5698. })
  5699. c.Assert(err, checker.IsNil)
  5700. defer ctx.Close()
  5701. err = os.Symlink(filepath.Join(ctx.Dir, "nosuchfile"), filepath.Join(ctx.Dir, "asymlink"))
  5702. c.Assert(err, checker.IsNil)
  5703. // warm up cache
  5704. _, err = buildImageFromContext(name, ctx, true)
  5705. c.Assert(err, checker.IsNil)
  5706. // add new file to context, should invalidate cache
  5707. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "newfile"), []byte("foo"), 0644)
  5708. c.Assert(err, checker.IsNil)
  5709. _, out, err := buildImageFromContextWithOut(name, ctx, true)
  5710. c.Assert(err, checker.IsNil)
  5711. c.Assert(out, checker.Not(checker.Contains), "Using cache")
  5712. }
  5713. func (s *DockerSuite) TestBuildFollowSymlinkToFile(c *check.C) {
  5714. testRequires(c, DaemonIsLinux)
  5715. name := "testbuildbrokensymlink"
  5716. ctx, err := fakeContext(`
  5717. FROM busybox
  5718. COPY asymlink target`,
  5719. map[string]string{
  5720. "foo": "bar",
  5721. })
  5722. c.Assert(err, checker.IsNil)
  5723. defer ctx.Close()
  5724. err = os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink"))
  5725. c.Assert(err, checker.IsNil)
  5726. id, err := buildImageFromContext(name, ctx, true)
  5727. c.Assert(err, checker.IsNil)
  5728. out, _ := dockerCmd(c, "run", "--rm", id, "cat", "target")
  5729. c.Assert(out, checker.Matches, "bar")
  5730. // change target file should invalidate cache
  5731. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "foo"), []byte("baz"), 0644)
  5732. c.Assert(err, checker.IsNil)
  5733. id, out, err = buildImageFromContextWithOut(name, ctx, true)
  5734. c.Assert(err, checker.IsNil)
  5735. c.Assert(out, checker.Not(checker.Contains), "Using cache")
  5736. out, _ = dockerCmd(c, "run", "--rm", id, "cat", "target")
  5737. c.Assert(out, checker.Matches, "baz")
  5738. }
  5739. func (s *DockerSuite) TestBuildFollowSymlinkToDir(c *check.C) {
  5740. testRequires(c, DaemonIsLinux)
  5741. name := "testbuildbrokensymlink"
  5742. ctx, err := fakeContext(`
  5743. FROM busybox
  5744. COPY asymlink /`,
  5745. map[string]string{
  5746. "foo/abc": "bar",
  5747. "foo/def": "baz",
  5748. })
  5749. c.Assert(err, checker.IsNil)
  5750. defer ctx.Close()
  5751. err = os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink"))
  5752. c.Assert(err, checker.IsNil)
  5753. id, err := buildImageFromContext(name, ctx, true)
  5754. c.Assert(err, checker.IsNil)
  5755. out, _ := dockerCmd(c, "run", "--rm", id, "cat", "abc", "def")
  5756. c.Assert(out, checker.Matches, "barbaz")
  5757. // change target file should invalidate cache
  5758. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "foo/def"), []byte("bax"), 0644)
  5759. c.Assert(err, checker.IsNil)
  5760. id, out, err = buildImageFromContextWithOut(name, ctx, true)
  5761. c.Assert(err, checker.IsNil)
  5762. c.Assert(out, checker.Not(checker.Contains), "Using cache")
  5763. out, _ = dockerCmd(c, "run", "--rm", id, "cat", "abc", "def")
  5764. c.Assert(out, checker.Matches, "barbax")
  5765. }
  5766. // TestBuildSymlinkBasename tests that target file gets basename from symlink,
  5767. // not from the target file.
  5768. func (s *DockerSuite) TestBuildSymlinkBasename(c *check.C) {
  5769. testRequires(c, DaemonIsLinux)
  5770. name := "testbuildbrokensymlink"
  5771. ctx, err := fakeContext(`
  5772. FROM busybox
  5773. COPY asymlink /`,
  5774. map[string]string{
  5775. "foo": "bar",
  5776. })
  5777. c.Assert(err, checker.IsNil)
  5778. defer ctx.Close()
  5779. err = os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink"))
  5780. c.Assert(err, checker.IsNil)
  5781. id, err := buildImageFromContext(name, ctx, true)
  5782. c.Assert(err, checker.IsNil)
  5783. out, _ := dockerCmd(c, "run", "--rm", id, "cat", "asymlink")
  5784. c.Assert(out, checker.Matches, "bar")
  5785. }
  5786. // #17827
  5787. func (s *DockerSuite) TestBuildCacheRootSource(c *check.C) {
  5788. testRequires(c, DaemonIsLinux)
  5789. name := "testbuildrootsource"
  5790. ctx, err := fakeContext(`
  5791. FROM busybox
  5792. COPY / /data`,
  5793. map[string]string{
  5794. "foo": "bar",
  5795. })
  5796. c.Assert(err, checker.IsNil)
  5797. defer ctx.Close()
  5798. // warm up cache
  5799. _, err = buildImageFromContext(name, ctx, true)
  5800. c.Assert(err, checker.IsNil)
  5801. // change file, should invalidate cache
  5802. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "foo"), []byte("baz"), 0644)
  5803. c.Assert(err, checker.IsNil)
  5804. _, out, err := buildImageFromContextWithOut(name, ctx, true)
  5805. c.Assert(err, checker.IsNil)
  5806. c.Assert(out, checker.Not(checker.Contains), "Using cache")
  5807. }