docker_cli_build_test.go 185 KB

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