docker_cli_build_test.go 131 KB

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