docker_cli_build_test.go 135 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330
  1. package main
  2. import (
  3. "archive/tar"
  4. "bufio"
  5. "bytes"
  6. "encoding/json"
  7. "fmt"
  8. "io/ioutil"
  9. "os"
  10. "os/exec"
  11. "path/filepath"
  12. "reflect"
  13. "regexp"
  14. "runtime"
  15. "strconv"
  16. "strings"
  17. "text/template"
  18. "time"
  19. "github.com/docker/docker/builder/command"
  20. "github.com/docker/docker/pkg/archive"
  21. "github.com/docker/docker/pkg/stringutils"
  22. "github.com/go-check/check"
  23. )
  24. func (s *DockerSuite) TestBuildJSONEmptyRun(c *check.C) {
  25. name := "testbuildjsonemptyrun"
  26. _, err := buildImage(
  27. name,
  28. `
  29. FROM busybox
  30. RUN []
  31. `,
  32. true)
  33. if err != nil {
  34. c.Fatal("error when dealing with a RUN statement with empty JSON array")
  35. }
  36. }
  37. func (s *DockerSuite) TestBuildEmptyWhitespace(c *check.C) {
  38. name := "testbuildemptywhitespace"
  39. _, err := buildImage(
  40. name,
  41. `
  42. FROM busybox
  43. COPY
  44. quux \
  45. bar
  46. `,
  47. true)
  48. if err == nil {
  49. c.Fatal("no error when dealing with a COPY statement with no content on the same line")
  50. }
  51. }
  52. func (s *DockerSuite) TestBuildShCmdJSONEntrypoint(c *check.C) {
  53. name := "testbuildshcmdjsonentrypoint"
  54. _, err := buildImage(
  55. name,
  56. `
  57. FROM busybox
  58. ENTRYPOINT ["/bin/echo"]
  59. CMD echo test
  60. `,
  61. true)
  62. if err != nil {
  63. c.Fatal(err)
  64. }
  65. out, _ := dockerCmd(c, "run", "--rm", name)
  66. if strings.TrimSpace(out) != "/bin/sh -c echo test" {
  67. c.Fatalf("CMD did not contain /bin/sh -c : %s", out)
  68. }
  69. }
  70. func (s *DockerSuite) TestBuildEnvironmentReplacementUser(c *check.C) {
  71. name := "testbuildenvironmentreplacement"
  72. _, err := buildImage(name, `
  73. FROM scratch
  74. ENV user foo
  75. USER ${user}
  76. `, true)
  77. if err != nil {
  78. c.Fatal(err)
  79. }
  80. res, err := inspectFieldJSON(name, "Config.User")
  81. if err != nil {
  82. c.Fatal(err)
  83. }
  84. if res != `"foo"` {
  85. c.Fatal("User foo from environment not in Config.User on image")
  86. }
  87. }
  88. func (s *DockerSuite) TestBuildEnvironmentReplacementVolume(c *check.C) {
  89. name := "testbuildenvironmentreplacement"
  90. _, err := buildImage(name, `
  91. FROM scratch
  92. ENV volume /quux
  93. VOLUME ${volume}
  94. `, true)
  95. if err != nil {
  96. c.Fatal(err)
  97. }
  98. res, err := inspectFieldJSON(name, "Config.Volumes")
  99. if err != nil {
  100. c.Fatal(err)
  101. }
  102. var volumes map[string]interface{}
  103. if err := json.Unmarshal([]byte(res), &volumes); err != nil {
  104. c.Fatal(err)
  105. }
  106. if _, ok := volumes["/quux"]; !ok {
  107. c.Fatal("Volume /quux from environment not in Config.Volumes on image")
  108. }
  109. }
  110. func (s *DockerSuite) TestBuildEnvironmentReplacementExpose(c *check.C) {
  111. name := "testbuildenvironmentreplacement"
  112. _, err := buildImage(name, `
  113. FROM scratch
  114. ENV port 80
  115. EXPOSE ${port}
  116. `, true)
  117. if err != nil {
  118. c.Fatal(err)
  119. }
  120. res, err := inspectFieldJSON(name, "Config.ExposedPorts")
  121. if err != nil {
  122. c.Fatal(err)
  123. }
  124. var exposedPorts map[string]interface{}
  125. if err := json.Unmarshal([]byte(res), &exposedPorts); err != nil {
  126. c.Fatal(err)
  127. }
  128. if _, ok := exposedPorts["80/tcp"]; !ok {
  129. c.Fatal("Exposed port 80 from environment not in Config.ExposedPorts on image")
  130. }
  131. }
  132. func (s *DockerSuite) TestBuildEnvironmentReplacementWorkdir(c *check.C) {
  133. name := "testbuildenvironmentreplacement"
  134. _, err := buildImage(name, `
  135. FROM busybox
  136. ENV MYWORKDIR /work
  137. RUN mkdir ${MYWORKDIR}
  138. WORKDIR ${MYWORKDIR}
  139. `, true)
  140. if err != nil {
  141. c.Fatal(err)
  142. }
  143. }
  144. func (s *DockerSuite) TestBuildEnvironmentReplacementAddCopy(c *check.C) {
  145. name := "testbuildenvironmentreplacement"
  146. ctx, err := fakeContext(`
  147. FROM scratch
  148. ENV baz foo
  149. ENV quux bar
  150. ENV dot .
  151. ENV fee fff
  152. ENV gee ggg
  153. ADD ${baz} ${dot}
  154. COPY ${quux} ${dot}
  155. ADD ${zzz:-${fee}} ${dot}
  156. COPY ${zzz:-${gee}} ${dot}
  157. `,
  158. map[string]string{
  159. "foo": "test1",
  160. "bar": "test2",
  161. "fff": "test3",
  162. "ggg": "test4",
  163. })
  164. if err != nil {
  165. c.Fatal(err)
  166. }
  167. defer ctx.Close()
  168. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  169. c.Fatal(err)
  170. }
  171. }
  172. func (s *DockerSuite) TestBuildEnvironmentReplacementEnv(c *check.C) {
  173. name := "testbuildenvironmentreplacement"
  174. _, err := buildImage(name,
  175. `
  176. FROM busybox
  177. ENV foo zzz
  178. ENV bar ${foo}
  179. ENV abc1='$foo'
  180. ENV env1=$foo env2=${foo} env3="$foo" env4="${foo}"
  181. RUN [ "$abc1" = '$foo' ] && (echo "$abc1" | grep -q foo)
  182. ENV abc2="\$foo"
  183. RUN [ "$abc2" = '$foo' ] && (echo "$abc2" | grep -q foo)
  184. ENV abc3 '$foo'
  185. RUN [ "$abc3" = '$foo' ] && (echo "$abc3" | grep -q foo)
  186. ENV abc4 "\$foo"
  187. RUN [ "$abc4" = '$foo' ] && (echo "$abc4" | grep -q foo)
  188. `, true)
  189. if err != nil {
  190. c.Fatal(err)
  191. }
  192. res, err := inspectFieldJSON(name, "Config.Env")
  193. if err != nil {
  194. c.Fatal(err)
  195. }
  196. envResult := []string{}
  197. if err = unmarshalJSON([]byte(res), &envResult); err != nil {
  198. c.Fatal(err)
  199. }
  200. found := false
  201. envCount := 0
  202. for _, env := range envResult {
  203. parts := strings.SplitN(env, "=", 2)
  204. if parts[0] == "bar" {
  205. found = true
  206. if parts[1] != "zzz" {
  207. c.Fatalf("Could not find replaced var for env `bar`: got %q instead of `zzz`", parts[1])
  208. }
  209. } else if strings.HasPrefix(parts[0], "env") {
  210. envCount++
  211. if parts[1] != "zzz" {
  212. c.Fatalf("%s should be 'foo' but instead its %q", parts[0], parts[1])
  213. }
  214. } else if strings.HasPrefix(parts[0], "env") {
  215. envCount++
  216. if parts[1] != "foo" {
  217. c.Fatalf("%s should be 'foo' but instead its %q", parts[0], parts[1])
  218. }
  219. }
  220. }
  221. if !found {
  222. c.Fatal("Never found the `bar` env variable")
  223. }
  224. if envCount != 4 {
  225. c.Fatalf("Didn't find all env vars - only saw %d\n%s", envCount, envResult)
  226. }
  227. }
  228. func (s *DockerSuite) TestBuildHandleEscapes(c *check.C) {
  229. name := "testbuildhandleescapes"
  230. _, err := buildImage(name,
  231. `
  232. FROM scratch
  233. ENV FOO bar
  234. VOLUME ${FOO}
  235. `, true)
  236. if err != nil {
  237. c.Fatal(err)
  238. }
  239. var result map[string]map[string]struct{}
  240. res, err := inspectFieldJSON(name, "Config.Volumes")
  241. if err != nil {
  242. c.Fatal(err)
  243. }
  244. if err = unmarshalJSON([]byte(res), &result); err != nil {
  245. c.Fatal(err)
  246. }
  247. if _, ok := result["bar"]; !ok {
  248. c.Fatal("Could not find volume bar set from env foo in volumes table")
  249. }
  250. deleteImages(name)
  251. _, err = buildImage(name,
  252. `
  253. FROM scratch
  254. ENV FOO bar
  255. VOLUME \${FOO}
  256. `, true)
  257. if err != nil {
  258. c.Fatal(err)
  259. }
  260. res, err = inspectFieldJSON(name, "Config.Volumes")
  261. if err != nil {
  262. c.Fatal(err)
  263. }
  264. if err = unmarshalJSON([]byte(res), &result); err != nil {
  265. c.Fatal(err)
  266. }
  267. if _, ok := result["${FOO}"]; !ok {
  268. c.Fatal("Could not find volume ${FOO} set from env foo in volumes table")
  269. }
  270. deleteImages(name)
  271. // this test in particular provides *7* backslashes and expects 6 to come back.
  272. // Like above, the first escape is swallowed and the rest are treated as
  273. // literals, this one is just less obvious because of all the character noise.
  274. _, err = buildImage(name,
  275. `
  276. FROM scratch
  277. ENV FOO bar
  278. VOLUME \\\\\\\${FOO}
  279. `, true)
  280. if err != nil {
  281. c.Fatal(err)
  282. }
  283. res, err = inspectFieldJSON(name, "Config.Volumes")
  284. if err != nil {
  285. c.Fatal(err)
  286. }
  287. if err = unmarshalJSON([]byte(res), &result); err != nil {
  288. c.Fatal(err)
  289. }
  290. if _, ok := result[`\\\${FOO}`]; !ok {
  291. c.Fatal(`Could not find volume \\\${FOO} set from env foo in volumes table`, result)
  292. }
  293. }
  294. func (s *DockerSuite) TestBuildOnBuildLowercase(c *check.C) {
  295. name := "testbuildonbuildlowercase"
  296. name2 := "testbuildonbuildlowercase2"
  297. _, err := buildImage(name,
  298. `
  299. FROM busybox
  300. onbuild run echo quux
  301. `, true)
  302. if err != nil {
  303. c.Fatal(err)
  304. }
  305. _, out, err := buildImageWithOut(name2, fmt.Sprintf(`
  306. FROM %s
  307. `, name), true)
  308. if err != nil {
  309. c.Fatal(err)
  310. }
  311. if !strings.Contains(out, "quux") {
  312. c.Fatalf("Did not receive the expected echo text, got %s", out)
  313. }
  314. if strings.Contains(out, "ONBUILD ONBUILD") {
  315. c.Fatalf("Got an ONBUILD ONBUILD error with no error: got %s", out)
  316. }
  317. }
  318. func (s *DockerSuite) TestBuildEnvEscapes(c *check.C) {
  319. name := "testbuildenvescapes"
  320. _, err := buildImage(name,
  321. `
  322. FROM busybox
  323. ENV TEST foo
  324. CMD echo \$
  325. `,
  326. true)
  327. if err != nil {
  328. c.Fatal(err)
  329. }
  330. out, _ := dockerCmd(c, "run", "-t", name)
  331. if strings.TrimSpace(out) != "$" {
  332. c.Fatalf("Env TEST was not overwritten with bar when foo was supplied to dockerfile: was %q", strings.TrimSpace(out))
  333. }
  334. }
  335. func (s *DockerSuite) TestBuildEnvOverwrite(c *check.C) {
  336. name := "testbuildenvoverwrite"
  337. _, err := buildImage(name,
  338. `
  339. FROM busybox
  340. ENV TEST foo
  341. CMD echo ${TEST}
  342. `,
  343. true)
  344. if err != nil {
  345. c.Fatal(err)
  346. }
  347. out, _ := dockerCmd(c, "run", "-e", "TEST=bar", "-t", name)
  348. if strings.TrimSpace(out) != "bar" {
  349. c.Fatalf("Env TEST was not overwritten with bar when foo was supplied to dockerfile: was %q", strings.TrimSpace(out))
  350. }
  351. }
  352. func (s *DockerSuite) TestBuildOnBuildForbiddenMaintainerInSourceImage(c *check.C) {
  353. name := "testbuildonbuildforbiddenmaintainerinsourceimage"
  354. out, _ := dockerCmd(c, "create", "busybox", "true")
  355. cleanedContainerID := strings.TrimSpace(out)
  356. dockerCmd(c, "commit", "--run", "{\"OnBuild\":[\"MAINTAINER docker.io\"]}", cleanedContainerID, "onbuild")
  357. _, err := buildImage(name,
  358. `FROM onbuild`,
  359. true)
  360. if err != nil {
  361. if !strings.Contains(err.Error(), "maintainer isn't allowed as an ONBUILD trigger") {
  362. c.Fatalf("Wrong error %v, must be about MAINTAINER and ONBUILD in source image", err)
  363. }
  364. } else {
  365. c.Fatal("Error must not be nil")
  366. }
  367. }
  368. func (s *DockerSuite) TestBuildOnBuildForbiddenFromInSourceImage(c *check.C) {
  369. name := "testbuildonbuildforbiddenfrominsourceimage"
  370. out, _ := dockerCmd(c, "create", "busybox", "true")
  371. cleanedContainerID := strings.TrimSpace(out)
  372. dockerCmd(c, "commit", "--run", "{\"OnBuild\":[\"FROM busybox\"]}", cleanedContainerID, "onbuild")
  373. _, err := buildImage(name,
  374. `FROM onbuild`,
  375. true)
  376. if err != nil {
  377. if !strings.Contains(err.Error(), "from isn't allowed as an ONBUILD trigger") {
  378. c.Fatalf("Wrong error %v, must be about FROM and ONBUILD in source image", err)
  379. }
  380. } else {
  381. c.Fatal("Error must not be nil")
  382. }
  383. }
  384. func (s *DockerSuite) TestBuildOnBuildForbiddenChainedInSourceImage(c *check.C) {
  385. name := "testbuildonbuildforbiddenchainedinsourceimage"
  386. out, _ := dockerCmd(c, "create", "busybox", "true")
  387. cleanedContainerID := strings.TrimSpace(out)
  388. dockerCmd(c, "commit", "--run", "{\"OnBuild\":[\"ONBUILD RUN ls\"]}", cleanedContainerID, "onbuild")
  389. _, err := buildImage(name,
  390. `FROM onbuild`,
  391. true)
  392. if err != nil {
  393. if !strings.Contains(err.Error(), "Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed") {
  394. c.Fatalf("Wrong error %v, must be about chaining ONBUILD in source image", err)
  395. }
  396. } else {
  397. c.Fatal("Error must not be nil")
  398. }
  399. }
  400. func (s *DockerSuite) TestBuildOnBuildCmdEntrypointJSON(c *check.C) {
  401. name1 := "onbuildcmd"
  402. name2 := "onbuildgenerated"
  403. _, err := buildImage(name1, `
  404. FROM busybox
  405. ONBUILD CMD ["hello world"]
  406. ONBUILD ENTRYPOINT ["echo"]
  407. ONBUILD RUN ["true"]`,
  408. false)
  409. if err != nil {
  410. c.Fatal(err)
  411. }
  412. _, err = buildImage(name2, fmt.Sprintf(`FROM %s`, name1), false)
  413. if err != nil {
  414. c.Fatal(err)
  415. }
  416. out, _ := dockerCmd(c, "run", "-t", name2)
  417. if !regexp.MustCompile(`(?m)^hello world`).MatchString(out) {
  418. c.Fatal("did not get echo output from onbuild", out)
  419. }
  420. }
  421. func (s *DockerSuite) TestBuildOnBuildEntrypointJSON(c *check.C) {
  422. name1 := "onbuildcmd"
  423. name2 := "onbuildgenerated"
  424. _, err := buildImage(name1, `
  425. FROM busybox
  426. ONBUILD ENTRYPOINT ["echo"]`,
  427. false)
  428. if err != nil {
  429. c.Fatal(err)
  430. }
  431. _, err = buildImage(name2, fmt.Sprintf("FROM %s\nCMD [\"hello world\"]\n", name1), false)
  432. if err != nil {
  433. c.Fatal(err)
  434. }
  435. out, _ := dockerCmd(c, "run", "-t", name2)
  436. if !regexp.MustCompile(`(?m)^hello world`).MatchString(out) {
  437. c.Fatal("got malformed output from onbuild", out)
  438. }
  439. }
  440. func (s *DockerSuite) TestBuildCacheAdd(c *check.C) {
  441. name := "testbuildtwoimageswithadd"
  442. server, err := fakeStorage(map[string]string{
  443. "robots.txt": "hello",
  444. "index.html": "world",
  445. })
  446. if err != nil {
  447. c.Fatal(err)
  448. }
  449. defer server.Close()
  450. if _, err := buildImage(name,
  451. fmt.Sprintf(`FROM scratch
  452. ADD %s/robots.txt /`, server.URL()),
  453. true); err != nil {
  454. c.Fatal(err)
  455. }
  456. if err != nil {
  457. c.Fatal(err)
  458. }
  459. deleteImages(name)
  460. _, out, err := buildImageWithOut(name,
  461. fmt.Sprintf(`FROM scratch
  462. ADD %s/index.html /`, server.URL()),
  463. true)
  464. if err != nil {
  465. c.Fatal(err)
  466. }
  467. if strings.Contains(out, "Using cache") {
  468. c.Fatal("2nd build used cache on ADD, it shouldn't")
  469. }
  470. }
  471. func (s *DockerSuite) TestBuildLastModified(c *check.C) {
  472. name := "testbuildlastmodified"
  473. server, err := fakeStorage(map[string]string{
  474. "file": "hello",
  475. })
  476. if err != nil {
  477. c.Fatal(err)
  478. }
  479. defer server.Close()
  480. var out, out2 string
  481. dFmt := `FROM busybox
  482. ADD %s/file /
  483. RUN ls -le /file`
  484. dockerfile := fmt.Sprintf(dFmt, server.URL())
  485. if _, out, err = buildImageWithOut(name, dockerfile, false); err != nil {
  486. c.Fatal(err)
  487. }
  488. originMTime := regexp.MustCompile(`root.*/file.*\n`).FindString(out)
  489. // Make sure our regexp is correct
  490. if strings.Index(originMTime, "/file") < 0 {
  491. c.Fatalf("Missing ls info on 'file':\n%s", out)
  492. }
  493. // Build it again and make sure the mtime of the file didn't change.
  494. // Wait a few seconds to make sure the time changed enough to notice
  495. time.Sleep(2 * time.Second)
  496. if _, out2, err = buildImageWithOut(name, dockerfile, false); err != nil {
  497. c.Fatal(err)
  498. }
  499. newMTime := regexp.MustCompile(`root.*/file.*\n`).FindString(out2)
  500. if newMTime != originMTime {
  501. c.Fatalf("MTime changed:\nOrigin:%s\nNew:%s", originMTime, newMTime)
  502. }
  503. // Now 'touch' the file and make sure the timestamp DID change this time
  504. // Create a new fakeStorage instead of just using Add() to help windows
  505. server, err = fakeStorage(map[string]string{
  506. "file": "hello",
  507. })
  508. if err != nil {
  509. c.Fatal(err)
  510. }
  511. defer server.Close()
  512. dockerfile = fmt.Sprintf(dFmt, server.URL())
  513. if _, out2, err = buildImageWithOut(name, dockerfile, false); err != nil {
  514. c.Fatal(err)
  515. }
  516. newMTime = regexp.MustCompile(`root.*/file.*\n`).FindString(out2)
  517. if newMTime == originMTime {
  518. c.Fatalf("MTime didn't change:\nOrigin:%s\nNew:%s", originMTime, newMTime)
  519. }
  520. }
  521. func (s *DockerSuite) TestBuildSixtySteps(c *check.C) {
  522. name := "foobuildsixtysteps"
  523. ctx, err := fakeContext("FROM scratch\n"+strings.Repeat("ADD foo /\n", 60),
  524. map[string]string{
  525. "foo": "test1",
  526. })
  527. if err != nil {
  528. c.Fatal(err)
  529. }
  530. defer ctx.Close()
  531. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  532. c.Fatal(err)
  533. }
  534. }
  535. func (s *DockerSuite) TestBuildAddSingleFileToRoot(c *check.C) {
  536. name := "testaddimg"
  537. ctx, err := fakeContext(fmt.Sprintf(`FROM busybox
  538. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  539. RUN echo 'dockerio:x:1001:' >> /etc/group
  540. RUN touch /exists
  541. RUN chown dockerio.dockerio /exists
  542. ADD test_file /
  543. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  544. RUN [ $(ls -l /test_file | awk '{print $1}') = '%s' ]
  545. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod),
  546. map[string]string{
  547. "test_file": "test1",
  548. })
  549. if err != nil {
  550. c.Fatal(err)
  551. }
  552. defer ctx.Close()
  553. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  554. c.Fatal(err)
  555. }
  556. }
  557. // Issue #3960: "ADD src ." hangs
  558. func (s *DockerSuite) TestBuildAddSingleFileToWorkdir(c *check.C) {
  559. name := "testaddsinglefiletoworkdir"
  560. ctx, err := fakeContext(`FROM busybox
  561. ADD test_file .`,
  562. map[string]string{
  563. "test_file": "test1",
  564. })
  565. if err != nil {
  566. c.Fatal(err)
  567. }
  568. defer ctx.Close()
  569. errChan := make(chan error)
  570. go func() {
  571. _, err := buildImageFromContext(name, ctx, true)
  572. errChan <- err
  573. close(errChan)
  574. }()
  575. select {
  576. case <-time.After(5 * time.Second):
  577. c.Fatal("Build with adding to workdir timed out")
  578. case err := <-errChan:
  579. c.Assert(err, check.IsNil)
  580. }
  581. }
  582. func (s *DockerSuite) TestBuildAddSingleFileToExistDir(c *check.C) {
  583. name := "testaddsinglefiletoexistdir"
  584. ctx, err := fakeContext(`FROM busybox
  585. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  586. RUN echo 'dockerio:x:1001:' >> /etc/group
  587. RUN mkdir /exists
  588. RUN touch /exists/exists_file
  589. RUN chown -R dockerio.dockerio /exists
  590. ADD test_file /exists/
  591. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  592. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]
  593. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
  594. map[string]string{
  595. "test_file": "test1",
  596. })
  597. if err != nil {
  598. c.Fatal(err)
  599. }
  600. defer ctx.Close()
  601. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  602. c.Fatal(err)
  603. }
  604. }
  605. func (s *DockerSuite) TestBuildCopyAddMultipleFiles(c *check.C) {
  606. server, err := fakeStorage(map[string]string{
  607. "robots.txt": "hello",
  608. })
  609. if err != nil {
  610. c.Fatal(err)
  611. }
  612. defer server.Close()
  613. name := "testcopymultiplefilestofile"
  614. ctx, err := fakeContext(fmt.Sprintf(`FROM busybox
  615. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  616. RUN echo 'dockerio:x:1001:' >> /etc/group
  617. RUN mkdir /exists
  618. RUN touch /exists/exists_file
  619. RUN chown -R dockerio.dockerio /exists
  620. COPY test_file1 test_file2 /exists/
  621. ADD test_file3 test_file4 %s/robots.txt /exists/
  622. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  623. RUN [ $(ls -l /exists/test_file1 | awk '{print $3":"$4}') = 'root:root' ]
  624. RUN [ $(ls -l /exists/test_file2 | awk '{print $3":"$4}') = 'root:root' ]
  625. RUN [ $(ls -l /exists/test_file3 | awk '{print $3":"$4}') = 'root:root' ]
  626. RUN [ $(ls -l /exists/test_file4 | awk '{print $3":"$4}') = 'root:root' ]
  627. RUN [ $(ls -l /exists/robots.txt | awk '{print $3":"$4}') = 'root:root' ]
  628. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  629. `, server.URL()),
  630. map[string]string{
  631. "test_file1": "test1",
  632. "test_file2": "test2",
  633. "test_file3": "test3",
  634. "test_file4": "test4",
  635. })
  636. defer ctx.Close()
  637. if err != nil {
  638. c.Fatal(err)
  639. }
  640. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  641. c.Fatal(err)
  642. }
  643. }
  644. func (s *DockerSuite) TestBuildAddMultipleFilesToFile(c *check.C) {
  645. name := "testaddmultiplefilestofile"
  646. ctx, err := fakeContext(`FROM scratch
  647. ADD file1.txt file2.txt test
  648. `,
  649. map[string]string{
  650. "file1.txt": "test1",
  651. "file2.txt": "test1",
  652. })
  653. defer ctx.Close()
  654. if err != nil {
  655. c.Fatal(err)
  656. }
  657. expected := "When using ADD with more than one source file, the destination must be a directory and end with a /"
  658. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  659. c.Fatalf("Wrong error: (should contain %q) got:\n%v", expected, err)
  660. }
  661. }
  662. func (s *DockerSuite) TestBuildJSONAddMultipleFilesToFile(c *check.C) {
  663. name := "testjsonaddmultiplefilestofile"
  664. ctx, err := fakeContext(`FROM scratch
  665. ADD ["file1.txt", "file2.txt", "test"]
  666. `,
  667. map[string]string{
  668. "file1.txt": "test1",
  669. "file2.txt": "test1",
  670. })
  671. defer ctx.Close()
  672. if err != nil {
  673. c.Fatal(err)
  674. }
  675. expected := "When using ADD with more than one source file, the destination must be a directory and end with a /"
  676. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  677. c.Fatalf("Wrong error: (should contain %q) got:\n%v", expected, err)
  678. }
  679. }
  680. func (s *DockerSuite) TestBuildAddMultipleFilesToFileWild(c *check.C) {
  681. name := "testaddmultiplefilestofilewild"
  682. ctx, err := fakeContext(`FROM scratch
  683. ADD file*.txt test
  684. `,
  685. map[string]string{
  686. "file1.txt": "test1",
  687. "file2.txt": "test1",
  688. })
  689. defer ctx.Close()
  690. if err != nil {
  691. c.Fatal(err)
  692. }
  693. expected := "When using ADD with more than one source file, the destination must be a directory and end with a /"
  694. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  695. c.Fatalf("Wrong error: (should contain %q) got:\n%v", expected, err)
  696. }
  697. }
  698. func (s *DockerSuite) TestBuildJSONAddMultipleFilesToFileWild(c *check.C) {
  699. name := "testjsonaddmultiplefilestofilewild"
  700. ctx, err := fakeContext(`FROM scratch
  701. ADD ["file*.txt", "test"]
  702. `,
  703. map[string]string{
  704. "file1.txt": "test1",
  705. "file2.txt": "test1",
  706. })
  707. defer ctx.Close()
  708. if err != nil {
  709. c.Fatal(err)
  710. }
  711. expected := "When using ADD with more than one source file, the destination must be a directory and end with a /"
  712. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  713. c.Fatalf("Wrong error: (should contain %q) got:\n%v", expected, err)
  714. }
  715. }
  716. func (s *DockerSuite) TestBuildCopyMultipleFilesToFile(c *check.C) {
  717. name := "testcopymultiplefilestofile"
  718. ctx, err := fakeContext(`FROM scratch
  719. COPY file1.txt file2.txt test
  720. `,
  721. map[string]string{
  722. "file1.txt": "test1",
  723. "file2.txt": "test1",
  724. })
  725. defer ctx.Close()
  726. if err != nil {
  727. c.Fatal(err)
  728. }
  729. expected := "When using COPY with more than one source file, the destination must be a directory and end with a /"
  730. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  731. c.Fatalf("Wrong error: (should contain %q) got:\n%v", expected, err)
  732. }
  733. }
  734. func (s *DockerSuite) TestBuildJSONCopyMultipleFilesToFile(c *check.C) {
  735. name := "testjsoncopymultiplefilestofile"
  736. ctx, err := fakeContext(`FROM scratch
  737. COPY ["file1.txt", "file2.txt", "test"]
  738. `,
  739. map[string]string{
  740. "file1.txt": "test1",
  741. "file2.txt": "test1",
  742. })
  743. defer ctx.Close()
  744. if err != nil {
  745. c.Fatal(err)
  746. }
  747. expected := "When using COPY with more than one source file, the destination must be a directory and end with a /"
  748. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  749. c.Fatalf("Wrong error: (should contain %q) got:\n%v", expected, err)
  750. }
  751. }
  752. func (s *DockerSuite) TestBuildAddFileWithWhitespace(c *check.C) {
  753. name := "testaddfilewithwhitespace"
  754. ctx, err := fakeContext(`FROM busybox
  755. RUN mkdir "/test dir"
  756. RUN mkdir "/test_dir"
  757. ADD [ "test file1", "/test_file1" ]
  758. ADD [ "test_file2", "/test file2" ]
  759. ADD [ "test file3", "/test file3" ]
  760. ADD [ "test dir/test_file4", "/test_dir/test_file4" ]
  761. ADD [ "test_dir/test_file5", "/test dir/test_file5" ]
  762. ADD [ "test dir/test_file6", "/test dir/test_file6" ]
  763. RUN [ $(cat "/test_file1") = 'test1' ]
  764. RUN [ $(cat "/test file2") = 'test2' ]
  765. RUN [ $(cat "/test file3") = 'test3' ]
  766. RUN [ $(cat "/test_dir/test_file4") = 'test4' ]
  767. RUN [ $(cat "/test dir/test_file5") = 'test5' ]
  768. RUN [ $(cat "/test dir/test_file6") = 'test6' ]`,
  769. map[string]string{
  770. "test file1": "test1",
  771. "test_file2": "test2",
  772. "test file3": "test3",
  773. "test dir/test_file4": "test4",
  774. "test_dir/test_file5": "test5",
  775. "test dir/test_file6": "test6",
  776. })
  777. defer ctx.Close()
  778. if err != nil {
  779. c.Fatal(err)
  780. }
  781. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  782. c.Fatal(err)
  783. }
  784. }
  785. func (s *DockerSuite) TestBuildCopyFileWithWhitespace(c *check.C) {
  786. name := "testcopyfilewithwhitespace"
  787. ctx, err := fakeContext(`FROM busybox
  788. RUN mkdir "/test dir"
  789. RUN mkdir "/test_dir"
  790. COPY [ "test file1", "/test_file1" ]
  791. COPY [ "test_file2", "/test file2" ]
  792. COPY [ "test file3", "/test file3" ]
  793. COPY [ "test dir/test_file4", "/test_dir/test_file4" ]
  794. COPY [ "test_dir/test_file5", "/test dir/test_file5" ]
  795. COPY [ "test dir/test_file6", "/test dir/test_file6" ]
  796. RUN [ $(cat "/test_file1") = 'test1' ]
  797. RUN [ $(cat "/test file2") = 'test2' ]
  798. RUN [ $(cat "/test file3") = 'test3' ]
  799. RUN [ $(cat "/test_dir/test_file4") = 'test4' ]
  800. RUN [ $(cat "/test dir/test_file5") = 'test5' ]
  801. RUN [ $(cat "/test dir/test_file6") = 'test6' ]`,
  802. map[string]string{
  803. "test file1": "test1",
  804. "test_file2": "test2",
  805. "test file3": "test3",
  806. "test dir/test_file4": "test4",
  807. "test_dir/test_file5": "test5",
  808. "test dir/test_file6": "test6",
  809. })
  810. defer ctx.Close()
  811. if err != nil {
  812. c.Fatal(err)
  813. }
  814. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  815. c.Fatal(err)
  816. }
  817. }
  818. func (s *DockerSuite) TestBuildAddMultipleFilesToFileWithWhitespace(c *check.C) {
  819. name := "testaddmultiplefilestofilewithwhitespace"
  820. ctx, err := fakeContext(`FROM busybox
  821. ADD [ "test file1", "test file2", "test" ]
  822. `,
  823. map[string]string{
  824. "test file1": "test1",
  825. "test file2": "test2",
  826. })
  827. defer ctx.Close()
  828. if err != nil {
  829. c.Fatal(err)
  830. }
  831. expected := "When using ADD with more than one source file, the destination must be a directory and end with a /"
  832. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  833. c.Fatalf("Wrong error: (should contain %q) got:\n%v", expected, err)
  834. }
  835. }
  836. func (s *DockerSuite) TestBuildCopyMultipleFilesToFileWithWhitespace(c *check.C) {
  837. name := "testcopymultiplefilestofilewithwhitespace"
  838. ctx, err := fakeContext(`FROM busybox
  839. COPY [ "test file1", "test file2", "test" ]
  840. `,
  841. map[string]string{
  842. "test file1": "test1",
  843. "test file2": "test2",
  844. })
  845. defer ctx.Close()
  846. if err != nil {
  847. c.Fatal(err)
  848. }
  849. expected := "When using COPY with more than one source file, the destination must be a directory and end with a /"
  850. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  851. c.Fatalf("Wrong error: (should contain %q) got:\n%v", expected, err)
  852. }
  853. }
  854. func (s *DockerSuite) TestBuildCopyWildcard(c *check.C) {
  855. name := "testcopywildcard"
  856. server, err := fakeStorage(map[string]string{
  857. "robots.txt": "hello",
  858. "index.html": "world",
  859. })
  860. if err != nil {
  861. c.Fatal(err)
  862. }
  863. defer server.Close()
  864. ctx, err := fakeContext(fmt.Sprintf(`FROM busybox
  865. COPY file*.txt /tmp/
  866. RUN ls /tmp/file1.txt /tmp/file2.txt
  867. RUN mkdir /tmp1
  868. COPY dir* /tmp1/
  869. RUN ls /tmp1/dirt /tmp1/nested_file /tmp1/nested_dir/nest_nest_file
  870. RUN mkdir /tmp2
  871. ADD dir/*dir %s/robots.txt /tmp2/
  872. RUN ls /tmp2/nest_nest_file /tmp2/robots.txt
  873. `, server.URL()),
  874. map[string]string{
  875. "file1.txt": "test1",
  876. "file2.txt": "test2",
  877. "dir/nested_file": "nested file",
  878. "dir/nested_dir/nest_nest_file": "2 times nested",
  879. "dirt": "dirty",
  880. })
  881. if err != nil {
  882. c.Fatal(err)
  883. }
  884. defer ctx.Close()
  885. id1, err := buildImageFromContext(name, ctx, true)
  886. if err != nil {
  887. c.Fatal(err)
  888. }
  889. // Now make sure we use a cache the 2nd time
  890. id2, err := buildImageFromContext(name, ctx, true)
  891. if err != nil {
  892. c.Fatal(err)
  893. }
  894. if id1 != id2 {
  895. c.Fatal("didn't use the cache")
  896. }
  897. }
  898. func (s *DockerSuite) TestBuildCopyWildcardNoFind(c *check.C) {
  899. name := "testcopywildcardnofind"
  900. ctx, err := fakeContext(`FROM busybox
  901. COPY file*.txt /tmp/
  902. `, nil)
  903. defer ctx.Close()
  904. if err != nil {
  905. c.Fatal(err)
  906. }
  907. _, err = buildImageFromContext(name, ctx, true)
  908. if err == nil {
  909. c.Fatal("should have failed to find a file")
  910. }
  911. if !strings.Contains(err.Error(), "No source files were specified") {
  912. c.Fatalf("Wrong error %v, must be about no source files", err)
  913. }
  914. }
  915. func (s *DockerSuite) TestBuildCopyWildcardInName(c *check.C) {
  916. name := "testcopywildcardinname"
  917. ctx, err := fakeContext(`FROM busybox
  918. COPY *.txt /tmp/
  919. RUN [ "$(cat /tmp/\*.txt)" = 'hi there' ]
  920. `, map[string]string{"*.txt": "hi there"})
  921. if err != nil {
  922. // Normally we would do c.Fatal(err) here but given that
  923. // the odds of this failing are so rare, it must be because
  924. // the OS we're running the client on doesn't support * in
  925. // filenames (like windows). So, instead of failing the test
  926. // just let it pass. Then we don't need to explicitly
  927. // say which OSs this works on or not.
  928. return
  929. }
  930. defer ctx.Close()
  931. _, err = buildImageFromContext(name, ctx, true)
  932. if err != nil {
  933. c.Fatalf("should have built: %q", err)
  934. }
  935. }
  936. func (s *DockerSuite) TestBuildCopyWildcardCache(c *check.C) {
  937. name := "testcopywildcardcache"
  938. ctx, err := fakeContext(`FROM busybox
  939. COPY file1.txt /tmp/`,
  940. map[string]string{
  941. "file1.txt": "test1",
  942. })
  943. defer ctx.Close()
  944. if err != nil {
  945. c.Fatal(err)
  946. }
  947. id1, err := buildImageFromContext(name, ctx, true)
  948. if err != nil {
  949. c.Fatal(err)
  950. }
  951. // Now make sure we use a cache the 2nd time even with wild cards.
  952. // Use the same context so the file is the same and the checksum will match
  953. ctx.Add("Dockerfile", `FROM busybox
  954. COPY file*.txt /tmp/`)
  955. id2, err := buildImageFromContext(name, ctx, true)
  956. if err != nil {
  957. c.Fatal(err)
  958. }
  959. if id1 != id2 {
  960. c.Fatal("didn't use the cache")
  961. }
  962. }
  963. func (s *DockerSuite) TestBuildAddSingleFileToNonExistingDir(c *check.C) {
  964. name := "testaddsinglefiletononexistingdir"
  965. ctx, err := fakeContext(`FROM busybox
  966. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  967. RUN echo 'dockerio:x:1001:' >> /etc/group
  968. RUN touch /exists
  969. RUN chown dockerio.dockerio /exists
  970. ADD test_file /test_dir/
  971. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  972. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  973. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
  974. map[string]string{
  975. "test_file": "test1",
  976. })
  977. if err != nil {
  978. c.Fatal(err)
  979. }
  980. defer ctx.Close()
  981. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  982. c.Fatal(err)
  983. }
  984. }
  985. func (s *DockerSuite) TestBuildAddDirContentToRoot(c *check.C) {
  986. name := "testadddircontenttoroot"
  987. ctx, err := fakeContext(`FROM busybox
  988. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  989. RUN echo 'dockerio:x:1001:' >> /etc/group
  990. RUN touch /exists
  991. RUN chown dockerio.dockerio exists
  992. ADD test_dir /
  993. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  994. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
  995. map[string]string{
  996. "test_dir/test_file": "test1",
  997. })
  998. if err != nil {
  999. c.Fatal(err)
  1000. }
  1001. defer ctx.Close()
  1002. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1003. c.Fatal(err)
  1004. }
  1005. }
  1006. func (s *DockerSuite) TestBuildAddDirContentToExistingDir(c *check.C) {
  1007. name := "testadddircontenttoexistingdir"
  1008. ctx, err := fakeContext(`FROM busybox
  1009. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1010. RUN echo 'dockerio:x:1001:' >> /etc/group
  1011. RUN mkdir /exists
  1012. RUN touch /exists/exists_file
  1013. RUN chown -R dockerio.dockerio /exists
  1014. ADD test_dir/ /exists/
  1015. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  1016. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  1017. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]`,
  1018. map[string]string{
  1019. "test_dir/test_file": "test1",
  1020. })
  1021. if err != nil {
  1022. c.Fatal(err)
  1023. }
  1024. defer ctx.Close()
  1025. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1026. c.Fatal(err)
  1027. }
  1028. }
  1029. func (s *DockerSuite) TestBuildAddWholeDirToRoot(c *check.C) {
  1030. name := "testaddwholedirtoroot"
  1031. ctx, err := fakeContext(fmt.Sprintf(`FROM busybox
  1032. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1033. RUN echo 'dockerio:x:1001:' >> /etc/group
  1034. RUN touch /exists
  1035. RUN chown dockerio.dockerio exists
  1036. ADD test_dir /test_dir
  1037. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  1038. RUN [ $(ls -l / | grep test_dir | awk '{print $1}') = 'drwxr-xr-x' ]
  1039. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  1040. RUN [ $(ls -l /test_dir/test_file | awk '{print $1}') = '%s' ]
  1041. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod),
  1042. map[string]string{
  1043. "test_dir/test_file": "test1",
  1044. })
  1045. if err != nil {
  1046. c.Fatal(err)
  1047. }
  1048. defer ctx.Close()
  1049. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1050. c.Fatal(err)
  1051. }
  1052. }
  1053. // Testing #5941
  1054. func (s *DockerSuite) TestBuildAddEtcToRoot(c *check.C) {
  1055. name := "testaddetctoroot"
  1056. ctx, err := fakeContext(`FROM scratch
  1057. ADD . /`,
  1058. map[string]string{
  1059. "etc/test_file": "test1",
  1060. })
  1061. if err != nil {
  1062. c.Fatal(err)
  1063. }
  1064. defer ctx.Close()
  1065. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1066. c.Fatal(err)
  1067. }
  1068. }
  1069. // Testing #9401
  1070. func (s *DockerSuite) TestBuildAddPreservesFilesSpecialBits(c *check.C) {
  1071. name := "testaddpreservesfilesspecialbits"
  1072. ctx, err := fakeContext(`FROM busybox
  1073. ADD suidbin /usr/bin/suidbin
  1074. RUN chmod 4755 /usr/bin/suidbin
  1075. RUN [ $(ls -l /usr/bin/suidbin | awk '{print $1}') = '-rwsr-xr-x' ]
  1076. ADD ./data/ /
  1077. RUN [ $(ls -l /usr/bin/suidbin | awk '{print $1}') = '-rwsr-xr-x' ]`,
  1078. map[string]string{
  1079. "suidbin": "suidbin",
  1080. "/data/usr/test_file": "test1",
  1081. })
  1082. if err != nil {
  1083. c.Fatal(err)
  1084. }
  1085. defer ctx.Close()
  1086. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1087. c.Fatal(err)
  1088. }
  1089. }
  1090. func (s *DockerSuite) TestBuildCopySingleFileToRoot(c *check.C) {
  1091. name := "testcopysinglefiletoroot"
  1092. ctx, err := fakeContext(fmt.Sprintf(`FROM busybox
  1093. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1094. RUN echo 'dockerio:x:1001:' >> /etc/group
  1095. RUN touch /exists
  1096. RUN chown dockerio.dockerio /exists
  1097. COPY test_file /
  1098. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  1099. RUN [ $(ls -l /test_file | awk '{print $1}') = '%s' ]
  1100. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod),
  1101. map[string]string{
  1102. "test_file": "test1",
  1103. })
  1104. if err != nil {
  1105. c.Fatal(err)
  1106. }
  1107. defer ctx.Close()
  1108. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1109. c.Fatal(err)
  1110. }
  1111. }
  1112. // Issue #3960: "ADD src ." hangs - adapted for COPY
  1113. func (s *DockerSuite) TestBuildCopySingleFileToWorkdir(c *check.C) {
  1114. name := "testcopysinglefiletoworkdir"
  1115. ctx, err := fakeContext(`FROM busybox
  1116. COPY test_file .`,
  1117. map[string]string{
  1118. "test_file": "test1",
  1119. })
  1120. if err != nil {
  1121. c.Fatal(err)
  1122. }
  1123. defer ctx.Close()
  1124. errChan := make(chan error)
  1125. go func() {
  1126. _, err := buildImageFromContext(name, ctx, true)
  1127. errChan <- err
  1128. close(errChan)
  1129. }()
  1130. select {
  1131. case <-time.After(5 * time.Second):
  1132. c.Fatal("Build with adding to workdir timed out")
  1133. case err := <-errChan:
  1134. c.Assert(err, check.IsNil)
  1135. }
  1136. }
  1137. func (s *DockerSuite) TestBuildCopySingleFileToExistDir(c *check.C) {
  1138. name := "testcopysinglefiletoexistdir"
  1139. ctx, err := fakeContext(`FROM busybox
  1140. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1141. RUN echo 'dockerio:x:1001:' >> /etc/group
  1142. RUN mkdir /exists
  1143. RUN touch /exists/exists_file
  1144. RUN chown -R dockerio.dockerio /exists
  1145. COPY test_file /exists/
  1146. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  1147. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]
  1148. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
  1149. map[string]string{
  1150. "test_file": "test1",
  1151. })
  1152. if err != nil {
  1153. c.Fatal(err)
  1154. }
  1155. defer ctx.Close()
  1156. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1157. c.Fatal(err)
  1158. }
  1159. }
  1160. func (s *DockerSuite) TestBuildCopySingleFileToNonExistDir(c *check.C) {
  1161. name := "testcopysinglefiletononexistdir"
  1162. ctx, err := fakeContext(`FROM busybox
  1163. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1164. RUN echo 'dockerio:x:1001:' >> /etc/group
  1165. RUN touch /exists
  1166. RUN chown dockerio.dockerio /exists
  1167. COPY test_file /test_dir/
  1168. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  1169. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  1170. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
  1171. map[string]string{
  1172. "test_file": "test1",
  1173. })
  1174. if err != nil {
  1175. c.Fatal(err)
  1176. }
  1177. defer ctx.Close()
  1178. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1179. c.Fatal(err)
  1180. }
  1181. }
  1182. func (s *DockerSuite) TestBuildCopyDirContentToRoot(c *check.C) {
  1183. name := "testcopydircontenttoroot"
  1184. ctx, err := fakeContext(`FROM busybox
  1185. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1186. RUN echo 'dockerio:x:1001:' >> /etc/group
  1187. RUN touch /exists
  1188. RUN chown dockerio.dockerio exists
  1189. COPY test_dir /
  1190. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  1191. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
  1192. map[string]string{
  1193. "test_dir/test_file": "test1",
  1194. })
  1195. if err != nil {
  1196. c.Fatal(err)
  1197. }
  1198. defer ctx.Close()
  1199. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1200. c.Fatal(err)
  1201. }
  1202. }
  1203. func (s *DockerSuite) TestBuildCopyDirContentToExistDir(c *check.C) {
  1204. name := "testcopydircontenttoexistdir"
  1205. ctx, err := fakeContext(`FROM busybox
  1206. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1207. RUN echo 'dockerio:x:1001:' >> /etc/group
  1208. RUN mkdir /exists
  1209. RUN touch /exists/exists_file
  1210. RUN chown -R dockerio.dockerio /exists
  1211. COPY test_dir/ /exists/
  1212. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  1213. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  1214. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]`,
  1215. map[string]string{
  1216. "test_dir/test_file": "test1",
  1217. })
  1218. if err != nil {
  1219. c.Fatal(err)
  1220. }
  1221. defer ctx.Close()
  1222. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1223. c.Fatal(err)
  1224. }
  1225. }
  1226. func (s *DockerSuite) TestBuildCopyWholeDirToRoot(c *check.C) {
  1227. name := "testcopywholedirtoroot"
  1228. ctx, err := fakeContext(fmt.Sprintf(`FROM busybox
  1229. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1230. RUN echo 'dockerio:x:1001:' >> /etc/group
  1231. RUN touch /exists
  1232. RUN chown dockerio.dockerio exists
  1233. COPY test_dir /test_dir
  1234. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  1235. RUN [ $(ls -l / | grep test_dir | awk '{print $1}') = 'drwxr-xr-x' ]
  1236. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  1237. RUN [ $(ls -l /test_dir/test_file | awk '{print $1}') = '%s' ]
  1238. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod),
  1239. map[string]string{
  1240. "test_dir/test_file": "test1",
  1241. })
  1242. if err != nil {
  1243. c.Fatal(err)
  1244. }
  1245. defer ctx.Close()
  1246. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1247. c.Fatal(err)
  1248. }
  1249. }
  1250. func (s *DockerSuite) TestBuildCopyEtcToRoot(c *check.C) {
  1251. name := "testcopyetctoroot"
  1252. ctx, err := fakeContext(`FROM scratch
  1253. COPY . /`,
  1254. map[string]string{
  1255. "etc/test_file": "test1",
  1256. })
  1257. if err != nil {
  1258. c.Fatal(err)
  1259. }
  1260. defer ctx.Close()
  1261. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1262. c.Fatal(err)
  1263. }
  1264. }
  1265. func (s *DockerSuite) TestBuildCopyDisallowRemote(c *check.C) {
  1266. name := "testcopydisallowremote"
  1267. _, out, err := buildImageWithOut(name, `FROM scratch
  1268. COPY https://index.docker.io/robots.txt /`,
  1269. true)
  1270. if err == nil || !strings.Contains(out, "Source can't be a URL for COPY") {
  1271. c.Fatalf("Error should be about disallowed remote source, got err: %s, out: %q", err, out)
  1272. }
  1273. }
  1274. func (s *DockerSuite) TestBuildAddBadLinks(c *check.C) {
  1275. const (
  1276. dockerfile = `
  1277. FROM scratch
  1278. ADD links.tar /
  1279. ADD foo.txt /symlink/
  1280. `
  1281. targetFile = "foo.txt"
  1282. )
  1283. var (
  1284. name = "test-link-absolute"
  1285. )
  1286. ctx, err := fakeContext(dockerfile, nil)
  1287. if err != nil {
  1288. c.Fatal(err)
  1289. }
  1290. defer ctx.Close()
  1291. tempDir, err := ioutil.TempDir("", "test-link-absolute-temp-")
  1292. if err != nil {
  1293. c.Fatalf("failed to create temporary directory: %s", tempDir)
  1294. }
  1295. defer os.RemoveAll(tempDir)
  1296. var symlinkTarget string
  1297. if runtime.GOOS == "windows" {
  1298. var driveLetter string
  1299. if abs, err := filepath.Abs(tempDir); err != nil {
  1300. c.Fatal(err)
  1301. } else {
  1302. driveLetter = abs[:1]
  1303. }
  1304. tempDirWithoutDrive := tempDir[2:]
  1305. symlinkTarget = fmt.Sprintf(`%s:\..\..\..\..\..\..\..\..\..\..\..\..%s`, driveLetter, tempDirWithoutDrive)
  1306. } else {
  1307. symlinkTarget = fmt.Sprintf("/../../../../../../../../../../../..%s", tempDir)
  1308. }
  1309. tarPath := filepath.Join(ctx.Dir, "links.tar")
  1310. nonExistingFile := filepath.Join(tempDir, targetFile)
  1311. fooPath := filepath.Join(ctx.Dir, targetFile)
  1312. tarOut, err := os.Create(tarPath)
  1313. if err != nil {
  1314. c.Fatal(err)
  1315. }
  1316. tarWriter := tar.NewWriter(tarOut)
  1317. header := &tar.Header{
  1318. Name: "symlink",
  1319. Typeflag: tar.TypeSymlink,
  1320. Linkname: symlinkTarget,
  1321. Mode: 0755,
  1322. Uid: 0,
  1323. Gid: 0,
  1324. }
  1325. err = tarWriter.WriteHeader(header)
  1326. if err != nil {
  1327. c.Fatal(err)
  1328. }
  1329. tarWriter.Close()
  1330. tarOut.Close()
  1331. foo, err := os.Create(fooPath)
  1332. if err != nil {
  1333. c.Fatal(err)
  1334. }
  1335. defer foo.Close()
  1336. if _, err := foo.WriteString("test"); err != nil {
  1337. c.Fatal(err)
  1338. }
  1339. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1340. c.Fatal(err)
  1341. }
  1342. if _, err := os.Stat(nonExistingFile); err == nil || err != nil && !os.IsNotExist(err) {
  1343. c.Fatalf("%s shouldn't have been written and it shouldn't exist", nonExistingFile)
  1344. }
  1345. }
  1346. func (s *DockerSuite) TestBuildAddBadLinksVolume(c *check.C) {
  1347. const (
  1348. dockerfileTemplate = `
  1349. FROM busybox
  1350. RUN ln -s /../../../../../../../../%s /x
  1351. VOLUME /x
  1352. ADD foo.txt /x/`
  1353. targetFile = "foo.txt"
  1354. )
  1355. var (
  1356. name = "test-link-absolute-volume"
  1357. dockerfile = ""
  1358. )
  1359. tempDir, err := ioutil.TempDir("", "test-link-absolute-volume-temp-")
  1360. if err != nil {
  1361. c.Fatalf("failed to create temporary directory: %s", tempDir)
  1362. }
  1363. defer os.RemoveAll(tempDir)
  1364. dockerfile = fmt.Sprintf(dockerfileTemplate, tempDir)
  1365. nonExistingFile := filepath.Join(tempDir, targetFile)
  1366. ctx, err := fakeContext(dockerfile, nil)
  1367. if err != nil {
  1368. c.Fatal(err)
  1369. }
  1370. defer ctx.Close()
  1371. fooPath := filepath.Join(ctx.Dir, targetFile)
  1372. foo, err := os.Create(fooPath)
  1373. if err != nil {
  1374. c.Fatal(err)
  1375. }
  1376. defer foo.Close()
  1377. if _, err := foo.WriteString("test"); err != nil {
  1378. c.Fatal(err)
  1379. }
  1380. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1381. c.Fatal(err)
  1382. }
  1383. if _, err := os.Stat(nonExistingFile); err == nil || err != nil && !os.IsNotExist(err) {
  1384. c.Fatalf("%s shouldn't have been written and it shouldn't exist", nonExistingFile)
  1385. }
  1386. }
  1387. // Issue #5270 - ensure we throw a better error than "unexpected EOF"
  1388. // when we can't access files in the context.
  1389. func (s *DockerSuite) TestBuildWithInaccessibleFilesInContext(c *check.C) {
  1390. testRequires(c, UnixCli) // test uses chown/chmod: not available on windows
  1391. {
  1392. name := "testbuildinaccessiblefiles"
  1393. ctx, err := fakeContext("FROM scratch\nADD . /foo/", map[string]string{"fileWithoutReadAccess": "foo"})
  1394. if err != nil {
  1395. c.Fatal(err)
  1396. }
  1397. defer ctx.Close()
  1398. // This is used to ensure we detect inaccessible files early during build in the cli client
  1399. pathToFileWithoutReadAccess := filepath.Join(ctx.Dir, "fileWithoutReadAccess")
  1400. if err = os.Chown(pathToFileWithoutReadAccess, 0, 0); err != nil {
  1401. c.Fatalf("failed to chown file to root: %s", err)
  1402. }
  1403. if err = os.Chmod(pathToFileWithoutReadAccess, 0700); err != nil {
  1404. c.Fatalf("failed to chmod file to 700: %s", err)
  1405. }
  1406. buildCmd := exec.Command("su", "unprivilegeduser", "-c", fmt.Sprintf("%s build -t %s .", dockerBinary, name))
  1407. buildCmd.Dir = ctx.Dir
  1408. out, _, err := runCommandWithOutput(buildCmd)
  1409. if err == nil {
  1410. c.Fatalf("build should have failed: %s %s", err, out)
  1411. }
  1412. // check if we've detected the failure before we started building
  1413. if !strings.Contains(out, "no permission to read from ") {
  1414. c.Fatalf("output should've contained the string: no permission to read from but contained: %s", out)
  1415. }
  1416. if !strings.Contains(out, "Error checking context") {
  1417. c.Fatalf("output should've contained the string: Error checking context")
  1418. }
  1419. }
  1420. {
  1421. name := "testbuildinaccessibledirectory"
  1422. ctx, err := fakeContext("FROM scratch\nADD . /foo/", map[string]string{"directoryWeCantStat/bar": "foo"})
  1423. if err != nil {
  1424. c.Fatal(err)
  1425. }
  1426. defer ctx.Close()
  1427. // This is used to ensure we detect inaccessible directories early during build in the cli client
  1428. pathToDirectoryWithoutReadAccess := filepath.Join(ctx.Dir, "directoryWeCantStat")
  1429. pathToFileInDirectoryWithoutReadAccess := filepath.Join(pathToDirectoryWithoutReadAccess, "bar")
  1430. if err = os.Chown(pathToDirectoryWithoutReadAccess, 0, 0); err != nil {
  1431. c.Fatalf("failed to chown directory to root: %s", err)
  1432. }
  1433. if err = os.Chmod(pathToDirectoryWithoutReadAccess, 0444); err != nil {
  1434. c.Fatalf("failed to chmod directory to 444: %s", err)
  1435. }
  1436. if err = os.Chmod(pathToFileInDirectoryWithoutReadAccess, 0700); err != nil {
  1437. c.Fatalf("failed to chmod file to 700: %s", err)
  1438. }
  1439. buildCmd := exec.Command("su", "unprivilegeduser", "-c", fmt.Sprintf("%s build -t %s .", dockerBinary, name))
  1440. buildCmd.Dir = ctx.Dir
  1441. out, _, err := runCommandWithOutput(buildCmd)
  1442. if err == nil {
  1443. c.Fatalf("build should have failed: %s %s", err, out)
  1444. }
  1445. // check if we've detected the failure before we started building
  1446. if !strings.Contains(out, "can't stat") {
  1447. c.Fatalf("output should've contained the string: can't access %s", out)
  1448. }
  1449. if !strings.Contains(out, "Error checking context") {
  1450. c.Fatalf("output should've contained the string: Error checking context\ngot:%s", out)
  1451. }
  1452. }
  1453. {
  1454. name := "testlinksok"
  1455. ctx, err := fakeContext("FROM scratch\nADD . /foo/", nil)
  1456. if err != nil {
  1457. c.Fatal(err)
  1458. }
  1459. defer ctx.Close()
  1460. target := "../../../../../../../../../../../../../../../../../../../azA"
  1461. if err := os.Symlink(filepath.Join(ctx.Dir, "g"), target); err != nil {
  1462. c.Fatal(err)
  1463. }
  1464. defer os.Remove(target)
  1465. // This is used to ensure we don't follow links when checking if everything in the context is accessible
  1466. // This test doesn't require that we run commands as an unprivileged user
  1467. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1468. c.Fatal(err)
  1469. }
  1470. }
  1471. {
  1472. name := "testbuildignoredinaccessible"
  1473. ctx, err := fakeContext("FROM scratch\nADD . /foo/",
  1474. map[string]string{
  1475. "directoryWeCantStat/bar": "foo",
  1476. ".dockerignore": "directoryWeCantStat",
  1477. })
  1478. if err != nil {
  1479. c.Fatal(err)
  1480. }
  1481. defer ctx.Close()
  1482. // This is used to ensure we don't try to add inaccessible files when they are ignored by a .dockerignore pattern
  1483. pathToDirectoryWithoutReadAccess := filepath.Join(ctx.Dir, "directoryWeCantStat")
  1484. pathToFileInDirectoryWithoutReadAccess := filepath.Join(pathToDirectoryWithoutReadAccess, "bar")
  1485. if err = os.Chown(pathToDirectoryWithoutReadAccess, 0, 0); err != nil {
  1486. c.Fatalf("failed to chown directory to root: %s", err)
  1487. }
  1488. if err = os.Chmod(pathToDirectoryWithoutReadAccess, 0444); err != nil {
  1489. c.Fatalf("failed to chmod directory to 755: %s", err)
  1490. }
  1491. if err = os.Chmod(pathToFileInDirectoryWithoutReadAccess, 0700); err != nil {
  1492. c.Fatalf("failed to chmod file to 444: %s", err)
  1493. }
  1494. buildCmd := exec.Command("su", "unprivilegeduser", "-c", fmt.Sprintf("%s build -t %s .", dockerBinary, name))
  1495. buildCmd.Dir = ctx.Dir
  1496. if out, _, err := runCommandWithOutput(buildCmd); err != nil {
  1497. c.Fatalf("build should have worked: %s %s", err, out)
  1498. }
  1499. }
  1500. }
  1501. func (s *DockerSuite) TestBuildForceRm(c *check.C) {
  1502. containerCountBefore, err := getContainerCount()
  1503. if err != nil {
  1504. c.Fatalf("failed to get the container count: %s", err)
  1505. }
  1506. name := "testbuildforcerm"
  1507. ctx, err := fakeContext("FROM scratch\nRUN true\nRUN thiswillfail", nil)
  1508. if err != nil {
  1509. c.Fatal(err)
  1510. }
  1511. defer ctx.Close()
  1512. dockerCmdInDir(c, ctx.Dir, "build", "-t", name, "--force-rm", ".")
  1513. containerCountAfter, err := getContainerCount()
  1514. if err != nil {
  1515. c.Fatalf("failed to get the container count: %s", err)
  1516. }
  1517. if containerCountBefore != containerCountAfter {
  1518. c.Fatalf("--force-rm shouldn't have left containers behind")
  1519. }
  1520. }
  1521. // Test that an infinite sleep during a build is killed if the client disconnects.
  1522. // This test is fairly hairy because there are lots of ways to race.
  1523. // Strategy:
  1524. // * Monitor the output of docker events starting from before
  1525. // * Run a 1-year-long sleep from a docker build.
  1526. // * When docker events sees container start, close the "docker build" command
  1527. // * Wait for docker events to emit a dying event.
  1528. func (s *DockerSuite) TestBuildCancelationKillsSleep(c *check.C) {
  1529. name := "testbuildcancelation"
  1530. // (Note: one year, will never finish)
  1531. ctx, err := fakeContext("FROM busybox\nRUN sleep 31536000", nil)
  1532. if err != nil {
  1533. c.Fatal(err)
  1534. }
  1535. defer ctx.Close()
  1536. finish := make(chan struct{})
  1537. defer close(finish)
  1538. eventStart := make(chan struct{})
  1539. eventDie := make(chan struct{})
  1540. containerID := make(chan string)
  1541. startEpoch := daemonTime(c).Unix()
  1542. // Watch for events since epoch.
  1543. eventsCmd := exec.Command(
  1544. dockerBinary, "events",
  1545. "--since", strconv.FormatInt(startEpoch, 10))
  1546. stdout, err := eventsCmd.StdoutPipe()
  1547. if err != nil {
  1548. c.Fatal(err)
  1549. }
  1550. if err := eventsCmd.Start(); err != nil {
  1551. c.Fatal(err)
  1552. }
  1553. defer eventsCmd.Process.Kill()
  1554. // Goroutine responsible for watching start/die events from `docker events`
  1555. go func() {
  1556. cid := <-containerID
  1557. matchStart := regexp.MustCompile(cid + `(.*) start$`)
  1558. matchDie := regexp.MustCompile(cid + `(.*) die$`)
  1559. //
  1560. // Read lines of `docker events` looking for container start and stop.
  1561. //
  1562. scanner := bufio.NewScanner(stdout)
  1563. for scanner.Scan() {
  1564. switch {
  1565. case matchStart.MatchString(scanner.Text()):
  1566. close(eventStart)
  1567. case matchDie.MatchString(scanner.Text()):
  1568. close(eventDie)
  1569. }
  1570. }
  1571. }()
  1572. buildCmd := exec.Command(dockerBinary, "build", "-t", name, ".")
  1573. buildCmd.Dir = ctx.Dir
  1574. stdoutBuild, err := buildCmd.StdoutPipe()
  1575. if err := buildCmd.Start(); err != nil {
  1576. c.Fatalf("failed to run build: %s", err)
  1577. }
  1578. matchCID := regexp.MustCompile("Running in ")
  1579. scanner := bufio.NewScanner(stdoutBuild)
  1580. for scanner.Scan() {
  1581. line := scanner.Text()
  1582. if ok := matchCID.MatchString(line); ok {
  1583. containerID <- line[len(line)-12:]
  1584. break
  1585. }
  1586. }
  1587. select {
  1588. case <-time.After(5 * time.Second):
  1589. c.Fatal("failed to observe build container start in timely fashion")
  1590. case <-eventStart:
  1591. // Proceeds from here when we see the container fly past in the
  1592. // output of "docker events".
  1593. // Now we know the container is running.
  1594. }
  1595. // Send a kill to the `docker build` command.
  1596. // Causes the underlying build to be cancelled due to socket close.
  1597. if err := buildCmd.Process.Kill(); err != nil {
  1598. c.Fatalf("error killing build command: %s", err)
  1599. }
  1600. // Get the exit status of `docker build`, check it exited because killed.
  1601. if err := buildCmd.Wait(); err != nil && !isKilled(err) {
  1602. c.Fatalf("wait failed during build run: %T %s", err, err)
  1603. }
  1604. select {
  1605. case <-time.After(5 * time.Second):
  1606. // If we don't get here in a timely fashion, it wasn't killed.
  1607. c.Fatal("container cancel did not succeed")
  1608. case <-eventDie:
  1609. // We saw the container shut down in the `docker events` stream,
  1610. // as expected.
  1611. }
  1612. }
  1613. func (s *DockerSuite) TestBuildRm(c *check.C) {
  1614. name := "testbuildrm"
  1615. ctx, err := fakeContext("FROM scratch\nADD foo /\nADD foo /", map[string]string{"foo": "bar"})
  1616. if err != nil {
  1617. c.Fatal(err)
  1618. }
  1619. defer ctx.Close()
  1620. {
  1621. containerCountBefore, err := getContainerCount()
  1622. if err != nil {
  1623. c.Fatalf("failed to get the container count: %s", err)
  1624. }
  1625. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "--rm", "-t", name, ".")
  1626. if err != nil {
  1627. c.Fatal("failed to build the image", out)
  1628. }
  1629. containerCountAfter, err := getContainerCount()
  1630. if err != nil {
  1631. c.Fatalf("failed to get the container count: %s", err)
  1632. }
  1633. if containerCountBefore != containerCountAfter {
  1634. c.Fatalf("-rm shouldn't have left containers behind")
  1635. }
  1636. deleteImages(name)
  1637. }
  1638. {
  1639. containerCountBefore, err := getContainerCount()
  1640. if err != nil {
  1641. c.Fatalf("failed to get the container count: %s", err)
  1642. }
  1643. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", name, ".")
  1644. if err != nil {
  1645. c.Fatal("failed to build the image", out)
  1646. }
  1647. containerCountAfter, err := getContainerCount()
  1648. if err != nil {
  1649. c.Fatalf("failed to get the container count: %s", err)
  1650. }
  1651. if containerCountBefore != containerCountAfter {
  1652. c.Fatalf("--rm shouldn't have left containers behind")
  1653. }
  1654. deleteImages(name)
  1655. }
  1656. {
  1657. containerCountBefore, err := getContainerCount()
  1658. if err != nil {
  1659. c.Fatalf("failed to get the container count: %s", err)
  1660. }
  1661. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "--rm=false", "-t", name, ".")
  1662. if err != nil {
  1663. c.Fatal("failed to build the image", out)
  1664. }
  1665. containerCountAfter, err := getContainerCount()
  1666. if err != nil {
  1667. c.Fatalf("failed to get the container count: %s", err)
  1668. }
  1669. if containerCountBefore == containerCountAfter {
  1670. c.Fatalf("--rm=false should have left containers behind")
  1671. }
  1672. deleteImages(name)
  1673. }
  1674. }
  1675. func (s *DockerSuite) TestBuildWithVolumes(c *check.C) {
  1676. var (
  1677. result map[string]map[string]struct{}
  1678. name = "testbuildvolumes"
  1679. emptyMap = make(map[string]struct{})
  1680. expected = map[string]map[string]struct{}{
  1681. "/test1": emptyMap,
  1682. "/test2": emptyMap,
  1683. "/test3": emptyMap,
  1684. "/test4": emptyMap,
  1685. "/test5": emptyMap,
  1686. "/test6": emptyMap,
  1687. "[/test7": emptyMap,
  1688. "/test8]": emptyMap,
  1689. }
  1690. )
  1691. _, err := buildImage(name,
  1692. `FROM scratch
  1693. VOLUME /test1
  1694. VOLUME /test2
  1695. VOLUME /test3 /test4
  1696. VOLUME ["/test5", "/test6"]
  1697. VOLUME [/test7 /test8]
  1698. `,
  1699. true)
  1700. if err != nil {
  1701. c.Fatal(err)
  1702. }
  1703. res, err := inspectFieldJSON(name, "Config.Volumes")
  1704. if err != nil {
  1705. c.Fatal(err)
  1706. }
  1707. err = unmarshalJSON([]byte(res), &result)
  1708. if err != nil {
  1709. c.Fatal(err)
  1710. }
  1711. equal := reflect.DeepEqual(&result, &expected)
  1712. if !equal {
  1713. c.Fatalf("Volumes %s, expected %s", result, expected)
  1714. }
  1715. }
  1716. func (s *DockerSuite) TestBuildMaintainer(c *check.C) {
  1717. name := "testbuildmaintainer"
  1718. expected := "dockerio"
  1719. _, err := buildImage(name,
  1720. `FROM scratch
  1721. MAINTAINER dockerio`,
  1722. true)
  1723. if err != nil {
  1724. c.Fatal(err)
  1725. }
  1726. res, err := inspectField(name, "Author")
  1727. if err != nil {
  1728. c.Fatal(err)
  1729. }
  1730. if res != expected {
  1731. c.Fatalf("Maintainer %s, expected %s", res, expected)
  1732. }
  1733. }
  1734. func (s *DockerSuite) TestBuildUser(c *check.C) {
  1735. name := "testbuilduser"
  1736. expected := "dockerio"
  1737. _, err := buildImage(name,
  1738. `FROM busybox
  1739. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1740. USER dockerio
  1741. RUN [ $(whoami) = 'dockerio' ]`,
  1742. true)
  1743. if err != nil {
  1744. c.Fatal(err)
  1745. }
  1746. res, err := inspectField(name, "Config.User")
  1747. if err != nil {
  1748. c.Fatal(err)
  1749. }
  1750. if res != expected {
  1751. c.Fatalf("User %s, expected %s", res, expected)
  1752. }
  1753. }
  1754. func (s *DockerSuite) TestBuildRelativeWorkdir(c *check.C) {
  1755. name := "testbuildrelativeworkdir"
  1756. expected := "/test2/test3"
  1757. _, err := buildImage(name,
  1758. `FROM busybox
  1759. RUN [ "$PWD" = '/' ]
  1760. WORKDIR test1
  1761. RUN [ "$PWD" = '/test1' ]
  1762. WORKDIR /test2
  1763. RUN [ "$PWD" = '/test2' ]
  1764. WORKDIR test3
  1765. RUN [ "$PWD" = '/test2/test3' ]`,
  1766. true)
  1767. if err != nil {
  1768. c.Fatal(err)
  1769. }
  1770. res, err := inspectField(name, "Config.WorkingDir")
  1771. if err != nil {
  1772. c.Fatal(err)
  1773. }
  1774. if res != expected {
  1775. c.Fatalf("Workdir %s, expected %s", res, expected)
  1776. }
  1777. }
  1778. func (s *DockerSuite) TestBuildWorkdirWithEnvVariables(c *check.C) {
  1779. name := "testbuildworkdirwithenvvariables"
  1780. expected := "/test1/test2"
  1781. _, err := buildImage(name,
  1782. `FROM busybox
  1783. ENV DIRPATH /test1
  1784. ENV SUBDIRNAME test2
  1785. WORKDIR $DIRPATH
  1786. WORKDIR $SUBDIRNAME/$MISSING_VAR`,
  1787. true)
  1788. if err != nil {
  1789. c.Fatal(err)
  1790. }
  1791. res, err := inspectField(name, "Config.WorkingDir")
  1792. if err != nil {
  1793. c.Fatal(err)
  1794. }
  1795. if res != expected {
  1796. c.Fatalf("Workdir %s, expected %s", res, expected)
  1797. }
  1798. }
  1799. func (s *DockerSuite) TestBuildRelativeCopy(c *check.C) {
  1800. name := "testbuildrelativecopy"
  1801. dockerfile := `
  1802. FROM busybox
  1803. WORKDIR /test1
  1804. WORKDIR test2
  1805. RUN [ "$PWD" = '/test1/test2' ]
  1806. COPY foo ./
  1807. RUN [ "$(cat /test1/test2/foo)" = 'hello' ]
  1808. ADD foo ./bar/baz
  1809. RUN [ "$(cat /test1/test2/bar/baz)" = 'hello' ]
  1810. COPY foo ./bar/baz2
  1811. RUN [ "$(cat /test1/test2/bar/baz2)" = 'hello' ]
  1812. WORKDIR ..
  1813. COPY foo ./
  1814. RUN [ "$(cat /test1/foo)" = 'hello' ]
  1815. COPY foo /test3/
  1816. RUN [ "$(cat /test3/foo)" = 'hello' ]
  1817. WORKDIR /test4
  1818. COPY . .
  1819. RUN [ "$(cat /test4/foo)" = 'hello' ]
  1820. WORKDIR /test5/test6
  1821. COPY foo ../
  1822. RUN [ "$(cat /test5/foo)" = 'hello' ]
  1823. `
  1824. ctx, err := fakeContext(dockerfile, map[string]string{
  1825. "foo": "hello",
  1826. })
  1827. defer ctx.Close()
  1828. if err != nil {
  1829. c.Fatal(err)
  1830. }
  1831. _, err = buildImageFromContext(name, ctx, false)
  1832. if err != nil {
  1833. c.Fatal(err)
  1834. }
  1835. }
  1836. func (s *DockerSuite) TestBuildEnv(c *check.C) {
  1837. name := "testbuildenv"
  1838. expected := "[PATH=/test:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin PORT=2375]"
  1839. _, err := buildImage(name,
  1840. `FROM busybox
  1841. ENV PATH /test:$PATH
  1842. ENV PORT 2375
  1843. RUN [ $(env | grep PORT) = 'PORT=2375' ]`,
  1844. true)
  1845. if err != nil {
  1846. c.Fatal(err)
  1847. }
  1848. res, err := inspectField(name, "Config.Env")
  1849. if err != nil {
  1850. c.Fatal(err)
  1851. }
  1852. if res != expected {
  1853. c.Fatalf("Env %s, expected %s", res, expected)
  1854. }
  1855. }
  1856. func (s *DockerSuite) TestBuildContextCleanup(c *check.C) {
  1857. testRequires(c, SameHostDaemon)
  1858. name := "testbuildcontextcleanup"
  1859. entries, err := ioutil.ReadDir("/var/lib/docker/tmp")
  1860. if err != nil {
  1861. c.Fatalf("failed to list contents of tmp dir: %s", err)
  1862. }
  1863. _, err = buildImage(name,
  1864. `FROM scratch
  1865. ENTRYPOINT ["/bin/echo"]`,
  1866. true)
  1867. if err != nil {
  1868. c.Fatal(err)
  1869. }
  1870. entriesFinal, err := ioutil.ReadDir("/var/lib/docker/tmp")
  1871. if err != nil {
  1872. c.Fatalf("failed to list contents of tmp dir: %s", err)
  1873. }
  1874. if err = compareDirectoryEntries(entries, entriesFinal); err != nil {
  1875. c.Fatalf("context should have been deleted, but wasn't")
  1876. }
  1877. }
  1878. func (s *DockerSuite) TestBuildContextCleanupFailedBuild(c *check.C) {
  1879. testRequires(c, SameHostDaemon)
  1880. name := "testbuildcontextcleanup"
  1881. entries, err := ioutil.ReadDir("/var/lib/docker/tmp")
  1882. if err != nil {
  1883. c.Fatalf("failed to list contents of tmp dir: %s", err)
  1884. }
  1885. _, err = buildImage(name,
  1886. `FROM scratch
  1887. RUN /non/existing/command`,
  1888. true)
  1889. if err == nil {
  1890. c.Fatalf("expected build to fail, but it didn't")
  1891. }
  1892. entriesFinal, err := ioutil.ReadDir("/var/lib/docker/tmp")
  1893. if err != nil {
  1894. c.Fatalf("failed to list contents of tmp dir: %s", err)
  1895. }
  1896. if err = compareDirectoryEntries(entries, entriesFinal); err != nil {
  1897. c.Fatalf("context should have been deleted, but wasn't")
  1898. }
  1899. }
  1900. func (s *DockerSuite) TestBuildCmd(c *check.C) {
  1901. name := "testbuildcmd"
  1902. expected := "{[/bin/echo Hello World]}"
  1903. _, err := buildImage(name,
  1904. `FROM scratch
  1905. CMD ["/bin/echo", "Hello World"]`,
  1906. true)
  1907. if err != nil {
  1908. c.Fatal(err)
  1909. }
  1910. res, err := inspectField(name, "Config.Cmd")
  1911. if err != nil {
  1912. c.Fatal(err)
  1913. }
  1914. if res != expected {
  1915. c.Fatalf("Cmd %s, expected %s", res, expected)
  1916. }
  1917. }
  1918. func (s *DockerSuite) TestBuildExpose(c *check.C) {
  1919. name := "testbuildexpose"
  1920. expected := "map[2375/tcp:{}]"
  1921. _, err := buildImage(name,
  1922. `FROM scratch
  1923. EXPOSE 2375`,
  1924. true)
  1925. if err != nil {
  1926. c.Fatal(err)
  1927. }
  1928. res, err := inspectField(name, "Config.ExposedPorts")
  1929. if err != nil {
  1930. c.Fatal(err)
  1931. }
  1932. if res != expected {
  1933. c.Fatalf("Exposed ports %s, expected %s", res, expected)
  1934. }
  1935. }
  1936. func (s *DockerSuite) TestBuildExposeMorePorts(c *check.C) {
  1937. // start building docker file with a large number of ports
  1938. portList := make([]string, 50)
  1939. line := make([]string, 100)
  1940. expectedPorts := make([]int, len(portList)*len(line))
  1941. for i := 0; i < len(portList); i++ {
  1942. for j := 0; j < len(line); j++ {
  1943. p := i*len(line) + j + 1
  1944. line[j] = strconv.Itoa(p)
  1945. expectedPorts[p-1] = p
  1946. }
  1947. if i == len(portList)-1 {
  1948. portList[i] = strings.Join(line, " ")
  1949. } else {
  1950. portList[i] = strings.Join(line, " ") + ` \`
  1951. }
  1952. }
  1953. dockerfile := `FROM scratch
  1954. EXPOSE {{range .}} {{.}}
  1955. {{end}}`
  1956. tmpl := template.Must(template.New("dockerfile").Parse(dockerfile))
  1957. buf := bytes.NewBuffer(nil)
  1958. tmpl.Execute(buf, portList)
  1959. name := "testbuildexpose"
  1960. _, err := buildImage(name, buf.String(), true)
  1961. if err != nil {
  1962. c.Fatal(err)
  1963. }
  1964. // check if all the ports are saved inside Config.ExposedPorts
  1965. res, err := inspectFieldJSON(name, "Config.ExposedPorts")
  1966. if err != nil {
  1967. c.Fatal(err)
  1968. }
  1969. var exposedPorts map[string]interface{}
  1970. if err := json.Unmarshal([]byte(res), &exposedPorts); err != nil {
  1971. c.Fatal(err)
  1972. }
  1973. for _, p := range expectedPorts {
  1974. ep := fmt.Sprintf("%d/tcp", p)
  1975. if _, ok := exposedPorts[ep]; !ok {
  1976. c.Errorf("Port(%s) is not exposed", ep)
  1977. } else {
  1978. delete(exposedPorts, ep)
  1979. }
  1980. }
  1981. if len(exposedPorts) != 0 {
  1982. c.Errorf("Unexpected extra exposed ports %v", exposedPorts)
  1983. }
  1984. }
  1985. func (s *DockerSuite) TestBuildExposeOrder(c *check.C) {
  1986. buildID := func(name, exposed string) string {
  1987. _, err := buildImage(name, fmt.Sprintf(`FROM scratch
  1988. EXPOSE %s`, exposed), true)
  1989. if err != nil {
  1990. c.Fatal(err)
  1991. }
  1992. id, err := inspectField(name, "Id")
  1993. if err != nil {
  1994. c.Fatal(err)
  1995. }
  1996. return id
  1997. }
  1998. id1 := buildID("testbuildexpose1", "80 2375")
  1999. id2 := buildID("testbuildexpose2", "2375 80")
  2000. if id1 != id2 {
  2001. c.Errorf("EXPOSE should invalidate the cache only when ports actually changed")
  2002. }
  2003. }
  2004. func (s *DockerSuite) TestBuildExposeUpperCaseProto(c *check.C) {
  2005. name := "testbuildexposeuppercaseproto"
  2006. expected := "map[5678/udp:{}]"
  2007. _, err := buildImage(name,
  2008. `FROM scratch
  2009. EXPOSE 5678/UDP`,
  2010. true)
  2011. if err != nil {
  2012. c.Fatal(err)
  2013. }
  2014. res, err := inspectField(name, "Config.ExposedPorts")
  2015. if err != nil {
  2016. c.Fatal(err)
  2017. }
  2018. if res != expected {
  2019. c.Fatalf("Exposed ports %s, expected %s", res, expected)
  2020. }
  2021. }
  2022. func (s *DockerSuite) TestBuildEmptyEntrypointInheritance(c *check.C) {
  2023. name := "testbuildentrypointinheritance"
  2024. name2 := "testbuildentrypointinheritance2"
  2025. _, err := buildImage(name,
  2026. `FROM busybox
  2027. ENTRYPOINT ["/bin/echo"]`,
  2028. true)
  2029. if err != nil {
  2030. c.Fatal(err)
  2031. }
  2032. res, err := inspectField(name, "Config.Entrypoint")
  2033. if err != nil {
  2034. c.Fatal(err)
  2035. }
  2036. expected := "{[/bin/echo]}"
  2037. if res != expected {
  2038. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  2039. }
  2040. _, err = buildImage(name2,
  2041. fmt.Sprintf(`FROM %s
  2042. ENTRYPOINT []`, name),
  2043. true)
  2044. if err != nil {
  2045. c.Fatal(err)
  2046. }
  2047. res, err = inspectField(name2, "Config.Entrypoint")
  2048. if err != nil {
  2049. c.Fatal(err)
  2050. }
  2051. expected = "{[]}"
  2052. if res != expected {
  2053. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  2054. }
  2055. }
  2056. func (s *DockerSuite) TestBuildEmptyEntrypoint(c *check.C) {
  2057. name := "testbuildentrypoint"
  2058. expected := "{[]}"
  2059. _, err := buildImage(name,
  2060. `FROM busybox
  2061. ENTRYPOINT []`,
  2062. true)
  2063. if err != nil {
  2064. c.Fatal(err)
  2065. }
  2066. res, err := inspectField(name, "Config.Entrypoint")
  2067. if err != nil {
  2068. c.Fatal(err)
  2069. }
  2070. if res != expected {
  2071. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  2072. }
  2073. }
  2074. func (s *DockerSuite) TestBuildEntrypoint(c *check.C) {
  2075. name := "testbuildentrypoint"
  2076. expected := "{[/bin/echo]}"
  2077. _, err := buildImage(name,
  2078. `FROM scratch
  2079. ENTRYPOINT ["/bin/echo"]`,
  2080. true)
  2081. if err != nil {
  2082. c.Fatal(err)
  2083. }
  2084. res, err := inspectField(name, "Config.Entrypoint")
  2085. if err != nil {
  2086. c.Fatal(err)
  2087. }
  2088. if res != expected {
  2089. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  2090. }
  2091. }
  2092. // #6445 ensure ONBUILD triggers aren't committed to grandchildren
  2093. func (s *DockerSuite) TestBuildOnBuildLimitedInheritence(c *check.C) {
  2094. var (
  2095. out2, out3 string
  2096. )
  2097. {
  2098. name1 := "testonbuildtrigger1"
  2099. dockerfile1 := `
  2100. FROM busybox
  2101. RUN echo "GRANDPARENT"
  2102. ONBUILD RUN echo "ONBUILD PARENT"
  2103. `
  2104. ctx, err := fakeContext(dockerfile1, nil)
  2105. if err != nil {
  2106. c.Fatal(err)
  2107. }
  2108. defer ctx.Close()
  2109. out1, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", name1, ".")
  2110. if err != nil {
  2111. c.Fatalf("build failed to complete: %s, %v", out1, err)
  2112. }
  2113. }
  2114. {
  2115. name2 := "testonbuildtrigger2"
  2116. dockerfile2 := `
  2117. FROM testonbuildtrigger1
  2118. `
  2119. ctx, err := fakeContext(dockerfile2, nil)
  2120. if err != nil {
  2121. c.Fatal(err)
  2122. }
  2123. defer ctx.Close()
  2124. out2, _, err = dockerCmdInDir(c, ctx.Dir, "build", "-t", name2, ".")
  2125. if err != nil {
  2126. c.Fatalf("build failed to complete: %s, %v", out2, err)
  2127. }
  2128. }
  2129. {
  2130. name3 := "testonbuildtrigger3"
  2131. dockerfile3 := `
  2132. FROM testonbuildtrigger2
  2133. `
  2134. ctx, err := fakeContext(dockerfile3, nil)
  2135. if err != nil {
  2136. c.Fatal(err)
  2137. }
  2138. defer ctx.Close()
  2139. out3, _, err = dockerCmdInDir(c, ctx.Dir, "build", "-t", name3, ".")
  2140. if err != nil {
  2141. c.Fatalf("build failed to complete: %s, %v", out3, err)
  2142. }
  2143. }
  2144. // ONBUILD should be run in second build.
  2145. if !strings.Contains(out2, "ONBUILD PARENT") {
  2146. c.Fatalf("ONBUILD instruction did not run in child of ONBUILD parent")
  2147. }
  2148. // ONBUILD should *not* be run in third build.
  2149. if strings.Contains(out3, "ONBUILD PARENT") {
  2150. c.Fatalf("ONBUILD instruction ran in grandchild of ONBUILD parent")
  2151. }
  2152. }
  2153. func (s *DockerSuite) TestBuildWithCache(c *check.C) {
  2154. name := "testbuildwithcache"
  2155. id1, err := buildImage(name,
  2156. `FROM scratch
  2157. MAINTAINER dockerio
  2158. EXPOSE 5432
  2159. ENTRYPOINT ["/bin/echo"]`,
  2160. true)
  2161. if err != nil {
  2162. c.Fatal(err)
  2163. }
  2164. id2, err := buildImage(name,
  2165. `FROM scratch
  2166. MAINTAINER dockerio
  2167. EXPOSE 5432
  2168. ENTRYPOINT ["/bin/echo"]`,
  2169. true)
  2170. if err != nil {
  2171. c.Fatal(err)
  2172. }
  2173. if id1 != id2 {
  2174. c.Fatal("The cache should have been used but hasn't.")
  2175. }
  2176. }
  2177. func (s *DockerSuite) TestBuildWithoutCache(c *check.C) {
  2178. name := "testbuildwithoutcache"
  2179. name2 := "testbuildwithoutcache2"
  2180. id1, err := buildImage(name,
  2181. `FROM scratch
  2182. MAINTAINER dockerio
  2183. EXPOSE 5432
  2184. ENTRYPOINT ["/bin/echo"]`,
  2185. true)
  2186. if err != nil {
  2187. c.Fatal(err)
  2188. }
  2189. id2, err := buildImage(name2,
  2190. `FROM scratch
  2191. MAINTAINER dockerio
  2192. EXPOSE 5432
  2193. ENTRYPOINT ["/bin/echo"]`,
  2194. false)
  2195. if err != nil {
  2196. c.Fatal(err)
  2197. }
  2198. if id1 == id2 {
  2199. c.Fatal("The cache should have been invalided but hasn't.")
  2200. }
  2201. }
  2202. func (s *DockerSuite) TestBuildConditionalCache(c *check.C) {
  2203. name := "testbuildconditionalcache"
  2204. dockerfile := `
  2205. FROM busybox
  2206. ADD foo /tmp/`
  2207. ctx, err := fakeContext(dockerfile, map[string]string{
  2208. "foo": "hello",
  2209. })
  2210. if err != nil {
  2211. c.Fatal(err)
  2212. }
  2213. defer ctx.Close()
  2214. id1, err := buildImageFromContext(name, ctx, true)
  2215. if err != nil {
  2216. c.Fatalf("Error building #1: %s", err)
  2217. }
  2218. if err := ctx.Add("foo", "bye"); err != nil {
  2219. c.Fatalf("Error modifying foo: %s", err)
  2220. }
  2221. id2, err := buildImageFromContext(name, ctx, false)
  2222. if err != nil {
  2223. c.Fatalf("Error building #2: %s", err)
  2224. }
  2225. if id2 == id1 {
  2226. c.Fatal("Should not have used the cache")
  2227. }
  2228. id3, err := buildImageFromContext(name, ctx, true)
  2229. if err != nil {
  2230. c.Fatalf("Error building #3: %s", err)
  2231. }
  2232. if id3 != id2 {
  2233. c.Fatal("Should have used the cache")
  2234. }
  2235. }
  2236. func (s *DockerSuite) TestBuildAddLocalFileWithCache(c *check.C) {
  2237. name := "testbuildaddlocalfilewithcache"
  2238. name2 := "testbuildaddlocalfilewithcache2"
  2239. dockerfile := `
  2240. FROM busybox
  2241. MAINTAINER dockerio
  2242. ADD foo /usr/lib/bla/bar
  2243. RUN [ "$(cat /usr/lib/bla/bar)" = "hello" ]`
  2244. ctx, err := fakeContext(dockerfile, map[string]string{
  2245. "foo": "hello",
  2246. })
  2247. defer ctx.Close()
  2248. if err != nil {
  2249. c.Fatal(err)
  2250. }
  2251. id1, err := buildImageFromContext(name, ctx, true)
  2252. if err != nil {
  2253. c.Fatal(err)
  2254. }
  2255. id2, err := buildImageFromContext(name2, ctx, true)
  2256. if err != nil {
  2257. c.Fatal(err)
  2258. }
  2259. if id1 != id2 {
  2260. c.Fatal("The cache should have been used but hasn't.")
  2261. }
  2262. }
  2263. func (s *DockerSuite) TestBuildAddMultipleLocalFileWithCache(c *check.C) {
  2264. name := "testbuildaddmultiplelocalfilewithcache"
  2265. name2 := "testbuildaddmultiplelocalfilewithcache2"
  2266. dockerfile := `
  2267. FROM busybox
  2268. MAINTAINER dockerio
  2269. ADD foo Dockerfile /usr/lib/bla/
  2270. RUN [ "$(cat /usr/lib/bla/foo)" = "hello" ]`
  2271. ctx, err := fakeContext(dockerfile, map[string]string{
  2272. "foo": "hello",
  2273. })
  2274. defer ctx.Close()
  2275. if err != nil {
  2276. c.Fatal(err)
  2277. }
  2278. id1, err := buildImageFromContext(name, ctx, true)
  2279. if err != nil {
  2280. c.Fatal(err)
  2281. }
  2282. id2, err := buildImageFromContext(name2, ctx, true)
  2283. if err != nil {
  2284. c.Fatal(err)
  2285. }
  2286. if id1 != id2 {
  2287. c.Fatal("The cache should have been used but hasn't.")
  2288. }
  2289. }
  2290. func (s *DockerSuite) TestBuildAddLocalFileWithoutCache(c *check.C) {
  2291. name := "testbuildaddlocalfilewithoutcache"
  2292. name2 := "testbuildaddlocalfilewithoutcache2"
  2293. dockerfile := `
  2294. FROM busybox
  2295. MAINTAINER dockerio
  2296. ADD foo /usr/lib/bla/bar
  2297. RUN [ "$(cat /usr/lib/bla/bar)" = "hello" ]`
  2298. ctx, err := fakeContext(dockerfile, map[string]string{
  2299. "foo": "hello",
  2300. })
  2301. defer ctx.Close()
  2302. if err != nil {
  2303. c.Fatal(err)
  2304. }
  2305. id1, err := buildImageFromContext(name, ctx, true)
  2306. if err != nil {
  2307. c.Fatal(err)
  2308. }
  2309. id2, err := buildImageFromContext(name2, ctx, false)
  2310. if err != nil {
  2311. c.Fatal(err)
  2312. }
  2313. if id1 == id2 {
  2314. c.Fatal("The cache should have been invalided but hasn't.")
  2315. }
  2316. }
  2317. func (s *DockerSuite) TestBuildCopyDirButNotFile(c *check.C) {
  2318. name := "testbuildcopydirbutnotfile"
  2319. name2 := "testbuildcopydirbutnotfile2"
  2320. dockerfile := `
  2321. FROM scratch
  2322. COPY dir /tmp/`
  2323. ctx, err := fakeContext(dockerfile, map[string]string{
  2324. "dir/foo": "hello",
  2325. })
  2326. defer ctx.Close()
  2327. if err != nil {
  2328. c.Fatal(err)
  2329. }
  2330. id1, err := buildImageFromContext(name, ctx, true)
  2331. if err != nil {
  2332. c.Fatal(err)
  2333. }
  2334. // Check that adding file with similar name doesn't mess with cache
  2335. if err := ctx.Add("dir_file", "hello2"); err != nil {
  2336. c.Fatal(err)
  2337. }
  2338. id2, err := buildImageFromContext(name2, ctx, true)
  2339. if err != nil {
  2340. c.Fatal(err)
  2341. }
  2342. if id1 != id2 {
  2343. c.Fatal("The cache should have been used but wasn't")
  2344. }
  2345. }
  2346. func (s *DockerSuite) TestBuildAddCurrentDirWithCache(c *check.C) {
  2347. name := "testbuildaddcurrentdirwithcache"
  2348. name2 := name + "2"
  2349. name3 := name + "3"
  2350. name4 := name + "4"
  2351. dockerfile := `
  2352. FROM scratch
  2353. MAINTAINER dockerio
  2354. ADD . /usr/lib/bla`
  2355. ctx, err := fakeContext(dockerfile, map[string]string{
  2356. "foo": "hello",
  2357. })
  2358. defer ctx.Close()
  2359. if err != nil {
  2360. c.Fatal(err)
  2361. }
  2362. id1, err := buildImageFromContext(name, ctx, true)
  2363. if err != nil {
  2364. c.Fatal(err)
  2365. }
  2366. // Check that adding file invalidate cache of "ADD ."
  2367. if err := ctx.Add("bar", "hello2"); err != nil {
  2368. c.Fatal(err)
  2369. }
  2370. id2, err := buildImageFromContext(name2, ctx, true)
  2371. if err != nil {
  2372. c.Fatal(err)
  2373. }
  2374. if id1 == id2 {
  2375. c.Fatal("The cache should have been invalided but hasn't.")
  2376. }
  2377. // Check that changing file invalidate cache of "ADD ."
  2378. if err := ctx.Add("foo", "hello1"); err != nil {
  2379. c.Fatal(err)
  2380. }
  2381. id3, err := buildImageFromContext(name3, ctx, true)
  2382. if err != nil {
  2383. c.Fatal(err)
  2384. }
  2385. if id2 == id3 {
  2386. c.Fatal("The cache should have been invalided but hasn't.")
  2387. }
  2388. // Check that changing file to same content with different mtime does not
  2389. // invalidate cache of "ADD ."
  2390. time.Sleep(1 * time.Second) // wait second because of mtime precision
  2391. if err := ctx.Add("foo", "hello1"); err != nil {
  2392. c.Fatal(err)
  2393. }
  2394. id4, err := buildImageFromContext(name4, ctx, true)
  2395. if err != nil {
  2396. c.Fatal(err)
  2397. }
  2398. if id3 != id4 {
  2399. c.Fatal("The cache should have been used but hasn't.")
  2400. }
  2401. }
  2402. func (s *DockerSuite) TestBuildAddCurrentDirWithoutCache(c *check.C) {
  2403. name := "testbuildaddcurrentdirwithoutcache"
  2404. name2 := "testbuildaddcurrentdirwithoutcache2"
  2405. dockerfile := `
  2406. FROM scratch
  2407. MAINTAINER dockerio
  2408. ADD . /usr/lib/bla`
  2409. ctx, err := fakeContext(dockerfile, map[string]string{
  2410. "foo": "hello",
  2411. })
  2412. defer ctx.Close()
  2413. if err != nil {
  2414. c.Fatal(err)
  2415. }
  2416. id1, err := buildImageFromContext(name, ctx, true)
  2417. if err != nil {
  2418. c.Fatal(err)
  2419. }
  2420. id2, err := buildImageFromContext(name2, ctx, false)
  2421. if err != nil {
  2422. c.Fatal(err)
  2423. }
  2424. if id1 == id2 {
  2425. c.Fatal("The cache should have been invalided but hasn't.")
  2426. }
  2427. }
  2428. func (s *DockerSuite) TestBuildAddRemoteFileWithCache(c *check.C) {
  2429. name := "testbuildaddremotefilewithcache"
  2430. server, err := fakeStorage(map[string]string{
  2431. "baz": "hello",
  2432. })
  2433. if err != nil {
  2434. c.Fatal(err)
  2435. }
  2436. defer server.Close()
  2437. id1, err := buildImage(name,
  2438. fmt.Sprintf(`FROM scratch
  2439. MAINTAINER dockerio
  2440. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2441. true)
  2442. if err != nil {
  2443. c.Fatal(err)
  2444. }
  2445. id2, err := buildImage(name,
  2446. fmt.Sprintf(`FROM scratch
  2447. MAINTAINER dockerio
  2448. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2449. true)
  2450. if err != nil {
  2451. c.Fatal(err)
  2452. }
  2453. if id1 != id2 {
  2454. c.Fatal("The cache should have been used but hasn't.")
  2455. }
  2456. }
  2457. func (s *DockerSuite) TestBuildAddRemoteFileWithoutCache(c *check.C) {
  2458. name := "testbuildaddremotefilewithoutcache"
  2459. name2 := "testbuildaddremotefilewithoutcache2"
  2460. server, err := fakeStorage(map[string]string{
  2461. "baz": "hello",
  2462. })
  2463. if err != nil {
  2464. c.Fatal(err)
  2465. }
  2466. defer server.Close()
  2467. id1, err := buildImage(name,
  2468. fmt.Sprintf(`FROM scratch
  2469. MAINTAINER dockerio
  2470. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2471. true)
  2472. if err != nil {
  2473. c.Fatal(err)
  2474. }
  2475. id2, err := buildImage(name2,
  2476. fmt.Sprintf(`FROM scratch
  2477. MAINTAINER dockerio
  2478. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2479. false)
  2480. if err != nil {
  2481. c.Fatal(err)
  2482. }
  2483. if id1 == id2 {
  2484. c.Fatal("The cache should have been invalided but hasn't.")
  2485. }
  2486. }
  2487. func (s *DockerSuite) TestBuildAddRemoteFileMTime(c *check.C) {
  2488. name := "testbuildaddremotefilemtime"
  2489. name2 := name + "2"
  2490. name3 := name + "3"
  2491. files := map[string]string{"baz": "hello"}
  2492. server, err := fakeStorage(files)
  2493. if err != nil {
  2494. c.Fatal(err)
  2495. }
  2496. defer server.Close()
  2497. ctx, err := fakeContext(fmt.Sprintf(`FROM scratch
  2498. MAINTAINER dockerio
  2499. ADD %s/baz /usr/lib/baz/quux`, server.URL()), nil)
  2500. if err != nil {
  2501. c.Fatal(err)
  2502. }
  2503. defer ctx.Close()
  2504. id1, err := buildImageFromContext(name, ctx, true)
  2505. if err != nil {
  2506. c.Fatal(err)
  2507. }
  2508. id2, err := buildImageFromContext(name2, ctx, true)
  2509. if err != nil {
  2510. c.Fatal(err)
  2511. }
  2512. if id1 != id2 {
  2513. c.Fatal("The cache should have been used but wasn't - #1")
  2514. }
  2515. // Now create a different server with same contents (causes different mtime)
  2516. // The cache should still be used
  2517. // allow some time for clock to pass as mtime precision is only 1s
  2518. time.Sleep(2 * time.Second)
  2519. server2, err := fakeStorage(files)
  2520. if err != nil {
  2521. c.Fatal(err)
  2522. }
  2523. defer server2.Close()
  2524. ctx2, err := fakeContext(fmt.Sprintf(`FROM scratch
  2525. MAINTAINER dockerio
  2526. ADD %s/baz /usr/lib/baz/quux`, server2.URL()), nil)
  2527. if err != nil {
  2528. c.Fatal(err)
  2529. }
  2530. defer ctx2.Close()
  2531. id3, err := buildImageFromContext(name3, ctx2, true)
  2532. if err != nil {
  2533. c.Fatal(err)
  2534. }
  2535. if id1 != id3 {
  2536. c.Fatal("The cache should have been used but wasn't")
  2537. }
  2538. }
  2539. func (s *DockerSuite) TestBuildAddLocalAndRemoteFilesWithCache(c *check.C) {
  2540. name := "testbuildaddlocalandremotefilewithcache"
  2541. server, err := fakeStorage(map[string]string{
  2542. "baz": "hello",
  2543. })
  2544. if err != nil {
  2545. c.Fatal(err)
  2546. }
  2547. defer server.Close()
  2548. ctx, err := fakeContext(fmt.Sprintf(`FROM scratch
  2549. MAINTAINER dockerio
  2550. ADD foo /usr/lib/bla/bar
  2551. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2552. map[string]string{
  2553. "foo": "hello world",
  2554. })
  2555. if err != nil {
  2556. c.Fatal(err)
  2557. }
  2558. defer ctx.Close()
  2559. id1, err := buildImageFromContext(name, ctx, true)
  2560. if err != nil {
  2561. c.Fatal(err)
  2562. }
  2563. id2, err := buildImageFromContext(name, ctx, true)
  2564. if err != nil {
  2565. c.Fatal(err)
  2566. }
  2567. if id1 != id2 {
  2568. c.Fatal("The cache should have been used but hasn't.")
  2569. }
  2570. }
  2571. func testContextTar(c *check.C, compression archive.Compression) {
  2572. ctx, err := fakeContext(
  2573. `FROM busybox
  2574. ADD foo /foo
  2575. CMD ["cat", "/foo"]`,
  2576. map[string]string{
  2577. "foo": "bar",
  2578. },
  2579. )
  2580. defer ctx.Close()
  2581. if err != nil {
  2582. c.Fatal(err)
  2583. }
  2584. context, err := archive.Tar(ctx.Dir, compression)
  2585. if err != nil {
  2586. c.Fatalf("failed to build context tar: %v", err)
  2587. }
  2588. name := "contexttar"
  2589. buildCmd := exec.Command(dockerBinary, "build", "-t", name, "-")
  2590. buildCmd.Stdin = context
  2591. if out, _, err := runCommandWithOutput(buildCmd); err != nil {
  2592. c.Fatalf("build failed to complete: %v %v", out, err)
  2593. }
  2594. }
  2595. func (s *DockerSuite) TestBuildContextTarGzip(c *check.C) {
  2596. testContextTar(c, archive.Gzip)
  2597. }
  2598. func (s *DockerSuite) TestBuildContextTarNoCompression(c *check.C) {
  2599. testContextTar(c, archive.Uncompressed)
  2600. }
  2601. func (s *DockerSuite) TestBuildNoContext(c *check.C) {
  2602. buildCmd := exec.Command(dockerBinary, "build", "-t", "nocontext", "-")
  2603. buildCmd.Stdin = strings.NewReader("FROM busybox\nCMD echo ok\n")
  2604. if out, _, err := runCommandWithOutput(buildCmd); err != nil {
  2605. c.Fatalf("build failed to complete: %v %v", out, err)
  2606. }
  2607. if out, _ := dockerCmd(c, "run", "--rm", "nocontext"); out != "ok\n" {
  2608. c.Fatalf("run produced invalid output: %q, expected %q", out, "ok")
  2609. }
  2610. }
  2611. // TODO: TestCaching
  2612. func (s *DockerSuite) TestBuildAddLocalAndRemoteFilesWithoutCache(c *check.C) {
  2613. name := "testbuildaddlocalandremotefilewithoutcache"
  2614. name2 := "testbuildaddlocalandremotefilewithoutcache2"
  2615. server, err := fakeStorage(map[string]string{
  2616. "baz": "hello",
  2617. })
  2618. if err != nil {
  2619. c.Fatal(err)
  2620. }
  2621. defer server.Close()
  2622. ctx, err := fakeContext(fmt.Sprintf(`FROM scratch
  2623. MAINTAINER dockerio
  2624. ADD foo /usr/lib/bla/bar
  2625. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2626. map[string]string{
  2627. "foo": "hello world",
  2628. })
  2629. if err != nil {
  2630. c.Fatal(err)
  2631. }
  2632. defer ctx.Close()
  2633. id1, err := buildImageFromContext(name, ctx, true)
  2634. if err != nil {
  2635. c.Fatal(err)
  2636. }
  2637. id2, err := buildImageFromContext(name2, ctx, false)
  2638. if err != nil {
  2639. c.Fatal(err)
  2640. }
  2641. if id1 == id2 {
  2642. c.Fatal("The cache should have been invalided but hasn't.")
  2643. }
  2644. }
  2645. func (s *DockerSuite) TestBuildWithVolumeOwnership(c *check.C) {
  2646. name := "testbuildimg"
  2647. _, err := buildImage(name,
  2648. `FROM busybox:latest
  2649. RUN mkdir /test && chown daemon:daemon /test && chmod 0600 /test
  2650. VOLUME /test`,
  2651. true)
  2652. if err != nil {
  2653. c.Fatal(err)
  2654. }
  2655. out, _ := dockerCmd(c, "run", "--rm", "testbuildimg", "ls", "-la", "/test")
  2656. if expected := "drw-------"; !strings.Contains(out, expected) {
  2657. c.Fatalf("expected %s received %s", expected, out)
  2658. }
  2659. if expected := "daemon daemon"; !strings.Contains(out, expected) {
  2660. c.Fatalf("expected %s received %s", expected, out)
  2661. }
  2662. }
  2663. // testing #1405 - config.Cmd does not get cleaned up if
  2664. // utilizing cache
  2665. func (s *DockerSuite) TestBuildEntrypointRunCleanup(c *check.C) {
  2666. name := "testbuildcmdcleanup"
  2667. if _, err := buildImage(name,
  2668. `FROM busybox
  2669. RUN echo "hello"`,
  2670. true); err != nil {
  2671. c.Fatal(err)
  2672. }
  2673. ctx, err := fakeContext(`FROM busybox
  2674. RUN echo "hello"
  2675. ADD foo /foo
  2676. ENTRYPOINT ["/bin/echo"]`,
  2677. map[string]string{
  2678. "foo": "hello",
  2679. })
  2680. defer ctx.Close()
  2681. if err != nil {
  2682. c.Fatal(err)
  2683. }
  2684. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2685. c.Fatal(err)
  2686. }
  2687. res, err := inspectField(name, "Config.Cmd")
  2688. if err != nil {
  2689. c.Fatal(err)
  2690. }
  2691. // Cmd must be cleaned up
  2692. if res != "<nil>" {
  2693. c.Fatalf("Cmd %s, expected nil", res)
  2694. }
  2695. }
  2696. func (s *DockerSuite) TestBuildForbiddenContextPath(c *check.C) {
  2697. name := "testbuildforbidpath"
  2698. ctx, err := fakeContext(`FROM scratch
  2699. ADD ../../ test/
  2700. `,
  2701. map[string]string{
  2702. "test.txt": "test1",
  2703. "other.txt": "other",
  2704. })
  2705. defer ctx.Close()
  2706. if err != nil {
  2707. c.Fatal(err)
  2708. }
  2709. expected := "Forbidden path outside the build context: ../../ "
  2710. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  2711. c.Fatalf("Wrong error: (should contain \"%s\") got:\n%v", expected, err)
  2712. }
  2713. }
  2714. func (s *DockerSuite) TestBuildAddFileNotFound(c *check.C) {
  2715. name := "testbuildaddnotfound"
  2716. ctx, err := fakeContext(`FROM scratch
  2717. ADD foo /usr/local/bar`,
  2718. map[string]string{"bar": "hello"})
  2719. defer ctx.Close()
  2720. if err != nil {
  2721. c.Fatal(err)
  2722. }
  2723. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2724. if !strings.Contains(err.Error(), "foo: no such file or directory") {
  2725. c.Fatalf("Wrong error %v, must be about missing foo file or directory", err)
  2726. }
  2727. } else {
  2728. c.Fatal("Error must not be nil")
  2729. }
  2730. }
  2731. func (s *DockerSuite) TestBuildInheritance(c *check.C) {
  2732. name := "testbuildinheritance"
  2733. _, err := buildImage(name,
  2734. `FROM scratch
  2735. EXPOSE 2375`,
  2736. true)
  2737. if err != nil {
  2738. c.Fatal(err)
  2739. }
  2740. ports1, err := inspectField(name, "Config.ExposedPorts")
  2741. if err != nil {
  2742. c.Fatal(err)
  2743. }
  2744. _, err = buildImage(name,
  2745. fmt.Sprintf(`FROM %s
  2746. ENTRYPOINT ["/bin/echo"]`, name),
  2747. true)
  2748. if err != nil {
  2749. c.Fatal(err)
  2750. }
  2751. res, err := inspectField(name, "Config.Entrypoint")
  2752. if err != nil {
  2753. c.Fatal(err)
  2754. }
  2755. if expected := "{[/bin/echo]}"; res != expected {
  2756. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  2757. }
  2758. ports2, err := inspectField(name, "Config.ExposedPorts")
  2759. if err != nil {
  2760. c.Fatal(err)
  2761. }
  2762. if ports1 != ports2 {
  2763. c.Fatalf("Ports must be same: %s != %s", ports1, ports2)
  2764. }
  2765. }
  2766. func (s *DockerSuite) TestBuildFails(c *check.C) {
  2767. name := "testbuildfails"
  2768. _, err := buildImage(name,
  2769. `FROM busybox
  2770. RUN sh -c "exit 23"`,
  2771. true)
  2772. if err != nil {
  2773. if !strings.Contains(err.Error(), "returned a non-zero code: 23") {
  2774. c.Fatalf("Wrong error %v, must be about non-zero code 23", err)
  2775. }
  2776. } else {
  2777. c.Fatal("Error must not be nil")
  2778. }
  2779. }
  2780. func (s *DockerSuite) TestBuildFailsDockerfileEmpty(c *check.C) {
  2781. name := "testbuildfails"
  2782. _, err := buildImage(name, ``, true)
  2783. if err != nil {
  2784. if !strings.Contains(err.Error(), "The Dockerfile (Dockerfile) cannot be empty") {
  2785. c.Fatalf("Wrong error %v, must be about empty Dockerfile", err)
  2786. }
  2787. } else {
  2788. c.Fatal("Error must not be nil")
  2789. }
  2790. }
  2791. func (s *DockerSuite) TestBuildOnBuild(c *check.C) {
  2792. name := "testbuildonbuild"
  2793. _, err := buildImage(name,
  2794. `FROM busybox
  2795. ONBUILD RUN touch foobar`,
  2796. true)
  2797. if err != nil {
  2798. c.Fatal(err)
  2799. }
  2800. _, err = buildImage(name,
  2801. fmt.Sprintf(`FROM %s
  2802. RUN [ -f foobar ]`, name),
  2803. true)
  2804. if err != nil {
  2805. c.Fatal(err)
  2806. }
  2807. }
  2808. func (s *DockerSuite) TestBuildOnBuildForbiddenChained(c *check.C) {
  2809. name := "testbuildonbuildforbiddenchained"
  2810. _, err := buildImage(name,
  2811. `FROM busybox
  2812. ONBUILD ONBUILD RUN touch foobar`,
  2813. true)
  2814. if err != nil {
  2815. if !strings.Contains(err.Error(), "Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed") {
  2816. c.Fatalf("Wrong error %v, must be about chaining ONBUILD", err)
  2817. }
  2818. } else {
  2819. c.Fatal("Error must not be nil")
  2820. }
  2821. }
  2822. func (s *DockerSuite) TestBuildOnBuildForbiddenFrom(c *check.C) {
  2823. name := "testbuildonbuildforbiddenfrom"
  2824. _, err := buildImage(name,
  2825. `FROM busybox
  2826. ONBUILD FROM scratch`,
  2827. true)
  2828. if err != nil {
  2829. if !strings.Contains(err.Error(), "FROM isn't allowed as an ONBUILD trigger") {
  2830. c.Fatalf("Wrong error %v, must be about FROM forbidden", err)
  2831. }
  2832. } else {
  2833. c.Fatal("Error must not be nil")
  2834. }
  2835. }
  2836. func (s *DockerSuite) TestBuildOnBuildForbiddenMaintainer(c *check.C) {
  2837. name := "testbuildonbuildforbiddenmaintainer"
  2838. _, err := buildImage(name,
  2839. `FROM busybox
  2840. ONBUILD MAINTAINER docker.io`,
  2841. true)
  2842. if err != nil {
  2843. if !strings.Contains(err.Error(), "MAINTAINER isn't allowed as an ONBUILD trigger") {
  2844. c.Fatalf("Wrong error %v, must be about MAINTAINER forbidden", err)
  2845. }
  2846. } else {
  2847. c.Fatal("Error must not be nil")
  2848. }
  2849. }
  2850. // gh #2446
  2851. func (s *DockerSuite) TestBuildAddToSymlinkDest(c *check.C) {
  2852. name := "testbuildaddtosymlinkdest"
  2853. ctx, err := fakeContext(`FROM busybox
  2854. RUN mkdir /foo
  2855. RUN ln -s /foo /bar
  2856. ADD foo /bar/
  2857. RUN [ -f /bar/foo ]
  2858. RUN [ -f /foo/foo ]`,
  2859. map[string]string{
  2860. "foo": "hello",
  2861. })
  2862. if err != nil {
  2863. c.Fatal(err)
  2864. }
  2865. defer ctx.Close()
  2866. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2867. c.Fatal(err)
  2868. }
  2869. }
  2870. func (s *DockerSuite) TestBuildEscapeWhitespace(c *check.C) {
  2871. name := "testbuildescaping"
  2872. _, err := buildImage(name, `
  2873. FROM busybox
  2874. MAINTAINER "Docker \
  2875. IO <io@\
  2876. docker.com>"
  2877. `, true)
  2878. if err != nil {
  2879. c.Fatal(err)
  2880. }
  2881. res, err := inspectField(name, "Author")
  2882. if err != nil {
  2883. c.Fatal(err)
  2884. }
  2885. if res != "\"Docker IO <io@docker.com>\"" {
  2886. c.Fatalf("Parsed string did not match the escaped string. Got: %q", res)
  2887. }
  2888. }
  2889. func (s *DockerSuite) TestBuildVerifyIntString(c *check.C) {
  2890. // Verify that strings that look like ints are still passed as strings
  2891. name := "testbuildstringing"
  2892. _, err := buildImage(name, `
  2893. FROM busybox
  2894. MAINTAINER 123
  2895. `, true)
  2896. if err != nil {
  2897. c.Fatal(err)
  2898. }
  2899. out, _ := dockerCmd(c, "inspect", name)
  2900. if !strings.Contains(out, "\"123\"") {
  2901. c.Fatalf("Output does not contain the int as a string:\n%s", out)
  2902. }
  2903. }
  2904. func (s *DockerSuite) TestBuildDockerignore(c *check.C) {
  2905. name := "testbuilddockerignore"
  2906. dockerfile := `
  2907. FROM busybox
  2908. ADD . /bla
  2909. RUN [[ -f /bla/src/x.go ]]
  2910. RUN [[ -f /bla/Makefile ]]
  2911. RUN [[ ! -e /bla/src/_vendor ]]
  2912. RUN [[ ! -e /bla/.gitignore ]]
  2913. RUN [[ ! -e /bla/README.md ]]
  2914. RUN [[ ! -e /bla/dir/foo ]]
  2915. RUN [[ ! -e /bla/foo ]]
  2916. RUN [[ ! -e /bla/.git ]]`
  2917. ctx, err := fakeContext(dockerfile, map[string]string{
  2918. "Makefile": "all:",
  2919. ".git/HEAD": "ref: foo",
  2920. "src/x.go": "package main",
  2921. "src/_vendor/v.go": "package main",
  2922. "dir/foo": "",
  2923. ".gitignore": "",
  2924. "README.md": "readme",
  2925. ".dockerignore": `
  2926. .git
  2927. pkg
  2928. .gitignore
  2929. src/_vendor
  2930. *.md
  2931. dir`,
  2932. })
  2933. if err != nil {
  2934. c.Fatal(err)
  2935. }
  2936. defer ctx.Close()
  2937. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2938. c.Fatal(err)
  2939. }
  2940. }
  2941. func (s *DockerSuite) TestBuildDockerignoreCleanPaths(c *check.C) {
  2942. name := "testbuilddockerignorecleanpaths"
  2943. dockerfile := `
  2944. FROM busybox
  2945. ADD . /tmp/
  2946. RUN (! ls /tmp/foo) && (! ls /tmp/foo2) && (! ls /tmp/dir1/foo)`
  2947. ctx, err := fakeContext(dockerfile, map[string]string{
  2948. "foo": "foo",
  2949. "foo2": "foo2",
  2950. "dir1/foo": "foo in dir1",
  2951. ".dockerignore": "./foo\ndir1//foo\n./dir1/../foo2",
  2952. })
  2953. if err != nil {
  2954. c.Fatal(err)
  2955. }
  2956. defer ctx.Close()
  2957. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2958. c.Fatal(err)
  2959. }
  2960. }
  2961. func (s *DockerSuite) TestBuildDockerignoreExceptions(c *check.C) {
  2962. name := "testbuilddockerignoreexceptions"
  2963. dockerfile := `
  2964. FROM busybox
  2965. ADD . /bla
  2966. RUN [[ -f /bla/src/x.go ]]
  2967. RUN [[ -f /bla/Makefile ]]
  2968. RUN [[ ! -e /bla/src/_vendor ]]
  2969. RUN [[ ! -e /bla/.gitignore ]]
  2970. RUN [[ ! -e /bla/README.md ]]
  2971. RUN [[ -e /bla/dir/dir/foo ]]
  2972. RUN [[ ! -e /bla/dir/foo1 ]]
  2973. RUN [[ -f /bla/dir/e ]]
  2974. RUN [[ -f /bla/dir/e-dir/foo ]]
  2975. RUN [[ ! -e /bla/foo ]]
  2976. RUN [[ ! -e /bla/.git ]]`
  2977. ctx, err := fakeContext(dockerfile, map[string]string{
  2978. "Makefile": "all:",
  2979. ".git/HEAD": "ref: foo",
  2980. "src/x.go": "package main",
  2981. "src/_vendor/v.go": "package main",
  2982. "dir/foo": "",
  2983. "dir/foo1": "",
  2984. "dir/dir/f1": "",
  2985. "dir/dir/foo": "",
  2986. "dir/e": "",
  2987. "dir/e-dir/foo": "",
  2988. ".gitignore": "",
  2989. "README.md": "readme",
  2990. ".dockerignore": `
  2991. .git
  2992. pkg
  2993. .gitignore
  2994. src/_vendor
  2995. *.md
  2996. dir
  2997. !dir/e*
  2998. !dir/dir/foo`,
  2999. })
  3000. if err != nil {
  3001. c.Fatal(err)
  3002. }
  3003. defer ctx.Close()
  3004. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3005. c.Fatal(err)
  3006. }
  3007. }
  3008. func (s *DockerSuite) TestBuildDockerignoringDockerfile(c *check.C) {
  3009. name := "testbuilddockerignoredockerfile"
  3010. dockerfile := `
  3011. FROM busybox
  3012. ADD . /tmp/
  3013. RUN ! ls /tmp/Dockerfile
  3014. RUN ls /tmp/.dockerignore`
  3015. ctx, err := fakeContext(dockerfile, map[string]string{
  3016. "Dockerfile": dockerfile,
  3017. ".dockerignore": "Dockerfile\n",
  3018. })
  3019. if err != nil {
  3020. c.Fatal(err)
  3021. }
  3022. defer ctx.Close()
  3023. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3024. c.Fatalf("Didn't ignore Dockerfile correctly:%s", err)
  3025. }
  3026. // now try it with ./Dockerfile
  3027. ctx.Add(".dockerignore", "./Dockerfile\n")
  3028. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3029. c.Fatalf("Didn't ignore ./Dockerfile correctly:%s", err)
  3030. }
  3031. }
  3032. func (s *DockerSuite) TestBuildDockerignoringRenamedDockerfile(c *check.C) {
  3033. name := "testbuilddockerignoredockerfile"
  3034. dockerfile := `
  3035. FROM busybox
  3036. ADD . /tmp/
  3037. RUN ls /tmp/Dockerfile
  3038. RUN ! ls /tmp/MyDockerfile
  3039. RUN ls /tmp/.dockerignore`
  3040. ctx, err := fakeContext(dockerfile, map[string]string{
  3041. "Dockerfile": "Should not use me",
  3042. "MyDockerfile": dockerfile,
  3043. ".dockerignore": "MyDockerfile\n",
  3044. })
  3045. if err != nil {
  3046. c.Fatal(err)
  3047. }
  3048. defer ctx.Close()
  3049. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3050. c.Fatalf("Didn't ignore MyDockerfile correctly:%s", err)
  3051. }
  3052. // now try it with ./MyDockerfile
  3053. ctx.Add(".dockerignore", "./MyDockerfile\n")
  3054. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3055. c.Fatalf("Didn't ignore ./MyDockerfile correctly:%s", err)
  3056. }
  3057. }
  3058. func (s *DockerSuite) TestBuildDockerignoringDockerignore(c *check.C) {
  3059. name := "testbuilddockerignoredockerignore"
  3060. dockerfile := `
  3061. FROM busybox
  3062. ADD . /tmp/
  3063. RUN ! ls /tmp/.dockerignore
  3064. RUN ls /tmp/Dockerfile`
  3065. ctx, err := fakeContext(dockerfile, map[string]string{
  3066. "Dockerfile": dockerfile,
  3067. ".dockerignore": ".dockerignore\n",
  3068. })
  3069. defer ctx.Close()
  3070. if err != nil {
  3071. c.Fatal(err)
  3072. }
  3073. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3074. c.Fatalf("Didn't ignore .dockerignore correctly:%s", err)
  3075. }
  3076. }
  3077. func (s *DockerSuite) TestBuildDockerignoreTouchDockerfile(c *check.C) {
  3078. var id1 string
  3079. var id2 string
  3080. name := "testbuilddockerignoretouchdockerfile"
  3081. dockerfile := `
  3082. FROM busybox
  3083. ADD . /tmp/`
  3084. ctx, err := fakeContext(dockerfile, map[string]string{
  3085. "Dockerfile": dockerfile,
  3086. ".dockerignore": "Dockerfile\n",
  3087. })
  3088. defer ctx.Close()
  3089. if err != nil {
  3090. c.Fatal(err)
  3091. }
  3092. if id1, err = buildImageFromContext(name, ctx, true); err != nil {
  3093. c.Fatalf("Didn't build it correctly:%s", err)
  3094. }
  3095. if id2, err = buildImageFromContext(name, ctx, true); err != nil {
  3096. c.Fatalf("Didn't build it correctly:%s", err)
  3097. }
  3098. if id1 != id2 {
  3099. c.Fatalf("Didn't use the cache - 1")
  3100. }
  3101. // Now make sure touching Dockerfile doesn't invalidate the cache
  3102. if err = ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil {
  3103. c.Fatalf("Didn't add Dockerfile: %s", err)
  3104. }
  3105. if id2, err = buildImageFromContext(name, ctx, true); err != nil {
  3106. c.Fatalf("Didn't build it correctly:%s", err)
  3107. }
  3108. if id1 != id2 {
  3109. c.Fatalf("Didn't use the cache - 2")
  3110. }
  3111. // One more time but just 'touch' it instead of changing the content
  3112. if err = ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil {
  3113. c.Fatalf("Didn't add Dockerfile: %s", err)
  3114. }
  3115. if id2, err = buildImageFromContext(name, ctx, true); err != nil {
  3116. c.Fatalf("Didn't build it correctly:%s", err)
  3117. }
  3118. if id1 != id2 {
  3119. c.Fatalf("Didn't use the cache - 3")
  3120. }
  3121. }
  3122. func (s *DockerSuite) TestBuildDockerignoringWholeDir(c *check.C) {
  3123. name := "testbuilddockerignorewholedir"
  3124. dockerfile := `
  3125. FROM busybox
  3126. COPY . /
  3127. RUN [[ ! -e /.gitignore ]]
  3128. RUN [[ -f /Makefile ]]`
  3129. ctx, err := fakeContext(dockerfile, map[string]string{
  3130. "Dockerfile": "FROM scratch",
  3131. "Makefile": "all:",
  3132. ".gitignore": "",
  3133. ".dockerignore": ".*\n",
  3134. })
  3135. c.Assert(err, check.IsNil)
  3136. defer ctx.Close()
  3137. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3138. c.Fatal(err)
  3139. }
  3140. c.Assert(ctx.Add(".dockerfile", "*"), check.IsNil)
  3141. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3142. c.Fatal(err)
  3143. }
  3144. c.Assert(ctx.Add(".dockerfile", "."), check.IsNil)
  3145. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3146. c.Fatal(err)
  3147. }
  3148. c.Assert(ctx.Add(".dockerfile", "?"), check.IsNil)
  3149. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3150. c.Fatal(err)
  3151. }
  3152. }
  3153. func (s *DockerSuite) TestBuildDockerignoringBadExclusion(c *check.C) {
  3154. name := "testbuilddockerignorewholedir"
  3155. dockerfile := `
  3156. FROM busybox
  3157. COPY . /
  3158. RUN [[ ! -e /.gitignore ]]
  3159. RUN [[ -f /Makefile ]]`
  3160. ctx, err := fakeContext(dockerfile, map[string]string{
  3161. "Dockerfile": "FROM scratch",
  3162. "Makefile": "all:",
  3163. ".gitignore": "",
  3164. ".dockerignore": "!\n",
  3165. })
  3166. c.Assert(err, check.IsNil)
  3167. defer ctx.Close()
  3168. if _, err = buildImageFromContext(name, ctx, true); err == nil {
  3169. c.Fatalf("Build was supposed to fail but didn't")
  3170. }
  3171. if err.Error() != "failed to build the image: Error checking context: 'Illegal exclusion pattern: !'.\n" {
  3172. c.Fatalf("Incorrect output, got:%q", err.Error())
  3173. }
  3174. }
  3175. func (s *DockerSuite) TestBuildLineBreak(c *check.C) {
  3176. name := "testbuildlinebreak"
  3177. _, err := buildImage(name,
  3178. `FROM busybox
  3179. RUN sh -c 'echo root:testpass \
  3180. > /tmp/passwd'
  3181. RUN mkdir -p /var/run/sshd
  3182. RUN [ "$(cat /tmp/passwd)" = "root:testpass" ]
  3183. RUN [ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]`,
  3184. true)
  3185. if err != nil {
  3186. c.Fatal(err)
  3187. }
  3188. }
  3189. func (s *DockerSuite) TestBuildEOLInLine(c *check.C) {
  3190. name := "testbuildeolinline"
  3191. _, err := buildImage(name,
  3192. `FROM busybox
  3193. RUN sh -c 'echo root:testpass > /tmp/passwd'
  3194. RUN echo "foo \n bar"; echo "baz"
  3195. RUN mkdir -p /var/run/sshd
  3196. RUN [ "$(cat /tmp/passwd)" = "root:testpass" ]
  3197. RUN [ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]`,
  3198. true)
  3199. if err != nil {
  3200. c.Fatal(err)
  3201. }
  3202. }
  3203. func (s *DockerSuite) TestBuildCommentsShebangs(c *check.C) {
  3204. name := "testbuildcomments"
  3205. _, err := buildImage(name,
  3206. `FROM busybox
  3207. # This is an ordinary comment.
  3208. RUN { echo '#!/bin/sh'; echo 'echo hello world'; } > /hello.sh
  3209. RUN [ ! -x /hello.sh ]
  3210. # comment with line break \
  3211. RUN chmod +x /hello.sh
  3212. RUN [ -x /hello.sh ]
  3213. RUN [ "$(cat /hello.sh)" = $'#!/bin/sh\necho hello world' ]
  3214. RUN [ "$(/hello.sh)" = "hello world" ]`,
  3215. true)
  3216. if err != nil {
  3217. c.Fatal(err)
  3218. }
  3219. }
  3220. func (s *DockerSuite) TestBuildUsersAndGroups(c *check.C) {
  3221. name := "testbuildusers"
  3222. _, err := buildImage(name,
  3223. `FROM busybox
  3224. # Make sure our defaults work
  3225. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)" = '0:0/root:root' ]
  3226. # 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)
  3227. USER root
  3228. RUN [ "$(id -G):$(id -Gn)" = '0 10:root wheel' ]
  3229. # Setup dockerio user and group
  3230. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  3231. RUN echo 'dockerio:x:1001:' >> /etc/group
  3232. # Make sure we can switch to our user and all the information is exactly as we expect it to be
  3233. USER dockerio
  3234. RUN id -G
  3235. RUN id -Gn
  3236. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3237. # Switch back to root and double check that worked exactly as we might expect it to
  3238. USER root
  3239. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '0:0/root:root/0 10:root wheel' ]
  3240. # Add a "supplementary" group for our dockerio user
  3241. RUN echo 'supplementary:x:1002:dockerio' >> /etc/group
  3242. # ... and then go verify that we get it like we expect
  3243. USER dockerio
  3244. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  3245. USER 1001
  3246. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  3247. # super test the new "user:group" syntax
  3248. USER dockerio:dockerio
  3249. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3250. USER 1001:dockerio
  3251. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3252. USER dockerio:1001
  3253. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3254. USER 1001:1001
  3255. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3256. USER dockerio:supplementary
  3257. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3258. USER dockerio:1002
  3259. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3260. USER 1001:supplementary
  3261. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3262. USER 1001:1002
  3263. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3264. # make sure unknown uid/gid still works properly
  3265. USER 1042:1043
  3266. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1042:1043/1042:1043/1043:1043' ]`,
  3267. true)
  3268. if err != nil {
  3269. c.Fatal(err)
  3270. }
  3271. }
  3272. func (s *DockerSuite) TestBuildEnvUsage(c *check.C) {
  3273. name := "testbuildenvusage"
  3274. dockerfile := `FROM busybox
  3275. ENV HOME /root
  3276. ENV PATH $HOME/bin:$PATH
  3277. ENV PATH /tmp:$PATH
  3278. RUN [ "$PATH" = "/tmp:$HOME/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ]
  3279. ENV FOO /foo/baz
  3280. ENV BAR /bar
  3281. ENV BAZ $BAR
  3282. ENV FOOPATH $PATH:$FOO
  3283. RUN [ "$BAR" = "$BAZ" ]
  3284. RUN [ "$FOOPATH" = "$PATH:/foo/baz" ]
  3285. ENV FROM hello/docker/world
  3286. ENV TO /docker/world/hello
  3287. ADD $FROM $TO
  3288. RUN [ "$(cat $TO)" = "hello" ]
  3289. ENV abc=def
  3290. ENV ghi=$abc
  3291. RUN [ "$ghi" = "def" ]
  3292. `
  3293. ctx, err := fakeContext(dockerfile, map[string]string{
  3294. "hello/docker/world": "hello",
  3295. })
  3296. if err != nil {
  3297. c.Fatal(err)
  3298. }
  3299. defer ctx.Close()
  3300. _, err = buildImageFromContext(name, ctx, true)
  3301. if err != nil {
  3302. c.Fatal(err)
  3303. }
  3304. }
  3305. func (s *DockerSuite) TestBuildEnvUsage2(c *check.C) {
  3306. name := "testbuildenvusage2"
  3307. dockerfile := `FROM busybox
  3308. ENV abc=def
  3309. RUN [ "$abc" = "def" ]
  3310. ENV def="hello world"
  3311. RUN [ "$def" = "hello world" ]
  3312. ENV def=hello\ world
  3313. RUN [ "$def" = "hello world" ]
  3314. ENV v1=abc v2="hi there"
  3315. RUN [ "$v1" = "abc" ]
  3316. RUN [ "$v2" = "hi there" ]
  3317. ENV v3='boogie nights' v4="with'quotes too"
  3318. RUN [ "$v3" = "boogie nights" ]
  3319. RUN [ "$v4" = "with'quotes too" ]
  3320. ENV abc=zzz FROM=hello/docker/world
  3321. ENV abc=zzz TO=/docker/world/hello
  3322. ADD $FROM $TO
  3323. RUN [ "$(cat $TO)" = "hello" ]
  3324. ENV abc "zzz"
  3325. RUN [ $abc = "zzz" ]
  3326. ENV abc 'yyy'
  3327. RUN [ $abc = 'yyy' ]
  3328. ENV abc=
  3329. RUN [ "$abc" = "" ]
  3330. # use grep to make sure if the builder substitutes \$foo by mistake
  3331. # we don't get a false positive
  3332. ENV abc=\$foo
  3333. RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep foo)
  3334. ENV abc \$foo
  3335. RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep foo)
  3336. ENV abc=\'foo\'
  3337. RUN [ "$abc" = "'foo'" ]
  3338. ENV abc=\"foo\"
  3339. RUN [ "$abc" = "\"foo\"" ]
  3340. ENV abc "foo"
  3341. RUN [ "$abc" = "foo" ]
  3342. ENV abc 'foo'
  3343. RUN [ "$abc" = 'foo' ]
  3344. ENV abc \'foo\'
  3345. RUN [ "$abc" = "'foo'" ]
  3346. ENV abc \"foo\"
  3347. RUN [ "$abc" = '"foo"' ]
  3348. ENV abc=ABC
  3349. RUN [ "$abc" = "ABC" ]
  3350. ENV def=${abc:-DEF}
  3351. RUN [ "$def" = "ABC" ]
  3352. ENV def=${ccc:-DEF}
  3353. RUN [ "$def" = "DEF" ]
  3354. ENV def=${ccc:-${def}xx}
  3355. RUN [ "$def" = "DEFxx" ]
  3356. ENV def=${def:+ALT}
  3357. RUN [ "$def" = "ALT" ]
  3358. ENV def=${def:+${abc}:}
  3359. RUN [ "$def" = "ABC:" ]
  3360. ENV def=${ccc:-\$abc:}
  3361. RUN [ "$def" = '$abc:' ]
  3362. ENV def=${ccc:-\${abc}:}
  3363. RUN [ "$def" = '${abc:}' ]
  3364. ENV mypath=${mypath:+$mypath:}/home
  3365. RUN [ "$mypath" = '/home' ]
  3366. ENV mypath=${mypath:+$mypath:}/away
  3367. RUN [ "$mypath" = '/home:/away' ]
  3368. ENV e1=bar
  3369. ENV e2=$e1
  3370. ENV e3=$e11
  3371. ENV e4=\$e1
  3372. ENV e5=\$e11
  3373. RUN [ "$e0,$e1,$e2,$e3,$e4,$e5" = ',bar,bar,,$e1,$e11' ]
  3374. ENV ee1 bar
  3375. ENV ee2 $ee1
  3376. ENV ee3 $ee11
  3377. ENV ee4 \$ee1
  3378. ENV ee5 \$ee11
  3379. RUN [ "$ee1,$ee2,$ee3,$ee4,$ee5" = 'bar,bar,,$ee1,$ee11' ]
  3380. ENV eee1="foo"
  3381. ENV eee2='foo'
  3382. ENV eee3 "foo"
  3383. ENV eee4 'foo'
  3384. RUN [ "$eee1,$eee2,$eee3,$eee4" = 'foo,foo,foo,foo' ]
  3385. `
  3386. ctx, err := fakeContext(dockerfile, map[string]string{
  3387. "hello/docker/world": "hello",
  3388. })
  3389. if err != nil {
  3390. c.Fatal(err)
  3391. }
  3392. defer ctx.Close()
  3393. _, err = buildImageFromContext(name, ctx, true)
  3394. if err != nil {
  3395. c.Fatal(err)
  3396. }
  3397. }
  3398. func (s *DockerSuite) TestBuildAddScript(c *check.C) {
  3399. name := "testbuildaddscript"
  3400. dockerfile := `
  3401. FROM busybox
  3402. ADD test /test
  3403. RUN ["chmod","+x","/test"]
  3404. RUN ["/test"]
  3405. RUN [ "$(cat /testfile)" = 'test!' ]`
  3406. ctx, err := fakeContext(dockerfile, map[string]string{
  3407. "test": "#!/bin/sh\necho 'test!' > /testfile",
  3408. })
  3409. if err != nil {
  3410. c.Fatal(err)
  3411. }
  3412. defer ctx.Close()
  3413. _, err = buildImageFromContext(name, ctx, true)
  3414. if err != nil {
  3415. c.Fatal(err)
  3416. }
  3417. }
  3418. func (s *DockerSuite) TestBuildAddTar(c *check.C) {
  3419. name := "testbuildaddtar"
  3420. ctx := func() *FakeContext {
  3421. dockerfile := `
  3422. FROM busybox
  3423. ADD test.tar /
  3424. RUN cat /test/foo | grep Hi
  3425. ADD test.tar /test.tar
  3426. RUN cat /test.tar/test/foo | grep Hi
  3427. ADD test.tar /unlikely-to-exist
  3428. RUN cat /unlikely-to-exist/test/foo | grep Hi
  3429. ADD test.tar /unlikely-to-exist-trailing-slash/
  3430. RUN cat /unlikely-to-exist-trailing-slash/test/foo | grep Hi
  3431. RUN mkdir /existing-directory
  3432. ADD test.tar /existing-directory
  3433. RUN cat /existing-directory/test/foo | grep Hi
  3434. ADD test.tar /existing-directory-trailing-slash/
  3435. RUN cat /existing-directory-trailing-slash/test/foo | grep Hi`
  3436. tmpDir, err := ioutil.TempDir("", "fake-context")
  3437. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3438. if err != nil {
  3439. c.Fatalf("failed to create test.tar archive: %v", err)
  3440. }
  3441. defer testTar.Close()
  3442. tw := tar.NewWriter(testTar)
  3443. if err := tw.WriteHeader(&tar.Header{
  3444. Name: "test/foo",
  3445. Size: 2,
  3446. }); err != nil {
  3447. c.Fatalf("failed to write tar file header: %v", err)
  3448. }
  3449. if _, err := tw.Write([]byte("Hi")); err != nil {
  3450. c.Fatalf("failed to write tar file content: %v", err)
  3451. }
  3452. if err := tw.Close(); err != nil {
  3453. c.Fatalf("failed to close tar archive: %v", err)
  3454. }
  3455. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3456. c.Fatalf("failed to open destination dockerfile: %v", err)
  3457. }
  3458. return fakeContextFromDir(tmpDir)
  3459. }()
  3460. defer ctx.Close()
  3461. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3462. c.Fatalf("build failed to complete for TestBuildAddTar: %v", err)
  3463. }
  3464. }
  3465. func (s *DockerSuite) TestBuildAddTarXz(c *check.C) {
  3466. name := "testbuildaddtarxz"
  3467. ctx := func() *FakeContext {
  3468. dockerfile := `
  3469. FROM busybox
  3470. ADD test.tar.xz /
  3471. RUN cat /test/foo | grep Hi`
  3472. tmpDir, err := ioutil.TempDir("", "fake-context")
  3473. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3474. if err != nil {
  3475. c.Fatalf("failed to create test.tar archive: %v", err)
  3476. }
  3477. defer testTar.Close()
  3478. tw := tar.NewWriter(testTar)
  3479. if err := tw.WriteHeader(&tar.Header{
  3480. Name: "test/foo",
  3481. Size: 2,
  3482. }); err != nil {
  3483. c.Fatalf("failed to write tar file header: %v", err)
  3484. }
  3485. if _, err := tw.Write([]byte("Hi")); err != nil {
  3486. c.Fatalf("failed to write tar file content: %v", err)
  3487. }
  3488. if err := tw.Close(); err != nil {
  3489. c.Fatalf("failed to close tar archive: %v", err)
  3490. }
  3491. xzCompressCmd := exec.Command("xz", "-k", "test.tar")
  3492. xzCompressCmd.Dir = tmpDir
  3493. out, _, err := runCommandWithOutput(xzCompressCmd)
  3494. if err != nil {
  3495. c.Fatal(err, out)
  3496. }
  3497. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3498. c.Fatalf("failed to open destination dockerfile: %v", err)
  3499. }
  3500. return fakeContextFromDir(tmpDir)
  3501. }()
  3502. defer ctx.Close()
  3503. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3504. c.Fatalf("build failed to complete for TestBuildAddTarXz: %v", err)
  3505. }
  3506. }
  3507. func (s *DockerSuite) TestBuildAddTarXzGz(c *check.C) {
  3508. name := "testbuildaddtarxzgz"
  3509. ctx := func() *FakeContext {
  3510. dockerfile := `
  3511. FROM busybox
  3512. ADD test.tar.xz.gz /
  3513. RUN ls /test.tar.xz.gz`
  3514. tmpDir, err := ioutil.TempDir("", "fake-context")
  3515. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3516. if err != nil {
  3517. c.Fatalf("failed to create test.tar archive: %v", err)
  3518. }
  3519. defer testTar.Close()
  3520. tw := tar.NewWriter(testTar)
  3521. if err := tw.WriteHeader(&tar.Header{
  3522. Name: "test/foo",
  3523. Size: 2,
  3524. }); err != nil {
  3525. c.Fatalf("failed to write tar file header: %v", err)
  3526. }
  3527. if _, err := tw.Write([]byte("Hi")); err != nil {
  3528. c.Fatalf("failed to write tar file content: %v", err)
  3529. }
  3530. if err := tw.Close(); err != nil {
  3531. c.Fatalf("failed to close tar archive: %v", err)
  3532. }
  3533. xzCompressCmd := exec.Command("xz", "-k", "test.tar")
  3534. xzCompressCmd.Dir = tmpDir
  3535. out, _, err := runCommandWithOutput(xzCompressCmd)
  3536. if err != nil {
  3537. c.Fatal(err, out)
  3538. }
  3539. gzipCompressCmd := exec.Command("gzip", "test.tar.xz")
  3540. gzipCompressCmd.Dir = tmpDir
  3541. out, _, err = runCommandWithOutput(gzipCompressCmd)
  3542. if err != nil {
  3543. c.Fatal(err, out)
  3544. }
  3545. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3546. c.Fatalf("failed to open destination dockerfile: %v", err)
  3547. }
  3548. return fakeContextFromDir(tmpDir)
  3549. }()
  3550. defer ctx.Close()
  3551. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3552. c.Fatalf("build failed to complete for TestBuildAddTarXz: %v", err)
  3553. }
  3554. }
  3555. func (s *DockerSuite) TestBuildFromGIT(c *check.C) {
  3556. name := "testbuildfromgit"
  3557. git, err := newFakeGit("repo", map[string]string{
  3558. "Dockerfile": `FROM busybox
  3559. ADD first /first
  3560. RUN [ -f /first ]
  3561. MAINTAINER docker`,
  3562. "first": "test git data",
  3563. }, true)
  3564. if err != nil {
  3565. c.Fatal(err)
  3566. }
  3567. defer git.Close()
  3568. _, err = buildImageFromPath(name, git.RepoURL, true)
  3569. if err != nil {
  3570. c.Fatal(err)
  3571. }
  3572. res, err := inspectField(name, "Author")
  3573. if err != nil {
  3574. c.Fatal(err)
  3575. }
  3576. if res != "docker" {
  3577. c.Fatalf("Maintainer should be docker, got %s", res)
  3578. }
  3579. }
  3580. func (s *DockerSuite) TestBuildFromGITWithContext(c *check.C) {
  3581. name := "testbuildfromgit"
  3582. git, err := newFakeGit("repo", map[string]string{
  3583. "docker/Dockerfile": `FROM busybox
  3584. ADD first /first
  3585. RUN [ -f /first ]
  3586. MAINTAINER docker`,
  3587. "docker/first": "test git data",
  3588. }, true)
  3589. if err != nil {
  3590. c.Fatal(err)
  3591. }
  3592. defer git.Close()
  3593. u := fmt.Sprintf("%s#master:docker", git.RepoURL)
  3594. _, err = buildImageFromPath(name, u, true)
  3595. if err != nil {
  3596. c.Fatal(err)
  3597. }
  3598. res, err := inspectField(name, "Author")
  3599. if err != nil {
  3600. c.Fatal(err)
  3601. }
  3602. if res != "docker" {
  3603. c.Fatalf("Maintainer should be docker, got %s", res)
  3604. }
  3605. }
  3606. func (s *DockerSuite) TestBuildFromRemoteTarball(c *check.C) {
  3607. name := "testbuildfromremotetarball"
  3608. buffer := new(bytes.Buffer)
  3609. tw := tar.NewWriter(buffer)
  3610. defer tw.Close()
  3611. dockerfile := []byte(`FROM busybox
  3612. MAINTAINER docker`)
  3613. if err := tw.WriteHeader(&tar.Header{
  3614. Name: "Dockerfile",
  3615. Size: int64(len(dockerfile)),
  3616. }); err != nil {
  3617. c.Fatalf("failed to write tar file header: %v", err)
  3618. }
  3619. if _, err := tw.Write(dockerfile); err != nil {
  3620. c.Fatalf("failed to write tar file content: %v", err)
  3621. }
  3622. if err := tw.Close(); err != nil {
  3623. c.Fatalf("failed to close tar archive: %v", err)
  3624. }
  3625. server, err := fakeBinaryStorage(map[string]*bytes.Buffer{
  3626. "testT.tar": buffer,
  3627. })
  3628. c.Assert(err, check.IsNil)
  3629. defer server.Close()
  3630. _, err = buildImageFromPath(name, server.URL()+"/testT.tar", true)
  3631. c.Assert(err, check.IsNil)
  3632. res, err := inspectField(name, "Author")
  3633. c.Assert(err, check.IsNil)
  3634. if res != "docker" {
  3635. c.Fatalf("Maintainer should be docker, got %s", res)
  3636. }
  3637. }
  3638. func (s *DockerSuite) TestBuildCleanupCmdOnEntrypoint(c *check.C) {
  3639. name := "testbuildcmdcleanuponentrypoint"
  3640. if _, err := buildImage(name,
  3641. `FROM scratch
  3642. CMD ["test"]
  3643. ENTRYPOINT ["echo"]`,
  3644. true); err != nil {
  3645. c.Fatal(err)
  3646. }
  3647. if _, err := buildImage(name,
  3648. fmt.Sprintf(`FROM %s
  3649. ENTRYPOINT ["cat"]`, name),
  3650. true); err != nil {
  3651. c.Fatal(err)
  3652. }
  3653. res, err := inspectField(name, "Config.Cmd")
  3654. if err != nil {
  3655. c.Fatal(err)
  3656. }
  3657. if res != "<nil>" {
  3658. c.Fatalf("Cmd %s, expected nil", res)
  3659. }
  3660. res, err = inspectField(name, "Config.Entrypoint")
  3661. if err != nil {
  3662. c.Fatal(err)
  3663. }
  3664. if expected := "{[cat]}"; res != expected {
  3665. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  3666. }
  3667. }
  3668. func (s *DockerSuite) TestBuildClearCmd(c *check.C) {
  3669. name := "testbuildclearcmd"
  3670. _, err := buildImage(name,
  3671. `From scratch
  3672. ENTRYPOINT ["/bin/bash"]
  3673. CMD []`,
  3674. true)
  3675. if err != nil {
  3676. c.Fatal(err)
  3677. }
  3678. res, err := inspectFieldJSON(name, "Config.Cmd")
  3679. if err != nil {
  3680. c.Fatal(err)
  3681. }
  3682. if res != "[]" {
  3683. c.Fatalf("Cmd %s, expected %s", res, "[]")
  3684. }
  3685. }
  3686. func (s *DockerSuite) TestBuildEmptyCmd(c *check.C) {
  3687. name := "testbuildemptycmd"
  3688. if _, err := buildImage(name, "FROM scratch\nMAINTAINER quux\n", true); err != nil {
  3689. c.Fatal(err)
  3690. }
  3691. res, err := inspectFieldJSON(name, "Config.Cmd")
  3692. if err != nil {
  3693. c.Fatal(err)
  3694. }
  3695. if res != "null" {
  3696. c.Fatalf("Cmd %s, expected %s", res, "null")
  3697. }
  3698. }
  3699. func (s *DockerSuite) TestBuildOnBuildOutput(c *check.C) {
  3700. name := "testbuildonbuildparent"
  3701. if _, err := buildImage(name, "FROM busybox\nONBUILD RUN echo foo\n", true); err != nil {
  3702. c.Fatal(err)
  3703. }
  3704. _, out, err := buildImageWithOut(name, "FROM "+name+"\nMAINTAINER quux\n", true)
  3705. if err != nil {
  3706. c.Fatal(err)
  3707. }
  3708. if !strings.Contains(out, "Trigger 0, RUN echo foo") {
  3709. c.Fatal("failed to find the ONBUILD output", out)
  3710. }
  3711. }
  3712. func (s *DockerSuite) TestBuildInvalidTag(c *check.C) {
  3713. name := "abcd:" + stringutils.GenerateRandomAlphaOnlyString(200)
  3714. _, out, err := buildImageWithOut(name, "FROM scratch\nMAINTAINER quux\n", true)
  3715. // if the error doesnt check for illegal tag name, or the image is built
  3716. // then this should fail
  3717. if !strings.Contains(out, "Illegal tag name") || strings.Contains(out, "Sending build context to Docker daemon") {
  3718. c.Fatalf("failed to stop before building. Error: %s, Output: %s", err, out)
  3719. }
  3720. }
  3721. func (s *DockerSuite) TestBuildCmdShDashC(c *check.C) {
  3722. name := "testbuildcmdshc"
  3723. if _, err := buildImage(name, "FROM busybox\nCMD echo cmd\n", true); err != nil {
  3724. c.Fatal(err)
  3725. }
  3726. res, err := inspectFieldJSON(name, "Config.Cmd")
  3727. if err != nil {
  3728. c.Fatal(err, res)
  3729. }
  3730. expected := `["/bin/sh","-c","echo cmd"]`
  3731. if res != expected {
  3732. c.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  3733. }
  3734. }
  3735. func (s *DockerSuite) TestBuildCmdSpaces(c *check.C) {
  3736. // Test to make sure that when we strcat arrays we take into account
  3737. // the arg separator to make sure ["echo","hi"] and ["echo hi"] don't
  3738. // look the same
  3739. name := "testbuildcmdspaces"
  3740. var id1 string
  3741. var id2 string
  3742. var err error
  3743. if id1, err = buildImage(name, "FROM busybox\nCMD [\"echo hi\"]\n", true); err != nil {
  3744. c.Fatal(err)
  3745. }
  3746. if id2, err = buildImage(name, "FROM busybox\nCMD [\"echo\", \"hi\"]\n", true); err != nil {
  3747. c.Fatal(err)
  3748. }
  3749. if id1 == id2 {
  3750. c.Fatal("Should not have resulted in the same CMD")
  3751. }
  3752. // Now do the same with ENTRYPOINT
  3753. if id1, err = buildImage(name, "FROM busybox\nENTRYPOINT [\"echo hi\"]\n", true); err != nil {
  3754. c.Fatal(err)
  3755. }
  3756. if id2, err = buildImage(name, "FROM busybox\nENTRYPOINT [\"echo\", \"hi\"]\n", true); err != nil {
  3757. c.Fatal(err)
  3758. }
  3759. if id1 == id2 {
  3760. c.Fatal("Should not have resulted in the same ENTRYPOINT")
  3761. }
  3762. }
  3763. func (s *DockerSuite) TestBuildCmdJSONNoShDashC(c *check.C) {
  3764. name := "testbuildcmdjson"
  3765. if _, err := buildImage(name, "FROM busybox\nCMD [\"echo\", \"cmd\"]", true); err != nil {
  3766. c.Fatal(err)
  3767. }
  3768. res, err := inspectFieldJSON(name, "Config.Cmd")
  3769. if err != nil {
  3770. c.Fatal(err, res)
  3771. }
  3772. expected := `["echo","cmd"]`
  3773. if res != expected {
  3774. c.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  3775. }
  3776. }
  3777. func (s *DockerSuite) TestBuildErrorInvalidInstruction(c *check.C) {
  3778. name := "testbuildignoreinvalidinstruction"
  3779. out, _, err := buildImageWithOut(name, "FROM busybox\nfoo bar", true)
  3780. if err == nil {
  3781. c.Fatalf("Should have failed: %s", out)
  3782. }
  3783. }
  3784. func (s *DockerSuite) TestBuildEntrypointInheritance(c *check.C) {
  3785. if _, err := buildImage("parent", `
  3786. FROM busybox
  3787. ENTRYPOINT exit 130
  3788. `, true); err != nil {
  3789. c.Fatal(err)
  3790. }
  3791. if _, status, _ := dockerCmdWithError(c, "run", "parent"); status != 130 {
  3792. c.Fatalf("expected exit code 130 but received %d", status)
  3793. }
  3794. if _, err := buildImage("child", `
  3795. FROM parent
  3796. ENTRYPOINT exit 5
  3797. `, true); err != nil {
  3798. c.Fatal(err)
  3799. }
  3800. if _, status, _ := dockerCmdWithError(c, "run", "child"); status != 5 {
  3801. c.Fatalf("expected exit code 5 but received %d", status)
  3802. }
  3803. }
  3804. func (s *DockerSuite) TestBuildEntrypointInheritanceInspect(c *check.C) {
  3805. var (
  3806. name = "testbuildepinherit"
  3807. name2 = "testbuildepinherit2"
  3808. expected = `["/bin/sh","-c","echo quux"]`
  3809. )
  3810. if _, err := buildImage(name, "FROM busybox\nENTRYPOINT /foo/bar", true); err != nil {
  3811. c.Fatal(err)
  3812. }
  3813. if _, err := buildImage(name2, fmt.Sprintf("FROM %s\nENTRYPOINT echo quux", name), true); err != nil {
  3814. c.Fatal(err)
  3815. }
  3816. res, err := inspectFieldJSON(name2, "Config.Entrypoint")
  3817. if err != nil {
  3818. c.Fatal(err, res)
  3819. }
  3820. if res != expected {
  3821. c.Fatalf("Expected value %s not in Config.Entrypoint: %s", expected, res)
  3822. }
  3823. out, _ := dockerCmd(c, "run", "-t", name2)
  3824. expected = "quux"
  3825. if strings.TrimSpace(out) != expected {
  3826. c.Fatalf("Expected output is %s, got %s", expected, out)
  3827. }
  3828. }
  3829. func (s *DockerSuite) TestBuildRunShEntrypoint(c *check.C) {
  3830. name := "testbuildentrypoint"
  3831. _, err := buildImage(name,
  3832. `FROM busybox
  3833. ENTRYPOINT /bin/echo`,
  3834. true)
  3835. if err != nil {
  3836. c.Fatal(err)
  3837. }
  3838. dockerCmd(c, "run", "--rm", name)
  3839. }
  3840. func (s *DockerSuite) TestBuildExoticShellInterpolation(c *check.C) {
  3841. name := "testbuildexoticshellinterpolation"
  3842. _, err := buildImage(name, `
  3843. FROM busybox
  3844. ENV SOME_VAR a.b.c
  3845. RUN [ "$SOME_VAR" = 'a.b.c' ]
  3846. RUN [ "${SOME_VAR}" = 'a.b.c' ]
  3847. RUN [ "${SOME_VAR%.*}" = 'a.b' ]
  3848. RUN [ "${SOME_VAR%%.*}" = 'a' ]
  3849. RUN [ "${SOME_VAR#*.}" = 'b.c' ]
  3850. RUN [ "${SOME_VAR##*.}" = 'c' ]
  3851. RUN [ "${SOME_VAR/c/d}" = 'a.b.d' ]
  3852. RUN [ "${#SOME_VAR}" = '5' ]
  3853. RUN [ "${SOME_UNSET_VAR:-$SOME_VAR}" = 'a.b.c' ]
  3854. RUN [ "${SOME_VAR:+Version: ${SOME_VAR}}" = 'Version: a.b.c' ]
  3855. RUN [ "${SOME_UNSET_VAR:+${SOME_VAR}}" = '' ]
  3856. RUN [ "${SOME_UNSET_VAR:-${SOME_VAR:-d.e.f}}" = 'a.b.c' ]
  3857. `, false)
  3858. if err != nil {
  3859. c.Fatal(err)
  3860. }
  3861. }
  3862. func (s *DockerSuite) TestBuildVerifySingleQuoteFails(c *check.C) {
  3863. // This testcase is supposed to generate an error because the
  3864. // JSON array we're passing in on the CMD uses single quotes instead
  3865. // of double quotes (per the JSON spec). This means we interpret it
  3866. // as a "string" insead of "JSON array" and pass it on to "sh -c" and
  3867. // it should barf on it.
  3868. name := "testbuildsinglequotefails"
  3869. if _, err := buildImage(name,
  3870. `FROM busybox
  3871. CMD [ '/bin/sh', '-c', 'echo hi' ]`,
  3872. true); err != nil {
  3873. c.Fatal(err)
  3874. }
  3875. if _, _, err := dockerCmdWithError(c, "run", "--rm", name); err == nil {
  3876. c.Fatal("The image was not supposed to be able to run")
  3877. }
  3878. }
  3879. func (s *DockerSuite) TestBuildVerboseOut(c *check.C) {
  3880. name := "testbuildverboseout"
  3881. _, out, err := buildImageWithOut(name,
  3882. `FROM busybox
  3883. RUN echo 123`,
  3884. false)
  3885. if err != nil {
  3886. c.Fatal(err)
  3887. }
  3888. if !strings.Contains(out, "\n123\n") {
  3889. c.Fatalf("Output should contain %q: %q", "123", out)
  3890. }
  3891. }
  3892. func (s *DockerSuite) TestBuildWithTabs(c *check.C) {
  3893. name := "testbuildwithtabs"
  3894. _, err := buildImage(name,
  3895. "FROM busybox\nRUN echo\tone\t\ttwo", true)
  3896. if err != nil {
  3897. c.Fatal(err)
  3898. }
  3899. res, err := inspectFieldJSON(name, "ContainerConfig.Cmd")
  3900. if err != nil {
  3901. c.Fatal(err)
  3902. }
  3903. expected1 := `["/bin/sh","-c","echo\tone\t\ttwo"]`
  3904. expected2 := `["/bin/sh","-c","echo\u0009one\u0009\u0009two"]` // syntactically equivalent, and what Go 1.3 generates
  3905. if res != expected1 && res != expected2 {
  3906. c.Fatalf("Missing tabs.\nGot: %s\nExp: %s or %s", res, expected1, expected2)
  3907. }
  3908. }
  3909. func (s *DockerSuite) TestBuildLabels(c *check.C) {
  3910. name := "testbuildlabel"
  3911. expected := `{"License":"GPL","Vendor":"Acme"}`
  3912. _, err := buildImage(name,
  3913. `FROM busybox
  3914. LABEL Vendor=Acme
  3915. LABEL License GPL`,
  3916. true)
  3917. if err != nil {
  3918. c.Fatal(err)
  3919. }
  3920. res, err := inspectFieldJSON(name, "Config.Labels")
  3921. if err != nil {
  3922. c.Fatal(err)
  3923. }
  3924. if res != expected {
  3925. c.Fatalf("Labels %s, expected %s", res, expected)
  3926. }
  3927. }
  3928. func (s *DockerSuite) TestBuildLabelsCache(c *check.C) {
  3929. name := "testbuildlabelcache"
  3930. id1, err := buildImage(name,
  3931. `FROM busybox
  3932. LABEL Vendor=Acme`, false)
  3933. if err != nil {
  3934. c.Fatalf("Build 1 should have worked: %v", err)
  3935. }
  3936. id2, err := buildImage(name,
  3937. `FROM busybox
  3938. LABEL Vendor=Acme`, true)
  3939. if err != nil || id1 != id2 {
  3940. c.Fatalf("Build 2 should have worked & used cache(%s,%s): %v", id1, id2, err)
  3941. }
  3942. id2, err = buildImage(name,
  3943. `FROM busybox
  3944. LABEL Vendor=Acme1`, true)
  3945. if err != nil || id1 == id2 {
  3946. c.Fatalf("Build 3 should have worked & NOT used cache(%s,%s): %v", id1, id2, err)
  3947. }
  3948. id2, err = buildImage(name,
  3949. `FROM busybox
  3950. LABEL Vendor Acme`, true) // Note: " " and "=" should be same
  3951. if err != nil || id1 != id2 {
  3952. c.Fatalf("Build 4 should have worked & used cache(%s,%s): %v", id1, id2, err)
  3953. }
  3954. // Now make sure the cache isn't used by mistake
  3955. id1, err = buildImage(name,
  3956. `FROM busybox
  3957. LABEL f1=b1 f2=b2`, false)
  3958. if err != nil {
  3959. c.Fatalf("Build 5 should have worked: %q", err)
  3960. }
  3961. id2, err = buildImage(name,
  3962. `FROM busybox
  3963. LABEL f1="b1 f2=b2"`, true)
  3964. if err != nil || id1 == id2 {
  3965. c.Fatalf("Build 6 should have worked & NOT used the cache(%s,%s): %q", id1, id2, err)
  3966. }
  3967. }
  3968. func (s *DockerSuite) TestBuildStderr(c *check.C) {
  3969. // This test just makes sure that no non-error output goes
  3970. // to stderr
  3971. name := "testbuildstderr"
  3972. _, _, stderr, err := buildImageWithStdoutStderr(name,
  3973. "FROM busybox\nRUN echo one", true)
  3974. if err != nil {
  3975. c.Fatal(err)
  3976. }
  3977. if runtime.GOOS == "windows" {
  3978. // stderr might contain a security warning on windows
  3979. lines := strings.Split(stderr, "\n")
  3980. for _, v := range lines {
  3981. if v != "" && !strings.Contains(v, "SECURITY WARNING:") {
  3982. c.Fatalf("Stderr contains unexpected output line: %q", v)
  3983. }
  3984. }
  3985. } else {
  3986. if stderr != "" {
  3987. c.Fatalf("Stderr should have been empty, instead its: %q", stderr)
  3988. }
  3989. }
  3990. }
  3991. func (s *DockerSuite) TestBuildChownSingleFile(c *check.C) {
  3992. testRequires(c, UnixCli) // test uses chown: not available on windows
  3993. name := "testbuildchownsinglefile"
  3994. ctx, err := fakeContext(`
  3995. FROM busybox
  3996. COPY test /
  3997. RUN ls -l /test
  3998. RUN [ $(ls -l /test | awk '{print $3":"$4}') = 'root:root' ]
  3999. `, map[string]string{
  4000. "test": "test",
  4001. })
  4002. if err != nil {
  4003. c.Fatal(err)
  4004. }
  4005. defer ctx.Close()
  4006. if err := os.Chown(filepath.Join(ctx.Dir, "test"), 4242, 4242); err != nil {
  4007. c.Fatal(err)
  4008. }
  4009. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  4010. c.Fatal(err)
  4011. }
  4012. }
  4013. func (s *DockerSuite) TestBuildSymlinkBreakout(c *check.C) {
  4014. name := "testbuildsymlinkbreakout"
  4015. tmpdir, err := ioutil.TempDir("", name)
  4016. if err != nil {
  4017. c.Fatal(err)
  4018. }
  4019. defer os.RemoveAll(tmpdir)
  4020. ctx := filepath.Join(tmpdir, "context")
  4021. if err := os.MkdirAll(ctx, 0755); err != nil {
  4022. c.Fatal(err)
  4023. }
  4024. if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte(`
  4025. from busybox
  4026. add symlink.tar /
  4027. add inject /symlink/
  4028. `), 0644); err != nil {
  4029. c.Fatal(err)
  4030. }
  4031. inject := filepath.Join(ctx, "inject")
  4032. if err := ioutil.WriteFile(inject, nil, 0644); err != nil {
  4033. c.Fatal(err)
  4034. }
  4035. f, err := os.Create(filepath.Join(ctx, "symlink.tar"))
  4036. if err != nil {
  4037. c.Fatal(err)
  4038. }
  4039. w := tar.NewWriter(f)
  4040. w.WriteHeader(&tar.Header{
  4041. Name: "symlink2",
  4042. Typeflag: tar.TypeSymlink,
  4043. Linkname: "/../../../../../../../../../../../../../../",
  4044. Uid: os.Getuid(),
  4045. Gid: os.Getgid(),
  4046. })
  4047. w.WriteHeader(&tar.Header{
  4048. Name: "symlink",
  4049. Typeflag: tar.TypeSymlink,
  4050. Linkname: filepath.Join("symlink2", tmpdir),
  4051. Uid: os.Getuid(),
  4052. Gid: os.Getgid(),
  4053. })
  4054. w.Close()
  4055. f.Close()
  4056. if _, err := buildImageFromContext(name, fakeContextFromDir(ctx), false); err != nil {
  4057. c.Fatal(err)
  4058. }
  4059. if _, err := os.Lstat(filepath.Join(tmpdir, "inject")); err == nil {
  4060. c.Fatal("symlink breakout - inject")
  4061. } else if !os.IsNotExist(err) {
  4062. c.Fatalf("unexpected error: %v", err)
  4063. }
  4064. }
  4065. func (s *DockerSuite) TestBuildXZHost(c *check.C) {
  4066. name := "testbuildxzhost"
  4067. ctx, err := fakeContext(`
  4068. FROM busybox
  4069. ADD xz /usr/local/sbin/
  4070. RUN chmod 755 /usr/local/sbin/xz
  4071. ADD test.xz /
  4072. RUN [ ! -e /injected ]`,
  4073. map[string]string{
  4074. "test.xz": "\xfd\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00" +
  4075. "\x21\x01\x16\x00\x00\x00\x74\x2f\xe5\xa3\x01\x00\x3f\xfd" +
  4076. "\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00\x21",
  4077. "xz": "#!/bin/sh\ntouch /injected",
  4078. })
  4079. if err != nil {
  4080. c.Fatal(err)
  4081. }
  4082. defer ctx.Close()
  4083. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  4084. c.Fatal(err)
  4085. }
  4086. }
  4087. func (s *DockerSuite) TestBuildVolumesRetainContents(c *check.C) {
  4088. var (
  4089. name = "testbuildvolumescontent"
  4090. expected = "some text"
  4091. )
  4092. ctx, err := fakeContext(`
  4093. FROM busybox
  4094. COPY content /foo/file
  4095. VOLUME /foo
  4096. CMD cat /foo/file`,
  4097. map[string]string{
  4098. "content": expected,
  4099. })
  4100. if err != nil {
  4101. c.Fatal(err)
  4102. }
  4103. defer ctx.Close()
  4104. if _, err := buildImageFromContext(name, ctx, false); err != nil {
  4105. c.Fatal(err)
  4106. }
  4107. out, _ := dockerCmd(c, "run", "--rm", name)
  4108. if out != expected {
  4109. c.Fatalf("expected file contents for /foo/file to be %q but received %q", expected, out)
  4110. }
  4111. }
  4112. func (s *DockerSuite) TestBuildRenamedDockerfile(c *check.C) {
  4113. ctx, err := fakeContext(`FROM busybox
  4114. RUN echo from Dockerfile`,
  4115. map[string]string{
  4116. "Dockerfile": "FROM busybox\nRUN echo from Dockerfile",
  4117. "files/Dockerfile": "FROM busybox\nRUN echo from files/Dockerfile",
  4118. "files/dFile": "FROM busybox\nRUN echo from files/dFile",
  4119. "dFile": "FROM busybox\nRUN echo from dFile",
  4120. "files/dFile2": "FROM busybox\nRUN echo from files/dFile2",
  4121. })
  4122. defer ctx.Close()
  4123. if err != nil {
  4124. c.Fatal(err)
  4125. }
  4126. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", "test1", ".")
  4127. if err != nil {
  4128. c.Fatalf("Failed to build: %s\n%s", out, err)
  4129. }
  4130. if !strings.Contains(out, "from Dockerfile") {
  4131. c.Fatalf("test1 should have used Dockerfile, output:%s", out)
  4132. }
  4133. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", "-f", filepath.Join("files", "Dockerfile"), "-t", "test2", ".")
  4134. if err != nil {
  4135. c.Fatal(err)
  4136. }
  4137. if !strings.Contains(out, "from files/Dockerfile") {
  4138. c.Fatalf("test2 should have used files/Dockerfile, output:%s", out)
  4139. }
  4140. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", fmt.Sprintf("--file=%s", filepath.Join("files", "dFile")), "-t", "test3", ".")
  4141. if err != nil {
  4142. c.Fatal(err)
  4143. }
  4144. if !strings.Contains(out, "from files/dFile") {
  4145. c.Fatalf("test3 should have used files/dFile, output:%s", out)
  4146. }
  4147. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", "--file=dFile", "-t", "test4", ".")
  4148. if err != nil {
  4149. c.Fatal(err)
  4150. }
  4151. if !strings.Contains(out, "from dFile") {
  4152. c.Fatalf("test4 should have used dFile, output:%s", out)
  4153. }
  4154. dirWithNoDockerfile, _ := ioutil.TempDir(os.TempDir(), "test5")
  4155. nonDockerfileFile := filepath.Join(dirWithNoDockerfile, "notDockerfile")
  4156. if _, err = os.Create(nonDockerfileFile); err != nil {
  4157. c.Fatal(err)
  4158. }
  4159. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", fmt.Sprintf("--file=%s", nonDockerfileFile), "-t", "test5", ".")
  4160. if err == nil {
  4161. c.Fatalf("test5 was supposed to fail to find passwd")
  4162. }
  4163. if expected := fmt.Sprintf("The Dockerfile (%s) must be within the build context (.)", nonDockerfileFile); !strings.Contains(out, expected) {
  4164. c.Fatalf("wrong error messsage:%v\nexpected to contain=%v", out, expected)
  4165. }
  4166. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join("..", "Dockerfile"), "-t", "test6", "..")
  4167. if err != nil {
  4168. c.Fatalf("test6 failed: %s", err)
  4169. }
  4170. if !strings.Contains(out, "from Dockerfile") {
  4171. c.Fatalf("test6 should have used root Dockerfile, output:%s", out)
  4172. }
  4173. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join(ctx.Dir, "files", "Dockerfile"), "-t", "test7", "..")
  4174. if err != nil {
  4175. c.Fatalf("test7 failed: %s", err)
  4176. }
  4177. if !strings.Contains(out, "from files/Dockerfile") {
  4178. c.Fatalf("test7 should have used files Dockerfile, output:%s", out)
  4179. }
  4180. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join("..", "Dockerfile"), "-t", "test8", ".")
  4181. if err == nil || !strings.Contains(out, "must be within the build context") {
  4182. c.Fatalf("test8 should have failed with Dockerfile out of context: %s", err)
  4183. }
  4184. tmpDir := os.TempDir()
  4185. out, _, err = dockerCmdInDir(c, tmpDir, "build", "-t", "test9", ctx.Dir)
  4186. if err != nil {
  4187. c.Fatalf("test9 - failed: %s", err)
  4188. }
  4189. if !strings.Contains(out, "from Dockerfile") {
  4190. c.Fatalf("test9 should have used root Dockerfile, output:%s", out)
  4191. }
  4192. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", "dFile2", "-t", "test10", ".")
  4193. if err != nil {
  4194. c.Fatalf("test10 should have worked: %s", err)
  4195. }
  4196. if !strings.Contains(out, "from files/dFile2") {
  4197. c.Fatalf("test10 should have used files/dFile2, output:%s", out)
  4198. }
  4199. }
  4200. func (s *DockerSuite) TestBuildFromMixedcaseDockerfile(c *check.C) {
  4201. testRequires(c, UnixCli) // Dockerfile overwrites dockerfile on windows
  4202. ctx, err := fakeContext(`FROM busybox
  4203. RUN echo from dockerfile`,
  4204. map[string]string{
  4205. "dockerfile": "FROM busybox\nRUN echo from dockerfile",
  4206. })
  4207. defer ctx.Close()
  4208. if err != nil {
  4209. c.Fatal(err)
  4210. }
  4211. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", "test1", ".")
  4212. if err != nil {
  4213. c.Fatalf("Failed to build: %s\n%s", out, err)
  4214. }
  4215. if !strings.Contains(out, "from dockerfile") {
  4216. c.Fatalf("Missing proper output: %s", out)
  4217. }
  4218. }
  4219. func (s *DockerSuite) TestBuildWithTwoDockerfiles(c *check.C) {
  4220. testRequires(c, UnixCli) // Dockerfile overwrites dockerfile on windows
  4221. ctx, err := fakeContext(`FROM busybox
  4222. RUN echo from Dockerfile`,
  4223. map[string]string{
  4224. "dockerfile": "FROM busybox\nRUN echo from dockerfile",
  4225. })
  4226. defer ctx.Close()
  4227. if err != nil {
  4228. c.Fatal(err)
  4229. }
  4230. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", "test1", ".")
  4231. if err != nil {
  4232. c.Fatalf("Failed to build: %s\n%s", out, err)
  4233. }
  4234. if !strings.Contains(out, "from Dockerfile") {
  4235. c.Fatalf("Missing proper output: %s", out)
  4236. }
  4237. }
  4238. func (s *DockerSuite) TestBuildFromURLWithF(c *check.C) {
  4239. server, err := fakeStorage(map[string]string{"baz": `FROM busybox
  4240. RUN echo from baz
  4241. COPY * /tmp/
  4242. RUN find /tmp/`})
  4243. if err != nil {
  4244. c.Fatal(err)
  4245. }
  4246. defer server.Close()
  4247. ctx, err := fakeContext(`FROM busybox
  4248. RUN echo from Dockerfile`,
  4249. map[string]string{})
  4250. defer ctx.Close()
  4251. if err != nil {
  4252. c.Fatal(err)
  4253. }
  4254. // Make sure that -f is ignored and that we don't use the Dockerfile
  4255. // that's in the current dir
  4256. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-f", "baz", "-t", "test1", server.URL()+"/baz")
  4257. if err != nil {
  4258. c.Fatalf("Failed to build: %s\n%s", out, err)
  4259. }
  4260. if !strings.Contains(out, "from baz") ||
  4261. strings.Contains(out, "/tmp/baz") ||
  4262. !strings.Contains(out, "/tmp/Dockerfile") {
  4263. c.Fatalf("Missing proper output: %s", out)
  4264. }
  4265. }
  4266. func (s *DockerSuite) TestBuildFromStdinWithF(c *check.C) {
  4267. ctx, err := fakeContext(`FROM busybox
  4268. RUN echo from Dockerfile`,
  4269. map[string]string{})
  4270. defer ctx.Close()
  4271. if err != nil {
  4272. c.Fatal(err)
  4273. }
  4274. // Make sure that -f is ignored and that we don't use the Dockerfile
  4275. // that's in the current dir
  4276. dockerCommand := exec.Command(dockerBinary, "build", "-f", "baz", "-t", "test1", "-")
  4277. dockerCommand.Dir = ctx.Dir
  4278. dockerCommand.Stdin = strings.NewReader(`FROM busybox
  4279. RUN echo from baz
  4280. COPY * /tmp/
  4281. RUN find /tmp/`)
  4282. out, status, err := runCommandWithOutput(dockerCommand)
  4283. if err != nil || status != 0 {
  4284. c.Fatalf("Error building: %s", err)
  4285. }
  4286. if !strings.Contains(out, "from baz") ||
  4287. strings.Contains(out, "/tmp/baz") ||
  4288. !strings.Contains(out, "/tmp/Dockerfile") {
  4289. c.Fatalf("Missing proper output: %s", out)
  4290. }
  4291. }
  4292. func (s *DockerSuite) TestBuildFromOfficialNames(c *check.C) {
  4293. name := "testbuildfromofficial"
  4294. fromNames := []string{
  4295. "busybox",
  4296. "docker.io/busybox",
  4297. "index.docker.io/busybox",
  4298. "library/busybox",
  4299. "docker.io/library/busybox",
  4300. "index.docker.io/library/busybox",
  4301. }
  4302. for idx, fromName := range fromNames {
  4303. imgName := fmt.Sprintf("%s%d", name, idx)
  4304. _, err := buildImage(imgName, "FROM "+fromName, true)
  4305. if err != nil {
  4306. c.Errorf("Build failed using FROM %s: %s", fromName, err)
  4307. }
  4308. deleteImages(imgName)
  4309. }
  4310. }
  4311. func (s *DockerSuite) TestBuildDockerfileOutsideContext(c *check.C) {
  4312. testRequires(c, UnixCli) // uses os.Symlink: not implemented in windows at the time of writing (go-1.4.2)
  4313. name := "testbuilddockerfileoutsidecontext"
  4314. tmpdir, err := ioutil.TempDir("", name)
  4315. if err != nil {
  4316. c.Fatal(err)
  4317. }
  4318. defer os.RemoveAll(tmpdir)
  4319. ctx := filepath.Join(tmpdir, "context")
  4320. if err := os.MkdirAll(ctx, 0755); err != nil {
  4321. c.Fatal(err)
  4322. }
  4323. if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte("FROM scratch\nENV X Y"), 0644); err != nil {
  4324. c.Fatal(err)
  4325. }
  4326. wd, err := os.Getwd()
  4327. if err != nil {
  4328. c.Fatal(err)
  4329. }
  4330. defer os.Chdir(wd)
  4331. if err := os.Chdir(ctx); err != nil {
  4332. c.Fatal(err)
  4333. }
  4334. if err := ioutil.WriteFile(filepath.Join(tmpdir, "outsideDockerfile"), []byte("FROM scratch\nENV x y"), 0644); err != nil {
  4335. c.Fatal(err)
  4336. }
  4337. if err := os.Symlink(filepath.Join("..", "outsideDockerfile"), filepath.Join(ctx, "dockerfile1")); err != nil {
  4338. c.Fatal(err)
  4339. }
  4340. if err := os.Symlink(filepath.Join(tmpdir, "outsideDockerfile"), filepath.Join(ctx, "dockerfile2")); err != nil {
  4341. c.Fatal(err)
  4342. }
  4343. for _, dockerfilePath := range []string{
  4344. filepath.Join("..", "outsideDockerfile"),
  4345. filepath.Join(ctx, "dockerfile1"),
  4346. filepath.Join(ctx, "dockerfile2"),
  4347. } {
  4348. out, _, err := dockerCmdWithError(c, "build", "-t", name, "--no-cache", "-f", dockerfilePath, ".")
  4349. if err == nil {
  4350. c.Fatalf("Expected error with %s. Out: %s", dockerfilePath, out)
  4351. }
  4352. if !strings.Contains(out, "must be within the build context") && !strings.Contains(out, "Cannot locate Dockerfile") {
  4353. c.Fatalf("Unexpected error with %s. Out: %s", dockerfilePath, out)
  4354. }
  4355. deleteImages(name)
  4356. }
  4357. os.Chdir(tmpdir)
  4358. // Path to Dockerfile should be resolved relative to working directory, not relative to context.
  4359. // There is a Dockerfile in the context, but since there is no Dockerfile in the current directory, the following should fail
  4360. out, _, err := dockerCmdWithError(c, "build", "-t", name, "--no-cache", "-f", "Dockerfile", ctx)
  4361. if err == nil {
  4362. c.Fatalf("Expected error. Out: %s", out)
  4363. }
  4364. }
  4365. func (s *DockerSuite) TestBuildSpaces(c *check.C) {
  4366. // Test to make sure that leading/trailing spaces on a command
  4367. // doesn't change the error msg we get
  4368. var (
  4369. err1 error
  4370. err2 error
  4371. )
  4372. name := "testspaces"
  4373. ctx, err := fakeContext("FROM busybox\nCOPY\n",
  4374. map[string]string{
  4375. "Dockerfile": "FROM busybox\nCOPY\n",
  4376. })
  4377. if err != nil {
  4378. c.Fatal(err)
  4379. }
  4380. defer ctx.Close()
  4381. if _, err1 = buildImageFromContext(name, ctx, false); err1 == nil {
  4382. c.Fatal("Build 1 was supposed to fail, but didn't")
  4383. }
  4384. ctx.Add("Dockerfile", "FROM busybox\nCOPY ")
  4385. if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil {
  4386. c.Fatal("Build 2 was supposed to fail, but didn't")
  4387. }
  4388. removeLogTimestamps := func(s string) string {
  4389. return regexp.MustCompile(`time="(.*?)"`).ReplaceAllString(s, `time=[TIMESTAMP]`)
  4390. }
  4391. // Skip over the times
  4392. e1 := removeLogTimestamps(err1.Error())
  4393. e2 := removeLogTimestamps(err2.Error())
  4394. // Ignore whitespace since that's what were verifying doesn't change stuff
  4395. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  4396. c.Fatalf("Build 2's error wasn't the same as build 1's\n1:%s\n2:%s", err1, err2)
  4397. }
  4398. ctx.Add("Dockerfile", "FROM busybox\n COPY")
  4399. if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil {
  4400. c.Fatal("Build 3 was supposed to fail, but didn't")
  4401. }
  4402. // Skip over the times
  4403. e1 = removeLogTimestamps(err1.Error())
  4404. e2 = removeLogTimestamps(err2.Error())
  4405. // Ignore whitespace since that's what were verifying doesn't change stuff
  4406. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  4407. c.Fatalf("Build 3's error wasn't the same as build 1's\n1:%s\n3:%s", err1, err2)
  4408. }
  4409. ctx.Add("Dockerfile", "FROM busybox\n COPY ")
  4410. if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil {
  4411. c.Fatal("Build 4 was supposed to fail, but didn't")
  4412. }
  4413. // Skip over the times
  4414. e1 = removeLogTimestamps(err1.Error())
  4415. e2 = removeLogTimestamps(err2.Error())
  4416. // Ignore whitespace since that's what were verifying doesn't change stuff
  4417. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  4418. c.Fatalf("Build 4's error wasn't the same as build 1's\n1:%s\n4:%s", err1, err2)
  4419. }
  4420. }
  4421. func (s *DockerSuite) TestBuildSpacesWithQuotes(c *check.C) {
  4422. // Test to make sure that spaces in quotes aren't lost
  4423. name := "testspacesquotes"
  4424. dockerfile := `FROM busybox
  4425. RUN echo " \
  4426. foo "`
  4427. _, out, err := buildImageWithOut(name, dockerfile, false)
  4428. if err != nil {
  4429. c.Fatal("Build failed:", err)
  4430. }
  4431. expecting := "\n foo \n"
  4432. if !strings.Contains(out, expecting) {
  4433. c.Fatalf("Bad output: %q expecting to contain %q", out, expecting)
  4434. }
  4435. }
  4436. // #4393
  4437. func (s *DockerSuite) TestBuildVolumeFileExistsinContainer(c *check.C) {
  4438. buildCmd := exec.Command(dockerBinary, "build", "-t", "docker-test-errcreatevolumewithfile", "-")
  4439. buildCmd.Stdin = strings.NewReader(`
  4440. FROM busybox
  4441. RUN touch /foo
  4442. VOLUME /foo
  4443. `)
  4444. out, _, err := runCommandWithOutput(buildCmd)
  4445. if err == nil || !strings.Contains(out, "file exists") {
  4446. c.Fatalf("expected build to fail when file exists in container at requested volume path")
  4447. }
  4448. }
  4449. func (s *DockerSuite) TestBuildMissingArgs(c *check.C) {
  4450. // Test to make sure that all Dockerfile commands (except the ones listed
  4451. // in skipCmds) will generate an error if no args are provided.
  4452. // Note: INSERT is deprecated so we exclude it because of that.
  4453. skipCmds := map[string]struct{}{
  4454. "CMD": {},
  4455. "RUN": {},
  4456. "ENTRYPOINT": {},
  4457. "INSERT": {},
  4458. }
  4459. for cmd := range command.Commands {
  4460. cmd = strings.ToUpper(cmd)
  4461. if _, ok := skipCmds[cmd]; ok {
  4462. continue
  4463. }
  4464. var dockerfile string
  4465. if cmd == "FROM" {
  4466. dockerfile = cmd
  4467. } else {
  4468. // Add FROM to make sure we don't complain about it missing
  4469. dockerfile = "FROM busybox\n" + cmd
  4470. }
  4471. ctx, err := fakeContext(dockerfile, map[string]string{})
  4472. if err != nil {
  4473. c.Fatal(err)
  4474. }
  4475. defer ctx.Close()
  4476. var out string
  4477. if out, err = buildImageFromContext("args", ctx, true); err == nil {
  4478. c.Fatalf("%s was supposed to fail. Out:%s", cmd, out)
  4479. }
  4480. if !strings.Contains(err.Error(), cmd+" requires") {
  4481. c.Fatalf("%s returned the wrong type of error:%s", cmd, err)
  4482. }
  4483. }
  4484. }
  4485. func (s *DockerSuite) TestBuildEmptyScratch(c *check.C) {
  4486. _, out, err := buildImageWithOut("sc", "FROM scratch", true)
  4487. if err == nil {
  4488. c.Fatalf("Build was supposed to fail")
  4489. }
  4490. if !strings.Contains(out, "No image was generated") {
  4491. c.Fatalf("Wrong error message: %v", out)
  4492. }
  4493. }
  4494. func (s *DockerSuite) TestBuildDotDotFile(c *check.C) {
  4495. ctx, err := fakeContext("FROM busybox\n",
  4496. map[string]string{
  4497. "..gitme": "",
  4498. })
  4499. if err != nil {
  4500. c.Fatal(err)
  4501. }
  4502. defer ctx.Close()
  4503. if _, err = buildImageFromContext("sc", ctx, false); err != nil {
  4504. c.Fatalf("Build was supposed to work: %s", err)
  4505. }
  4506. }
  4507. func (s *DockerSuite) TestBuildNotVerbose(c *check.C) {
  4508. ctx, err := fakeContext("FROM busybox\nENV abc=hi\nRUN echo $abc there", map[string]string{})
  4509. if err != nil {
  4510. c.Fatal(err)
  4511. }
  4512. defer ctx.Close()
  4513. // First do it w/verbose - baseline
  4514. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "--no-cache", "-t", "verbose", ".")
  4515. if err != nil {
  4516. c.Fatalf("failed to build the image w/o -q: %s, %v", out, err)
  4517. }
  4518. if !strings.Contains(out, "hi there") {
  4519. c.Fatalf("missing output:%s\n", out)
  4520. }
  4521. // Now do it w/o verbose
  4522. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", "--no-cache", "-q", "-t", "verbose", ".")
  4523. if err != nil {
  4524. c.Fatalf("failed to build the image w/ -q: %s, %v", out, err)
  4525. }
  4526. if strings.Contains(out, "hi there") {
  4527. c.Fatalf("Bad output, should not contain 'hi there':%s", out)
  4528. }
  4529. }
  4530. func (s *DockerSuite) TestBuildRUNoneJSON(c *check.C) {
  4531. name := "testbuildrunonejson"
  4532. ctx, err := fakeContext(`FROM hello-world:frozen
  4533. RUN [ "/hello" ]`, map[string]string{})
  4534. if err != nil {
  4535. c.Fatal(err)
  4536. }
  4537. defer ctx.Close()
  4538. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "--no-cache", "-t", name, ".")
  4539. if err != nil {
  4540. c.Fatalf("failed to build the image: %s, %v", out, err)
  4541. }
  4542. if !strings.Contains(out, "Hello from Docker") {
  4543. c.Fatalf("bad output: %s", out)
  4544. }
  4545. }
  4546. func (s *DockerSuite) TestBuildEmptyStringVolume(c *check.C) {
  4547. name := "testbuildemptystringvolume"
  4548. _, err := buildImage(name, `
  4549. FROM busybox
  4550. ENV foo=""
  4551. VOLUME $foo
  4552. `, false)
  4553. if err == nil {
  4554. c.Fatal("Should have failed to build")
  4555. }
  4556. }
  4557. func (s *DockerSuite) TestBuildContainerWithCgroupParent(c *check.C) {
  4558. testRequires(c, NativeExecDriver)
  4559. testRequires(c, SameHostDaemon)
  4560. cgroupParent := "test"
  4561. data, err := ioutil.ReadFile("/proc/self/cgroup")
  4562. if err != nil {
  4563. c.Fatalf("failed to read '/proc/self/cgroup - %v", err)
  4564. }
  4565. selfCgroupPaths := parseCgroupPaths(string(data))
  4566. _, found := selfCgroupPaths["memory"]
  4567. if !found {
  4568. c.Fatalf("unable to find self cpu cgroup path. CgroupsPath: %v", selfCgroupPaths)
  4569. }
  4570. cmd := exec.Command(dockerBinary, "build", "--cgroup-parent", cgroupParent, "-")
  4571. cmd.Stdin = strings.NewReader(`
  4572. FROM busybox
  4573. RUN cat /proc/self/cgroup
  4574. `)
  4575. out, _, err := runCommandWithOutput(cmd)
  4576. if err != nil {
  4577. c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err)
  4578. }
  4579. }
  4580. func (s *DockerSuite) TestBuildNoDupOutput(c *check.C) {
  4581. // Check to make sure our build output prints the Dockerfile cmd
  4582. // property - there was a bug that caused it to be duplicated on the
  4583. // Step X line
  4584. name := "testbuildnodupoutput"
  4585. _, out, err := buildImageWithOut(name, `
  4586. FROM busybox
  4587. RUN env`, false)
  4588. if err != nil {
  4589. c.Fatalf("Build should have worked: %q", err)
  4590. }
  4591. exp := "\nStep 1 : RUN env\n"
  4592. if !strings.Contains(out, exp) {
  4593. c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", out, exp)
  4594. }
  4595. }
  4596. func (s *DockerSuite) TestBuildBadCmdFlag(c *check.C) {
  4597. name := "testbuildbadcmdflag"
  4598. _, out, err := buildImageWithOut(name, `
  4599. FROM busybox
  4600. MAINTAINER --boo joe@example.com`, false)
  4601. if err == nil {
  4602. c.Fatal("Build should have failed")
  4603. }
  4604. exp := "\nUnknown flag: boo\n"
  4605. if !strings.Contains(out, exp) {
  4606. c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", out, exp)
  4607. }
  4608. }
  4609. func (s *DockerSuite) TestBuildRUNErrMsg(c *check.C) {
  4610. // Test to make sure the bad command is quoted with just "s and
  4611. // not as a Go []string
  4612. name := "testbuildbadrunerrmsg"
  4613. _, out, err := buildImageWithOut(name, `
  4614. FROM busybox
  4615. RUN badEXE a1 \& a2 a3`, false) // tab between a2 and a3
  4616. if err == nil {
  4617. c.Fatal("Should have failed to build")
  4618. }
  4619. exp := `The command '/bin/sh -c badEXE a1 \& a2 a3' returned a non-zero code: 127`
  4620. if !strings.Contains(out, exp) {
  4621. c.Fatalf("RUN doesn't have the correct output:\nGot:%s\nExpected:%s", out, exp)
  4622. }
  4623. }