docker_cli_build_test.go 187 KB

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