docker_cli_build_test.go 197 KB

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