docker_cli_build_test.go 200 KB

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