docker_cli_build_test.go 188 KB

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