docker_cli_build_test.go 118 KB

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