docker_cli_build_test.go 109 KB

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