docker_cli_build_test.go 105 KB

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