docker_cli_build_test.go 200 KB

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