docker_cli_build_test.go 108 KB

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