docker_cli_build_test.go 186 KB

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