docker_cli_build_test.go 136 KB

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