docker_cli_build_test.go 197 KB

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