docker_cli_build_test.go 196 KB

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