docker_cli_build_test.go 195 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191
  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. "testing"
  16. "text/template"
  17. "time"
  18. "github.com/docker/docker/integration-cli/cli"
  19. "github.com/docker/docker/integration-cli/cli/build"
  20. "github.com/docker/docker/pkg/archive"
  21. "github.com/docker/docker/pkg/system"
  22. "github.com/docker/docker/testutil"
  23. "github.com/docker/docker/testutil/fakecontext"
  24. "github.com/docker/docker/testutil/fakegit"
  25. "github.com/docker/docker/testutil/fakestorage"
  26. "github.com/moby/buildkit/frontend/dockerfile/command"
  27. digest "github.com/opencontainers/go-digest"
  28. "gotest.tools/v3/assert"
  29. "gotest.tools/v3/assert/cmp"
  30. "gotest.tools/v3/icmd"
  31. )
  32. func (s *DockerSuite) TestBuildJSONEmptyRun(c *testing.T) {
  33. cli.BuildCmd(c, "testbuildjsonemptyrun", build.WithDockerfile(`
  34. FROM busybox
  35. RUN []
  36. `))
  37. }
  38. func (s *DockerSuite) TestBuildShCmdJSONEntrypoint(c *testing.T) {
  39. name := "testbuildshcmdjsonentrypoint"
  40. expected := "/bin/sh -c echo test"
  41. if testEnv.OSType == "windows" {
  42. expected = "cmd /S /C echo test"
  43. }
  44. buildImageSuccessfully(c, name, build.WithDockerfile(`
  45. FROM busybox
  46. ENTRYPOINT ["echo"]
  47. CMD echo test
  48. `))
  49. out, _ := dockerCmd(c, "run", "--rm", name)
  50. if strings.TrimSpace(out) != expected {
  51. c.Fatalf("CMD did not contain %q : %q", expected, out)
  52. }
  53. }
  54. func (s *DockerSuite) TestBuildEnvironmentReplacementUser(c *testing.T) {
  55. // Windows does not support FROM scratch or the USER command
  56. testRequires(c, DaemonIsLinux)
  57. name := "testbuildenvironmentreplacement"
  58. buildImageSuccessfully(c, name, build.WithDockerfile(`
  59. FROM scratch
  60. ENV user foo
  61. USER ${user}
  62. `))
  63. res := inspectFieldJSON(c, name, "Config.User")
  64. if res != `"foo"` {
  65. c.Fatal("User foo from environment not in Config.User on image")
  66. }
  67. }
  68. func (s *DockerSuite) TestBuildEnvironmentReplacementVolume(c *testing.T) {
  69. name := "testbuildenvironmentreplacement"
  70. var volumePath string
  71. if testEnv.OSType == "windows" {
  72. volumePath = "c:/quux"
  73. } else {
  74. volumePath = "/quux"
  75. }
  76. buildImageSuccessfully(c, name, build.WithDockerfile(`
  77. FROM `+minimalBaseImage()+`
  78. ENV volume `+volumePath+`
  79. VOLUME ${volume}
  80. `))
  81. var volumes map[string]interface{}
  82. inspectFieldAndUnmarshall(c, name, "Config.Volumes", &volumes)
  83. if _, ok := volumes[volumePath]; !ok {
  84. c.Fatal("Volume " + volumePath + " from environment not in Config.Volumes on image")
  85. }
  86. }
  87. func (s *DockerSuite) TestBuildEnvironmentReplacementExpose(c *testing.T) {
  88. // Windows does not support FROM scratch or the EXPOSE command
  89. testRequires(c, DaemonIsLinux)
  90. name := "testbuildenvironmentreplacement"
  91. buildImageSuccessfully(c, name, build.WithDockerfile(`
  92. FROM scratch
  93. ENV port 80
  94. EXPOSE ${port}
  95. ENV ports " 99 100 "
  96. EXPOSE ${ports}
  97. `))
  98. var exposedPorts map[string]interface{}
  99. inspectFieldAndUnmarshall(c, name, "Config.ExposedPorts", &exposedPorts)
  100. exp := []int{80, 99, 100}
  101. for _, p := range exp {
  102. tmp := fmt.Sprintf("%d/tcp", p)
  103. if _, ok := exposedPorts[tmp]; !ok {
  104. c.Fatalf("Exposed port %d from environment not in Config.ExposedPorts on image", p)
  105. }
  106. }
  107. }
  108. func (s *DockerSuite) TestBuildEnvironmentReplacementWorkdir(c *testing.T) {
  109. name := "testbuildenvironmentreplacement"
  110. buildImageSuccessfully(c, name, build.WithDockerfile(`
  111. FROM busybox
  112. ENV MYWORKDIR /work
  113. RUN mkdir ${MYWORKDIR}
  114. WORKDIR ${MYWORKDIR}
  115. `))
  116. res := inspectFieldJSON(c, name, "Config.WorkingDir")
  117. expected := `"/work"`
  118. if testEnv.OSType == "windows" {
  119. expected = `"C:\\work"`
  120. }
  121. if res != expected {
  122. c.Fatalf("Workdir /workdir from environment not in Config.WorkingDir on image: %s", res)
  123. }
  124. }
  125. func (s *DockerSuite) TestBuildEnvironmentReplacementAddCopy(c *testing.T) {
  126. name := "testbuildenvironmentreplacement"
  127. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  128. build.WithFile("Dockerfile", `
  129. FROM `+minimalBaseImage()+`
  130. ENV baz foo
  131. ENV quux bar
  132. ENV dot .
  133. ENV fee fff
  134. ENV gee ggg
  135. ADD ${baz} ${dot}
  136. COPY ${quux} ${dot}
  137. ADD ${zzz:-${fee}} ${dot}
  138. COPY ${zzz:-${gee}} ${dot}
  139. `),
  140. build.WithFile("foo", "test1"),
  141. build.WithFile("bar", "test2"),
  142. build.WithFile("fff", "test3"),
  143. build.WithFile("ggg", "test4"),
  144. ))
  145. }
  146. func (s *DockerSuite) TestBuildEnvironmentReplacementEnv(c *testing.T) {
  147. // ENV expansions work differently in Windows
  148. testRequires(c, DaemonIsLinux)
  149. name := "testbuildenvironmentreplacement"
  150. buildImageSuccessfully(c, name, build.WithDockerfile(`
  151. FROM busybox
  152. ENV foo zzz
  153. ENV bar ${foo}
  154. ENV abc1='$foo'
  155. ENV env1=$foo env2=${foo} env3="$foo" env4="${foo}"
  156. RUN [ "$abc1" = '$foo' ] && (echo "$abc1" | grep -q foo)
  157. ENV abc2="\$foo"
  158. RUN [ "$abc2" = '$foo' ] && (echo "$abc2" | grep -q foo)
  159. ENV abc3 '$foo'
  160. RUN [ "$abc3" = '$foo' ] && (echo "$abc3" | grep -q foo)
  161. ENV abc4 "\$foo"
  162. RUN [ "$abc4" = '$foo' ] && (echo "$abc4" | grep -q foo)
  163. ENV foo2="abc\def"
  164. RUN [ "$foo2" = 'abc\def' ]
  165. ENV foo3="abc\\def"
  166. RUN [ "$foo3" = 'abc\def' ]
  167. ENV foo4='abc\\def'
  168. RUN [ "$foo4" = 'abc\\def' ]
  169. ENV foo5='abc\def'
  170. RUN [ "$foo5" = 'abc\def' ]
  171. `))
  172. var envResult []string
  173. inspectFieldAndUnmarshall(c, name, "Config.Env", &envResult)
  174. found := false
  175. envCount := 0
  176. for _, env := range envResult {
  177. parts := strings.SplitN(env, "=", 2)
  178. if parts[0] == "bar" {
  179. found = true
  180. if parts[1] != "zzz" {
  181. c.Fatalf("Could not find replaced var for env `bar`: got %q instead of `zzz`", parts[1])
  182. }
  183. } else if strings.HasPrefix(parts[0], "env") {
  184. envCount++
  185. if parts[1] != "zzz" {
  186. c.Fatalf("%s should be 'zzz' but instead its %q", parts[0], parts[1])
  187. }
  188. } else if strings.HasPrefix(parts[0], "env") {
  189. envCount++
  190. if parts[1] != "foo" {
  191. c.Fatalf("%s should be 'foo' but instead its %q", parts[0], parts[1])
  192. }
  193. }
  194. }
  195. if !found {
  196. c.Fatal("Never found the `bar` env variable")
  197. }
  198. if envCount != 4 {
  199. c.Fatalf("Didn't find all env vars - only saw %d\n%s", envCount, envResult)
  200. }
  201. }
  202. func (s *DockerSuite) TestBuildHandleEscapesInVolume(c *testing.T) {
  203. // The volume paths used in this test are invalid on Windows
  204. testRequires(c, DaemonIsLinux)
  205. name := "testbuildhandleescapes"
  206. testCases := []struct {
  207. volumeValue string
  208. expected string
  209. }{
  210. {
  211. volumeValue: "${FOO}",
  212. expected: "bar",
  213. },
  214. {
  215. volumeValue: `\${FOO}`,
  216. expected: "${FOO}",
  217. },
  218. // this test in particular provides *7* backslashes and expects 6 to come back.
  219. // Like above, the first escape is swallowed and the rest are treated as
  220. // literals, this one is just less obvious because of all the character noise.
  221. {
  222. volumeValue: `\\\\\\\${FOO}`,
  223. expected: `\\\${FOO}`,
  224. },
  225. }
  226. for _, tc := range testCases {
  227. buildImageSuccessfully(c, name, build.WithDockerfile(fmt.Sprintf(`
  228. FROM scratch
  229. ENV FOO bar
  230. VOLUME %s
  231. `, tc.volumeValue)))
  232. var result map[string]map[string]struct{}
  233. inspectFieldAndUnmarshall(c, name, "Config.Volumes", &result)
  234. if _, ok := result[tc.expected]; !ok {
  235. c.Fatalf("Could not find volume %s set from env foo in volumes table, got %q", tc.expected, result)
  236. }
  237. // Remove the image for the next iteration
  238. dockerCmd(c, "rmi", name)
  239. }
  240. }
  241. func (s *DockerSuite) TestBuildOnBuildLowercase(c *testing.T) {
  242. name := "testbuildonbuildlowercase"
  243. name2 := "testbuildonbuildlowercase2"
  244. buildImageSuccessfully(c, name, build.WithDockerfile(`
  245. FROM busybox
  246. onbuild run echo quux
  247. `))
  248. result := buildImage(name2, build.WithDockerfile(fmt.Sprintf(`
  249. FROM %s
  250. `, name)))
  251. result.Assert(c, icmd.Success)
  252. if !strings.Contains(result.Combined(), "quux") {
  253. c.Fatalf("Did not receive the expected echo text, got %s", result.Combined())
  254. }
  255. if strings.Contains(result.Combined(), "ONBUILD ONBUILD") {
  256. c.Fatalf("Got an ONBUILD ONBUILD error with no error: got %s", result.Combined())
  257. }
  258. }
  259. func (s *DockerSuite) TestBuildEnvEscapes(c *testing.T) {
  260. // ENV expansions work differently in Windows
  261. testRequires(c, DaemonIsLinux)
  262. name := "testbuildenvescapes"
  263. buildImageSuccessfully(c, name, build.WithDockerfile(`
  264. FROM busybox
  265. ENV TEST foo
  266. CMD echo \$
  267. `))
  268. out, _ := dockerCmd(c, "run", "-t", name)
  269. if strings.TrimSpace(out) != "$" {
  270. c.Fatalf("Env TEST was not overwritten with bar when foo was supplied to dockerfile: was %q", strings.TrimSpace(out))
  271. }
  272. }
  273. func (s *DockerSuite) TestBuildEnvOverwrite(c *testing.T) {
  274. // ENV expansions work differently in Windows
  275. testRequires(c, DaemonIsLinux)
  276. name := "testbuildenvoverwrite"
  277. buildImageSuccessfully(c, name, build.WithDockerfile(`
  278. FROM busybox
  279. ENV TEST foo
  280. CMD echo ${TEST}
  281. `))
  282. out, _ := dockerCmd(c, "run", "-e", "TEST=bar", "-t", name)
  283. if strings.TrimSpace(out) != "bar" {
  284. c.Fatalf("Env TEST was not overwritten with bar when foo was supplied to dockerfile: was %q", strings.TrimSpace(out))
  285. }
  286. }
  287. // FIXME(vdemeester) why we disabled cache here ?
  288. func (s *DockerSuite) TestBuildOnBuildCmdEntrypointJSON(c *testing.T) {
  289. name1 := "onbuildcmd"
  290. name2 := "onbuildgenerated"
  291. cli.BuildCmd(c, name1, build.WithDockerfile(`
  292. FROM busybox
  293. ONBUILD CMD ["hello world"]
  294. ONBUILD ENTRYPOINT ["echo"]
  295. ONBUILD RUN ["true"]`))
  296. cli.BuildCmd(c, name2, build.WithDockerfile(fmt.Sprintf(`FROM %s`, name1)))
  297. result := cli.DockerCmd(c, "run", name2)
  298. result.Assert(c, icmd.Expected{Out: "hello world"})
  299. }
  300. // FIXME(vdemeester) why we disabled cache here ?
  301. func (s *DockerSuite) TestBuildOnBuildEntrypointJSON(c *testing.T) {
  302. name1 := "onbuildcmd"
  303. name2 := "onbuildgenerated"
  304. buildImageSuccessfully(c, name1, build.WithDockerfile(`
  305. FROM busybox
  306. ONBUILD ENTRYPOINT ["echo"]`))
  307. buildImageSuccessfully(c, name2, build.WithDockerfile(fmt.Sprintf("FROM %s\nCMD [\"hello world\"]\n", name1)))
  308. out, _ := dockerCmd(c, "run", name2)
  309. if !regexp.MustCompile(`(?m)^hello world`).MatchString(out) {
  310. c.Fatal("got malformed output from onbuild", out)
  311. }
  312. }
  313. func (s *DockerSuite) TestBuildCacheAdd(c *testing.T) {
  314. testRequires(c, DaemonIsLinux) // Windows doesn't have httpserver image yet
  315. name := "testbuildtwoimageswithadd"
  316. server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{
  317. "robots.txt": "hello",
  318. "index.html": "world",
  319. }))
  320. defer server.Close()
  321. cli.BuildCmd(c, name, build.WithDockerfile(fmt.Sprintf(`FROM scratch
  322. ADD %s/robots.txt /`, server.URL())))
  323. result := cli.Docker(cli.Build(name), build.WithDockerfile(fmt.Sprintf(`FROM scratch
  324. ADD %s/index.html /`, server.URL())))
  325. result.Assert(c, icmd.Success)
  326. if strings.Contains(result.Combined(), "Using cache") {
  327. c.Fatal("2nd build used cache on ADD, it shouldn't")
  328. }
  329. }
  330. func (s *DockerSuite) TestBuildLastModified(c *testing.T) {
  331. // Temporary fix for #30890. TODO: figure out what
  332. // has changed in the master busybox image.
  333. testRequires(c, DaemonIsLinux)
  334. name := "testbuildlastmodified"
  335. server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{
  336. "file": "hello",
  337. }))
  338. defer server.Close()
  339. var out, out2 string
  340. args := []string{"run", name, "ls", "-l", "--full-time", "/file"}
  341. dFmt := `FROM busybox
  342. ADD %s/file /`
  343. dockerfile := fmt.Sprintf(dFmt, server.URL())
  344. cli.BuildCmd(c, name, build.WithoutCache, build.WithDockerfile(dockerfile))
  345. out = cli.DockerCmd(c, args...).Combined()
  346. // Build it again and make sure the mtime of the file didn't change.
  347. // Wait a few seconds to make sure the time changed enough to notice
  348. time.Sleep(2 * time.Second)
  349. cli.BuildCmd(c, name, build.WithoutCache, build.WithDockerfile(dockerfile))
  350. out2 = cli.DockerCmd(c, args...).Combined()
  351. if out != out2 {
  352. c.Fatalf("MTime changed:\nOrigin:%s\nNew:%s", out, out2)
  353. }
  354. // Now 'touch' the file and make sure the timestamp DID change this time
  355. // Create a new fakeStorage instead of just using Add() to help windows
  356. server = fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{
  357. "file": "hello",
  358. }))
  359. defer server.Close()
  360. dockerfile = fmt.Sprintf(dFmt, server.URL())
  361. cli.BuildCmd(c, name, build.WithoutCache, build.WithDockerfile(dockerfile))
  362. out2 = cli.DockerCmd(c, args...).Combined()
  363. if out == out2 {
  364. c.Fatalf("MTime didn't change:\nOrigin:%s\nNew:%s", out, out2)
  365. }
  366. }
  367. // Regression for https://github.com/docker/docker/pull/27805
  368. // Makes sure that we don't use the cache if the contents of
  369. // a file in a subfolder of the context is modified and we re-build.
  370. func (s *DockerSuite) TestBuildModifyFileInFolder(c *testing.T) {
  371. name := "testbuildmodifyfileinfolder"
  372. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(`FROM busybox
  373. RUN ["mkdir", "/test"]
  374. ADD folder/file /test/changetarget`))
  375. defer ctx.Close()
  376. if err := ctx.Add("folder/file", "first"); err != nil {
  377. c.Fatal(err)
  378. }
  379. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  380. id1 := getIDByName(c, name)
  381. if err := ctx.Add("folder/file", "second"); err != nil {
  382. c.Fatal(err)
  383. }
  384. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  385. id2 := getIDByName(c, name)
  386. if id1 == id2 {
  387. c.Fatal("cache was used even though file contents in folder was changed")
  388. }
  389. }
  390. func (s *DockerSuite) TestBuildAddSingleFileToRoot(c *testing.T) {
  391. testRequires(c, DaemonIsLinux) // Linux specific test
  392. buildImageSuccessfully(c, "testaddimg", build.WithBuildContext(c,
  393. build.WithFile("Dockerfile", fmt.Sprintf(`FROM busybox
  394. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  395. RUN echo 'dockerio:x:1001:' >> /etc/group
  396. RUN touch /exists
  397. RUN chown dockerio.dockerio /exists
  398. ADD test_file /
  399. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  400. RUN [ $(ls -l /test_file | awk '{print $1}') = '%s' ]
  401. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod)),
  402. build.WithFile("test_file", "test1")))
  403. }
  404. // Issue #3960: "ADD src ." hangs
  405. func (s *DockerSuite) TestBuildAddSingleFileToWorkdir(c *testing.T) {
  406. name := "testaddsinglefiletoworkdir"
  407. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(
  408. `FROM busybox
  409. ADD test_file .`),
  410. fakecontext.WithFiles(map[string]string{
  411. "test_file": "test1",
  412. }))
  413. defer ctx.Close()
  414. errChan := make(chan error, 1)
  415. go func() {
  416. errChan <- buildImage(name, build.WithExternalBuildContext(ctx)).Error
  417. close(errChan)
  418. }()
  419. select {
  420. case <-time.After(15 * time.Second):
  421. c.Fatal("Build with adding to workdir timed out")
  422. case err := <-errChan:
  423. assert.NilError(c, err)
  424. }
  425. }
  426. func (s *DockerSuite) TestBuildAddSingleFileToExistDir(c *testing.T) {
  427. testRequires(c, DaemonIsLinux) // Linux specific test
  428. cli.BuildCmd(c, "testaddsinglefiletoexistdir", build.WithBuildContext(c,
  429. build.WithFile("Dockerfile", `FROM busybox
  430. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  431. RUN echo 'dockerio:x:1001:' >> /etc/group
  432. RUN mkdir /exists
  433. RUN touch /exists/exists_file
  434. RUN chown -R dockerio.dockerio /exists
  435. ADD test_file /exists/
  436. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  437. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]
  438. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`),
  439. build.WithFile("test_file", "test1")))
  440. }
  441. func (s *DockerSuite) TestBuildCopyAddMultipleFiles(c *testing.T) {
  442. testRequires(c, DaemonIsLinux) // Linux specific test
  443. server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{
  444. "robots.txt": "hello",
  445. }))
  446. defer server.Close()
  447. cli.BuildCmd(c, "testcopymultiplefilestofile", build.WithBuildContext(c,
  448. build.WithFile("Dockerfile", fmt.Sprintf(`FROM busybox
  449. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  450. RUN echo 'dockerio:x:1001:' >> /etc/group
  451. RUN mkdir /exists
  452. RUN touch /exists/exists_file
  453. RUN chown -R dockerio.dockerio /exists
  454. COPY test_file1 test_file2 /exists/
  455. ADD test_file3 test_file4 %s/robots.txt /exists/
  456. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  457. RUN [ $(ls -l /exists/test_file1 | awk '{print $3":"$4}') = 'root:root' ]
  458. RUN [ $(ls -l /exists/test_file2 | awk '{print $3":"$4}') = 'root:root' ]
  459. RUN [ $(ls -l /exists/test_file3 | awk '{print $3":"$4}') = 'root:root' ]
  460. RUN [ $(ls -l /exists/test_file4 | awk '{print $3":"$4}') = 'root:root' ]
  461. RUN [ $(ls -l /exists/robots.txt | awk '{print $3":"$4}') = 'root:root' ]
  462. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  463. `, server.URL())),
  464. build.WithFile("test_file1", "test1"),
  465. build.WithFile("test_file2", "test2"),
  466. build.WithFile("test_file3", "test3"),
  467. build.WithFile("test_file3", "test3"),
  468. build.WithFile("test_file4", "test4")))
  469. }
  470. // These tests are mainly for user namespaces to verify that new directories
  471. // are created as the remapped root uid/gid pair
  472. func (s *DockerSuite) TestBuildUsernamespaceValidateRemappedRoot(c *testing.T) {
  473. testRequires(c, DaemonIsLinux)
  474. testCases := []string{
  475. "ADD . /new_dir",
  476. "COPY test_dir /new_dir",
  477. "WORKDIR /new_dir",
  478. }
  479. name := "testbuildusernamespacevalidateremappedroot"
  480. for _, tc := range testCases {
  481. cli.BuildCmd(c, name, build.WithBuildContext(c,
  482. build.WithFile("Dockerfile", fmt.Sprintf(`FROM busybox
  483. %s
  484. RUN [ $(ls -l / | grep new_dir | awk '{print $3":"$4}') = 'root:root' ]`, tc)),
  485. build.WithFile("test_dir/test_file", "test file")))
  486. cli.DockerCmd(c, "rmi", name)
  487. }
  488. }
  489. func (s *DockerSuite) TestBuildAddAndCopyFileWithWhitespace(c *testing.T) {
  490. testRequires(c, DaemonIsLinux) // Not currently passing on Windows
  491. name := "testaddfilewithwhitespace"
  492. for _, command := range []string{"ADD", "COPY"} {
  493. cli.BuildCmd(c, name, build.WithBuildContext(c,
  494. build.WithFile("Dockerfile", fmt.Sprintf(`FROM busybox
  495. RUN mkdir "/test dir"
  496. RUN mkdir "/test_dir"
  497. %s [ "test file1", "/test_file1" ]
  498. %s [ "test_file2", "/test file2" ]
  499. %s [ "test file3", "/test file3" ]
  500. %s [ "test dir/test_file4", "/test_dir/test_file4" ]
  501. %s [ "test_dir/test_file5", "/test dir/test_file5" ]
  502. %s [ "test dir/test_file6", "/test dir/test_file6" ]
  503. RUN [ $(cat "/test_file1") = 'test1' ]
  504. RUN [ $(cat "/test file2") = 'test2' ]
  505. RUN [ $(cat "/test file3") = 'test3' ]
  506. RUN [ $(cat "/test_dir/test_file4") = 'test4' ]
  507. RUN [ $(cat "/test dir/test_file5") = 'test5' ]
  508. RUN [ $(cat "/test dir/test_file6") = 'test6' ]`, command, command, command, command, command, command)),
  509. build.WithFile("test file1", "test1"),
  510. build.WithFile("test_file2", "test2"),
  511. build.WithFile("test file3", "test3"),
  512. build.WithFile("test dir/test_file4", "test4"),
  513. build.WithFile("test_dir/test_file5", "test5"),
  514. build.WithFile("test dir/test_file6", "test6"),
  515. ))
  516. cli.DockerCmd(c, "rmi", name)
  517. }
  518. }
  519. func (s *DockerSuite) TestBuildCopyFileWithWhitespaceOnWindows(c *testing.T) {
  520. testRequires(c, DaemonIsWindows)
  521. dockerfile := `FROM ` + testEnv.PlatformDefaults.BaseImage + `
  522. RUN mkdir "C:/test dir"
  523. RUN mkdir "C:/test_dir"
  524. COPY [ "test file1", "/test_file1" ]
  525. COPY [ "test_file2", "/test file2" ]
  526. COPY [ "test file3", "/test file3" ]
  527. COPY [ "test dir/test_file4", "/test_dir/test_file4" ]
  528. COPY [ "test_dir/test_file5", "/test dir/test_file5" ]
  529. COPY [ "test dir/test_file6", "/test dir/test_file6" ]
  530. RUN find "test1" "C:/test_file1"
  531. RUN find "test2" "C:/test file2"
  532. RUN find "test3" "C:/test file3"
  533. RUN find "test4" "C:/test_dir/test_file4"
  534. RUN find "test5" "C:/test dir/test_file5"
  535. RUN find "test6" "C:/test dir/test_file6"`
  536. name := "testcopyfilewithwhitespace"
  537. cli.BuildCmd(c, name, build.WithBuildContext(c,
  538. build.WithFile("Dockerfile", dockerfile),
  539. build.WithFile("test file1", "test1"),
  540. build.WithFile("test_file2", "test2"),
  541. build.WithFile("test file3", "test3"),
  542. build.WithFile("test dir/test_file4", "test4"),
  543. build.WithFile("test_dir/test_file5", "test5"),
  544. build.WithFile("test dir/test_file6", "test6"),
  545. ))
  546. }
  547. func (s *DockerSuite) TestBuildCopyWildcard(c *testing.T) {
  548. name := "testcopywildcard"
  549. server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{
  550. "robots.txt": "hello",
  551. "index.html": "world",
  552. }))
  553. defer server.Close()
  554. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(fmt.Sprintf(`FROM busybox
  555. COPY file*.txt /tmp/
  556. RUN ls /tmp/file1.txt /tmp/file2.txt
  557. RUN [ "mkdir", "/tmp1" ]
  558. COPY dir* /tmp1/
  559. RUN ls /tmp1/dirt /tmp1/nested_file /tmp1/nested_dir/nest_nest_file
  560. RUN [ "mkdir", "/tmp2" ]
  561. ADD dir/*dir %s/robots.txt /tmp2/
  562. RUN ls /tmp2/nest_nest_file /tmp2/robots.txt
  563. `, server.URL())),
  564. fakecontext.WithFiles(map[string]string{
  565. "file1.txt": "test1",
  566. "file2.txt": "test2",
  567. "dir/nested_file": "nested file",
  568. "dir/nested_dir/nest_nest_file": "2 times nested",
  569. "dirt": "dirty",
  570. }))
  571. defer ctx.Close()
  572. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  573. id1 := getIDByName(c, name)
  574. // Now make sure we use a cache the 2nd time
  575. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  576. id2 := getIDByName(c, name)
  577. if id1 != id2 {
  578. c.Fatal("didn't use the cache")
  579. }
  580. }
  581. func (s *DockerSuite) TestBuildCopyWildcardInName(c *testing.T) {
  582. // Run this only on Linux
  583. // Below is the original comment (that I don't agree with — vdemeester)
  584. // Normally we would do c.Fatal(err) here but given that
  585. // the odds of this failing are so rare, it must be because
  586. // the OS we're running the client on doesn't support * in
  587. // filenames (like windows). So, instead of failing the test
  588. // just let it pass. Then we don't need to explicitly
  589. // say which OSs this works on or not.
  590. testRequires(c, DaemonIsLinux, UnixCli)
  591. buildImageSuccessfully(c, "testcopywildcardinname", build.WithBuildContext(c,
  592. build.WithFile("Dockerfile", `FROM busybox
  593. COPY *.txt /tmp/
  594. RUN [ "$(cat /tmp/\*.txt)" = 'hi there' ]
  595. `),
  596. build.WithFile("*.txt", "hi there"),
  597. ))
  598. }
  599. func (s *DockerSuite) TestBuildCopyWildcardCache(c *testing.T) {
  600. name := "testcopywildcardcache"
  601. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(`FROM busybox
  602. COPY file1.txt /tmp/`),
  603. fakecontext.WithFiles(map[string]string{
  604. "file1.txt": "test1",
  605. }))
  606. defer ctx.Close()
  607. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  608. id1 := getIDByName(c, name)
  609. // Now make sure we use a cache the 2nd time even with wild cards.
  610. // Use the same context so the file is the same and the checksum will match
  611. ctx.Add("Dockerfile", `FROM busybox
  612. COPY file*.txt /tmp/`)
  613. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  614. id2 := getIDByName(c, name)
  615. if id1 != id2 {
  616. c.Fatal("didn't use the cache")
  617. }
  618. }
  619. func (s *DockerSuite) TestBuildAddSingleFileToNonExistingDir(c *testing.T) {
  620. testRequires(c, DaemonIsLinux) // Linux specific test
  621. buildImageSuccessfully(c, "testaddsinglefiletononexistingdir", build.WithBuildContext(c,
  622. build.WithFile("Dockerfile", `FROM busybox
  623. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  624. RUN echo 'dockerio:x:1001:' >> /etc/group
  625. RUN touch /exists
  626. RUN chown dockerio.dockerio /exists
  627. ADD test_file /test_dir/
  628. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  629. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  630. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`),
  631. build.WithFile("test_file", "test1")))
  632. }
  633. func (s *DockerSuite) TestBuildAddDirContentToRoot(c *testing.T) {
  634. testRequires(c, DaemonIsLinux) // Linux specific test
  635. buildImageSuccessfully(c, "testadddircontenttoroot", build.WithBuildContext(c,
  636. build.WithFile("Dockerfile", `FROM busybox
  637. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  638. RUN echo 'dockerio:x:1001:' >> /etc/group
  639. RUN touch /exists
  640. RUN chown dockerio.dockerio exists
  641. ADD test_dir /
  642. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  643. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`),
  644. build.WithFile("test_dir/test_file", "test1")))
  645. }
  646. func (s *DockerSuite) TestBuildAddDirContentToExistingDir(c *testing.T) {
  647. testRequires(c, DaemonIsLinux) // Linux specific test
  648. buildImageSuccessfully(c, "testadddircontenttoexistingdir", build.WithBuildContext(c,
  649. build.WithFile("Dockerfile", `FROM busybox
  650. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  651. RUN echo 'dockerio:x:1001:' >> /etc/group
  652. RUN mkdir /exists
  653. RUN touch /exists/exists_file
  654. RUN chown -R dockerio.dockerio /exists
  655. ADD test_dir/ /exists/
  656. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  657. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  658. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]`),
  659. build.WithFile("test_dir/test_file", "test1")))
  660. }
  661. func (s *DockerSuite) TestBuildAddWholeDirToRoot(c *testing.T) {
  662. testRequires(c, DaemonIsLinux) // Linux specific test
  663. buildImageSuccessfully(c, "testaddwholedirtoroot", build.WithBuildContext(c,
  664. build.WithFile("Dockerfile", fmt.Sprintf(`FROM busybox
  665. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  666. RUN echo 'dockerio:x:1001:' >> /etc/group
  667. RUN touch /exists
  668. RUN chown dockerio.dockerio exists
  669. ADD test_dir /test_dir
  670. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  671. RUN [ $(ls -l / | grep test_dir | awk '{print $1}') = 'drwxr-xr-x' ]
  672. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  673. RUN [ $(ls -l /test_dir/test_file | awk '{print $1}') = '%s' ]
  674. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod)),
  675. build.WithFile("test_dir/test_file", "test1")))
  676. }
  677. // Testing #5941 : Having an etc directory in context conflicts with the /etc/mtab
  678. func (s *DockerSuite) TestBuildAddOrCopyEtcToRootShouldNotConflict(c *testing.T) {
  679. buildImageSuccessfully(c, "testaddetctoroot", build.WithBuildContext(c,
  680. build.WithFile("Dockerfile", `FROM `+minimalBaseImage()+`
  681. ADD . /`),
  682. build.WithFile("etc/test_file", "test1")))
  683. buildImageSuccessfully(c, "testcopyetctoroot", build.WithBuildContext(c,
  684. build.WithFile("Dockerfile", `FROM `+minimalBaseImage()+`
  685. COPY . /`),
  686. build.WithFile("etc/test_file", "test1")))
  687. }
  688. // Testing #9401 : Losing setuid flag after a ADD
  689. func (s *DockerSuite) TestBuildAddPreservesFilesSpecialBits(c *testing.T) {
  690. testRequires(c, DaemonIsLinux) // Linux specific test
  691. buildImageSuccessfully(c, "testaddetctoroot", build.WithBuildContext(c,
  692. build.WithFile("Dockerfile", `FROM busybox
  693. ADD suidbin /usr/bin/suidbin
  694. RUN chmod 4755 /usr/bin/suidbin
  695. RUN [ $(ls -l /usr/bin/suidbin | awk '{print $1}') = '-rwsr-xr-x' ]
  696. ADD ./data/ /
  697. RUN [ $(ls -l /usr/bin/suidbin | awk '{print $1}') = '-rwsr-xr-x' ]`),
  698. build.WithFile("suidbin", "suidbin"),
  699. build.WithFile("/data/usr/test_file", "test1")))
  700. }
  701. func (s *DockerSuite) TestBuildCopySingleFileToRoot(c *testing.T) {
  702. testRequires(c, DaemonIsLinux) // Linux specific test
  703. buildImageSuccessfully(c, "testcopysinglefiletoroot", build.WithBuildContext(c,
  704. build.WithFile("Dockerfile", fmt.Sprintf(`FROM busybox
  705. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  706. RUN echo 'dockerio:x:1001:' >> /etc/group
  707. RUN touch /exists
  708. RUN chown dockerio.dockerio /exists
  709. COPY test_file /
  710. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  711. RUN [ $(ls -l /test_file | awk '{print $1}') = '%s' ]
  712. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod)),
  713. build.WithFile("test_file", "test1")))
  714. }
  715. // Issue #3960: "ADD src ." hangs - adapted for COPY
  716. func (s *DockerSuite) TestBuildCopySingleFileToWorkdir(c *testing.T) {
  717. name := "testcopysinglefiletoworkdir"
  718. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(`FROM busybox
  719. COPY test_file .`),
  720. fakecontext.WithFiles(map[string]string{
  721. "test_file": "test1",
  722. }))
  723. defer ctx.Close()
  724. errChan := make(chan error, 1)
  725. go func() {
  726. errChan <- buildImage(name, build.WithExternalBuildContext(ctx)).Error
  727. close(errChan)
  728. }()
  729. select {
  730. case <-time.After(15 * time.Second):
  731. c.Fatal("Build with adding to workdir timed out")
  732. case err := <-errChan:
  733. assert.NilError(c, err)
  734. }
  735. }
  736. func (s *DockerSuite) TestBuildCopySingleFileToExistDir(c *testing.T) {
  737. testRequires(c, DaemonIsLinux) // Linux specific test
  738. buildImageSuccessfully(c, "testcopysinglefiletoexistdir", build.WithBuildContext(c,
  739. build.WithFile("Dockerfile", `FROM busybox
  740. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  741. RUN echo 'dockerio:x:1001:' >> /etc/group
  742. RUN mkdir /exists
  743. RUN touch /exists/exists_file
  744. RUN chown -R dockerio.dockerio /exists
  745. COPY test_file /exists/
  746. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  747. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]
  748. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`),
  749. build.WithFile("test_file", "test1")))
  750. }
  751. func (s *DockerSuite) TestBuildCopySingleFileToNonExistDir(c *testing.T) {
  752. testRequires(c, DaemonIsLinux) // Linux specific
  753. buildImageSuccessfully(c, "testcopysinglefiletononexistdir", build.WithBuildContext(c,
  754. build.WithFile("Dockerfile", `FROM busybox
  755. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  756. RUN echo 'dockerio:x:1001:' >> /etc/group
  757. RUN touch /exists
  758. RUN chown dockerio.dockerio /exists
  759. COPY test_file /test_dir/
  760. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  761. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  762. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`),
  763. build.WithFile("test_file", "test1")))
  764. }
  765. func (s *DockerSuite) TestBuildCopyDirContentToRoot(c *testing.T) {
  766. testRequires(c, DaemonIsLinux) // Linux specific test
  767. buildImageSuccessfully(c, "testcopydircontenttoroot", build.WithBuildContext(c,
  768. build.WithFile("Dockerfile", `FROM busybox
  769. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  770. RUN echo 'dockerio:x:1001:' >> /etc/group
  771. RUN touch /exists
  772. RUN chown dockerio.dockerio exists
  773. COPY test_dir /
  774. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  775. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`),
  776. build.WithFile("test_dir/test_file", "test1")))
  777. }
  778. func (s *DockerSuite) TestBuildCopyDirContentToExistDir(c *testing.T) {
  779. testRequires(c, DaemonIsLinux) // Linux specific test
  780. buildImageSuccessfully(c, "testcopydircontenttoexistdir", build.WithBuildContext(c,
  781. build.WithFile("Dockerfile", `FROM busybox
  782. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  783. RUN echo 'dockerio:x:1001:' >> /etc/group
  784. RUN mkdir /exists
  785. RUN touch /exists/exists_file
  786. RUN chown -R dockerio.dockerio /exists
  787. COPY test_dir/ /exists/
  788. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  789. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  790. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]`),
  791. build.WithFile("test_dir/test_file", "test1")))
  792. }
  793. func (s *DockerSuite) TestBuildCopyWholeDirToRoot(c *testing.T) {
  794. testRequires(c, DaemonIsLinux) // Linux specific test
  795. buildImageSuccessfully(c, "testcopywholedirtoroot", build.WithBuildContext(c,
  796. build.WithFile("Dockerfile", fmt.Sprintf(`FROM busybox
  797. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  798. RUN echo 'dockerio:x:1001:' >> /etc/group
  799. RUN touch /exists
  800. RUN chown dockerio.dockerio exists
  801. COPY test_dir /test_dir
  802. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  803. RUN [ $(ls -l / | grep test_dir | awk '{print $1}') = 'drwxr-xr-x' ]
  804. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  805. RUN [ $(ls -l /test_dir/test_file | awk '{print $1}') = '%s' ]
  806. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod)),
  807. build.WithFile("test_dir/test_file", "test1")))
  808. }
  809. func (s *DockerSuite) TestBuildAddBadLinks(c *testing.T) {
  810. testRequires(c, DaemonIsLinux) // Not currently working on Windows
  811. dockerfile := `
  812. FROM scratch
  813. ADD links.tar /
  814. ADD foo.txt /symlink/
  815. `
  816. targetFile := "foo.txt"
  817. var (
  818. name = "test-link-absolute"
  819. )
  820. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(dockerfile))
  821. defer ctx.Close()
  822. tempDir, err := ioutil.TempDir("", "test-link-absolute-temp-")
  823. if err != nil {
  824. c.Fatalf("failed to create temporary directory: %s", tempDir)
  825. }
  826. defer os.RemoveAll(tempDir)
  827. var symlinkTarget string
  828. if runtime.GOOS == "windows" {
  829. var driveLetter string
  830. if abs, err := filepath.Abs(tempDir); err != nil {
  831. c.Fatal(err)
  832. } else {
  833. driveLetter = abs[:1]
  834. }
  835. tempDirWithoutDrive := tempDir[2:]
  836. symlinkTarget = fmt.Sprintf(`%s:\..\..\..\..\..\..\..\..\..\..\..\..%s`, driveLetter, tempDirWithoutDrive)
  837. } else {
  838. symlinkTarget = fmt.Sprintf("/../../../../../../../../../../../..%s", tempDir)
  839. }
  840. tarPath := filepath.Join(ctx.Dir, "links.tar")
  841. nonExistingFile := filepath.Join(tempDir, targetFile)
  842. fooPath := filepath.Join(ctx.Dir, targetFile)
  843. tarOut, err := os.Create(tarPath)
  844. if err != nil {
  845. c.Fatal(err)
  846. }
  847. tarWriter := tar.NewWriter(tarOut)
  848. header := &tar.Header{
  849. Name: "symlink",
  850. Typeflag: tar.TypeSymlink,
  851. Linkname: symlinkTarget,
  852. Mode: 0755,
  853. Uid: 0,
  854. Gid: 0,
  855. }
  856. err = tarWriter.WriteHeader(header)
  857. if err != nil {
  858. c.Fatal(err)
  859. }
  860. tarWriter.Close()
  861. tarOut.Close()
  862. foo, err := os.Create(fooPath)
  863. if err != nil {
  864. c.Fatal(err)
  865. }
  866. defer foo.Close()
  867. if _, err := foo.WriteString("test"); err != nil {
  868. c.Fatal(err)
  869. }
  870. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  871. if _, err := os.Stat(nonExistingFile); err == nil || !os.IsNotExist(err) {
  872. c.Fatalf("%s shouldn't have been written and it shouldn't exist", nonExistingFile)
  873. }
  874. }
  875. func (s *DockerSuite) TestBuildAddBadLinksVolume(c *testing.T) {
  876. testRequires(c, DaemonIsLinux) // ln not implemented on Windows busybox
  877. const (
  878. dockerfileTemplate = `
  879. FROM busybox
  880. RUN ln -s /../../../../../../../../%s /x
  881. VOLUME /x
  882. ADD foo.txt /x/`
  883. targetFile = "foo.txt"
  884. )
  885. tempDir, err := ioutil.TempDir("", "test-link-absolute-volume-temp-")
  886. if err != nil {
  887. c.Fatalf("failed to create temporary directory: %s", tempDir)
  888. }
  889. defer os.RemoveAll(tempDir)
  890. dockerfile := fmt.Sprintf(dockerfileTemplate, tempDir)
  891. nonExistingFile := filepath.Join(tempDir, targetFile)
  892. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(dockerfile))
  893. defer ctx.Close()
  894. fooPath := filepath.Join(ctx.Dir, targetFile)
  895. foo, err := os.Create(fooPath)
  896. if err != nil {
  897. c.Fatal(err)
  898. }
  899. defer foo.Close()
  900. if _, err := foo.WriteString("test"); err != nil {
  901. c.Fatal(err)
  902. }
  903. buildImageSuccessfully(c, "test-link-absolute-volume", build.WithExternalBuildContext(ctx))
  904. if _, err := os.Stat(nonExistingFile); err == nil || !os.IsNotExist(err) {
  905. c.Fatalf("%s shouldn't have been written and it shouldn't exist", nonExistingFile)
  906. }
  907. }
  908. // Issue #5270 - ensure we throw a better error than "unexpected EOF"
  909. // when we can't access files in the context.
  910. func (s *DockerSuite) TestBuildWithInaccessibleFilesInContext(c *testing.T) {
  911. testRequires(c, DaemonIsLinux, UnixCli, testEnv.IsLocalDaemon) // test uses chown/chmod: not available on windows
  912. {
  913. name := "testbuildinaccessiblefiles"
  914. ctx := fakecontext.New(c, "",
  915. fakecontext.WithDockerfile("FROM scratch\nADD . /foo/"),
  916. fakecontext.WithFiles(map[string]string{"fileWithoutReadAccess": "foo"}),
  917. )
  918. defer ctx.Close()
  919. // This is used to ensure we detect inaccessible files early during build in the cli client
  920. pathToFileWithoutReadAccess := filepath.Join(ctx.Dir, "fileWithoutReadAccess")
  921. if err := os.Chown(pathToFileWithoutReadAccess, 0, 0); err != nil {
  922. c.Fatalf("failed to chown file to root: %s", err)
  923. }
  924. if err := os.Chmod(pathToFileWithoutReadAccess, 0700); err != nil {
  925. c.Fatalf("failed to chmod file to 700: %s", err)
  926. }
  927. result := icmd.RunCmd(icmd.Cmd{
  928. Command: []string{"su", "unprivilegeduser", "-c", fmt.Sprintf("%s build -t %s .", dockerBinary, name)},
  929. Dir: ctx.Dir,
  930. })
  931. if result.Error == nil {
  932. c.Fatalf("build should have failed: %s %s", result.Error, result.Combined())
  933. }
  934. // check if we've detected the failure before we started building
  935. if !strings.Contains(result.Combined(), "no permission to read from ") {
  936. c.Fatalf("output should've contained the string: no permission to read from but contained: %s", result.Combined())
  937. }
  938. if !strings.Contains(result.Combined(), "error checking context") {
  939. c.Fatalf("output should've contained the string: error checking context")
  940. }
  941. }
  942. {
  943. name := "testbuildinaccessibledirectory"
  944. ctx := fakecontext.New(c, "",
  945. fakecontext.WithDockerfile("FROM scratch\nADD . /foo/"),
  946. fakecontext.WithFiles(map[string]string{"directoryWeCantStat/bar": "foo"}),
  947. )
  948. defer ctx.Close()
  949. // This is used to ensure we detect inaccessible directories early during build in the cli client
  950. pathToDirectoryWithoutReadAccess := filepath.Join(ctx.Dir, "directoryWeCantStat")
  951. pathToFileInDirectoryWithoutReadAccess := filepath.Join(pathToDirectoryWithoutReadAccess, "bar")
  952. if err := os.Chown(pathToDirectoryWithoutReadAccess, 0, 0); err != nil {
  953. c.Fatalf("failed to chown directory to root: %s", err)
  954. }
  955. if err := os.Chmod(pathToDirectoryWithoutReadAccess, 0444); err != nil {
  956. c.Fatalf("failed to chmod directory to 444: %s", err)
  957. }
  958. if err := os.Chmod(pathToFileInDirectoryWithoutReadAccess, 0700); err != nil {
  959. c.Fatalf("failed to chmod file to 700: %s", err)
  960. }
  961. result := icmd.RunCmd(icmd.Cmd{
  962. Command: []string{"su", "unprivilegeduser", "-c", fmt.Sprintf("%s build -t %s .", dockerBinary, name)},
  963. Dir: ctx.Dir,
  964. })
  965. if result.Error == nil {
  966. c.Fatalf("build should have failed: %s %s", result.Error, result.Combined())
  967. }
  968. // check if we've detected the failure before we started building
  969. if !strings.Contains(result.Combined(), "can't stat") {
  970. c.Fatalf("output should've contained the string: can't access %s", result.Combined())
  971. }
  972. if !strings.Contains(result.Combined(), "error checking context") {
  973. c.Fatalf("output should've contained the string: error checking context\ngot:%s", result.Combined())
  974. }
  975. }
  976. {
  977. name := "testlinksok"
  978. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile("FROM scratch\nADD . /foo/"))
  979. defer ctx.Close()
  980. target := "../../../../../../../../../../../../../../../../../../../azA"
  981. if err := os.Symlink(filepath.Join(ctx.Dir, "g"), target); err != nil {
  982. c.Fatal(err)
  983. }
  984. defer os.Remove(target)
  985. // This is used to ensure we don't follow links when checking if everything in the context is accessible
  986. // This test doesn't require that we run commands as an unprivileged user
  987. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  988. }
  989. {
  990. name := "testbuildignoredinaccessible"
  991. ctx := fakecontext.New(c, "",
  992. fakecontext.WithDockerfile("FROM scratch\nADD . /foo/"),
  993. fakecontext.WithFiles(map[string]string{
  994. "directoryWeCantStat/bar": "foo",
  995. ".dockerignore": "directoryWeCantStat",
  996. }),
  997. )
  998. defer ctx.Close()
  999. // This is used to ensure we don't try to add inaccessible files when they are ignored by a .dockerignore pattern
  1000. pathToDirectoryWithoutReadAccess := filepath.Join(ctx.Dir, "directoryWeCantStat")
  1001. pathToFileInDirectoryWithoutReadAccess := filepath.Join(pathToDirectoryWithoutReadAccess, "bar")
  1002. if err := os.Chown(pathToDirectoryWithoutReadAccess, 0, 0); err != nil {
  1003. c.Fatalf("failed to chown directory to root: %s", err)
  1004. }
  1005. if err := os.Chmod(pathToDirectoryWithoutReadAccess, 0444); err != nil {
  1006. c.Fatalf("failed to chmod directory to 444: %s", err)
  1007. }
  1008. if err := os.Chmod(pathToFileInDirectoryWithoutReadAccess, 0700); err != nil {
  1009. c.Fatalf("failed to chmod file to 700: %s", err)
  1010. }
  1011. result := icmd.RunCmd(icmd.Cmd{
  1012. Dir: ctx.Dir,
  1013. Command: []string{"su", "unprivilegeduser", "-c",
  1014. fmt.Sprintf("%s build -t %s .", dockerBinary, name)},
  1015. })
  1016. result.Assert(c, icmd.Expected{})
  1017. }
  1018. }
  1019. func (s *DockerSuite) TestBuildForceRm(c *testing.T) {
  1020. containerCountBefore := getContainerCount(c)
  1021. name := "testbuildforcerm"
  1022. r := buildImage(name, cli.WithFlags("--force-rm"), build.WithBuildContext(c,
  1023. build.WithFile("Dockerfile", `FROM busybox
  1024. RUN true
  1025. RUN thiswillfail`)))
  1026. if r.ExitCode != 1 && r.ExitCode != 127 { // different on Linux / Windows
  1027. c.Fatalf("Wrong exit code")
  1028. }
  1029. containerCountAfter := getContainerCount(c)
  1030. if containerCountBefore != containerCountAfter {
  1031. c.Fatalf("--force-rm shouldn't have left containers behind")
  1032. }
  1033. }
  1034. func (s *DockerSuite) TestBuildRm(c *testing.T) {
  1035. name := "testbuildrm"
  1036. testCases := []struct {
  1037. buildflags []string
  1038. shouldLeftContainerBehind bool
  1039. }{
  1040. // Default case (i.e. --rm=true)
  1041. {
  1042. buildflags: []string{},
  1043. shouldLeftContainerBehind: false,
  1044. },
  1045. {
  1046. buildflags: []string{"--rm"},
  1047. shouldLeftContainerBehind: false,
  1048. },
  1049. {
  1050. buildflags: []string{"--rm=false"},
  1051. shouldLeftContainerBehind: true,
  1052. },
  1053. }
  1054. for _, tc := range testCases {
  1055. containerCountBefore := getContainerCount(c)
  1056. buildImageSuccessfully(c, name, cli.WithFlags(tc.buildflags...), build.WithDockerfile(`FROM busybox
  1057. RUN echo hello world`))
  1058. containerCountAfter := getContainerCount(c)
  1059. if tc.shouldLeftContainerBehind {
  1060. if containerCountBefore == containerCountAfter {
  1061. c.Fatalf("flags %v should have left containers behind", tc.buildflags)
  1062. }
  1063. } else {
  1064. if containerCountBefore != containerCountAfter {
  1065. c.Fatalf("flags %v shouldn't have left containers behind", tc.buildflags)
  1066. }
  1067. }
  1068. dockerCmd(c, "rmi", name)
  1069. }
  1070. }
  1071. func (s *DockerSuite) TestBuildWithVolumes(c *testing.T) {
  1072. testRequires(c, DaemonIsLinux) // Invalid volume paths on Windows
  1073. var (
  1074. result map[string]map[string]struct{}
  1075. name = "testbuildvolumes"
  1076. emptyMap = make(map[string]struct{})
  1077. expected = map[string]map[string]struct{}{
  1078. "/test1": emptyMap,
  1079. "/test2": emptyMap,
  1080. "/test3": emptyMap,
  1081. "/test4": emptyMap,
  1082. "/test5": emptyMap,
  1083. "/test6": emptyMap,
  1084. "[/test7": emptyMap,
  1085. "/test8]": emptyMap,
  1086. }
  1087. )
  1088. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM scratch
  1089. VOLUME /test1
  1090. VOLUME /test2
  1091. VOLUME /test3 /test4
  1092. VOLUME ["/test5", "/test6"]
  1093. VOLUME [/test7 /test8]
  1094. `))
  1095. inspectFieldAndUnmarshall(c, name, "Config.Volumes", &result)
  1096. equal := reflect.DeepEqual(&result, &expected)
  1097. if !equal {
  1098. c.Fatalf("Volumes %s, expected %s", result, expected)
  1099. }
  1100. }
  1101. func (s *DockerSuite) TestBuildMaintainer(c *testing.T) {
  1102. name := "testbuildmaintainer"
  1103. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  1104. MAINTAINER dockerio`))
  1105. expected := "dockerio"
  1106. res := inspectField(c, name, "Author")
  1107. if res != expected {
  1108. c.Fatalf("Maintainer %s, expected %s", res, expected)
  1109. }
  1110. }
  1111. func (s *DockerSuite) TestBuildUser(c *testing.T) {
  1112. testRequires(c, DaemonIsLinux)
  1113. name := "testbuilduser"
  1114. expected := "dockerio"
  1115. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  1116. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1117. USER dockerio
  1118. RUN [ $(whoami) = 'dockerio' ]`))
  1119. res := inspectField(c, name, "Config.User")
  1120. if res != expected {
  1121. c.Fatalf("User %s, expected %s", res, expected)
  1122. }
  1123. }
  1124. func (s *DockerSuite) TestBuildRelativeWorkdir(c *testing.T) {
  1125. name := "testbuildrelativeworkdir"
  1126. var (
  1127. expected1 string
  1128. expected2 string
  1129. expected3 string
  1130. expected4 string
  1131. expectedFinal string
  1132. )
  1133. if testEnv.OSType == "windows" {
  1134. expected1 = `C:/`
  1135. expected2 = `C:/test1`
  1136. expected3 = `C:/test2`
  1137. expected4 = `C:/test2/test3`
  1138. expectedFinal = `C:\test2\test3` // Note inspect is going to return Windows paths, as it's not in busybox
  1139. } else {
  1140. expected1 = `/`
  1141. expected2 = `/test1`
  1142. expected3 = `/test2`
  1143. expected4 = `/test2/test3`
  1144. expectedFinal = `/test2/test3`
  1145. }
  1146. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  1147. RUN sh -c "[ "$PWD" = "`+expected1+`" ]"
  1148. WORKDIR test1
  1149. RUN sh -c "[ "$PWD" = "`+expected2+`" ]"
  1150. WORKDIR /test2
  1151. RUN sh -c "[ "$PWD" = "`+expected3+`" ]"
  1152. WORKDIR test3
  1153. RUN sh -c "[ "$PWD" = "`+expected4+`" ]"`))
  1154. res := inspectField(c, name, "Config.WorkingDir")
  1155. if res != expectedFinal {
  1156. c.Fatalf("Workdir %s, expected %s", res, expectedFinal)
  1157. }
  1158. }
  1159. // #22181 Regression test. Single end-to-end test of using
  1160. // Windows semantics. Most path handling verifications are in unit tests
  1161. func (s *DockerSuite) TestBuildWindowsWorkdirProcessing(c *testing.T) {
  1162. testRequires(c, DaemonIsWindows)
  1163. buildImageSuccessfully(c, "testbuildwindowsworkdirprocessing", build.WithDockerfile(`FROM busybox
  1164. WORKDIR C:\\foo
  1165. WORKDIR bar
  1166. RUN sh -c "[ "$PWD" = "C:/foo/bar" ]"
  1167. `))
  1168. }
  1169. // #22181 Regression test. Most paths handling verifications are in unit test.
  1170. // One functional test for end-to-end
  1171. func (s *DockerSuite) TestBuildWindowsAddCopyPathProcessing(c *testing.T) {
  1172. testRequires(c, DaemonIsWindows)
  1173. // TODO Windows. Needs a follow-up PR to 22181 to
  1174. // support backslash such as .\\ being equivalent to ./ and c:\\ being
  1175. // equivalent to c:/. This is not currently (nor ever has been) supported
  1176. // by docker on the Windows platform.
  1177. buildImageSuccessfully(c, "testbuildwindowsaddcopypathprocessing", build.WithBuildContext(c,
  1178. build.WithFile("Dockerfile", `FROM busybox
  1179. # No trailing slash on COPY/ADD
  1180. # Results in dir being changed to a file
  1181. WORKDIR /wc1
  1182. COPY wc1 c:/wc1
  1183. WORKDIR /wc2
  1184. ADD wc2 c:/wc2
  1185. WORKDIR c:/
  1186. RUN sh -c "[ $(cat c:/wc1/wc1) = 'hellowc1' ]"
  1187. RUN sh -c "[ $(cat c:/wc2/wc2) = 'worldwc2' ]"
  1188. # Trailing slash on COPY/ADD, Windows-style path.
  1189. WORKDIR /wd1
  1190. COPY wd1 c:/wd1/
  1191. WORKDIR /wd2
  1192. ADD wd2 c:/wd2/
  1193. RUN sh -c "[ $(cat c:/wd1/wd1) = 'hellowd1' ]"
  1194. RUN sh -c "[ $(cat c:/wd2/wd2) = 'worldwd2' ]"
  1195. `),
  1196. build.WithFile("wc1", "hellowc1"),
  1197. build.WithFile("wc2", "worldwc2"),
  1198. build.WithFile("wd1", "hellowd1"),
  1199. build.WithFile("wd2", "worldwd2"),
  1200. ))
  1201. }
  1202. func (s *DockerSuite) TestBuildWorkdirWithEnvVariables(c *testing.T) {
  1203. name := "testbuildworkdirwithenvvariables"
  1204. var expected string
  1205. if testEnv.OSType == "windows" {
  1206. expected = `C:\test1\test2`
  1207. } else {
  1208. expected = `/test1/test2`
  1209. }
  1210. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  1211. ENV DIRPATH /test1
  1212. ENV SUBDIRNAME test2
  1213. WORKDIR $DIRPATH
  1214. WORKDIR $SUBDIRNAME/$MISSING_VAR`))
  1215. res := inspectField(c, name, "Config.WorkingDir")
  1216. if res != expected {
  1217. c.Fatalf("Workdir %s, expected %s", res, expected)
  1218. }
  1219. }
  1220. func (s *DockerSuite) TestBuildRelativeCopy(c *testing.T) {
  1221. // cat /test1/test2/foo gets permission denied for the user
  1222. testRequires(c, NotUserNamespace)
  1223. var expected string
  1224. if testEnv.OSType == "windows" {
  1225. expected = `C:/test1/test2`
  1226. } else {
  1227. expected = `/test1/test2`
  1228. }
  1229. buildImageSuccessfully(c, "testbuildrelativecopy", build.WithBuildContext(c,
  1230. build.WithFile("Dockerfile", `FROM busybox
  1231. WORKDIR /test1
  1232. WORKDIR test2
  1233. RUN sh -c "[ "$PWD" = '`+expected+`' ]"
  1234. COPY foo ./
  1235. RUN sh -c "[ $(cat /test1/test2/foo) = 'hello' ]"
  1236. ADD foo ./bar/baz
  1237. RUN sh -c "[ $(cat /test1/test2/bar/baz) = 'hello' ]"
  1238. COPY foo ./bar/baz2
  1239. RUN sh -c "[ $(cat /test1/test2/bar/baz2) = 'hello' ]"
  1240. WORKDIR ..
  1241. COPY foo ./
  1242. RUN sh -c "[ $(cat /test1/foo) = 'hello' ]"
  1243. COPY foo /test3/
  1244. RUN sh -c "[ $(cat /test3/foo) = 'hello' ]"
  1245. WORKDIR /test4
  1246. COPY . .
  1247. RUN sh -c "[ $(cat /test4/foo) = 'hello' ]"
  1248. WORKDIR /test5/test6
  1249. COPY foo ../
  1250. RUN sh -c "[ $(cat /test5/foo) = 'hello' ]"
  1251. `),
  1252. build.WithFile("foo", "hello"),
  1253. ))
  1254. }
  1255. // FIXME(vdemeester) should be unit test
  1256. func (s *DockerSuite) TestBuildBlankName(c *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  1321. testRequires(c, testEnv.IsLocalDaemon)
  1322. name := "testbuildcontextcleanup"
  1323. entries, err := ioutil.ReadDir(filepath.Join(testEnv.DaemonInfo.DockerRootDir, "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.DaemonInfo.DockerRootDir, "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 *testing.T) {
  1338. testRequires(c, testEnv.IsLocalDaemon)
  1339. name := "testbuildcontextcleanup"
  1340. entries, err := ioutil.ReadDir(filepath.Join(testEnv.DaemonInfo.DockerRootDir, "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.DaemonInfo.DockerRootDir, "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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T, 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 *testing.T) {
  1786. testContextTar(c, archive.Gzip)
  1787. }
  1788. func (s *DockerSuite) TestBuildContextTarNoCompression(c *testing.T) {
  1789. testContextTar(c, archive.Uncompressed)
  1790. }
  1791. func (s *DockerSuite) TestBuildNoContext(c *testing.T) {
  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. // FIXME(vdemeester) migrate to docker/cli e2e
  1804. func (s *DockerSuite) TestBuildDockerfileStdin(c *testing.T) {
  1805. name := "stdindockerfile"
  1806. tmpDir, err := ioutil.TempDir("", "fake-context")
  1807. assert.NilError(c, err)
  1808. err = ioutil.WriteFile(filepath.Join(tmpDir, "foo"), []byte("bar"), 0600)
  1809. assert.NilError(c, err)
  1810. icmd.RunCmd(icmd.Cmd{
  1811. Command: []string{dockerBinary, "build", "-t", name, "-f", "-", tmpDir},
  1812. Stdin: strings.NewReader(
  1813. `FROM busybox
  1814. ADD foo /foo
  1815. CMD ["cat", "/foo"]`),
  1816. }).Assert(c, icmd.Success)
  1817. res := inspectField(c, name, "Config.Cmd")
  1818. assert.Equal(c, strings.TrimSpace(res), `[cat /foo]`)
  1819. }
  1820. // FIXME(vdemeester) migrate to docker/cli tests (unit or e2e)
  1821. func (s *DockerSuite) TestBuildDockerfileStdinConflict(c *testing.T) {
  1822. name := "stdindockerfiletarcontext"
  1823. icmd.RunCmd(icmd.Cmd{
  1824. Command: []string{dockerBinary, "build", "-t", name, "-f", "-", "-"},
  1825. }).Assert(c, icmd.Expected{
  1826. ExitCode: 1,
  1827. Err: "use stdin for both build context and dockerfile",
  1828. })
  1829. }
  1830. func (s *DockerSuite) TestBuildDockerfileStdinNoExtraFiles(c *testing.T) {
  1831. s.testBuildDockerfileStdinNoExtraFiles(c, false, false)
  1832. }
  1833. func (s *DockerSuite) TestBuildDockerfileStdinDockerignore(c *testing.T) {
  1834. s.testBuildDockerfileStdinNoExtraFiles(c, true, false)
  1835. }
  1836. func (s *DockerSuite) TestBuildDockerfileStdinDockerignoreIgnored(c *testing.T) {
  1837. s.testBuildDockerfileStdinNoExtraFiles(c, true, true)
  1838. }
  1839. func (s *DockerSuite) testBuildDockerfileStdinNoExtraFiles(c *testing.T, hasDockerignore, ignoreDockerignore bool) {
  1840. name := "stdindockerfilenoextra"
  1841. tmpDir, err := ioutil.TempDir("", "fake-context")
  1842. assert.NilError(c, err)
  1843. defer os.RemoveAll(tmpDir)
  1844. writeFile := func(filename, content string) {
  1845. err = ioutil.WriteFile(filepath.Join(tmpDir, filename), []byte(content), 0600)
  1846. assert.NilError(c, err)
  1847. }
  1848. writeFile("foo", "bar")
  1849. if hasDockerignore {
  1850. // Add an empty Dockerfile to verify that it is not added to the image
  1851. writeFile("Dockerfile", "")
  1852. ignores := "Dockerfile\n"
  1853. if ignoreDockerignore {
  1854. ignores += ".dockerignore\n"
  1855. }
  1856. writeFile(".dockerignore", ignores)
  1857. }
  1858. result := icmd.RunCmd(icmd.Cmd{
  1859. Command: []string{dockerBinary, "build", "-t", name, "-f", "-", tmpDir},
  1860. Stdin: strings.NewReader(
  1861. `FROM busybox
  1862. COPY . /baz`),
  1863. })
  1864. result.Assert(c, icmd.Success)
  1865. result = cli.DockerCmd(c, "run", "--rm", name, "ls", "-A", "/baz")
  1866. if hasDockerignore && !ignoreDockerignore {
  1867. assert.Equal(c, result.Stdout(), ".dockerignore\nfoo\n")
  1868. } else {
  1869. assert.Equal(c, result.Stdout(), "foo\n")
  1870. }
  1871. }
  1872. func (s *DockerSuite) TestBuildWithVolumeOwnership(c *testing.T) {
  1873. testRequires(c, DaemonIsLinux)
  1874. name := "testbuildimg"
  1875. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox:latest
  1876. RUN mkdir /test && chown daemon:daemon /test && chmod 0600 /test
  1877. VOLUME /test`))
  1878. out, _ := dockerCmd(c, "run", "--rm", "testbuildimg", "ls", "-la", "/test")
  1879. if expected := "drw-------"; !strings.Contains(out, expected) {
  1880. c.Fatalf("expected %s received %s", expected, out)
  1881. }
  1882. if expected := "daemon daemon"; !strings.Contains(out, expected) {
  1883. c.Fatalf("expected %s received %s", expected, out)
  1884. }
  1885. }
  1886. // testing #1405 - config.Cmd does not get cleaned up if
  1887. // utilizing cache
  1888. func (s *DockerSuite) TestBuildEntrypointRunCleanup(c *testing.T) {
  1889. name := "testbuildcmdcleanup"
  1890. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  1891. RUN echo "hello"`))
  1892. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  1893. build.WithFile("Dockerfile", `FROM busybox
  1894. RUN echo "hello"
  1895. ADD foo /foo
  1896. ENTRYPOINT ["/bin/echo"]`),
  1897. build.WithFile("foo", "hello")))
  1898. res := inspectField(c, name, "Config.Cmd")
  1899. // Cmd must be cleaned up
  1900. if res != "[]" {
  1901. c.Fatalf("Cmd %s, expected nil", res)
  1902. }
  1903. }
  1904. func (s *DockerSuite) TestBuildAddFileNotFound(c *testing.T) {
  1905. name := "testbuildaddnotfound"
  1906. buildImage(name, build.WithBuildContext(c,
  1907. build.WithFile("Dockerfile", `FROM `+minimalBaseImage()+`
  1908. ADD foo /usr/local/bar`),
  1909. build.WithFile("bar", "hello"))).Assert(c, icmd.Expected{
  1910. ExitCode: 1,
  1911. Err: "stat foo: file does not exist",
  1912. })
  1913. }
  1914. func (s *DockerSuite) TestBuildInheritance(c *testing.T) {
  1915. testRequires(c, DaemonIsLinux)
  1916. name := "testbuildinheritance"
  1917. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM scratch
  1918. EXPOSE 2375`))
  1919. ports1 := inspectField(c, name, "Config.ExposedPorts")
  1920. buildImageSuccessfully(c, name, build.WithDockerfile(fmt.Sprintf(`FROM %s
  1921. ENTRYPOINT ["/bin/echo"]`, name)))
  1922. res := inspectField(c, name, "Config.Entrypoint")
  1923. if expected := "[/bin/echo]"; res != expected {
  1924. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  1925. }
  1926. ports2 := inspectField(c, name, "Config.ExposedPorts")
  1927. if ports1 != ports2 {
  1928. c.Fatalf("Ports must be same: %s != %s", ports1, ports2)
  1929. }
  1930. }
  1931. func (s *DockerSuite) TestBuildFails(c *testing.T) {
  1932. name := "testbuildfails"
  1933. buildImage(name, build.WithDockerfile(`FROM busybox
  1934. RUN sh -c "exit 23"`)).Assert(c, icmd.Expected{
  1935. ExitCode: 23,
  1936. Err: "returned a non-zero code: 23",
  1937. })
  1938. }
  1939. func (s *DockerSuite) TestBuildOnBuild(c *testing.T) {
  1940. name := "testbuildonbuild"
  1941. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  1942. ONBUILD RUN touch foobar`))
  1943. buildImageSuccessfully(c, name, build.WithDockerfile(fmt.Sprintf(`FROM %s
  1944. RUN [ -f foobar ]`, name)))
  1945. }
  1946. // gh #2446
  1947. func (s *DockerSuite) TestBuildAddToSymlinkDest(c *testing.T) {
  1948. makeLink := `ln -s /foo /bar`
  1949. if testEnv.OSType == "windows" {
  1950. makeLink = `mklink /D C:\bar C:\foo`
  1951. }
  1952. name := "testbuildaddtosymlinkdest"
  1953. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  1954. build.WithFile("Dockerfile", `
  1955. FROM busybox
  1956. RUN sh -c "mkdir /foo"
  1957. RUN `+makeLink+`
  1958. ADD foo /bar/
  1959. RUN sh -c "[ -f /bar/foo ]"
  1960. RUN sh -c "[ -f /foo/foo ]"`),
  1961. build.WithFile("foo", "hello"),
  1962. ))
  1963. }
  1964. func (s *DockerSuite) TestBuildEscapeWhitespace(c *testing.T) {
  1965. name := "testbuildescapewhitespace"
  1966. buildImageSuccessfully(c, name, build.WithDockerfile(`
  1967. # ESCAPE=\
  1968. FROM busybox
  1969. MAINTAINER "Docker \
  1970. IO <io@\
  1971. docker.com>"
  1972. `))
  1973. res := inspectField(c, name, "Author")
  1974. if res != "\"Docker IO <io@docker.com>\"" {
  1975. c.Fatalf("Parsed string did not match the escaped string. Got: %q", res)
  1976. }
  1977. }
  1978. func (s *DockerSuite) TestBuildVerifyIntString(c *testing.T) {
  1979. // Verify that strings that look like ints are still passed as strings
  1980. name := "testbuildstringing"
  1981. buildImageSuccessfully(c, name, build.WithDockerfile(`
  1982. FROM busybox
  1983. MAINTAINER 123`))
  1984. out, _ := dockerCmd(c, "inspect", name)
  1985. if !strings.Contains(out, "\"123\"") {
  1986. c.Fatalf("Output does not contain the int as a string:\n%s", out)
  1987. }
  1988. }
  1989. func (s *DockerSuite) TestBuildDockerignore(c *testing.T) {
  1990. name := "testbuilddockerignore"
  1991. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  1992. build.WithFile("Dockerfile", `
  1993. FROM busybox
  1994. ADD . /bla
  1995. RUN sh -c "[[ -f /bla/src/x.go ]]"
  1996. RUN sh -c "[[ -f /bla/Makefile ]]"
  1997. RUN sh -c "[[ ! -e /bla/src/_vendor ]]"
  1998. RUN sh -c "[[ ! -e /bla/.gitignore ]]"
  1999. RUN sh -c "[[ ! -e /bla/README.md ]]"
  2000. RUN sh -c "[[ ! -e /bla/dir/foo ]]"
  2001. RUN sh -c "[[ ! -e /bla/foo ]]"
  2002. RUN sh -c "[[ ! -e /bla/.git ]]"
  2003. RUN sh -c "[[ ! -e v.cc ]]"
  2004. RUN sh -c "[[ ! -e src/v.cc ]]"
  2005. RUN sh -c "[[ ! -e src/_vendor/v.cc ]]"`),
  2006. build.WithFile("Makefile", "all:"),
  2007. build.WithFile(".git/HEAD", "ref: foo"),
  2008. build.WithFile("src/x.go", "package main"),
  2009. build.WithFile("src/_vendor/v.go", "package main"),
  2010. build.WithFile("src/_vendor/v.cc", "package main"),
  2011. build.WithFile("src/v.cc", "package main"),
  2012. build.WithFile("v.cc", "package main"),
  2013. build.WithFile("dir/foo", ""),
  2014. build.WithFile(".gitignore", ""),
  2015. build.WithFile("README.md", "readme"),
  2016. build.WithFile(".dockerignore", `
  2017. .git
  2018. pkg
  2019. .gitignore
  2020. src/_vendor
  2021. *.md
  2022. **/*.cc
  2023. dir`),
  2024. ))
  2025. }
  2026. func (s *DockerSuite) TestBuildDockerignoreCleanPaths(c *testing.T) {
  2027. name := "testbuilddockerignorecleanpaths"
  2028. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2029. build.WithFile("Dockerfile", `
  2030. FROM busybox
  2031. ADD . /tmp/
  2032. RUN sh -c "(! ls /tmp/foo) && (! ls /tmp/foo2) && (! ls /tmp/dir1/foo)"`),
  2033. build.WithFile("foo", "foo"),
  2034. build.WithFile("foo2", "foo2"),
  2035. build.WithFile("dir1/foo", "foo in dir1"),
  2036. build.WithFile(".dockerignore", "./foo\ndir1//foo\n./dir1/../foo2"),
  2037. ))
  2038. }
  2039. func (s *DockerSuite) TestBuildDockerignoreExceptions(c *testing.T) {
  2040. name := "testbuilddockerignoreexceptions"
  2041. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2042. build.WithFile("Dockerfile", `
  2043. FROM busybox
  2044. ADD . /bla
  2045. RUN sh -c "[[ -f /bla/src/x.go ]]"
  2046. RUN sh -c "[[ -f /bla/Makefile ]]"
  2047. RUN sh -c "[[ ! -e /bla/src/_vendor ]]"
  2048. RUN sh -c "[[ ! -e /bla/.gitignore ]]"
  2049. RUN sh -c "[[ ! -e /bla/README.md ]]"
  2050. RUN sh -c "[[ -e /bla/dir/dir/foo ]]"
  2051. RUN sh -c "[[ ! -e /bla/dir/foo1 ]]"
  2052. RUN sh -c "[[ -f /bla/dir/e ]]"
  2053. RUN sh -c "[[ -f /bla/dir/e-dir/foo ]]"
  2054. RUN sh -c "[[ ! -e /bla/foo ]]"
  2055. RUN sh -c "[[ ! -e /bla/.git ]]"
  2056. RUN sh -c "[[ -e /bla/dir/a.cc ]]"`),
  2057. build.WithFile("Makefile", "all:"),
  2058. build.WithFile(".git/HEAD", "ref: foo"),
  2059. build.WithFile("src/x.go", "package main"),
  2060. build.WithFile("src/_vendor/v.go", "package main"),
  2061. build.WithFile("dir/foo", ""),
  2062. build.WithFile("dir/foo1", ""),
  2063. build.WithFile("dir/dir/f1", ""),
  2064. build.WithFile("dir/dir/foo", ""),
  2065. build.WithFile("dir/e", ""),
  2066. build.WithFile("dir/e-dir/foo", ""),
  2067. build.WithFile(".gitignore", ""),
  2068. build.WithFile("README.md", "readme"),
  2069. build.WithFile("dir/a.cc", "hello"),
  2070. build.WithFile(".dockerignore", `
  2071. .git
  2072. pkg
  2073. .gitignore
  2074. src/_vendor
  2075. *.md
  2076. dir
  2077. !dir/e*
  2078. !dir/dir/foo
  2079. **/*.cc
  2080. !**/*.cc`),
  2081. ))
  2082. }
  2083. func (s *DockerSuite) TestBuildDockerignoringDockerfile(c *testing.T) {
  2084. name := "testbuilddockerignoredockerfile"
  2085. dockerfile := `
  2086. FROM busybox
  2087. ADD . /tmp/
  2088. RUN sh -c "! ls /tmp/Dockerfile"
  2089. RUN ls /tmp/.dockerignore`
  2090. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2091. build.WithFile("Dockerfile", dockerfile),
  2092. build.WithFile(".dockerignore", "Dockerfile\n"),
  2093. ))
  2094. // FIXME(vdemeester) why twice ?
  2095. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  2096. build.WithFile("Dockerfile", dockerfile),
  2097. build.WithFile(".dockerignore", "./Dockerfile\n"),
  2098. ))
  2099. }
  2100. func (s *DockerSuite) TestBuildDockerignoringRenamedDockerfile(c *testing.T) {
  2101. name := "testbuilddockerignoredockerfile"
  2102. dockerfile := `
  2103. FROM busybox
  2104. ADD . /tmp/
  2105. RUN ls /tmp/Dockerfile
  2106. RUN sh -c "! ls /tmp/MyDockerfile"
  2107. RUN ls /tmp/.dockerignore`
  2108. buildImageSuccessfully(c, name, cli.WithFlags("-f", "MyDockerfile"), build.WithBuildContext(c,
  2109. build.WithFile("Dockerfile", "Should not use me"),
  2110. build.WithFile("MyDockerfile", dockerfile),
  2111. build.WithFile(".dockerignore", "MyDockerfile\n"),
  2112. ))
  2113. // FIXME(vdemeester) why twice ?
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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: `illegal exclusion pattern: "!"`,
  2211. })
  2212. }
  2213. func (s *DockerSuite) TestBuildDockerignoringWildTopDir(c *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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. assert.NilError(c, err)
  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 *testing.T) {
  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. assert.NilError(c, err)
  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 *testing.T) {
  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 *testing.T) {
  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. assert.NilError(c, err)
  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 *testing.T) {
  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. assert.NilError(c, err)
  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. // FIXME(vdemeester) most of the from git tests could be moved to `docker/cli` e2e tests
  2666. func (s *DockerSuite) TestBuildFromGit(c *testing.T) {
  2667. name := "testbuildfromgit"
  2668. git := fakegit.New(c, "repo", map[string]string{
  2669. "Dockerfile": `FROM busybox
  2670. ADD first /first
  2671. RUN [ -f /first ]
  2672. MAINTAINER docker`,
  2673. "first": "test git data",
  2674. }, true)
  2675. defer git.Close()
  2676. buildImageSuccessfully(c, name, build.WithContextPath(git.RepoURL))
  2677. res := inspectField(c, name, "Author")
  2678. if res != "docker" {
  2679. c.Fatalf("Maintainer should be docker, got %s", res)
  2680. }
  2681. }
  2682. func (s *DockerSuite) TestBuildFromGitWithContext(c *testing.T) {
  2683. name := "testbuildfromgit"
  2684. git := fakegit.New(c, "repo", map[string]string{
  2685. "docker/Dockerfile": `FROM busybox
  2686. ADD first /first
  2687. RUN [ -f /first ]
  2688. MAINTAINER docker`,
  2689. "docker/first": "test git data",
  2690. }, true)
  2691. defer git.Close()
  2692. buildImageSuccessfully(c, name, build.WithContextPath(fmt.Sprintf("%s#master:docker", git.RepoURL)))
  2693. res := inspectField(c, name, "Author")
  2694. if res != "docker" {
  2695. c.Fatalf("Maintainer should be docker, got %s", res)
  2696. }
  2697. }
  2698. func (s *DockerSuite) TestBuildFromGitWithF(c *testing.T) {
  2699. name := "testbuildfromgitwithf"
  2700. git := fakegit.New(c, "repo", map[string]string{
  2701. "myApp/myDockerfile": `FROM busybox
  2702. RUN echo hi from Dockerfile`,
  2703. }, true)
  2704. defer git.Close()
  2705. buildImage(name, cli.WithFlags("-f", "myApp/myDockerfile"), build.WithContextPath(git.RepoURL)).Assert(c, icmd.Expected{
  2706. Out: "hi from Dockerfile",
  2707. })
  2708. }
  2709. func (s *DockerSuite) TestBuildFromRemoteTarball(c *testing.T) {
  2710. name := "testbuildfromremotetarball"
  2711. buffer := new(bytes.Buffer)
  2712. tw := tar.NewWriter(buffer)
  2713. defer tw.Close()
  2714. dockerfile := []byte(`FROM busybox
  2715. MAINTAINER docker`)
  2716. if err := tw.WriteHeader(&tar.Header{
  2717. Name: "Dockerfile",
  2718. Size: int64(len(dockerfile)),
  2719. }); err != nil {
  2720. c.Fatalf("failed to write tar file header: %v", err)
  2721. }
  2722. if _, err := tw.Write(dockerfile); err != nil {
  2723. c.Fatalf("failed to write tar file content: %v", err)
  2724. }
  2725. if err := tw.Close(); err != nil {
  2726. c.Fatalf("failed to close tar archive: %v", err)
  2727. }
  2728. server := fakestorage.New(c, "", fakecontext.WithBinaryFiles(map[string]*bytes.Buffer{
  2729. "testT.tar": buffer,
  2730. }))
  2731. defer server.Close()
  2732. cli.BuildCmd(c, name, build.WithContextPath(server.URL()+"/testT.tar"))
  2733. res := inspectField(c, name, "Author")
  2734. if res != "docker" {
  2735. c.Fatalf("Maintainer should be docker, got %s", res)
  2736. }
  2737. }
  2738. func (s *DockerSuite) TestBuildCleanupCmdOnEntrypoint(c *testing.T) {
  2739. name := "testbuildcmdcleanuponentrypoint"
  2740. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  2741. CMD ["test"]
  2742. ENTRYPOINT ["echo"]`))
  2743. buildImageSuccessfully(c, name, build.WithDockerfile(fmt.Sprintf(`FROM %s
  2744. ENTRYPOINT ["cat"]`, name)))
  2745. res := inspectField(c, name, "Config.Cmd")
  2746. if res != "[]" {
  2747. c.Fatalf("Cmd %s, expected nil", res)
  2748. }
  2749. res = inspectField(c, name, "Config.Entrypoint")
  2750. if expected := "[cat]"; res != expected {
  2751. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  2752. }
  2753. }
  2754. func (s *DockerSuite) TestBuildClearCmd(c *testing.T) {
  2755. name := "testbuildclearcmd"
  2756. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  2757. ENTRYPOINT ["/bin/bash"]
  2758. CMD []`))
  2759. res := inspectFieldJSON(c, name, "Config.Cmd")
  2760. if res != "[]" {
  2761. c.Fatalf("Cmd %s, expected %s", res, "[]")
  2762. }
  2763. }
  2764. func (s *DockerSuite) TestBuildEmptyCmd(c *testing.T) {
  2765. // Skip on Windows. Base image on Windows has a CMD set in the image.
  2766. testRequires(c, DaemonIsLinux)
  2767. name := "testbuildemptycmd"
  2768. buildImageSuccessfully(c, name, build.WithDockerfile("FROM "+minimalBaseImage()+"\nMAINTAINER quux\n"))
  2769. res := inspectFieldJSON(c, name, "Config.Cmd")
  2770. if res != "null" {
  2771. c.Fatalf("Cmd %s, expected %s", res, "null")
  2772. }
  2773. }
  2774. func (s *DockerSuite) TestBuildOnBuildOutput(c *testing.T) {
  2775. name := "testbuildonbuildparent"
  2776. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nONBUILD RUN echo foo\n"))
  2777. buildImage(name, build.WithDockerfile("FROM "+name+"\nMAINTAINER quux\n")).Assert(c, icmd.Expected{
  2778. Out: "# Executing 1 build trigger",
  2779. })
  2780. }
  2781. // FIXME(vdemeester) should be a unit test
  2782. func (s *DockerSuite) TestBuildInvalidTag(c *testing.T) {
  2783. name := "abcd:" + testutil.GenerateRandomAlphaOnlyString(200)
  2784. buildImage(name, build.WithDockerfile("FROM "+minimalBaseImage()+"\nMAINTAINER quux\n")).Assert(c, icmd.Expected{
  2785. ExitCode: 125,
  2786. Err: "invalid reference format",
  2787. })
  2788. }
  2789. func (s *DockerSuite) TestBuildCmdShDashC(c *testing.T) {
  2790. name := "testbuildcmdshc"
  2791. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nCMD echo cmd\n"))
  2792. res := inspectFieldJSON(c, name, "Config.Cmd")
  2793. expected := `["/bin/sh","-c","echo cmd"]`
  2794. if testEnv.OSType == "windows" {
  2795. expected = `["cmd /S /C echo cmd"]`
  2796. }
  2797. if res != expected {
  2798. c.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  2799. }
  2800. }
  2801. func (s *DockerSuite) TestBuildCmdSpaces(c *testing.T) {
  2802. // Test to make sure that when we strcat arrays we take into account
  2803. // the arg separator to make sure ["echo","hi"] and ["echo hi"] don't
  2804. // look the same
  2805. name := "testbuildcmdspaces"
  2806. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nCMD [\"echo hi\"]\n"))
  2807. id1 := getIDByName(c, name)
  2808. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nCMD [\"echo\", \"hi\"]\n"))
  2809. id2 := getIDByName(c, name)
  2810. if id1 == id2 {
  2811. c.Fatal("Should not have resulted in the same CMD")
  2812. }
  2813. // Now do the same with ENTRYPOINT
  2814. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nENTRYPOINT [\"echo hi\"]\n"))
  2815. id1 = getIDByName(c, name)
  2816. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nENTRYPOINT [\"echo\", \"hi\"]\n"))
  2817. id2 = getIDByName(c, name)
  2818. if id1 == id2 {
  2819. c.Fatal("Should not have resulted in the same ENTRYPOINT")
  2820. }
  2821. }
  2822. func (s *DockerSuite) TestBuildCmdJSONNoShDashC(c *testing.T) {
  2823. name := "testbuildcmdjson"
  2824. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nCMD [\"echo\", \"cmd\"]"))
  2825. res := inspectFieldJSON(c, name, "Config.Cmd")
  2826. expected := `["echo","cmd"]`
  2827. if res != expected {
  2828. c.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  2829. }
  2830. }
  2831. func (s *DockerSuite) TestBuildEntrypointCanBeOverriddenByChild(c *testing.T) {
  2832. buildImageSuccessfully(c, "parent", build.WithDockerfile(`
  2833. FROM busybox
  2834. ENTRYPOINT exit 130
  2835. `))
  2836. icmd.RunCommand(dockerBinary, "run", "parent").Assert(c, icmd.Expected{
  2837. ExitCode: 130,
  2838. })
  2839. buildImageSuccessfully(c, "child", build.WithDockerfile(`
  2840. FROM parent
  2841. ENTRYPOINT exit 5
  2842. `))
  2843. icmd.RunCommand(dockerBinary, "run", "child").Assert(c, icmd.Expected{
  2844. ExitCode: 5,
  2845. })
  2846. }
  2847. func (s *DockerSuite) TestBuildEntrypointCanBeOverriddenByChildInspect(c *testing.T) {
  2848. var (
  2849. name = "testbuildepinherit"
  2850. name2 = "testbuildepinherit2"
  2851. expected = `["/bin/sh","-c","echo quux"]`
  2852. )
  2853. if testEnv.OSType == "windows" {
  2854. expected = `["cmd /S /C echo quux"]`
  2855. }
  2856. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nENTRYPOINT /foo/bar"))
  2857. buildImageSuccessfully(c, name2, build.WithDockerfile(fmt.Sprintf("FROM %s\nENTRYPOINT echo quux", name)))
  2858. res := inspectFieldJSON(c, name2, "Config.Entrypoint")
  2859. if res != expected {
  2860. c.Fatalf("Expected value %s not in Config.Entrypoint: %s", expected, res)
  2861. }
  2862. icmd.RunCommand(dockerBinary, "run", name2).Assert(c, icmd.Expected{
  2863. Out: "quux",
  2864. })
  2865. }
  2866. func (s *DockerSuite) TestBuildRunShEntrypoint(c *testing.T) {
  2867. name := "testbuildentrypoint"
  2868. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2869. ENTRYPOINT echo`))
  2870. dockerCmd(c, "run", "--rm", name)
  2871. }
  2872. func (s *DockerSuite) TestBuildExoticShellInterpolation(c *testing.T) {
  2873. testRequires(c, DaemonIsLinux)
  2874. name := "testbuildexoticshellinterpolation"
  2875. buildImageSuccessfully(c, name, build.WithDockerfile(`
  2876. FROM busybox
  2877. ENV SOME_VAR a.b.c
  2878. RUN [ "$SOME_VAR" = 'a.b.c' ]
  2879. RUN [ "${SOME_VAR}" = 'a.b.c' ]
  2880. RUN [ "${SOME_VAR%.*}" = 'a.b' ]
  2881. RUN [ "${SOME_VAR%%.*}" = 'a' ]
  2882. RUN [ "${SOME_VAR#*.}" = 'b.c' ]
  2883. RUN [ "${SOME_VAR##*.}" = 'c' ]
  2884. RUN [ "${SOME_VAR/c/d}" = 'a.b.d' ]
  2885. RUN [ "${#SOME_VAR}" = '5' ]
  2886. RUN [ "${SOME_UNSET_VAR:-$SOME_VAR}" = 'a.b.c' ]
  2887. RUN [ "${SOME_VAR:+Version: ${SOME_VAR}}" = 'Version: a.b.c' ]
  2888. RUN [ "${SOME_UNSET_VAR:+${SOME_VAR}}" = '' ]
  2889. RUN [ "${SOME_UNSET_VAR:-${SOME_VAR:-d.e.f}}" = 'a.b.c' ]
  2890. `))
  2891. }
  2892. func (s *DockerSuite) TestBuildVerifySingleQuoteFails(c *testing.T) {
  2893. // This testcase is supposed to generate an error because the
  2894. // JSON array we're passing in on the CMD uses single quotes instead
  2895. // of double quotes (per the JSON spec). This means we interpret it
  2896. // as a "string" instead of "JSON array" and pass it on to "sh -c" and
  2897. // it should barf on it.
  2898. name := "testbuildsinglequotefails"
  2899. expectedExitCode := 2
  2900. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2901. CMD [ '/bin/sh', '-c', 'echo hi' ]`))
  2902. icmd.RunCommand(dockerBinary, "run", "--rm", name).Assert(c, icmd.Expected{
  2903. ExitCode: expectedExitCode,
  2904. })
  2905. }
  2906. func (s *DockerSuite) TestBuildVerboseOut(c *testing.T) {
  2907. name := "testbuildverboseout"
  2908. expected := "\n123\n"
  2909. if testEnv.OSType == "windows" {
  2910. expected = "\n123\r\n"
  2911. }
  2912. buildImage(name, build.WithDockerfile(`FROM busybox
  2913. RUN echo 123`)).Assert(c, icmd.Expected{
  2914. Out: expected,
  2915. })
  2916. }
  2917. func (s *DockerSuite) TestBuildWithTabs(c *testing.T) {
  2918. name := "testbuildwithtabs"
  2919. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nRUN echo\tone\t\ttwo"))
  2920. res := inspectFieldJSON(c, name, "ContainerConfig.Cmd")
  2921. expected1 := `["/bin/sh","-c","echo\tone\t\ttwo"]`
  2922. expected2 := `["/bin/sh","-c","echo\u0009one\u0009\u0009two"]` // syntactically equivalent, and what Go 1.3 generates
  2923. if testEnv.OSType == "windows" {
  2924. expected1 = `["cmd /S /C echo\tone\t\ttwo"]`
  2925. expected2 = `["cmd /S /C echo\u0009one\u0009\u0009two"]` // syntactically equivalent, and what Go 1.3 generates
  2926. }
  2927. if res != expected1 && res != expected2 {
  2928. c.Fatalf("Missing tabs.\nGot: %s\nExp: %s or %s", res, expected1, expected2)
  2929. }
  2930. }
  2931. func (s *DockerSuite) TestBuildLabels(c *testing.T) {
  2932. name := "testbuildlabel"
  2933. expected := `{"License":"GPL","Vendor":"Acme"}`
  2934. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2935. LABEL Vendor=Acme
  2936. LABEL License GPL`))
  2937. res := inspectFieldJSON(c, name, "Config.Labels")
  2938. if res != expected {
  2939. c.Fatalf("Labels %s, expected %s", res, expected)
  2940. }
  2941. }
  2942. func (s *DockerSuite) TestBuildLabelsCache(c *testing.T) {
  2943. name := "testbuildlabelcache"
  2944. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2945. LABEL Vendor=Acme`))
  2946. id1 := getIDByName(c, name)
  2947. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2948. LABEL Vendor=Acme`))
  2949. id2 := getIDByName(c, name)
  2950. if id1 != id2 {
  2951. c.Fatalf("Build 2 should have worked & used cache(%s,%s)", id1, id2)
  2952. }
  2953. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2954. LABEL Vendor=Acme1`))
  2955. id2 = getIDByName(c, name)
  2956. if id1 == id2 {
  2957. c.Fatalf("Build 3 should have worked & NOT used cache(%s,%s)", id1, id2)
  2958. }
  2959. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2960. LABEL Vendor Acme`))
  2961. id2 = getIDByName(c, name)
  2962. if id1 != id2 {
  2963. c.Fatalf("Build 4 should have worked & used cache(%s,%s)", id1, id2)
  2964. }
  2965. // Now make sure the cache isn't used by mistake
  2966. buildImageSuccessfully(c, name, build.WithoutCache, build.WithDockerfile(`FROM busybox
  2967. LABEL f1=b1 f2=b2`))
  2968. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2969. LABEL f1=b1 f2=b2`))
  2970. id2 = getIDByName(c, name)
  2971. if id1 == id2 {
  2972. c.Fatalf("Build 6 should have worked & NOT used the cache(%s,%s)", id1, id2)
  2973. }
  2974. }
  2975. // FIXME(vdemeester) port to docker/cli e2e tests (api tests should test suppressOutput option though)
  2976. func (s *DockerSuite) TestBuildNotVerboseSuccess(c *testing.T) {
  2977. // This test makes sure that -q works correctly when build is successful:
  2978. // stdout has only the image ID (long image ID) and stderr is empty.
  2979. outRegexp := regexp.MustCompile(`^(sha256:|)[a-z0-9]{64}\n$`)
  2980. buildFlags := cli.WithFlags("-q")
  2981. tt := []struct {
  2982. Name string
  2983. BuildFunc func(string) *icmd.Result
  2984. }{
  2985. {
  2986. Name: "quiet_build_stdin_success",
  2987. BuildFunc: func(name string) *icmd.Result {
  2988. return buildImage(name, buildFlags, build.WithDockerfile("FROM busybox"))
  2989. },
  2990. },
  2991. {
  2992. Name: "quiet_build_ctx_success",
  2993. BuildFunc: func(name string) *icmd.Result {
  2994. return buildImage(name, buildFlags, build.WithBuildContext(c,
  2995. build.WithFile("Dockerfile", "FROM busybox"),
  2996. build.WithFile("quiet_build_success_fctx", "test"),
  2997. ))
  2998. },
  2999. },
  3000. {
  3001. Name: "quiet_build_git_success",
  3002. BuildFunc: func(name string) *icmd.Result {
  3003. git := fakegit.New(c, "repo", map[string]string{
  3004. "Dockerfile": "FROM busybox",
  3005. }, true)
  3006. return buildImage(name, buildFlags, build.WithContextPath(git.RepoURL))
  3007. },
  3008. },
  3009. }
  3010. for _, te := range tt {
  3011. result := te.BuildFunc(te.Name)
  3012. result.Assert(c, icmd.Success)
  3013. if outRegexp.Find([]byte(result.Stdout())) == nil {
  3014. c.Fatalf("Test %s expected stdout to match the [%v] regexp, but it is [%v]", te.Name, outRegexp, result.Stdout())
  3015. }
  3016. if result.Stderr() != "" {
  3017. c.Fatalf("Test %s expected stderr to be empty, but it is [%#v]", te.Name, result.Stderr())
  3018. }
  3019. }
  3020. }
  3021. // FIXME(vdemeester) migrate to docker/cli tests
  3022. func (s *DockerSuite) TestBuildNotVerboseFailureWithNonExistImage(c *testing.T) {
  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. // FIXME(vdemeester) migrate to docker/cli tests
  3042. func (s *DockerSuite) TestBuildNotVerboseFailure(c *testing.T) {
  3043. // This test makes sure that -q works correctly when build fails by
  3044. // comparing between the stderr output in quiet mode and in stdout
  3045. // and stderr output in verbose mode
  3046. testCases := []struct {
  3047. testName string
  3048. dockerfile string
  3049. }{
  3050. {"quiet_build_no_from_at_the_beginning", "RUN whoami"},
  3051. {"quiet_build_unknown_instr", "FROMD busybox"},
  3052. }
  3053. for _, tc := range testCases {
  3054. quietResult := buildImage(tc.testName, cli.WithFlags("-q"), build.WithDockerfile(tc.dockerfile))
  3055. quietResult.Assert(c, icmd.Expected{
  3056. ExitCode: 1,
  3057. })
  3058. result := buildImage(tc.testName, build.WithDockerfile(tc.dockerfile))
  3059. result.Assert(c, icmd.Expected{
  3060. ExitCode: 1,
  3061. })
  3062. if quietResult.Stderr() != result.Combined() {
  3063. 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()))
  3064. }
  3065. }
  3066. }
  3067. // FIXME(vdemeester) migrate to docker/cli tests
  3068. func (s *DockerSuite) TestBuildNotVerboseFailureRemote(c *testing.T) {
  3069. // This test ensures that when given a wrong URL, stderr in quiet mode and
  3070. // stderr in verbose mode are identical.
  3071. // TODO(vdemeester) with cobra, stdout has a carriage return too much so this test should not check stdout
  3072. URL := "http://something.invalid"
  3073. name := "quiet_build_wrong_remote"
  3074. quietResult := buildImage(name, cli.WithFlags("-q"), build.WithContextPath(URL))
  3075. quietResult.Assert(c, icmd.Expected{
  3076. ExitCode: 1,
  3077. })
  3078. result := buildImage(name, build.WithContextPath(URL))
  3079. result.Assert(c, icmd.Expected{
  3080. ExitCode: 1,
  3081. })
  3082. // An error message should contain name server IP and port, like this:
  3083. // "dial tcp: lookup something.invalid on 172.29.128.11:53: no such host"
  3084. // The IP:port need to be removed in order to not trigger a test failur
  3085. // when more than one nameserver is configured.
  3086. // While at it, also strip excessive newlines.
  3087. normalize := func(msg string) string {
  3088. return strings.TrimSpace(regexp.MustCompile("[1-9][0-9.]+:[0-9]+").ReplaceAllLiteralString(msg, "<ip:port>"))
  3089. }
  3090. if normalize(quietResult.Stderr()) != normalize(result.Combined()) {
  3091. c.Fatal(fmt.Errorf("Test[%s] expected that quiet stderr and verbose stdout are equal; quiet [%v], verbose [%v]", name, quietResult.Stderr(), result.Combined()))
  3092. }
  3093. }
  3094. // FIXME(vdemeester) migrate to docker/cli tests
  3095. func (s *DockerSuite) TestBuildStderr(c *testing.T) {
  3096. // This test just makes sure that no non-error output goes
  3097. // to stderr
  3098. name := "testbuildstderr"
  3099. result := buildImage(name, build.WithDockerfile("FROM busybox\nRUN echo one"))
  3100. result.Assert(c, icmd.Success)
  3101. // Windows to non-Windows should have a security warning
  3102. if runtime.GOOS == "windows" && testEnv.OSType != "windows" && !strings.Contains(result.Stdout(), "SECURITY WARNING:") {
  3103. c.Fatalf("Stdout contains unexpected output: %q", result.Stdout())
  3104. }
  3105. // Stderr should always be empty
  3106. if result.Stderr() != "" {
  3107. c.Fatalf("Stderr should have been empty, instead it's: %q", result.Stderr())
  3108. }
  3109. }
  3110. func (s *DockerSuite) TestBuildChownSingleFile(c *testing.T) {
  3111. testRequires(c, UnixCli, DaemonIsLinux) // test uses chown: not available on windows
  3112. name := "testbuildchownsinglefile"
  3113. ctx := fakecontext.New(c, "",
  3114. fakecontext.WithDockerfile(`
  3115. FROM busybox
  3116. COPY test /
  3117. RUN ls -l /test
  3118. RUN [ $(ls -l /test | awk '{print $3":"$4}') = 'root:root' ]
  3119. `),
  3120. fakecontext.WithFiles(map[string]string{
  3121. "test": "test",
  3122. }))
  3123. defer ctx.Close()
  3124. if err := os.Chown(filepath.Join(ctx.Dir, "test"), 4242, 4242); err != nil {
  3125. c.Fatal(err)
  3126. }
  3127. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  3128. }
  3129. func (s *DockerSuite) TestBuildSymlinkBreakout(c *testing.T) {
  3130. name := "testbuildsymlinkbreakout"
  3131. tmpdir, err := ioutil.TempDir("", name)
  3132. assert.NilError(c, err)
  3133. // See https://github.com/moby/moby/pull/37770 for reason for next line.
  3134. tmpdir, err = system.GetLongPathName(tmpdir)
  3135. assert.NilError(c, err)
  3136. defer os.RemoveAll(tmpdir)
  3137. ctx := filepath.Join(tmpdir, "context")
  3138. if err := os.MkdirAll(ctx, 0755); err != nil {
  3139. c.Fatal(err)
  3140. }
  3141. if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte(`
  3142. from busybox
  3143. add symlink.tar /
  3144. add inject /symlink/
  3145. `), 0644); err != nil {
  3146. c.Fatal(err)
  3147. }
  3148. inject := filepath.Join(ctx, "inject")
  3149. if err := ioutil.WriteFile(inject, nil, 0644); err != nil {
  3150. c.Fatal(err)
  3151. }
  3152. f, err := os.Create(filepath.Join(ctx, "symlink.tar"))
  3153. if err != nil {
  3154. c.Fatal(err)
  3155. }
  3156. w := tar.NewWriter(f)
  3157. w.WriteHeader(&tar.Header{
  3158. Name: "symlink2",
  3159. Typeflag: tar.TypeSymlink,
  3160. Linkname: "/../../../../../../../../../../../../../../",
  3161. Uid: os.Getuid(),
  3162. Gid: os.Getgid(),
  3163. })
  3164. w.WriteHeader(&tar.Header{
  3165. Name: "symlink",
  3166. Typeflag: tar.TypeSymlink,
  3167. Linkname: filepath.Join("symlink2", tmpdir),
  3168. Uid: os.Getuid(),
  3169. Gid: os.Getgid(),
  3170. })
  3171. w.Close()
  3172. f.Close()
  3173. buildImageSuccessfully(c, name, build.WithoutCache, build.WithExternalBuildContext(fakecontext.New(c, ctx)))
  3174. if _, err := os.Lstat(filepath.Join(tmpdir, "inject")); err == nil {
  3175. c.Fatal("symlink breakout - inject")
  3176. } else if !os.IsNotExist(err) {
  3177. c.Fatalf("unexpected error: %v", err)
  3178. }
  3179. }
  3180. func (s *DockerSuite) TestBuildXZHost(c *testing.T) {
  3181. // /usr/local/sbin/xz gets permission denied for the user
  3182. testRequires(c, NotUserNamespace)
  3183. testRequires(c, DaemonIsLinux)
  3184. name := "testbuildxzhost"
  3185. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  3186. build.WithFile("Dockerfile", `
  3187. FROM busybox
  3188. ADD xz /usr/local/sbin/
  3189. RUN chmod 755 /usr/local/sbin/xz
  3190. ADD test.xz /
  3191. RUN [ ! -e /injected ]`),
  3192. 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"),
  3193. build.WithFile("xz", "#!/bin/sh\ntouch /injected"),
  3194. ))
  3195. }
  3196. func (s *DockerSuite) TestBuildVolumesRetainContents(c *testing.T) {
  3197. // /foo/file gets permission denied for the user
  3198. testRequires(c, NotUserNamespace)
  3199. testRequires(c, DaemonIsLinux) // TODO Windows: Issue #20127
  3200. var (
  3201. name = "testbuildvolumescontent"
  3202. expected = "some text"
  3203. volName = "/foo"
  3204. )
  3205. if testEnv.OSType == "windows" {
  3206. volName = "C:/foo"
  3207. }
  3208. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  3209. build.WithFile("Dockerfile", `
  3210. FROM busybox
  3211. COPY content /foo/file
  3212. VOLUME `+volName+`
  3213. CMD cat /foo/file`),
  3214. build.WithFile("content", expected),
  3215. ))
  3216. out, _ := dockerCmd(c, "run", "--rm", name)
  3217. if out != expected {
  3218. c.Fatalf("expected file contents for /foo/file to be %q but received %q", expected, out)
  3219. }
  3220. }
  3221. func (s *DockerSuite) TestBuildFromMixedcaseDockerfile(c *testing.T) {
  3222. testRequires(c, UnixCli) // Dockerfile overwrites dockerfile on windows
  3223. testRequires(c, DaemonIsLinux)
  3224. // If Dockerfile is not present, use dockerfile
  3225. buildImage("test1", build.WithBuildContext(c,
  3226. build.WithFile("dockerfile", `FROM busybox
  3227. RUN echo from dockerfile`),
  3228. )).Assert(c, icmd.Expected{
  3229. Out: "from dockerfile",
  3230. })
  3231. // Prefer Dockerfile in place of dockerfile
  3232. buildImage("test1", build.WithBuildContext(c,
  3233. build.WithFile("dockerfile", `FROM busybox
  3234. RUN echo from dockerfile`),
  3235. build.WithFile("Dockerfile", `FROM busybox
  3236. RUN echo from Dockerfile`),
  3237. )).Assert(c, icmd.Expected{
  3238. Out: "from Dockerfile",
  3239. })
  3240. }
  3241. // FIXME(vdemeester) should migrate to docker/cli tests
  3242. func (s *DockerSuite) TestBuildFromURLWithF(c *testing.T) {
  3243. server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{"baz": `FROM busybox
  3244. RUN echo from baz
  3245. COPY * /tmp/
  3246. RUN find /tmp/`}))
  3247. defer server.Close()
  3248. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(`FROM busybox
  3249. RUN echo from Dockerfile`))
  3250. defer ctx.Close()
  3251. // Make sure that -f is ignored and that we don't use the Dockerfile
  3252. // that's in the current dir
  3253. result := cli.BuildCmd(c, "test1", cli.WithFlags("-f", "baz", server.URL()+"/baz"), func(cmd *icmd.Cmd) func() {
  3254. cmd.Dir = ctx.Dir
  3255. return nil
  3256. })
  3257. if !strings.Contains(result.Combined(), "from baz") ||
  3258. strings.Contains(result.Combined(), "/tmp/baz") ||
  3259. !strings.Contains(result.Combined(), "/tmp/Dockerfile") {
  3260. c.Fatalf("Missing proper output: %s", result.Combined())
  3261. }
  3262. }
  3263. // FIXME(vdemeester) should migrate to docker/cli tests
  3264. func (s *DockerSuite) TestBuildFromStdinWithF(c *testing.T) {
  3265. testRequires(c, DaemonIsLinux) // TODO Windows: This test is flaky; no idea why
  3266. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(`FROM busybox
  3267. RUN echo "from Dockerfile"`))
  3268. defer ctx.Close()
  3269. // Make sure that -f is ignored and that we don't use the Dockerfile
  3270. // that's in the current dir
  3271. result := cli.BuildCmd(c, "test1", cli.WithFlags("-f", "baz", "-"), func(cmd *icmd.Cmd) func() {
  3272. cmd.Dir = ctx.Dir
  3273. cmd.Stdin = strings.NewReader(`FROM busybox
  3274. RUN echo "from baz"
  3275. COPY * /tmp/
  3276. RUN sh -c "find /tmp/" # sh -c is needed on Windows to use the correct find`)
  3277. return nil
  3278. })
  3279. if !strings.Contains(result.Combined(), "from baz") ||
  3280. strings.Contains(result.Combined(), "/tmp/baz") ||
  3281. !strings.Contains(result.Combined(), "/tmp/Dockerfile") {
  3282. c.Fatalf("Missing proper output: %s", result.Combined())
  3283. }
  3284. }
  3285. func (s *DockerSuite) TestBuildFromOfficialNames(c *testing.T) {
  3286. name := "testbuildfromofficial"
  3287. fromNames := []string{
  3288. "busybox",
  3289. "docker.io/busybox",
  3290. "index.docker.io/busybox",
  3291. "library/busybox",
  3292. "docker.io/library/busybox",
  3293. "index.docker.io/library/busybox",
  3294. }
  3295. for idx, fromName := range fromNames {
  3296. imgName := fmt.Sprintf("%s%d", name, idx)
  3297. buildImageSuccessfully(c, imgName, build.WithDockerfile("FROM "+fromName))
  3298. dockerCmd(c, "rmi", imgName)
  3299. }
  3300. }
  3301. // FIXME(vdemeester) should be a unit test
  3302. func (s *DockerSuite) TestBuildSpaces(c *testing.T) {
  3303. // Test to make sure that leading/trailing spaces on a command
  3304. // doesn't change the error msg we get
  3305. name := "testspaces"
  3306. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile("FROM busybox\nCOPY\n"))
  3307. defer ctx.Close()
  3308. result1 := cli.Docker(cli.Build(name), build.WithExternalBuildContext(ctx))
  3309. result1.Assert(c, icmd.Expected{
  3310. ExitCode: 1,
  3311. })
  3312. ctx.Add("Dockerfile", "FROM busybox\nCOPY ")
  3313. result2 := cli.Docker(cli.Build(name), build.WithExternalBuildContext(ctx))
  3314. result2.Assert(c, icmd.Expected{
  3315. ExitCode: 1,
  3316. })
  3317. removeLogTimestamps := func(s string) string {
  3318. return regexp.MustCompile(`time="(.*?)"`).ReplaceAllString(s, `time=[TIMESTAMP]`)
  3319. }
  3320. // Skip over the times
  3321. e1 := removeLogTimestamps(result1.Error.Error())
  3322. e2 := removeLogTimestamps(result2.Error.Error())
  3323. // Ignore whitespace since that's what were verifying doesn't change stuff
  3324. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  3325. c.Fatalf("Build 2's error wasn't the same as build 1's\n1:%s\n2:%s", result1.Error, result2.Error)
  3326. }
  3327. ctx.Add("Dockerfile", "FROM busybox\n COPY")
  3328. result2 = cli.Docker(cli.Build(name), build.WithoutCache, build.WithExternalBuildContext(ctx))
  3329. result2.Assert(c, icmd.Expected{
  3330. ExitCode: 1,
  3331. })
  3332. // Skip over the times
  3333. e1 = removeLogTimestamps(result1.Error.Error())
  3334. e2 = removeLogTimestamps(result2.Error.Error())
  3335. // Ignore whitespace since that's what were verifying doesn't change stuff
  3336. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  3337. c.Fatalf("Build 3's error wasn't the same as build 1's\n1:%s\n3:%s", result1.Error, result2.Error)
  3338. }
  3339. ctx.Add("Dockerfile", "FROM busybox\n COPY ")
  3340. result2 = cli.Docker(cli.Build(name), build.WithoutCache, build.WithExternalBuildContext(ctx))
  3341. result2.Assert(c, icmd.Expected{
  3342. ExitCode: 1,
  3343. })
  3344. // Skip over the times
  3345. e1 = removeLogTimestamps(result1.Error.Error())
  3346. e2 = removeLogTimestamps(result2.Error.Error())
  3347. // Ignore whitespace since that's what were verifying doesn't change stuff
  3348. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  3349. c.Fatalf("Build 4's error wasn't the same as build 1's\n1:%s\n4:%s", result1.Error, result2.Error)
  3350. }
  3351. }
  3352. func (s *DockerSuite) TestBuildSpacesWithQuotes(c *testing.T) {
  3353. // Test to make sure that spaces in quotes aren't lost
  3354. name := "testspacesquotes"
  3355. dockerfile := `FROM busybox
  3356. RUN echo " \
  3357. foo "`
  3358. expected := "\n foo \n"
  3359. // Windows uses the builtin echo, which preserves quotes
  3360. if testEnv.OSType == "windows" {
  3361. expected = "\" foo \""
  3362. }
  3363. buildImage(name, build.WithDockerfile(dockerfile)).Assert(c, icmd.Expected{
  3364. Out: expected,
  3365. })
  3366. }
  3367. // #4393
  3368. func (s *DockerSuite) TestBuildVolumeFileExistsinContainer(c *testing.T) {
  3369. testRequires(c, DaemonIsLinux) // TODO Windows: This should error out
  3370. buildImage("docker-test-errcreatevolumewithfile", build.WithDockerfile(`
  3371. FROM busybox
  3372. RUN touch /foo
  3373. VOLUME /foo
  3374. `)).Assert(c, icmd.Expected{
  3375. ExitCode: 1,
  3376. Err: "file exists",
  3377. })
  3378. }
  3379. // FIXME(vdemeester) should be a unit test
  3380. func (s *DockerSuite) TestBuildMissingArgs(c *testing.T) {
  3381. // Test to make sure that all Dockerfile commands (except the ones listed
  3382. // in skipCmds) will generate an error if no args are provided.
  3383. // Note: INSERT is deprecated so we exclude it because of that.
  3384. skipCmds := map[string]struct{}{
  3385. "CMD": {},
  3386. "RUN": {},
  3387. "ENTRYPOINT": {},
  3388. "INSERT": {},
  3389. }
  3390. if testEnv.OSType == "windows" {
  3391. skipCmds = map[string]struct{}{
  3392. "CMD": {},
  3393. "RUN": {},
  3394. "ENTRYPOINT": {},
  3395. "INSERT": {},
  3396. "STOPSIGNAL": {},
  3397. "ARG": {},
  3398. "USER": {},
  3399. "EXPOSE": {},
  3400. }
  3401. }
  3402. for cmd := range command.Commands {
  3403. cmd = strings.ToUpper(cmd)
  3404. if _, ok := skipCmds[cmd]; ok {
  3405. continue
  3406. }
  3407. var dockerfile string
  3408. if cmd == "FROM" {
  3409. dockerfile = cmd
  3410. } else {
  3411. // Add FROM to make sure we don't complain about it missing
  3412. dockerfile = "FROM busybox\n" + cmd
  3413. }
  3414. buildImage("args", build.WithDockerfile(dockerfile)).Assert(c, icmd.Expected{
  3415. ExitCode: 1,
  3416. Err: cmd + " requires",
  3417. })
  3418. }
  3419. }
  3420. func (s *DockerSuite) TestBuildEmptyScratch(c *testing.T) {
  3421. testRequires(c, DaemonIsLinux)
  3422. buildImage("sc", build.WithDockerfile("FROM scratch")).Assert(c, icmd.Expected{
  3423. ExitCode: 1,
  3424. Err: "No image was generated",
  3425. })
  3426. }
  3427. func (s *DockerSuite) TestBuildDotDotFile(c *testing.T) {
  3428. buildImageSuccessfully(c, "sc", build.WithBuildContext(c,
  3429. build.WithFile("Dockerfile", "FROM busybox\n"),
  3430. build.WithFile("..gitme", ""),
  3431. ))
  3432. }
  3433. func (s *DockerSuite) TestBuildRUNoneJSON(c *testing.T) {
  3434. testRequires(c, DaemonIsLinux) // No hello-world Windows image
  3435. name := "testbuildrunonejson"
  3436. buildImage(name, build.WithDockerfile(`FROM hello-world:frozen
  3437. RUN [ "/hello" ]`)).Assert(c, icmd.Expected{
  3438. Out: "Hello from Docker",
  3439. })
  3440. }
  3441. func (s *DockerSuite) TestBuildEmptyStringVolume(c *testing.T) {
  3442. name := "testbuildemptystringvolume"
  3443. buildImage(name, build.WithDockerfile(`
  3444. FROM busybox
  3445. ENV foo=""
  3446. VOLUME $foo
  3447. `)).Assert(c, icmd.Expected{
  3448. ExitCode: 1,
  3449. })
  3450. }
  3451. func (s *DockerSuite) TestBuildContainerWithCgroupParent(c *testing.T) {
  3452. testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
  3453. cgroupParent := "test"
  3454. data, err := ioutil.ReadFile("/proc/self/cgroup")
  3455. if err != nil {
  3456. c.Fatalf("failed to read '/proc/self/cgroup - %v", err)
  3457. }
  3458. selfCgroupPaths := ParseCgroupPaths(string(data))
  3459. _, found := selfCgroupPaths["memory"]
  3460. if !found {
  3461. c.Fatalf("unable to find self memory cgroup path. CgroupsPath: %v", selfCgroupPaths)
  3462. }
  3463. result := buildImage("buildcgroupparent",
  3464. cli.WithFlags("--cgroup-parent", cgroupParent),
  3465. build.WithDockerfile(`
  3466. FROM busybox
  3467. RUN cat /proc/self/cgroup
  3468. `))
  3469. result.Assert(c, icmd.Success)
  3470. m, err := regexp.MatchString(fmt.Sprintf("memory:.*/%s/.*", cgroupParent), result.Combined())
  3471. assert.NilError(c, err)
  3472. if !m {
  3473. c.Fatalf("There is no expected memory cgroup with parent /%s/: %s", cgroupParent, result.Combined())
  3474. }
  3475. }
  3476. // FIXME(vdemeester) could be a unit test
  3477. func (s *DockerSuite) TestBuildNoDupOutput(c *testing.T) {
  3478. // Check to make sure our build output prints the Dockerfile cmd
  3479. // property - there was a bug that caused it to be duplicated on the
  3480. // Step X line
  3481. name := "testbuildnodupoutput"
  3482. result := buildImage(name, build.WithDockerfile(`
  3483. FROM busybox
  3484. RUN env`))
  3485. result.Assert(c, icmd.Success)
  3486. exp := "\nStep 2/2 : RUN env\n"
  3487. if !strings.Contains(result.Combined(), exp) {
  3488. c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", result.Combined(), exp)
  3489. }
  3490. }
  3491. // GH15826
  3492. // FIXME(vdemeester) could be a unit test
  3493. func (s *DockerSuite) TestBuildStartsFromOne(c *testing.T) {
  3494. // Explicit check to ensure that build starts from step 1 rather than 0
  3495. name := "testbuildstartsfromone"
  3496. result := buildImage(name, build.WithDockerfile(`FROM busybox`))
  3497. result.Assert(c, icmd.Success)
  3498. exp := "\nStep 1/1 : FROM busybox\n"
  3499. if !strings.Contains(result.Combined(), exp) {
  3500. c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", result.Combined(), exp)
  3501. }
  3502. }
  3503. func (s *DockerSuite) TestBuildRUNErrMsg(c *testing.T) {
  3504. // Test to make sure the bad command is quoted with just "s and
  3505. // not as a Go []string
  3506. name := "testbuildbadrunerrmsg"
  3507. shell := "/bin/sh -c"
  3508. exitCode := 127
  3509. if testEnv.OSType == "windows" {
  3510. shell = "cmd /S /C"
  3511. // architectural - Windows has to start the container to determine the exe is bad, Linux does not
  3512. exitCode = 1
  3513. }
  3514. exp := fmt.Sprintf(`The command '%s badEXE a1 \& a2 a3' returned a non-zero code: %d`, shell, exitCode)
  3515. buildImage(name, build.WithDockerfile(`
  3516. FROM busybox
  3517. RUN badEXE a1 \& a2 a3`)).Assert(c, icmd.Expected{
  3518. ExitCode: exitCode,
  3519. Err: exp,
  3520. })
  3521. }
  3522. // Issue #15634: COPY fails when path starts with "null"
  3523. func (s *DockerSuite) TestBuildNullStringInAddCopyVolume(c *testing.T) {
  3524. name := "testbuildnullstringinaddcopyvolume"
  3525. volName := "nullvolume"
  3526. if testEnv.OSType == "windows" {
  3527. volName = `C:\\nullvolume`
  3528. }
  3529. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  3530. build.WithFile("Dockerfile", `
  3531. FROM busybox
  3532. ADD null /
  3533. COPY nullfile /
  3534. VOLUME `+volName+`
  3535. `),
  3536. build.WithFile("null", "test1"),
  3537. build.WithFile("nullfile", "test2"),
  3538. ))
  3539. }
  3540. func (s *DockerSuite) TestBuildStopSignal(c *testing.T) {
  3541. testRequires(c, DaemonIsLinux) // Windows does not support STOPSIGNAL yet
  3542. imgName := "test_build_stop_signal"
  3543. buildImageSuccessfully(c, imgName, build.WithDockerfile(`FROM busybox
  3544. STOPSIGNAL SIGKILL`))
  3545. res := inspectFieldJSON(c, imgName, "Config.StopSignal")
  3546. if res != `"SIGKILL"` {
  3547. c.Fatalf("Signal %s, expected SIGKILL", res)
  3548. }
  3549. containerName := "test-container-stop-signal"
  3550. dockerCmd(c, "run", "-d", "--name", containerName, imgName, "top")
  3551. res = inspectFieldJSON(c, containerName, "Config.StopSignal")
  3552. if res != `"SIGKILL"` {
  3553. c.Fatalf("Signal %s, expected SIGKILL", res)
  3554. }
  3555. }
  3556. func (s *DockerSuite) TestBuildBuildTimeArg(c *testing.T) {
  3557. imgName := "bldargtest"
  3558. envKey := "foo"
  3559. envVal := "bar"
  3560. var dockerfile string
  3561. if testEnv.OSType == "windows" {
  3562. // Bugs in Windows busybox port - use the default base image and native cmd stuff
  3563. dockerfile = fmt.Sprintf(`FROM `+minimalBaseImage()+`
  3564. ARG %s
  3565. RUN echo %%%s%%
  3566. CMD setlocal enableextensions && if defined %s (echo %%%s%%)`, envKey, envKey, envKey, envKey)
  3567. } else {
  3568. dockerfile = fmt.Sprintf(`FROM busybox
  3569. ARG %s
  3570. RUN echo $%s
  3571. CMD echo $%s`, envKey, envKey, envKey)
  3572. }
  3573. buildImage(imgName,
  3574. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3575. build.WithDockerfile(dockerfile),
  3576. ).Assert(c, icmd.Expected{
  3577. Out: envVal,
  3578. })
  3579. containerName := "bldargCont"
  3580. out, _ := dockerCmd(c, "run", "--name", containerName, imgName)
  3581. out = strings.Trim(out, " \r\n'")
  3582. if out != "" {
  3583. c.Fatalf("run produced invalid output: %q, expected empty string", out)
  3584. }
  3585. }
  3586. func (s *DockerSuite) TestBuildBuildTimeArgHistory(c *testing.T) {
  3587. imgName := "bldargtest"
  3588. envKey := "foo"
  3589. envVal := "bar"
  3590. envDef := "bar1"
  3591. dockerfile := fmt.Sprintf(`FROM busybox
  3592. ARG %s=%s`, envKey, envDef)
  3593. buildImage(imgName,
  3594. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3595. build.WithDockerfile(dockerfile),
  3596. ).Assert(c, icmd.Expected{
  3597. Out: envVal,
  3598. })
  3599. out, _ := dockerCmd(c, "history", "--no-trunc", imgName)
  3600. outputTabs := strings.Split(out, "\n")[1]
  3601. if !strings.Contains(outputTabs, envDef) {
  3602. c.Fatalf("failed to find arg default in image history output: %q expected: %q", outputTabs, envDef)
  3603. }
  3604. }
  3605. func (s *DockerSuite) TestBuildTimeArgHistoryExclusions(c *testing.T) {
  3606. imgName := "bldargtest"
  3607. envKey := "foo"
  3608. envVal := "bar"
  3609. proxy := "HTTP_PROXY=http://user:password@proxy.example.com"
  3610. explicitProxyKey := "http_proxy"
  3611. explicitProxyVal := "http://user:password@someproxy.example.com"
  3612. dockerfile := fmt.Sprintf(`FROM busybox
  3613. ARG %s
  3614. ARG %s
  3615. RUN echo "Testing Build Args!"`, envKey, explicitProxyKey)
  3616. buildImage := func(imgName string) string {
  3617. cli.BuildCmd(c, imgName,
  3618. cli.WithFlags("--build-arg", "https_proxy=https://proxy.example.com",
  3619. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  3620. "--build-arg", fmt.Sprintf("%s=%s", explicitProxyKey, explicitProxyVal),
  3621. "--build-arg", proxy),
  3622. build.WithDockerfile(dockerfile),
  3623. )
  3624. return getIDByName(c, imgName)
  3625. }
  3626. origID := buildImage(imgName)
  3627. result := cli.DockerCmd(c, "history", "--no-trunc", imgName)
  3628. out := result.Stdout()
  3629. if strings.Contains(out, proxy) {
  3630. c.Fatalf("failed to exclude proxy settings from history!")
  3631. }
  3632. if strings.Contains(out, "https_proxy") {
  3633. c.Fatalf("failed to exclude proxy settings from history!")
  3634. }
  3635. result.Assert(c, icmd.Expected{Out: fmt.Sprintf("%s=%s", envKey, envVal)})
  3636. result.Assert(c, icmd.Expected{Out: fmt.Sprintf("%s=%s", explicitProxyKey, explicitProxyVal)})
  3637. cacheID := buildImage(imgName + "-two")
  3638. assert.Equal(c, origID, cacheID)
  3639. }
  3640. func (s *DockerSuite) TestBuildBuildTimeArgCacheHit(c *testing.T) {
  3641. imgName := "bldargtest"
  3642. envKey := "foo"
  3643. envVal := "bar"
  3644. dockerfile := fmt.Sprintf(`FROM busybox
  3645. ARG %s
  3646. RUN echo $%s`, envKey, envKey)
  3647. buildImageSuccessfully(c, imgName,
  3648. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3649. build.WithDockerfile(dockerfile),
  3650. )
  3651. origImgID := getIDByName(c, imgName)
  3652. imgNameCache := "bldargtestcachehit"
  3653. buildImageSuccessfully(c, imgNameCache,
  3654. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3655. build.WithDockerfile(dockerfile),
  3656. )
  3657. newImgID := getIDByName(c, imgName)
  3658. if newImgID != origImgID {
  3659. c.Fatalf("build didn't use cache! expected image id: %q built image id: %q", origImgID, newImgID)
  3660. }
  3661. }
  3662. func (s *DockerSuite) TestBuildBuildTimeArgCacheMissExtraArg(c *testing.T) {
  3663. imgName := "bldargtest"
  3664. envKey := "foo"
  3665. envVal := "bar"
  3666. extraEnvKey := "foo1"
  3667. extraEnvVal := "bar1"
  3668. dockerfile := fmt.Sprintf(`FROM busybox
  3669. ARG %s
  3670. ARG %s
  3671. RUN echo $%s`, envKey, extraEnvKey, envKey)
  3672. buildImageSuccessfully(c, imgName,
  3673. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3674. build.WithDockerfile(dockerfile),
  3675. )
  3676. origImgID := getIDByName(c, imgName)
  3677. imgNameCache := "bldargtestcachemiss"
  3678. buildImageSuccessfully(c, imgNameCache,
  3679. cli.WithFlags(
  3680. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  3681. "--build-arg", fmt.Sprintf("%s=%s", extraEnvKey, extraEnvVal),
  3682. ),
  3683. build.WithDockerfile(dockerfile),
  3684. )
  3685. newImgID := getIDByName(c, imgNameCache)
  3686. if newImgID == origImgID {
  3687. c.Fatalf("build used cache, expected a miss!")
  3688. }
  3689. }
  3690. func (s *DockerSuite) TestBuildBuildTimeArgCacheMissSameArgDiffVal(c *testing.T) {
  3691. imgName := "bldargtest"
  3692. envKey := "foo"
  3693. envVal := "bar"
  3694. newEnvVal := "bar1"
  3695. dockerfile := fmt.Sprintf(`FROM busybox
  3696. ARG %s
  3697. RUN echo $%s`, envKey, envKey)
  3698. buildImageSuccessfully(c, imgName,
  3699. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3700. build.WithDockerfile(dockerfile),
  3701. )
  3702. origImgID := getIDByName(c, imgName)
  3703. imgNameCache := "bldargtestcachemiss"
  3704. buildImageSuccessfully(c, imgNameCache,
  3705. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, newEnvVal)),
  3706. build.WithDockerfile(dockerfile),
  3707. )
  3708. newImgID := getIDByName(c, imgNameCache)
  3709. if newImgID == origImgID {
  3710. c.Fatalf("build used cache, expected a miss!")
  3711. }
  3712. }
  3713. func (s *DockerSuite) TestBuildBuildTimeArgOverrideArgDefinedBeforeEnv(c *testing.T) {
  3714. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3715. imgName := "bldargtest"
  3716. envKey := "foo"
  3717. envVal := "bar"
  3718. envValOverride := "barOverride"
  3719. dockerfile := fmt.Sprintf(`FROM busybox
  3720. ARG %s
  3721. ENV %s %s
  3722. RUN echo $%s
  3723. CMD echo $%s
  3724. `, envKey, envKey, envValOverride, envKey, envKey)
  3725. result := buildImage(imgName,
  3726. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3727. build.WithDockerfile(dockerfile),
  3728. )
  3729. result.Assert(c, icmd.Success)
  3730. if strings.Count(result.Combined(), envValOverride) != 2 {
  3731. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envValOverride)
  3732. }
  3733. containerName := "bldargCont"
  3734. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOverride) {
  3735. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOverride)
  3736. }
  3737. }
  3738. // FIXME(vdemeester) might be useful to merge with the one above ?
  3739. func (s *DockerSuite) TestBuildBuildTimeArgOverrideEnvDefinedBeforeArg(c *testing.T) {
  3740. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3741. imgName := "bldargtest"
  3742. envKey := "foo"
  3743. envVal := "bar"
  3744. envValOverride := "barOverride"
  3745. dockerfile := fmt.Sprintf(`FROM busybox
  3746. ENV %s %s
  3747. ARG %s
  3748. RUN echo $%s
  3749. CMD echo $%s
  3750. `, envKey, envValOverride, envKey, envKey, envKey)
  3751. result := buildImage(imgName,
  3752. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3753. build.WithDockerfile(dockerfile),
  3754. )
  3755. result.Assert(c, icmd.Success)
  3756. if strings.Count(result.Combined(), envValOverride) != 2 {
  3757. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envValOverride)
  3758. }
  3759. containerName := "bldargCont"
  3760. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOverride) {
  3761. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOverride)
  3762. }
  3763. }
  3764. func (s *DockerSuite) TestBuildBuildTimeArgExpansion(c *testing.T) {
  3765. imgName := "bldvarstest"
  3766. wdVar := "WDIR"
  3767. wdVal := "/tmp/"
  3768. addVar := "AFILE"
  3769. addVal := "addFile"
  3770. copyVar := "CFILE"
  3771. copyVal := "copyFile"
  3772. envVar := "foo"
  3773. envVal := "bar"
  3774. exposeVar := "EPORT"
  3775. exposeVal := "9999"
  3776. userVar := "USER"
  3777. userVal := "testUser"
  3778. volVar := "VOL"
  3779. volVal := "/testVol/"
  3780. if DaemonIsWindows() {
  3781. volVal = "C:\\testVol"
  3782. wdVal = "C:\\tmp"
  3783. }
  3784. buildImageSuccessfully(c, imgName,
  3785. cli.WithFlags(
  3786. "--build-arg", fmt.Sprintf("%s=%s", wdVar, wdVal),
  3787. "--build-arg", fmt.Sprintf("%s=%s", addVar, addVal),
  3788. "--build-arg", fmt.Sprintf("%s=%s", copyVar, copyVal),
  3789. "--build-arg", fmt.Sprintf("%s=%s", envVar, envVal),
  3790. "--build-arg", fmt.Sprintf("%s=%s", exposeVar, exposeVal),
  3791. "--build-arg", fmt.Sprintf("%s=%s", userVar, userVal),
  3792. "--build-arg", fmt.Sprintf("%s=%s", volVar, volVal),
  3793. ),
  3794. build.WithBuildContext(c,
  3795. build.WithFile("Dockerfile", fmt.Sprintf(`FROM busybox
  3796. ARG %s
  3797. WORKDIR ${%s}
  3798. ARG %s
  3799. ADD ${%s} testDir/
  3800. ARG %s
  3801. COPY $%s testDir/
  3802. ARG %s
  3803. ENV %s=${%s}
  3804. ARG %s
  3805. EXPOSE $%s
  3806. ARG %s
  3807. USER $%s
  3808. ARG %s
  3809. VOLUME ${%s}`,
  3810. wdVar, wdVar, addVar, addVar, copyVar, copyVar, envVar, envVar,
  3811. envVar, exposeVar, exposeVar, userVar, userVar, volVar, volVar)),
  3812. build.WithFile(addVal, "some stuff"),
  3813. build.WithFile(copyVal, "some stuff"),
  3814. ),
  3815. )
  3816. res := inspectField(c, imgName, "Config.WorkingDir")
  3817. assert.Equal(c, filepath.ToSlash(res), filepath.ToSlash(wdVal))
  3818. var resArr []string
  3819. inspectFieldAndUnmarshall(c, imgName, "Config.Env", &resArr)
  3820. found := false
  3821. for _, v := range resArr {
  3822. if fmt.Sprintf("%s=%s", envVar, envVal) == v {
  3823. found = true
  3824. break
  3825. }
  3826. }
  3827. if !found {
  3828. c.Fatalf("Config.Env value mismatch. Expected <key=value> to exist: %s=%s, got: %v",
  3829. envVar, envVal, resArr)
  3830. }
  3831. var resMap map[string]interface{}
  3832. inspectFieldAndUnmarshall(c, imgName, "Config.ExposedPorts", &resMap)
  3833. if _, ok := resMap[fmt.Sprintf("%s/tcp", exposeVal)]; !ok {
  3834. c.Fatalf("Config.ExposedPorts value mismatch. Expected exposed port: %s/tcp, got: %v", exposeVal, resMap)
  3835. }
  3836. res = inspectField(c, imgName, "Config.User")
  3837. if res != userVal {
  3838. c.Fatalf("Config.User value mismatch. Expected: %s, got: %s", userVal, res)
  3839. }
  3840. inspectFieldAndUnmarshall(c, imgName, "Config.Volumes", &resMap)
  3841. if _, ok := resMap[volVal]; !ok {
  3842. c.Fatalf("Config.Volumes value mismatch. Expected volume: %s, got: %v", volVal, resMap)
  3843. }
  3844. }
  3845. func (s *DockerSuite) TestBuildBuildTimeArgExpansionOverride(c *testing.T) {
  3846. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3847. imgName := "bldvarstest"
  3848. envKey := "foo"
  3849. envVal := "bar"
  3850. envKey1 := "foo1"
  3851. envValOverride := "barOverride"
  3852. dockerfile := fmt.Sprintf(`FROM busybox
  3853. ARG %s
  3854. ENV %s %s
  3855. ENV %s ${%s}
  3856. RUN echo $%s
  3857. CMD echo $%s`, envKey, envKey, envValOverride, envKey1, envKey, envKey1, envKey1)
  3858. result := buildImage(imgName,
  3859. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3860. build.WithDockerfile(dockerfile),
  3861. )
  3862. result.Assert(c, icmd.Success)
  3863. if strings.Count(result.Combined(), envValOverride) != 2 {
  3864. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envValOverride)
  3865. }
  3866. containerName := "bldargCont"
  3867. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOverride) {
  3868. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOverride)
  3869. }
  3870. }
  3871. func (s *DockerSuite) TestBuildBuildTimeArgUntrustedDefinedAfterUse(c *testing.T) {
  3872. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3873. imgName := "bldargtest"
  3874. envKey := "foo"
  3875. envVal := "bar"
  3876. dockerfile := fmt.Sprintf(`FROM busybox
  3877. RUN echo $%s
  3878. ARG %s
  3879. CMD echo $%s`, envKey, envKey, envKey)
  3880. result := buildImage(imgName,
  3881. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3882. build.WithDockerfile(dockerfile),
  3883. )
  3884. result.Assert(c, icmd.Success)
  3885. if strings.Contains(result.Combined(), envVal) {
  3886. c.Fatalf("able to access environment variable in output: %q expected to be missing", result.Combined())
  3887. }
  3888. containerName := "bldargCont"
  3889. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); out != "\n" {
  3890. c.Fatalf("run produced invalid output: %q, expected empty string", out)
  3891. }
  3892. }
  3893. func (s *DockerSuite) TestBuildBuildTimeArgBuiltinArg(c *testing.T) {
  3894. testRequires(c, DaemonIsLinux) // Windows does not support --build-arg
  3895. imgName := "bldargtest"
  3896. envKey := "HTTP_PROXY"
  3897. envVal := "bar"
  3898. dockerfile := fmt.Sprintf(`FROM busybox
  3899. RUN echo $%s
  3900. CMD echo $%s`, envKey, envKey)
  3901. result := buildImage(imgName,
  3902. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3903. build.WithDockerfile(dockerfile),
  3904. )
  3905. result.Assert(c, icmd.Success)
  3906. if !strings.Contains(result.Combined(), envVal) {
  3907. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envVal)
  3908. }
  3909. containerName := "bldargCont"
  3910. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); out != "\n" {
  3911. c.Fatalf("run produced invalid output: %q, expected empty string", out)
  3912. }
  3913. }
  3914. func (s *DockerSuite) TestBuildBuildTimeArgDefaultOverride(c *testing.T) {
  3915. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3916. imgName := "bldargtest"
  3917. envKey := "foo"
  3918. envVal := "bar"
  3919. envValOverride := "barOverride"
  3920. dockerfile := fmt.Sprintf(`FROM busybox
  3921. ARG %s=%s
  3922. ENV %s $%s
  3923. RUN echo $%s
  3924. CMD echo $%s`, envKey, envVal, envKey, envKey, envKey, envKey)
  3925. result := buildImage(imgName,
  3926. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envValOverride)),
  3927. build.WithDockerfile(dockerfile),
  3928. )
  3929. result.Assert(c, icmd.Success)
  3930. if strings.Count(result.Combined(), envValOverride) != 1 {
  3931. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envValOverride)
  3932. }
  3933. containerName := "bldargCont"
  3934. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOverride) {
  3935. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOverride)
  3936. }
  3937. }
  3938. func (s *DockerSuite) TestBuildBuildTimeArgUnconsumedArg(c *testing.T) {
  3939. imgName := "bldargtest"
  3940. envKey := "foo"
  3941. envVal := "bar"
  3942. dockerfile := fmt.Sprintf(`FROM busybox
  3943. RUN echo $%s
  3944. CMD echo $%s`, envKey, envKey)
  3945. warnStr := "[Warning] One or more build-args"
  3946. buildImage(imgName,
  3947. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3948. build.WithDockerfile(dockerfile),
  3949. ).Assert(c, icmd.Expected{
  3950. Out: warnStr,
  3951. })
  3952. }
  3953. func (s *DockerSuite) TestBuildBuildTimeArgEnv(c *testing.T) {
  3954. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3955. dockerfile := `FROM busybox
  3956. ARG FOO1=fromfile
  3957. ARG FOO2=fromfile
  3958. ARG FOO3=fromfile
  3959. ARG FOO4=fromfile
  3960. ARG FOO5
  3961. ARG FOO6
  3962. ARG FO10
  3963. RUN env
  3964. RUN [ "$FOO1" = "fromcmd" ]
  3965. RUN [ "$FOO2" = "" ]
  3966. RUN [ "$FOO3" = "fromenv" ]
  3967. RUN [ "$FOO4" = "fromfile" ]
  3968. RUN [ "$FOO5" = "fromcmd" ]
  3969. # The following should not exist at all in the env
  3970. RUN [ "$(env | grep FOO6)" = "" ]
  3971. RUN [ "$(env | grep FOO7)" = "" ]
  3972. RUN [ "$(env | grep FOO8)" = "" ]
  3973. RUN [ "$(env | grep FOO9)" = "" ]
  3974. RUN [ "$FO10" = "" ]
  3975. `
  3976. result := buildImage("testbuildtimeargenv",
  3977. cli.WithFlags(
  3978. "--build-arg", fmt.Sprintf("FOO1=fromcmd"),
  3979. "--build-arg", fmt.Sprintf("FOO2="),
  3980. "--build-arg", fmt.Sprintf("FOO3"), // set in env
  3981. "--build-arg", fmt.Sprintf("FOO4"), // not set in env
  3982. "--build-arg", fmt.Sprintf("FOO5=fromcmd"),
  3983. // FOO6 is not set at all
  3984. "--build-arg", fmt.Sprintf("FOO7=fromcmd"), // should produce a warning
  3985. "--build-arg", fmt.Sprintf("FOO8="), // should produce a warning
  3986. "--build-arg", fmt.Sprintf("FOO9"), // should produce a warning
  3987. "--build-arg", fmt.Sprintf("FO10"), // not set in env, empty value
  3988. ),
  3989. cli.WithEnvironmentVariables(append(os.Environ(),
  3990. "FOO1=fromenv",
  3991. "FOO2=fromenv",
  3992. "FOO3=fromenv")...),
  3993. build.WithBuildContext(c,
  3994. build.WithFile("Dockerfile", dockerfile),
  3995. ),
  3996. )
  3997. result.Assert(c, icmd.Success)
  3998. // Now check to make sure we got a warning msg about unused build-args
  3999. i := strings.Index(result.Combined(), "[Warning]")
  4000. if i < 0 {
  4001. c.Fatalf("Missing the build-arg warning in %q", result.Combined())
  4002. }
  4003. out := result.Combined()[i:] // "out" should contain just the warning message now
  4004. // These were specified on a --build-arg but no ARG was in the Dockerfile
  4005. assert.Assert(c, strings.Contains(out, "FOO7"))
  4006. assert.Assert(c, strings.Contains(out, "FOO8"))
  4007. assert.Assert(c, strings.Contains(out, "FOO9"))
  4008. }
  4009. func (s *DockerSuite) TestBuildBuildTimeArgQuotedValVariants(c *testing.T) {
  4010. imgName := "bldargtest"
  4011. envKey := "foo"
  4012. envKey1 := "foo1"
  4013. envKey2 := "foo2"
  4014. envKey3 := "foo3"
  4015. dockerfile := fmt.Sprintf(`FROM busybox
  4016. ARG %s=""
  4017. ARG %s=''
  4018. ARG %s="''"
  4019. ARG %s='""'
  4020. RUN [ "$%s" != "$%s" ]
  4021. RUN [ "$%s" != "$%s" ]
  4022. RUN [ "$%s" != "$%s" ]
  4023. RUN [ "$%s" != "$%s" ]
  4024. RUN [ "$%s" != "$%s" ]`, envKey, envKey1, envKey2, envKey3,
  4025. envKey, envKey2, envKey, envKey3, envKey1, envKey2, envKey1, envKey3,
  4026. envKey2, envKey3)
  4027. buildImageSuccessfully(c, imgName, build.WithDockerfile(dockerfile))
  4028. }
  4029. func (s *DockerSuite) TestBuildBuildTimeArgEmptyValVariants(c *testing.T) {
  4030. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  4031. imgName := "bldargtest"
  4032. envKey := "foo"
  4033. envKey1 := "foo1"
  4034. envKey2 := "foo2"
  4035. dockerfile := fmt.Sprintf(`FROM busybox
  4036. ARG %s=
  4037. ARG %s=""
  4038. ARG %s=''
  4039. RUN [ "$%s" = "$%s" ]
  4040. RUN [ "$%s" = "$%s" ]
  4041. RUN [ "$%s" = "$%s" ]`, envKey, envKey1, envKey2, envKey, envKey1, envKey1, envKey2, envKey, envKey2)
  4042. buildImageSuccessfully(c, imgName, build.WithDockerfile(dockerfile))
  4043. }
  4044. func (s *DockerSuite) TestBuildBuildTimeArgDefinitionWithNoEnvInjection(c *testing.T) {
  4045. imgName := "bldargtest"
  4046. envKey := "foo"
  4047. dockerfile := fmt.Sprintf(`FROM busybox
  4048. ARG %s
  4049. RUN env`, envKey)
  4050. result := cli.BuildCmd(c, imgName, build.WithDockerfile(dockerfile))
  4051. result.Assert(c, icmd.Success)
  4052. if strings.Count(result.Combined(), envKey) != 1 {
  4053. c.Fatalf("unexpected number of occurrences of the arg in output: %q expected: 1", result.Combined())
  4054. }
  4055. }
  4056. func (s *DockerSuite) TestBuildMultiStageArg(c *testing.T) {
  4057. imgName := "multifrombldargtest"
  4058. dockerfile := `FROM busybox
  4059. ARG foo=abc
  4060. LABEL multifromtest=1
  4061. RUN env > /out
  4062. FROM busybox
  4063. ARG bar=def
  4064. RUN env > /out`
  4065. result := cli.BuildCmd(c, imgName, build.WithDockerfile(dockerfile))
  4066. result.Assert(c, icmd.Success)
  4067. result = cli.DockerCmd(c, "images", "-q", "-f", "label=multifromtest=1")
  4068. parentID := strings.TrimSpace(result.Stdout())
  4069. result = cli.DockerCmd(c, "run", "--rm", parentID, "cat", "/out")
  4070. assert.Assert(c, strings.Contains(result.Stdout(), "foo=abc"))
  4071. result = cli.DockerCmd(c, "run", "--rm", imgName, "cat", "/out")
  4072. assert.Assert(c, !strings.Contains(result.Stdout(), "foo"))
  4073. assert.Assert(c, strings.Contains(result.Stdout(), "bar=def"))
  4074. }
  4075. func (s *DockerSuite) TestBuildMultiStageGlobalArg(c *testing.T) {
  4076. imgName := "multifrombldargtest"
  4077. dockerfile := `ARG tag=nosuchtag
  4078. FROM busybox:${tag}
  4079. LABEL multifromtest=1
  4080. RUN env > /out
  4081. FROM busybox:${tag}
  4082. ARG tag
  4083. RUN env > /out`
  4084. result := cli.BuildCmd(c, imgName,
  4085. build.WithDockerfile(dockerfile),
  4086. cli.WithFlags("--build-arg", fmt.Sprintf("tag=latest")))
  4087. result.Assert(c, icmd.Success)
  4088. result = cli.DockerCmd(c, "images", "-q", "-f", "label=multifromtest=1")
  4089. parentID := strings.TrimSpace(result.Stdout())
  4090. result = cli.DockerCmd(c, "run", "--rm", parentID, "cat", "/out")
  4091. assert.Assert(c, !strings.Contains(result.Stdout(), "tag"))
  4092. result = cli.DockerCmd(c, "run", "--rm", imgName, "cat", "/out")
  4093. assert.Assert(c, strings.Contains(result.Stdout(), "tag=latest"))
  4094. }
  4095. func (s *DockerSuite) TestBuildMultiStageUnusedArg(c *testing.T) {
  4096. imgName := "multifromunusedarg"
  4097. dockerfile := `FROM busybox
  4098. ARG foo
  4099. FROM busybox
  4100. ARG bar
  4101. RUN env > /out`
  4102. result := cli.BuildCmd(c, imgName,
  4103. build.WithDockerfile(dockerfile),
  4104. cli.WithFlags("--build-arg", fmt.Sprintf("baz=abc")))
  4105. result.Assert(c, icmd.Success)
  4106. assert.Assert(c, strings.Contains(result.Combined(), "[Warning]"))
  4107. assert.Assert(c, strings.Contains(result.Combined(), "[baz] were not consumed"))
  4108. result = cli.DockerCmd(c, "run", "--rm", imgName, "cat", "/out")
  4109. assert.Assert(c, !strings.Contains(result.Stdout(), "bar"))
  4110. assert.Assert(c, !strings.Contains(result.Stdout(), "baz"))
  4111. }
  4112. func (s *DockerSuite) TestBuildNoNamedVolume(c *testing.T) {
  4113. volName := "testname:/foo"
  4114. if testEnv.OSType == "windows" {
  4115. volName = "testname:C:\\foo"
  4116. }
  4117. dockerCmd(c, "run", "-v", volName, "busybox", "sh", "-c", "touch /foo/oops")
  4118. dockerFile := `FROM busybox
  4119. VOLUME ` + volName + `
  4120. RUN ls /foo/oops
  4121. `
  4122. buildImage("test", build.WithDockerfile(dockerFile)).Assert(c, icmd.Expected{
  4123. ExitCode: 1,
  4124. })
  4125. }
  4126. func (s *DockerSuite) TestBuildTagEvent(c *testing.T) {
  4127. since := daemonUnixTime(c)
  4128. dockerFile := `FROM busybox
  4129. RUN echo events
  4130. `
  4131. buildImageSuccessfully(c, "test", build.WithDockerfile(dockerFile))
  4132. until := daemonUnixTime(c)
  4133. out, _ := dockerCmd(c, "events", "--since", since, "--until", until, "--filter", "type=image")
  4134. events := strings.Split(strings.TrimSpace(out), "\n")
  4135. actions := eventActionsByIDAndType(c, events, "test:latest", "image")
  4136. var foundTag bool
  4137. for _, a := range actions {
  4138. if a == "tag" {
  4139. foundTag = true
  4140. break
  4141. }
  4142. }
  4143. assert.Assert(c, foundTag, "No tag event found:\n%s", out)
  4144. }
  4145. // #15780
  4146. func (s *DockerSuite) TestBuildMultipleTags(c *testing.T) {
  4147. dockerfile := `
  4148. FROM busybox
  4149. MAINTAINER test-15780
  4150. `
  4151. buildImageSuccessfully(c, "tag1", cli.WithFlags("-t", "tag2:v2", "-t", "tag1:latest", "-t", "tag1"), build.WithDockerfile(dockerfile))
  4152. id1 := getIDByName(c, "tag1")
  4153. id2 := getIDByName(c, "tag2:v2")
  4154. assert.Equal(c, id1, id2)
  4155. }
  4156. // #17290
  4157. func (s *DockerSuite) TestBuildCacheBrokenSymlink(c *testing.T) {
  4158. name := "testbuildbrokensymlink"
  4159. ctx := fakecontext.New(c, "",
  4160. fakecontext.WithDockerfile(`
  4161. FROM busybox
  4162. COPY . ./`),
  4163. fakecontext.WithFiles(map[string]string{
  4164. "foo": "bar",
  4165. }))
  4166. defer ctx.Close()
  4167. err := os.Symlink(filepath.Join(ctx.Dir, "nosuchfile"), filepath.Join(ctx.Dir, "asymlink"))
  4168. assert.NilError(c, err)
  4169. // warm up cache
  4170. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4171. // add new file to context, should invalidate cache
  4172. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "newfile"), []byte("foo"), 0644)
  4173. assert.NilError(c, err)
  4174. result := cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4175. if strings.Contains(result.Combined(), "Using cache") {
  4176. c.Fatal("2nd build used cache on ADD, it shouldn't")
  4177. }
  4178. }
  4179. func (s *DockerSuite) TestBuildFollowSymlinkToFile(c *testing.T) {
  4180. name := "testbuildbrokensymlink"
  4181. ctx := fakecontext.New(c, "",
  4182. fakecontext.WithDockerfile(`
  4183. FROM busybox
  4184. COPY asymlink target`),
  4185. fakecontext.WithFiles(map[string]string{
  4186. "foo": "bar",
  4187. }))
  4188. defer ctx.Close()
  4189. err := os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink"))
  4190. assert.NilError(c, err)
  4191. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4192. out := cli.DockerCmd(c, "run", "--rm", name, "cat", "target").Combined()
  4193. assert.Assert(c, cmp.Regexp("^bar$", out))
  4194. // change target file should invalidate cache
  4195. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "foo"), []byte("baz"), 0644)
  4196. assert.NilError(c, err)
  4197. result := cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4198. assert.Assert(c, !strings.Contains(result.Combined(), "Using cache"))
  4199. out = cli.DockerCmd(c, "run", "--rm", name, "cat", "target").Combined()
  4200. assert.Assert(c, cmp.Regexp("^baz$", out))
  4201. }
  4202. func (s *DockerSuite) TestBuildFollowSymlinkToDir(c *testing.T) {
  4203. name := "testbuildbrokensymlink"
  4204. ctx := fakecontext.New(c, "",
  4205. fakecontext.WithDockerfile(`
  4206. FROM busybox
  4207. COPY asymlink /`),
  4208. fakecontext.WithFiles(map[string]string{
  4209. "foo/abc": "bar",
  4210. "foo/def": "baz",
  4211. }))
  4212. defer ctx.Close()
  4213. err := os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink"))
  4214. assert.NilError(c, err)
  4215. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4216. out := cli.DockerCmd(c, "run", "--rm", name, "cat", "abc", "def").Combined()
  4217. assert.Assert(c, cmp.Regexp("^barbaz$", out))
  4218. // change target file should invalidate cache
  4219. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "foo/def"), []byte("bax"), 0644)
  4220. assert.NilError(c, err)
  4221. result := cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4222. assert.Assert(c, !strings.Contains(result.Combined(), "Using cache"))
  4223. out = cli.DockerCmd(c, "run", "--rm", name, "cat", "abc", "def").Combined()
  4224. assert.Assert(c, cmp.Regexp("^barbax$", out))
  4225. }
  4226. // TestBuildSymlinkBasename tests that target file gets basename from symlink,
  4227. // not from the target file.
  4228. func (s *DockerSuite) TestBuildSymlinkBasename(c *testing.T) {
  4229. name := "testbuildbrokensymlink"
  4230. ctx := fakecontext.New(c, "",
  4231. fakecontext.WithDockerfile(`
  4232. FROM busybox
  4233. COPY asymlink /`),
  4234. fakecontext.WithFiles(map[string]string{
  4235. "foo": "bar",
  4236. }))
  4237. defer ctx.Close()
  4238. err := os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink"))
  4239. assert.NilError(c, err)
  4240. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4241. out := cli.DockerCmd(c, "run", "--rm", name, "cat", "asymlink").Combined()
  4242. assert.Assert(c, cmp.Regexp("^bar$", out))
  4243. }
  4244. // #17827
  4245. func (s *DockerSuite) TestBuildCacheRootSource(c *testing.T) {
  4246. name := "testbuildrootsource"
  4247. ctx := fakecontext.New(c, "",
  4248. fakecontext.WithDockerfile(`
  4249. FROM busybox
  4250. COPY / /data`),
  4251. fakecontext.WithFiles(map[string]string{
  4252. "foo": "bar",
  4253. }))
  4254. defer ctx.Close()
  4255. // warm up cache
  4256. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4257. // change file, should invalidate cache
  4258. err := ioutil.WriteFile(filepath.Join(ctx.Dir, "foo"), []byte("baz"), 0644)
  4259. assert.NilError(c, err)
  4260. result := cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4261. assert.Assert(c, !strings.Contains(result.Combined(), "Using cache"))
  4262. }
  4263. // #19375
  4264. // FIXME(vdemeester) should migrate to docker/cli tests
  4265. func (s *DockerSuite) TestBuildFailsGitNotCallable(c *testing.T) {
  4266. buildImage("gitnotcallable", cli.WithEnvironmentVariables("PATH="),
  4267. build.WithContextPath("github.com/docker/v1.10-migrator.git")).Assert(c, icmd.Expected{
  4268. ExitCode: 1,
  4269. Err: "unable to prepare context: unable to find 'git': ",
  4270. })
  4271. buildImage("gitnotcallable", cli.WithEnvironmentVariables("PATH="),
  4272. build.WithContextPath("https://github.com/docker/v1.10-migrator.git")).Assert(c, icmd.Expected{
  4273. ExitCode: 1,
  4274. Err: "unable to prepare context: unable to find 'git': ",
  4275. })
  4276. }
  4277. // TestBuildWorkdirWindowsPath tests that a Windows style path works as a workdir
  4278. func (s *DockerSuite) TestBuildWorkdirWindowsPath(c *testing.T) {
  4279. testRequires(c, DaemonIsWindows)
  4280. name := "testbuildworkdirwindowspath"
  4281. buildImageSuccessfully(c, name, build.WithDockerfile(`
  4282. FROM `+testEnv.PlatformDefaults.BaseImage+`
  4283. RUN mkdir C:\\work
  4284. WORKDIR C:\\work
  4285. RUN if "%CD%" NEQ "C:\work" exit -1
  4286. `))
  4287. }
  4288. func (s *DockerSuite) TestBuildLabel(c *testing.T) {
  4289. name := "testbuildlabel"
  4290. testLabel := "foo"
  4291. buildImageSuccessfully(c, name, cli.WithFlags("--label", testLabel),
  4292. build.WithDockerfile(`
  4293. FROM `+minimalBaseImage()+`
  4294. LABEL default foo
  4295. `))
  4296. var labels map[string]string
  4297. inspectFieldAndUnmarshall(c, name, "Config.Labels", &labels)
  4298. if _, ok := labels[testLabel]; !ok {
  4299. c.Fatal("label not found in image")
  4300. }
  4301. }
  4302. func (s *DockerSuite) TestBuildLabelOneNode(c *testing.T) {
  4303. name := "testbuildlabel"
  4304. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo=bar"),
  4305. build.WithDockerfile("FROM busybox"))
  4306. var labels map[string]string
  4307. inspectFieldAndUnmarshall(c, name, "Config.Labels", &labels)
  4308. v, ok := labels["foo"]
  4309. if !ok {
  4310. c.Fatal("label `foo` not found in image")
  4311. }
  4312. assert.Equal(c, v, "bar")
  4313. }
  4314. func (s *DockerSuite) TestBuildLabelCacheCommit(c *testing.T) {
  4315. name := "testbuildlabelcachecommit"
  4316. testLabel := "foo"
  4317. buildImageSuccessfully(c, name, build.WithDockerfile(`
  4318. FROM `+minimalBaseImage()+`
  4319. LABEL default foo
  4320. `))
  4321. buildImageSuccessfully(c, name, cli.WithFlags("--label", testLabel),
  4322. build.WithDockerfile(`
  4323. FROM `+minimalBaseImage()+`
  4324. LABEL default foo
  4325. `))
  4326. var labels map[string]string
  4327. inspectFieldAndUnmarshall(c, name, "Config.Labels", &labels)
  4328. if _, ok := labels[testLabel]; !ok {
  4329. c.Fatal("label not found in image")
  4330. }
  4331. }
  4332. func (s *DockerSuite) TestBuildLabelMultiple(c *testing.T) {
  4333. name := "testbuildlabelmultiple"
  4334. testLabels := map[string]string{
  4335. "foo": "bar",
  4336. "123": "456",
  4337. }
  4338. var labelArgs []string
  4339. for k, v := range testLabels {
  4340. labelArgs = append(labelArgs, "--label", k+"="+v)
  4341. }
  4342. buildImageSuccessfully(c, name, cli.WithFlags(labelArgs...),
  4343. build.WithDockerfile(`
  4344. FROM `+minimalBaseImage()+`
  4345. LABEL default foo
  4346. `))
  4347. var labels map[string]string
  4348. inspectFieldAndUnmarshall(c, name, "Config.Labels", &labels)
  4349. for k, v := range testLabels {
  4350. if x, ok := labels[k]; !ok || x != v {
  4351. c.Fatalf("label %s=%s not found in image", k, v)
  4352. }
  4353. }
  4354. }
  4355. func (s *DockerRegistryAuthHtpasswdSuite) TestBuildFromAuthenticatedRegistry(c *testing.T) {
  4356. dockerCmd(c, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL)
  4357. baseImage := privateRegistryURL + "/baseimage"
  4358. buildImageSuccessfully(c, baseImage, build.WithDockerfile(`
  4359. FROM busybox
  4360. ENV env1 val1
  4361. `))
  4362. dockerCmd(c, "push", baseImage)
  4363. dockerCmd(c, "rmi", baseImage)
  4364. buildImageSuccessfully(c, baseImage, build.WithDockerfile(fmt.Sprintf(`
  4365. FROM %s
  4366. ENV env2 val2
  4367. `, baseImage)))
  4368. }
  4369. func (s *DockerRegistryAuthHtpasswdSuite) TestBuildWithExternalAuth(c *testing.T) {
  4370. osPath := os.Getenv("PATH")
  4371. defer os.Setenv("PATH", osPath)
  4372. workingDir, err := os.Getwd()
  4373. assert.NilError(c, err)
  4374. absolute, err := filepath.Abs(filepath.Join(workingDir, "fixtures", "auth"))
  4375. assert.NilError(c, err)
  4376. testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute)
  4377. os.Setenv("PATH", testPath)
  4378. repoName := fmt.Sprintf("%v/dockercli/busybox:authtest", privateRegistryURL)
  4379. tmp, err := ioutil.TempDir("", "integration-cli-")
  4380. assert.NilError(c, err)
  4381. externalAuthConfig := `{ "credsStore": "shell-test" }`
  4382. configPath := filepath.Join(tmp, "config.json")
  4383. err = ioutil.WriteFile(configPath, []byte(externalAuthConfig), 0644)
  4384. assert.NilError(c, err)
  4385. dockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL)
  4386. b, err := ioutil.ReadFile(configPath)
  4387. assert.NilError(c, err)
  4388. assert.Assert(c, !strings.Contains(string(b), "\"auth\":"))
  4389. dockerCmd(c, "--config", tmp, "tag", "busybox", repoName)
  4390. dockerCmd(c, "--config", tmp, "push", repoName)
  4391. // make sure the image is pulled when building
  4392. dockerCmd(c, "rmi", repoName)
  4393. icmd.RunCmd(icmd.Cmd{
  4394. Command: []string{dockerBinary, "--config", tmp, "build", "-"},
  4395. Stdin: strings.NewReader(fmt.Sprintf("FROM %s", repoName)),
  4396. }).Assert(c, icmd.Success)
  4397. }
  4398. // Test cases in #22036
  4399. func (s *DockerSuite) TestBuildLabelsOverride(c *testing.T) {
  4400. // Command line option labels will always override
  4401. name := "scratchy"
  4402. expected := `{"bar":"from-flag","foo":"from-flag"}`
  4403. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo=from-flag", "--label", "bar=from-flag"),
  4404. build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4405. LABEL foo=from-dockerfile`))
  4406. res := inspectFieldJSON(c, name, "Config.Labels")
  4407. if res != expected {
  4408. c.Fatalf("Labels %s, expected %s", res, expected)
  4409. }
  4410. name = "from"
  4411. expected = `{"foo":"from-dockerfile"}`
  4412. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4413. LABEL foo from-dockerfile`))
  4414. res = inspectFieldJSON(c, name, "Config.Labels")
  4415. if res != expected {
  4416. c.Fatalf("Labels %s, expected %s", res, expected)
  4417. }
  4418. // Command line option label will override even via `FROM`
  4419. name = "new"
  4420. expected = `{"bar":"from-dockerfile2","foo":"new"}`
  4421. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo=new"),
  4422. build.WithDockerfile(`FROM from
  4423. LABEL bar from-dockerfile2`))
  4424. res = inspectFieldJSON(c, name, "Config.Labels")
  4425. if res != expected {
  4426. c.Fatalf("Labels %s, expected %s", res, expected)
  4427. }
  4428. // Command line option without a value set (--label foo, --label bar=)
  4429. // will be treated as --label foo="", --label bar=""
  4430. name = "scratchy2"
  4431. expected = `{"bar":"","foo":""}`
  4432. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo", "--label", "bar="),
  4433. build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4434. LABEL foo=from-dockerfile`))
  4435. res = inspectFieldJSON(c, name, "Config.Labels")
  4436. if res != expected {
  4437. c.Fatalf("Labels %s, expected %s", res, expected)
  4438. }
  4439. // Command line option without a value set (--label foo, --label bar=)
  4440. // will be treated as --label foo="", --label bar=""
  4441. // This time is for inherited images
  4442. name = "new2"
  4443. expected = `{"bar":"","foo":""}`
  4444. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo=", "--label", "bar"),
  4445. build.WithDockerfile(`FROM from
  4446. LABEL bar from-dockerfile2`))
  4447. res = inspectFieldJSON(c, name, "Config.Labels")
  4448. if res != expected {
  4449. c.Fatalf("Labels %s, expected %s", res, expected)
  4450. }
  4451. // Command line option labels with only `FROM`
  4452. name = "scratchy"
  4453. expected = `{"bar":"from-flag","foo":"from-flag"}`
  4454. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo=from-flag", "--label", "bar=from-flag"),
  4455. build.WithDockerfile(`FROM `+minimalBaseImage()))
  4456. res = inspectFieldJSON(c, name, "Config.Labels")
  4457. if res != expected {
  4458. c.Fatalf("Labels %s, expected %s", res, expected)
  4459. }
  4460. // Command line option labels with env var
  4461. name = "scratchz"
  4462. expected = `{"bar":"$PATH"}`
  4463. buildImageSuccessfully(c, name, cli.WithFlags("--label", "bar=$PATH"),
  4464. build.WithDockerfile(`FROM `+minimalBaseImage()))
  4465. res = inspectFieldJSON(c, name, "Config.Labels")
  4466. if res != expected {
  4467. c.Fatalf("Labels %s, expected %s", res, expected)
  4468. }
  4469. }
  4470. // Test case for #22855
  4471. func (s *DockerSuite) TestBuildDeleteCommittedFile(c *testing.T) {
  4472. name := "test-delete-committed-file"
  4473. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  4474. RUN echo test > file
  4475. RUN test -e file
  4476. RUN rm file
  4477. RUN sh -c "! test -e file"`))
  4478. }
  4479. // #20083
  4480. func (s *DockerSuite) TestBuildDockerignoreComment(c *testing.T) {
  4481. // TODO Windows: Figure out why this test is flakey on TP5. If you add
  4482. // something like RUN sleep 5, or even RUN ls /tmp after the ADD line,
  4483. // it is more reliable, but that's not a good fix.
  4484. testRequires(c, DaemonIsLinux)
  4485. name := "testbuilddockerignorecleanpaths"
  4486. dockerfile := `
  4487. FROM busybox
  4488. ADD . /tmp/
  4489. RUN sh -c "(ls -la /tmp/#1)"
  4490. RUN sh -c "(! ls -la /tmp/#2)"
  4491. RUN sh -c "(! ls /tmp/foo) && (! ls /tmp/foo2) && (ls /tmp/dir1/foo)"`
  4492. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  4493. build.WithFile("Dockerfile", dockerfile),
  4494. build.WithFile("foo", "foo"),
  4495. build.WithFile("foo2", "foo2"),
  4496. build.WithFile("dir1/foo", "foo in dir1"),
  4497. build.WithFile("#1", "# file 1"),
  4498. build.WithFile("#2", "# file 2"),
  4499. build.WithFile(".dockerignore", `# Visual C++ cache files
  4500. # because we have git ;-)
  4501. # The above comment is from #20083
  4502. foo
  4503. #dir1/foo
  4504. foo2
  4505. # The following is considered as comment as # is at the beginning
  4506. #1
  4507. # The following is not considered as comment as # is not at the beginning
  4508. #2
  4509. `)))
  4510. }
  4511. // Test case for #23221
  4512. func (s *DockerSuite) TestBuildWithUTF8BOM(c *testing.T) {
  4513. name := "test-with-utf8-bom"
  4514. dockerfile := []byte(`FROM busybox`)
  4515. bomDockerfile := append([]byte{0xEF, 0xBB, 0xBF}, dockerfile...)
  4516. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  4517. build.WithFile("Dockerfile", string(bomDockerfile)),
  4518. ))
  4519. }
  4520. // Test case for UTF-8 BOM in .dockerignore, related to #23221
  4521. func (s *DockerSuite) TestBuildWithUTF8BOMDockerignore(c *testing.T) {
  4522. name := "test-with-utf8-bom-dockerignore"
  4523. dockerfile := `
  4524. FROM busybox
  4525. ADD . /tmp/
  4526. RUN ls -la /tmp
  4527. RUN sh -c "! ls /tmp/Dockerfile"
  4528. RUN ls /tmp/.dockerignore`
  4529. dockerignore := []byte("./Dockerfile\n")
  4530. bomDockerignore := append([]byte{0xEF, 0xBB, 0xBF}, dockerignore...)
  4531. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  4532. build.WithFile("Dockerfile", dockerfile),
  4533. build.WithFile(".dockerignore", string(bomDockerignore)),
  4534. ))
  4535. }
  4536. // #22489 Shell test to confirm config gets updated correctly
  4537. func (s *DockerSuite) TestBuildShellUpdatesConfig(c *testing.T) {
  4538. name := "testbuildshellupdatesconfig"
  4539. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4540. SHELL ["foo", "-bar"]`))
  4541. expected := `["foo","-bar","#(nop) ","SHELL [foo -bar]"]`
  4542. res := inspectFieldJSON(c, name, "ContainerConfig.Cmd")
  4543. if res != expected {
  4544. c.Fatalf("%s, expected %s", res, expected)
  4545. }
  4546. res = inspectFieldJSON(c, name, "ContainerConfig.Shell")
  4547. if res != `["foo","-bar"]` {
  4548. c.Fatalf(`%s, expected ["foo","-bar"]`, res)
  4549. }
  4550. }
  4551. // #22489 Changing the shell multiple times and CMD after.
  4552. func (s *DockerSuite) TestBuildShellMultiple(c *testing.T) {
  4553. name := "testbuildshellmultiple"
  4554. result := buildImage(name, build.WithDockerfile(`FROM busybox
  4555. RUN echo defaultshell
  4556. SHELL ["echo"]
  4557. RUN echoshell
  4558. SHELL ["ls"]
  4559. RUN -l
  4560. CMD -l`))
  4561. result.Assert(c, icmd.Success)
  4562. // Must contain 'defaultshell' twice
  4563. if len(strings.Split(result.Combined(), "defaultshell")) != 3 {
  4564. c.Fatalf("defaultshell should have appeared twice in %s", result.Combined())
  4565. }
  4566. // Must contain 'echoshell' twice
  4567. if len(strings.Split(result.Combined(), "echoshell")) != 3 {
  4568. c.Fatalf("echoshell should have appeared twice in %s", result.Combined())
  4569. }
  4570. // Must contain "total " (part of ls -l)
  4571. if !strings.Contains(result.Combined(), "total ") {
  4572. c.Fatalf("%s should have contained 'total '", result.Combined())
  4573. }
  4574. // A container started from the image uses the shell-form CMD.
  4575. // Last shell is ls. CMD is -l. So should contain 'total '.
  4576. outrun, _ := dockerCmd(c, "run", "--rm", name)
  4577. if !strings.Contains(outrun, "total ") {
  4578. c.Fatalf("Expected started container to run ls -l. %s", outrun)
  4579. }
  4580. }
  4581. // #22489. Changed SHELL with ENTRYPOINT
  4582. func (s *DockerSuite) TestBuildShellEntrypoint(c *testing.T) {
  4583. name := "testbuildshellentrypoint"
  4584. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  4585. SHELL ["ls"]
  4586. ENTRYPOINT -l`))
  4587. // A container started from the image uses the shell-form ENTRYPOINT.
  4588. // Shell is ls. ENTRYPOINT is -l. So should contain 'total '.
  4589. outrun, _ := dockerCmd(c, "run", "--rm", name)
  4590. if !strings.Contains(outrun, "total ") {
  4591. c.Fatalf("Expected started container to run ls -l. %s", outrun)
  4592. }
  4593. }
  4594. // #22489 Shell test to confirm shell is inherited in a subsequent build
  4595. func (s *DockerSuite) TestBuildShellInherited(c *testing.T) {
  4596. name1 := "testbuildshellinherited1"
  4597. buildImageSuccessfully(c, name1, build.WithDockerfile(`FROM busybox
  4598. SHELL ["ls"]`))
  4599. name2 := "testbuildshellinherited2"
  4600. buildImage(name2, build.WithDockerfile(`FROM `+name1+`
  4601. RUN -l`)).Assert(c, icmd.Expected{
  4602. // ls -l has "total " followed by some number in it, ls without -l does not.
  4603. Out: "total ",
  4604. })
  4605. }
  4606. // #22489 Shell test to confirm non-JSON doesn't work
  4607. func (s *DockerSuite) TestBuildShellNotJSON(c *testing.T) {
  4608. name := "testbuildshellnotjson"
  4609. buildImage(name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4610. sHeLl exec -form`, // Casing explicit to ensure error is upper-cased.
  4611. )).Assert(c, icmd.Expected{
  4612. ExitCode: 1,
  4613. Err: "SHELL requires the arguments to be in JSON form",
  4614. })
  4615. }
  4616. // #22489 Windows shell test to confirm native is powershell if executing a PS command
  4617. // This would error if the default shell were still cmd.
  4618. func (s *DockerSuite) TestBuildShellWindowsPowershell(c *testing.T) {
  4619. testRequires(c, DaemonIsWindows)
  4620. name := "testbuildshellpowershell"
  4621. buildImage(name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4622. SHELL ["powershell", "-command"]
  4623. RUN Write-Host John`)).Assert(c, icmd.Expected{
  4624. Out: "\nJohn\n",
  4625. })
  4626. }
  4627. // Verify that escape is being correctly applied to words when escape directive is not \.
  4628. // Tests WORKDIR, ADD
  4629. func (s *DockerSuite) TestBuildEscapeNotBackslashWordTest(c *testing.T) {
  4630. testRequires(c, DaemonIsWindows)
  4631. name := "testbuildescapenotbackslashwordtesta"
  4632. buildImage(name, build.WithDockerfile(`# escape= `+"`"+`
  4633. FROM `+minimalBaseImage()+`
  4634. WORKDIR c:\windows
  4635. RUN dir /w`)).Assert(c, icmd.Expected{
  4636. Out: "[System32]",
  4637. })
  4638. name = "testbuildescapenotbackslashwordtestb"
  4639. buildImage(name, build.WithDockerfile(`# escape= `+"`"+`
  4640. FROM `+minimalBaseImage()+`
  4641. SHELL ["powershell.exe"]
  4642. WORKDIR c:\foo
  4643. ADD Dockerfile c:\foo\
  4644. RUN dir Dockerfile`)).Assert(c, icmd.Expected{
  4645. Out: "-a----",
  4646. })
  4647. }
  4648. // #22868. Make sure shell-form CMD is not marked as escaped in the config of the image,
  4649. // but an exec-form CMD is marked.
  4650. func (s *DockerSuite) TestBuildCmdShellArgsEscaped(c *testing.T) {
  4651. testRequires(c, DaemonIsWindows)
  4652. name1 := "testbuildcmdshellescapedshellform"
  4653. buildImageSuccessfully(c, name1, build.WithDockerfile(`
  4654. FROM `+minimalBaseImage()+`
  4655. CMD "ipconfig"
  4656. `))
  4657. res := inspectFieldJSON(c, name1, "Config.ArgsEscaped")
  4658. if res != "true" {
  4659. c.Fatalf("CMD did not update Config.ArgsEscaped on image: %v", res)
  4660. }
  4661. dockerCmd(c, "run", "--name", "inspectme1", name1)
  4662. dockerCmd(c, "wait", "inspectme1")
  4663. res = inspectFieldJSON(c, name1, "Config.Cmd")
  4664. if res != `["cmd /S /C \"ipconfig\""]` {
  4665. c.Fatalf("CMD incorrect in Config.Cmd: got %v", res)
  4666. }
  4667. // Now in JSON/exec-form
  4668. name2 := "testbuildcmdshellescapedexecform"
  4669. buildImageSuccessfully(c, name2, build.WithDockerfile(`
  4670. FROM `+minimalBaseImage()+`
  4671. CMD ["ipconfig"]
  4672. `))
  4673. res = inspectFieldJSON(c, name2, "Config.ArgsEscaped")
  4674. if res != "false" {
  4675. c.Fatalf("CMD set Config.ArgsEscaped on image: %v", res)
  4676. }
  4677. dockerCmd(c, "run", "--name", "inspectme2", name2)
  4678. dockerCmd(c, "wait", "inspectme2")
  4679. res = inspectFieldJSON(c, name2, "Config.Cmd")
  4680. if res != `["ipconfig"]` {
  4681. c.Fatalf("CMD incorrect in Config.Cmd: got %v", res)
  4682. }
  4683. }
  4684. // Test case for #24912.
  4685. func (s *DockerSuite) TestBuildStepsWithProgress(c *testing.T) {
  4686. name := "testbuildstepswithprogress"
  4687. totalRun := 5
  4688. result := buildImage(name, build.WithDockerfile("FROM busybox\n"+strings.Repeat("RUN echo foo\n", totalRun)))
  4689. result.Assert(c, icmd.Success)
  4690. assert.Assert(c, strings.Contains(result.Combined(), fmt.Sprintf("Step 1/%d : FROM busybox", 1+totalRun)))
  4691. for i := 2; i <= 1+totalRun; i++ {
  4692. assert.Assert(c, strings.Contains(result.Combined(), fmt.Sprintf("Step %d/%d : RUN echo foo", i, 1+totalRun)))
  4693. }
  4694. }
  4695. func (s *DockerSuite) TestBuildWithFailure(c *testing.T) {
  4696. name := "testbuildwithfailure"
  4697. // First test case can only detect `nobody` in runtime so all steps will show up
  4698. dockerfile := "FROM busybox\nRUN nobody"
  4699. result := buildImage(name, build.WithDockerfile(dockerfile))
  4700. assert.Assert(c, result.Error != nil)
  4701. assert.Assert(c, strings.Contains(result.Stdout(), "Step 1/2 : FROM busybox"))
  4702. assert.Assert(c, strings.Contains(result.Stdout(), "Step 2/2 : RUN nobody"))
  4703. // Second test case `FFOM` should have been detected before build runs so no steps
  4704. dockerfile = "FFOM nobody\nRUN nobody"
  4705. result = buildImage(name, build.WithDockerfile(dockerfile))
  4706. assert.Assert(c, result.Error != nil)
  4707. assert.Assert(c, !strings.Contains(result.Stdout(), "Step 1/2 : FROM busybox"))
  4708. assert.Assert(c, !strings.Contains(result.Stdout(), "Step 2/2 : RUN nobody"))
  4709. }
  4710. func (s *DockerSuite) TestBuildCacheFromEqualDiffIDsLength(c *testing.T) {
  4711. dockerfile := `
  4712. FROM busybox
  4713. RUN echo "test"
  4714. ENTRYPOINT ["sh"]`
  4715. ctx := fakecontext.New(c, "",
  4716. fakecontext.WithDockerfile(dockerfile),
  4717. fakecontext.WithFiles(map[string]string{
  4718. "Dockerfile": dockerfile,
  4719. }))
  4720. defer ctx.Close()
  4721. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  4722. id1 := getIDByName(c, "build1")
  4723. // rebuild with cache-from
  4724. result := cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4725. id2 := getIDByName(c, "build2")
  4726. assert.Equal(c, id1, id2)
  4727. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 2)
  4728. }
  4729. func (s *DockerSuite) TestBuildCacheFrom(c *testing.T) {
  4730. testRequires(c, DaemonIsLinux) // All tests that do save are skipped in windows
  4731. dockerfile := `
  4732. FROM busybox
  4733. ENV FOO=bar
  4734. ADD baz /
  4735. RUN touch bax`
  4736. ctx := fakecontext.New(c, "",
  4737. fakecontext.WithDockerfile(dockerfile),
  4738. fakecontext.WithFiles(map[string]string{
  4739. "Dockerfile": dockerfile,
  4740. "baz": "baz",
  4741. }))
  4742. defer ctx.Close()
  4743. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  4744. id1 := getIDByName(c, "build1")
  4745. // rebuild with cache-from
  4746. result := cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4747. id2 := getIDByName(c, "build2")
  4748. assert.Equal(c, id1, id2)
  4749. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 3)
  4750. cli.DockerCmd(c, "rmi", "build2")
  4751. // no cache match with unknown source
  4752. result = cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=nosuchtag"), build.WithExternalBuildContext(ctx))
  4753. id2 = getIDByName(c, "build2")
  4754. assert.Assert(c, id1 != id2)
  4755. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 0)
  4756. cli.DockerCmd(c, "rmi", "build2")
  4757. // clear parent images
  4758. tempDir, err := ioutil.TempDir("", "test-build-cache-from-")
  4759. if err != nil {
  4760. c.Fatalf("failed to create temporary directory: %s", tempDir)
  4761. }
  4762. defer os.RemoveAll(tempDir)
  4763. tempFile := filepath.Join(tempDir, "img.tar")
  4764. cli.DockerCmd(c, "save", "-o", tempFile, "build1")
  4765. cli.DockerCmd(c, "rmi", "build1")
  4766. cli.DockerCmd(c, "load", "-i", tempFile)
  4767. parentID := cli.DockerCmd(c, "inspect", "-f", "{{.Parent}}", "build1").Combined()
  4768. assert.Equal(c, strings.TrimSpace(parentID), "")
  4769. // cache still applies without parents
  4770. result = cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4771. id2 = getIDByName(c, "build2")
  4772. assert.Equal(c, id1, id2)
  4773. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 3)
  4774. history1 := cli.DockerCmd(c, "history", "-q", "build2").Combined()
  4775. // Retry, no new intermediate images
  4776. result = cli.BuildCmd(c, "build3", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4777. id3 := getIDByName(c, "build3")
  4778. assert.Equal(c, id1, id3)
  4779. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 3)
  4780. history2 := cli.DockerCmd(c, "history", "-q", "build3").Combined()
  4781. assert.Equal(c, history1, history2)
  4782. cli.DockerCmd(c, "rmi", "build2")
  4783. cli.DockerCmd(c, "rmi", "build3")
  4784. cli.DockerCmd(c, "rmi", "build1")
  4785. cli.DockerCmd(c, "load", "-i", tempFile)
  4786. // Modify file, everything up to last command and layers are reused
  4787. dockerfile = `
  4788. FROM busybox
  4789. ENV FOO=bar
  4790. ADD baz /
  4791. RUN touch newfile`
  4792. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "Dockerfile"), []byte(dockerfile), 0644)
  4793. assert.NilError(c, err)
  4794. result = cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4795. id2 = getIDByName(c, "build2")
  4796. assert.Assert(c, id1 != id2)
  4797. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 2)
  4798. layers1Str := cli.DockerCmd(c, "inspect", "-f", "{{json .RootFS.Layers}}", "build1").Combined()
  4799. layers2Str := cli.DockerCmd(c, "inspect", "-f", "{{json .RootFS.Layers}}", "build2").Combined()
  4800. var layers1 []string
  4801. var layers2 []string
  4802. assert.Assert(c, json.Unmarshal([]byte(layers1Str), &layers1) == nil)
  4803. assert.Assert(c, json.Unmarshal([]byte(layers2Str), &layers2) == nil)
  4804. assert.Equal(c, len(layers1), len(layers2))
  4805. for i := 0; i < len(layers1)-1; i++ {
  4806. assert.Equal(c, layers1[i], layers2[i])
  4807. }
  4808. assert.Assert(c, layers1[len(layers1)-1] != layers2[len(layers1)-1])
  4809. }
  4810. func (s *DockerSuite) TestBuildMultiStageCache(c *testing.T) {
  4811. testRequires(c, DaemonIsLinux) // All tests that do save are skipped in windows
  4812. dockerfile := `
  4813. FROM busybox
  4814. ADD baz /
  4815. FROM busybox
  4816. ADD baz /`
  4817. ctx := fakecontext.New(c, "",
  4818. fakecontext.WithDockerfile(dockerfile),
  4819. fakecontext.WithFiles(map[string]string{
  4820. "Dockerfile": dockerfile,
  4821. "baz": "baz",
  4822. }))
  4823. defer ctx.Close()
  4824. result := cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  4825. // second part of dockerfile was a repeat of first so should be cached
  4826. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 1)
  4827. result = cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4828. // now both parts of dockerfile should be cached
  4829. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 2)
  4830. }
  4831. func (s *DockerSuite) TestBuildNetNone(c *testing.T) {
  4832. testRequires(c, DaemonIsLinux)
  4833. name := "testbuildnetnone"
  4834. buildImage(name, cli.WithFlags("--network=none"), build.WithDockerfile(`
  4835. FROM busybox
  4836. RUN ping -c 1 8.8.8.8
  4837. `)).Assert(c, icmd.Expected{
  4838. ExitCode: 1,
  4839. Out: "unreachable",
  4840. })
  4841. }
  4842. func (s *DockerSuite) TestBuildNetContainer(c *testing.T) {
  4843. testRequires(c, DaemonIsLinux)
  4844. id, _ := dockerCmd(c, "run", "--hostname", "foobar", "-d", "busybox", "nc", "-ll", "-p", "1234", "-e", "hostname")
  4845. name := "testbuildnetcontainer"
  4846. buildImageSuccessfully(c, name, cli.WithFlags("--network=container:"+strings.TrimSpace(id)),
  4847. build.WithDockerfile(`
  4848. FROM busybox
  4849. RUN nc localhost 1234 > /otherhost
  4850. `))
  4851. host, _ := dockerCmd(c, "run", "testbuildnetcontainer", "cat", "/otherhost")
  4852. assert.Equal(c, strings.TrimSpace(host), "foobar")
  4853. }
  4854. func (s *DockerSuite) TestBuildWithExtraHost(c *testing.T) {
  4855. testRequires(c, DaemonIsLinux)
  4856. name := "testbuildwithextrahost"
  4857. buildImageSuccessfully(c, name,
  4858. cli.WithFlags(
  4859. "--add-host", "foo:127.0.0.1",
  4860. "--add-host", "bar:127.0.0.1",
  4861. ),
  4862. build.WithDockerfile(`
  4863. FROM busybox
  4864. RUN ping -c 1 foo
  4865. RUN ping -c 1 bar
  4866. `))
  4867. }
  4868. func (s *DockerSuite) TestBuildWithExtraHostInvalidFormat(c *testing.T) {
  4869. testRequires(c, DaemonIsLinux)
  4870. dockerfile := `
  4871. FROM busybox
  4872. RUN ping -c 1 foo`
  4873. testCases := []struct {
  4874. testName string
  4875. dockerfile string
  4876. buildFlag string
  4877. }{
  4878. {"extra_host_missing_ip", dockerfile, "--add-host=foo"},
  4879. {"extra_host_missing_ip_with_delimiter", dockerfile, "--add-host=foo:"},
  4880. {"extra_host_missing_hostname", dockerfile, "--add-host=:127.0.0.1"},
  4881. {"extra_host_invalid_ipv4", dockerfile, "--add-host=foo:101.10.2"},
  4882. {"extra_host_invalid_ipv6", dockerfile, "--add-host=foo:2001::1::3F"},
  4883. }
  4884. for _, tc := range testCases {
  4885. result := buildImage(tc.testName, cli.WithFlags(tc.buildFlag), build.WithDockerfile(tc.dockerfile))
  4886. result.Assert(c, icmd.Expected{
  4887. ExitCode: 125,
  4888. })
  4889. }
  4890. }
  4891. func (s *DockerSuite) TestBuildMultiStageCopyFromSyntax(c *testing.T) {
  4892. dockerfile := `
  4893. FROM busybox AS first
  4894. COPY foo bar
  4895. FROM busybox
  4896. %s
  4897. COPY baz baz
  4898. RUN echo mno > baz/cc
  4899. FROM busybox
  4900. COPY bar /
  4901. COPY --from=1 baz sub/
  4902. COPY --from=0 bar baz
  4903. COPY --from=first bar bay`
  4904. ctx := fakecontext.New(c, "",
  4905. fakecontext.WithDockerfile(fmt.Sprintf(dockerfile, "")),
  4906. fakecontext.WithFiles(map[string]string{
  4907. "foo": "abc",
  4908. "bar": "def",
  4909. "baz/aa": "ghi",
  4910. "baz/bb": "jkl",
  4911. }))
  4912. defer ctx.Close()
  4913. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  4914. cli.DockerCmd(c, "run", "build1", "cat", "bar").Assert(c, icmd.Expected{Out: "def"})
  4915. cli.DockerCmd(c, "run", "build1", "cat", "sub/aa").Assert(c, icmd.Expected{Out: "ghi"})
  4916. cli.DockerCmd(c, "run", "build1", "cat", "sub/cc").Assert(c, icmd.Expected{Out: "mno"})
  4917. cli.DockerCmd(c, "run", "build1", "cat", "baz").Assert(c, icmd.Expected{Out: "abc"})
  4918. cli.DockerCmd(c, "run", "build1", "cat", "bay").Assert(c, icmd.Expected{Out: "abc"})
  4919. result := cli.BuildCmd(c, "build2", build.WithExternalBuildContext(ctx))
  4920. // all commands should be cached
  4921. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 7)
  4922. assert.Equal(c, getIDByName(c, "build1"), getIDByName(c, "build2"))
  4923. err := ioutil.WriteFile(filepath.Join(ctx.Dir, "Dockerfile"), []byte(fmt.Sprintf(dockerfile, "COPY baz/aa foo")), 0644)
  4924. assert.NilError(c, err)
  4925. // changing file in parent block should not affect last block
  4926. result = cli.BuildCmd(c, "build3", build.WithExternalBuildContext(ctx))
  4927. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 5)
  4928. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "foo"), []byte("pqr"), 0644)
  4929. assert.NilError(c, err)
  4930. // changing file in parent block should affect both first and last block
  4931. result = cli.BuildCmd(c, "build4", build.WithExternalBuildContext(ctx))
  4932. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 5)
  4933. cli.DockerCmd(c, "run", "build4", "cat", "bay").Assert(c, icmd.Expected{Out: "pqr"})
  4934. cli.DockerCmd(c, "run", "build4", "cat", "baz").Assert(c, icmd.Expected{Out: "pqr"})
  4935. }
  4936. func (s *DockerSuite) TestBuildMultiStageCopyFromErrors(c *testing.T) {
  4937. testCases := []struct {
  4938. dockerfile string
  4939. expectedError string
  4940. }{
  4941. {
  4942. dockerfile: `
  4943. FROM busybox
  4944. COPY --from=foo foo bar`,
  4945. expectedError: "invalid from flag value foo",
  4946. },
  4947. {
  4948. dockerfile: `
  4949. FROM busybox
  4950. COPY --from=0 foo bar`,
  4951. expectedError: "invalid from flag value 0: refers to current build stage",
  4952. },
  4953. {
  4954. dockerfile: `
  4955. FROM busybox AS foo
  4956. COPY --from=bar foo bar`,
  4957. expectedError: "invalid from flag value bar",
  4958. },
  4959. {
  4960. dockerfile: `
  4961. FROM busybox AS 1
  4962. COPY --from=1 foo bar`,
  4963. expectedError: "invalid name for build stage",
  4964. },
  4965. }
  4966. for _, tc := range testCases {
  4967. ctx := fakecontext.New(c, "",
  4968. fakecontext.WithDockerfile(tc.dockerfile),
  4969. fakecontext.WithFiles(map[string]string{
  4970. "foo": "abc",
  4971. }))
  4972. cli.Docker(cli.Build("build1"), build.WithExternalBuildContext(ctx)).Assert(c, icmd.Expected{
  4973. ExitCode: 1,
  4974. Err: tc.expectedError,
  4975. })
  4976. ctx.Close()
  4977. }
  4978. }
  4979. func (s *DockerSuite) TestBuildMultiStageMultipleBuilds(c *testing.T) {
  4980. dockerfile := `
  4981. FROM busybox
  4982. COPY foo bar`
  4983. ctx := fakecontext.New(c, "",
  4984. fakecontext.WithDockerfile(dockerfile),
  4985. fakecontext.WithFiles(map[string]string{
  4986. "foo": "abc",
  4987. }))
  4988. defer ctx.Close()
  4989. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  4990. dockerfile = `
  4991. FROM build1:latest AS foo
  4992. FROM busybox
  4993. COPY --from=foo bar /
  4994. COPY foo /`
  4995. ctx = fakecontext.New(c, "",
  4996. fakecontext.WithDockerfile(dockerfile),
  4997. fakecontext.WithFiles(map[string]string{
  4998. "foo": "def",
  4999. }))
  5000. defer ctx.Close()
  5001. cli.BuildCmd(c, "build2", build.WithExternalBuildContext(ctx))
  5002. out := cli.DockerCmd(c, "run", "build2", "cat", "bar").Combined()
  5003. assert.Equal(c, strings.TrimSpace(out), "abc")
  5004. out = cli.DockerCmd(c, "run", "build2", "cat", "foo").Combined()
  5005. assert.Equal(c, strings.TrimSpace(out), "def")
  5006. }
  5007. func (s *DockerSuite) TestBuildMultiStageImplicitFrom(c *testing.T) {
  5008. dockerfile := `
  5009. FROM busybox
  5010. COPY --from=busybox /etc/passwd /mypasswd
  5011. RUN cmp /etc/passwd /mypasswd`
  5012. if DaemonIsWindows() {
  5013. dockerfile = `
  5014. FROM busybox
  5015. COPY --from=busybox License.txt foo`
  5016. }
  5017. ctx := fakecontext.New(c, "",
  5018. fakecontext.WithDockerfile(dockerfile),
  5019. )
  5020. defer ctx.Close()
  5021. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5022. if DaemonIsWindows() {
  5023. out := cli.DockerCmd(c, "run", "build1", "cat", "License.txt").Combined()
  5024. assert.Assert(c, len(out) > 10)
  5025. out2 := cli.DockerCmd(c, "run", "build1", "cat", "foo").Combined()
  5026. assert.Equal(c, out, out2)
  5027. }
  5028. }
  5029. func (s *DockerRegistrySuite) TestBuildMultiStageImplicitPull(c *testing.T) {
  5030. repoName := fmt.Sprintf("%v/dockercli/testf", privateRegistryURL)
  5031. dockerfile := `
  5032. FROM busybox
  5033. COPY foo bar`
  5034. ctx := fakecontext.New(c, "",
  5035. fakecontext.WithDockerfile(dockerfile),
  5036. fakecontext.WithFiles(map[string]string{
  5037. "foo": "abc",
  5038. }))
  5039. defer ctx.Close()
  5040. cli.BuildCmd(c, repoName, build.WithExternalBuildContext(ctx))
  5041. cli.DockerCmd(c, "push", repoName)
  5042. cli.DockerCmd(c, "rmi", repoName)
  5043. dockerfile = `
  5044. FROM busybox
  5045. COPY --from=%s bar baz`
  5046. ctx = fakecontext.New(c, "", fakecontext.WithDockerfile(fmt.Sprintf(dockerfile, repoName)))
  5047. defer ctx.Close()
  5048. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5049. cli.Docker(cli.Args("run", "build1", "cat", "baz")).Assert(c, icmd.Expected{Out: "abc"})
  5050. }
  5051. func (s *DockerSuite) TestBuildMultiStageNameVariants(c *testing.T) {
  5052. dockerfile := `
  5053. FROM busybox as foo
  5054. COPY foo /
  5055. FROM foo as foo1
  5056. RUN echo 1 >> foo
  5057. FROM foo as foO2
  5058. RUN echo 2 >> foo
  5059. FROM foo
  5060. COPY --from=foo1 foo f1
  5061. COPY --from=FOo2 foo f2
  5062. ` // foo2 case also tests that names are case insensitive
  5063. ctx := fakecontext.New(c, "",
  5064. fakecontext.WithDockerfile(dockerfile),
  5065. fakecontext.WithFiles(map[string]string{
  5066. "foo": "bar",
  5067. }))
  5068. defer ctx.Close()
  5069. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5070. cli.Docker(cli.Args("run", "build1", "cat", "foo")).Assert(c, icmd.Expected{Out: "bar"})
  5071. cli.Docker(cli.Args("run", "build1", "cat", "f1")).Assert(c, icmd.Expected{Out: "bar1"})
  5072. cli.Docker(cli.Args("run", "build1", "cat", "f2")).Assert(c, icmd.Expected{Out: "bar2"})
  5073. }
  5074. func (s *DockerSuite) TestBuildMultiStageMultipleBuildsWindows(c *testing.T) {
  5075. testRequires(c, DaemonIsWindows)
  5076. dockerfile := `
  5077. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5078. COPY foo c:\\bar`
  5079. ctx := fakecontext.New(c, "",
  5080. fakecontext.WithDockerfile(dockerfile),
  5081. fakecontext.WithFiles(map[string]string{
  5082. "foo": "abc",
  5083. }))
  5084. defer ctx.Close()
  5085. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5086. dockerfile = `
  5087. FROM build1:latest
  5088. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5089. COPY --from=0 c:\\bar /
  5090. COPY foo /`
  5091. ctx = fakecontext.New(c, "",
  5092. fakecontext.WithDockerfile(dockerfile),
  5093. fakecontext.WithFiles(map[string]string{
  5094. "foo": "def",
  5095. }))
  5096. defer ctx.Close()
  5097. cli.BuildCmd(c, "build2", build.WithExternalBuildContext(ctx))
  5098. out := cli.DockerCmd(c, "run", "build2", "cmd.exe", "/s", "/c", "type", "c:\\bar").Combined()
  5099. assert.Equal(c, strings.TrimSpace(out), "abc")
  5100. out = cli.DockerCmd(c, "run", "build2", "cmd.exe", "/s", "/c", "type", "c:\\foo").Combined()
  5101. assert.Equal(c, strings.TrimSpace(out), "def")
  5102. }
  5103. func (s *DockerSuite) TestBuildCopyFromForbidWindowsSystemPaths(c *testing.T) {
  5104. testRequires(c, DaemonIsWindows)
  5105. dockerfile := `
  5106. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5107. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5108. COPY --from=0 %s c:\\oscopy
  5109. `
  5110. exp := icmd.Expected{
  5111. ExitCode: 1,
  5112. Err: "copy from c:\\ or c:\\windows is not allowed on windows",
  5113. }
  5114. buildImage("testforbidsystempaths1", build.WithDockerfile(fmt.Sprintf(dockerfile, "c:\\\\"))).Assert(c, exp)
  5115. buildImage("testforbidsystempaths2", build.WithDockerfile(fmt.Sprintf(dockerfile, "C:\\\\"))).Assert(c, exp)
  5116. buildImage("testforbidsystempaths3", build.WithDockerfile(fmt.Sprintf(dockerfile, "c:\\\\windows"))).Assert(c, exp)
  5117. buildImage("testforbidsystempaths4", build.WithDockerfile(fmt.Sprintf(dockerfile, "c:\\\\wInDows"))).Assert(c, exp)
  5118. }
  5119. func (s *DockerSuite) TestBuildCopyFromForbidWindowsRelativePaths(c *testing.T) {
  5120. testRequires(c, DaemonIsWindows)
  5121. dockerfile := `
  5122. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5123. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5124. COPY --from=0 %s c:\\oscopy
  5125. `
  5126. exp := icmd.Expected{
  5127. ExitCode: 1,
  5128. Err: "copy from c:\\ or c:\\windows is not allowed on windows",
  5129. }
  5130. buildImage("testforbidsystempaths1", build.WithDockerfile(fmt.Sprintf(dockerfile, "c:"))).Assert(c, exp)
  5131. buildImage("testforbidsystempaths2", build.WithDockerfile(fmt.Sprintf(dockerfile, "."))).Assert(c, exp)
  5132. buildImage("testforbidsystempaths3", build.WithDockerfile(fmt.Sprintf(dockerfile, "..\\\\"))).Assert(c, exp)
  5133. buildImage("testforbidsystempaths4", build.WithDockerfile(fmt.Sprintf(dockerfile, ".\\\\windows"))).Assert(c, exp)
  5134. buildImage("testforbidsystempaths5", build.WithDockerfile(fmt.Sprintf(dockerfile, "\\\\windows"))).Assert(c, exp)
  5135. }
  5136. func (s *DockerSuite) TestBuildCopyFromWindowsIsCaseInsensitive(c *testing.T) {
  5137. testRequires(c, DaemonIsWindows)
  5138. dockerfile := `
  5139. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5140. COPY foo /
  5141. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5142. COPY --from=0 c:\\fOo c:\\copied
  5143. RUN type c:\\copied
  5144. `
  5145. cli.Docker(cli.Build("copyfrom-windows-insensitive"), build.WithBuildContext(c,
  5146. build.WithFile("Dockerfile", dockerfile),
  5147. build.WithFile("foo", "hello world"),
  5148. )).Assert(c, icmd.Expected{
  5149. ExitCode: 0,
  5150. Out: "hello world",
  5151. })
  5152. }
  5153. // #33176
  5154. func (s *DockerSuite) TestBuildMultiStageResetScratch(c *testing.T) {
  5155. testRequires(c, DaemonIsLinux)
  5156. dockerfile := `
  5157. FROM busybox
  5158. WORKDIR /foo/bar
  5159. FROM scratch
  5160. ENV FOO=bar
  5161. `
  5162. ctx := fakecontext.New(c, "",
  5163. fakecontext.WithDockerfile(dockerfile),
  5164. )
  5165. defer ctx.Close()
  5166. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5167. res := cli.InspectCmd(c, "build1", cli.Format(".Config.WorkingDir")).Combined()
  5168. assert.Equal(c, strings.TrimSpace(res), "")
  5169. }
  5170. func (s *DockerSuite) TestBuildIntermediateTarget(c *testing.T) {
  5171. //todo: need to be removed after 18.06 release
  5172. if strings.Contains(testEnv.DaemonInfo.ServerVersion, "18.05.0") {
  5173. c.Skip(fmt.Sprintf("Bug fixed in 18.06 or higher.Skipping it for %s", testEnv.DaemonInfo.ServerVersion))
  5174. }
  5175. dockerfile := `
  5176. FROM busybox AS build-env
  5177. CMD ["/dev"]
  5178. FROM busybox
  5179. CMD ["/dist"]
  5180. `
  5181. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(dockerfile))
  5182. defer ctx.Close()
  5183. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx),
  5184. cli.WithFlags("--target", "build-env"))
  5185. res := cli.InspectCmd(c, "build1", cli.Format("json .Config.Cmd")).Combined()
  5186. assert.Equal(c, strings.TrimSpace(res), `["/dev"]`)
  5187. // Stage name is case-insensitive by design
  5188. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx),
  5189. cli.WithFlags("--target", "BUIld-EnV"))
  5190. res = cli.InspectCmd(c, "build1", cli.Format("json .Config.Cmd")).Combined()
  5191. assert.Equal(c, strings.TrimSpace(res), `["/dev"]`)
  5192. result := cli.Docker(cli.Build("build1"), build.WithExternalBuildContext(ctx),
  5193. cli.WithFlags("--target", "nosuchtarget"))
  5194. result.Assert(c, icmd.Expected{
  5195. ExitCode: 1,
  5196. Err: "failed to reach build target",
  5197. })
  5198. }
  5199. // TestBuildOpaqueDirectory tests that a build succeeds which
  5200. // creates opaque directories.
  5201. // See https://github.com/docker/docker/issues/25244
  5202. func (s *DockerSuite) TestBuildOpaqueDirectory(c *testing.T) {
  5203. testRequires(c, DaemonIsLinux)
  5204. dockerFile := `
  5205. FROM busybox
  5206. RUN mkdir /dir1 && touch /dir1/f1
  5207. RUN rm -rf /dir1 && mkdir /dir1 && touch /dir1/f2
  5208. RUN touch /dir1/f3
  5209. RUN [ -f /dir1/f2 ]
  5210. `
  5211. // Test that build succeeds, last command fails if opaque directory
  5212. // was not handled correctly
  5213. buildImageSuccessfully(c, "testopaquedirectory", build.WithDockerfile(dockerFile))
  5214. }
  5215. // Windows test for USER in dockerfile
  5216. func (s *DockerSuite) TestBuildWindowsUser(c *testing.T) {
  5217. testRequires(c, DaemonIsWindows)
  5218. name := "testbuildwindowsuser"
  5219. buildImage(name, build.WithDockerfile(`FROM `+testEnv.PlatformDefaults.BaseImage+`
  5220. RUN net user user /add
  5221. USER user
  5222. RUN set username
  5223. `)).Assert(c, icmd.Expected{
  5224. Out: "USERNAME=user",
  5225. })
  5226. }
  5227. // Verifies if COPY file . when WORKDIR is set to a non-existing directory,
  5228. // the directory is created and the file is copied into the directory,
  5229. // as opposed to the file being copied as a file with the name of the
  5230. // directory. Fix for 27545 (found on Windows, but regression good for Linux too).
  5231. // Note 27545 was reverted in 28505, but a new fix was added subsequently in 28514.
  5232. func (s *DockerSuite) TestBuildCopyFileDotWithWorkdir(c *testing.T) {
  5233. name := "testbuildcopyfiledotwithworkdir"
  5234. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  5235. build.WithFile("Dockerfile", `FROM busybox
  5236. WORKDIR /foo
  5237. COPY file .
  5238. RUN ["cat", "/foo/file"]
  5239. `),
  5240. build.WithFile("file", "content"),
  5241. ))
  5242. }
  5243. // Case-insensitive environment variables on Windows
  5244. func (s *DockerSuite) TestBuildWindowsEnvCaseInsensitive(c *testing.T) {
  5245. testRequires(c, DaemonIsWindows)
  5246. name := "testbuildwindowsenvcaseinsensitive"
  5247. buildImageSuccessfully(c, name, build.WithDockerfile(`
  5248. FROM `+testEnv.PlatformDefaults.BaseImage+`
  5249. ENV FOO=bar foo=baz
  5250. `))
  5251. res := inspectFieldJSON(c, name, "Config.Env")
  5252. if res != `["foo=baz"]` { // Should not have FOO=bar in it - takes the last one processed. And only one entry as deduped.
  5253. c.Fatalf("Case insensitive environment variables on Windows failed. Got %s", res)
  5254. }
  5255. }
  5256. // Test case for 29667
  5257. func (s *DockerSuite) TestBuildWorkdirImageCmd(c *testing.T) {
  5258. image := "testworkdirimagecmd"
  5259. buildImageSuccessfully(c, image, build.WithDockerfile(`
  5260. FROM busybox
  5261. WORKDIR /foo/bar
  5262. `))
  5263. out, _ := dockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", image)
  5264. assert.Equal(c, strings.TrimSpace(out), `["sh"]`)
  5265. image = "testworkdirlabelimagecmd"
  5266. buildImageSuccessfully(c, image, build.WithDockerfile(`
  5267. FROM busybox
  5268. WORKDIR /foo/bar
  5269. LABEL a=b
  5270. `))
  5271. out, _ = dockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", image)
  5272. assert.Equal(c, strings.TrimSpace(out), `["sh"]`)
  5273. }
  5274. // Test case for 28902/28909
  5275. func (s *DockerSuite) TestBuildWorkdirCmd(c *testing.T) {
  5276. testRequires(c, DaemonIsLinux)
  5277. name := "testbuildworkdircmd"
  5278. dockerFile := `
  5279. FROM busybox
  5280. WORKDIR /
  5281. `
  5282. buildImageSuccessfully(c, name, build.WithDockerfile(dockerFile))
  5283. result := buildImage(name, build.WithDockerfile(dockerFile))
  5284. result.Assert(c, icmd.Success)
  5285. assert.Equal(c, strings.Count(result.Combined(), "Using cache"), 1)
  5286. }
  5287. // FIXME(vdemeester) should be a unit test
  5288. func (s *DockerSuite) TestBuildLineErrorOnBuild(c *testing.T) {
  5289. name := "test_build_line_error_onbuild"
  5290. buildImage(name, build.WithDockerfile(`FROM busybox
  5291. ONBUILD
  5292. `)).Assert(c, icmd.Expected{
  5293. ExitCode: 1,
  5294. Err: "parse error line 2: ONBUILD requires at least one argument",
  5295. })
  5296. }
  5297. // FIXME(vdemeester) should be a unit test
  5298. func (s *DockerSuite) TestBuildLineErrorUnknownInstruction(c *testing.T) {
  5299. name := "test_build_line_error_unknown_instruction"
  5300. cli.Docker(cli.Build(name), build.WithDockerfile(`FROM busybox
  5301. RUN echo hello world
  5302. NOINSTRUCTION echo ba
  5303. RUN echo hello
  5304. ERROR
  5305. `)).Assert(c, icmd.Expected{
  5306. ExitCode: 1,
  5307. Err: "parse error line 3: unknown instruction: NOINSTRUCTION",
  5308. })
  5309. }
  5310. // FIXME(vdemeester) should be a unit test
  5311. func (s *DockerSuite) TestBuildLineErrorWithEmptyLines(c *testing.T) {
  5312. name := "test_build_line_error_with_empty_lines"
  5313. cli.Docker(cli.Build(name), build.WithDockerfile(`
  5314. FROM busybox
  5315. RUN echo hello world
  5316. NOINSTRUCTION echo ba
  5317. CMD ["/bin/init"]
  5318. `)).Assert(c, icmd.Expected{
  5319. ExitCode: 1,
  5320. Err: "parse error line 6: unknown instruction: NOINSTRUCTION",
  5321. })
  5322. }
  5323. // FIXME(vdemeester) should be a unit test
  5324. func (s *DockerSuite) TestBuildLineErrorWithComments(c *testing.T) {
  5325. name := "test_build_line_error_with_comments"
  5326. cli.Docker(cli.Build(name), build.WithDockerfile(`FROM busybox
  5327. # This will print hello world
  5328. # and then ba
  5329. RUN echo hello world
  5330. NOINSTRUCTION echo ba
  5331. `)).Assert(c, icmd.Expected{
  5332. ExitCode: 1,
  5333. Err: "parse error line 5: unknown instruction: NOINSTRUCTION",
  5334. })
  5335. }
  5336. // #31957
  5337. func (s *DockerSuite) TestBuildSetCommandWithDefinedShell(c *testing.T) {
  5338. buildImageSuccessfully(c, "build1", build.WithDockerfile(`
  5339. FROM busybox
  5340. SHELL ["/bin/sh", "-c"]
  5341. `))
  5342. buildImageSuccessfully(c, "build2", build.WithDockerfile(`
  5343. FROM build1
  5344. CMD echo foo
  5345. `))
  5346. out, _ := dockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", "build2")
  5347. expected := `["/bin/sh","-c","echo foo"]`
  5348. if testEnv.OSType == "windows" {
  5349. expected = `["/bin/sh -c echo foo"]`
  5350. }
  5351. assert.Equal(c, strings.TrimSpace(out), expected)
  5352. }
  5353. // FIXME(vdemeester) should migrate to docker/cli tests
  5354. func (s *DockerSuite) TestBuildIidFile(c *testing.T) {
  5355. tmpDir, err := ioutil.TempDir("", "TestBuildIidFile")
  5356. if err != nil {
  5357. c.Fatal(err)
  5358. }
  5359. defer os.RemoveAll(tmpDir)
  5360. tmpIidFile := filepath.Join(tmpDir, "iid")
  5361. name := "testbuildiidfile"
  5362. // Use a Dockerfile with multiple stages to ensure we get the last one
  5363. cli.BuildCmd(c, name,
  5364. build.WithDockerfile(`FROM `+minimalBaseImage()+` AS stage1
  5365. ENV FOO FOO
  5366. FROM `+minimalBaseImage()+`
  5367. ENV BAR BAZ`),
  5368. cli.WithFlags("--iidfile", tmpIidFile))
  5369. id, err := ioutil.ReadFile(tmpIidFile)
  5370. assert.NilError(c, err)
  5371. d, err := digest.Parse(string(id))
  5372. assert.NilError(c, err)
  5373. assert.Equal(c, d.String(), getIDByName(c, name))
  5374. }
  5375. // FIXME(vdemeester) should migrate to docker/cli tests
  5376. func (s *DockerSuite) TestBuildIidFileCleanupOnFail(c *testing.T) {
  5377. tmpDir, err := ioutil.TempDir("", "TestBuildIidFileCleanupOnFail")
  5378. if err != nil {
  5379. c.Fatal(err)
  5380. }
  5381. defer os.RemoveAll(tmpDir)
  5382. tmpIidFile := filepath.Join(tmpDir, "iid")
  5383. err = ioutil.WriteFile(tmpIidFile, []byte("Dummy"), 0666)
  5384. assert.NilError(c, err)
  5385. cli.Docker(cli.Build("testbuildiidfilecleanuponfail"),
  5386. build.WithDockerfile(`FROM `+minimalBaseImage()+`
  5387. RUN /non/existing/command`),
  5388. cli.WithFlags("--iidfile", tmpIidFile)).Assert(c, icmd.Expected{
  5389. ExitCode: 1,
  5390. })
  5391. _, err = os.Stat(tmpIidFile)
  5392. assert.ErrorContains(c, err, "")
  5393. assert.Equal(c, os.IsNotExist(err), true)
  5394. }