docker_cli_build_test.go 189 KB

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