docker_cli_build_test.go 206 KB

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