docker_cli_build_test.go 126 KB

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