docker_cli_build_test.go 206 KB

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