docker_cli_build_test.go 194 KB

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