docker_cli_build_test.go 127 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981
  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. testRequires(t, SameHostDaemon)
  1849. name := "testbuildcontextcleanup"
  1850. defer deleteImages(name)
  1851. entries, err := ioutil.ReadDir("/var/lib/docker/tmp")
  1852. if err != nil {
  1853. t.Fatalf("failed to list contents of tmp dir: %s", err)
  1854. }
  1855. _, err = buildImage(name,
  1856. `FROM scratch
  1857. ENTRYPOINT ["/bin/echo"]`,
  1858. true)
  1859. if err != nil {
  1860. t.Fatal(err)
  1861. }
  1862. entriesFinal, err := ioutil.ReadDir("/var/lib/docker/tmp")
  1863. if err != nil {
  1864. t.Fatalf("failed to list contents of tmp dir: %s", err)
  1865. }
  1866. if err = compareDirectoryEntries(entries, entriesFinal); err != nil {
  1867. t.Fatalf("context should have been deleted, but wasn't")
  1868. }
  1869. logDone("build - verify context cleanup works properly")
  1870. }
  1871. func TestBuildContextCleanupFailedBuild(t *testing.T) {
  1872. testRequires(t, SameHostDaemon)
  1873. name := "testbuildcontextcleanup"
  1874. defer deleteImages(name)
  1875. defer deleteAllContainers()
  1876. entries, err := ioutil.ReadDir("/var/lib/docker/tmp")
  1877. if err != nil {
  1878. t.Fatalf("failed to list contents of tmp dir: %s", err)
  1879. }
  1880. _, err = buildImage(name,
  1881. `FROM scratch
  1882. RUN /non/existing/command`,
  1883. true)
  1884. if err == nil {
  1885. t.Fatalf("expected build to fail, but it didn't")
  1886. }
  1887. entriesFinal, err := ioutil.ReadDir("/var/lib/docker/tmp")
  1888. if err != nil {
  1889. t.Fatalf("failed to list contents of tmp dir: %s", err)
  1890. }
  1891. if err = compareDirectoryEntries(entries, entriesFinal); err != nil {
  1892. t.Fatalf("context should have been deleted, but wasn't")
  1893. }
  1894. logDone("build - verify context cleanup works properly after an unsuccessful build")
  1895. }
  1896. func TestBuildCmd(t *testing.T) {
  1897. name := "testbuildcmd"
  1898. expected := "[/bin/echo Hello World]"
  1899. defer deleteImages(name)
  1900. _, err := buildImage(name,
  1901. `FROM scratch
  1902. CMD ["/bin/echo", "Hello World"]`,
  1903. true)
  1904. if err != nil {
  1905. t.Fatal(err)
  1906. }
  1907. res, err := inspectField(name, "Config.Cmd")
  1908. if err != nil {
  1909. t.Fatal(err)
  1910. }
  1911. if res != expected {
  1912. t.Fatalf("Cmd %s, expected %s", res, expected)
  1913. }
  1914. logDone("build - cmd")
  1915. }
  1916. func TestBuildExpose(t *testing.T) {
  1917. name := "testbuildexpose"
  1918. expected := "map[2375/tcp:map[]]"
  1919. defer deleteImages(name)
  1920. _, err := buildImage(name,
  1921. `FROM scratch
  1922. EXPOSE 2375`,
  1923. true)
  1924. if err != nil {
  1925. t.Fatal(err)
  1926. }
  1927. res, err := inspectField(name, "Config.ExposedPorts")
  1928. if err != nil {
  1929. t.Fatal(err)
  1930. }
  1931. if res != expected {
  1932. t.Fatalf("Exposed ports %s, expected %s", res, expected)
  1933. }
  1934. logDone("build - expose")
  1935. }
  1936. func TestBuildExposeMorePorts(t *testing.T) {
  1937. // start building docker file with a large number of ports
  1938. portList := make([]string, 50)
  1939. line := make([]string, 100)
  1940. expectedPorts := make([]int, len(portList)*len(line))
  1941. for i := 0; i < len(portList); i++ {
  1942. for j := 0; j < len(line); j++ {
  1943. p := i*len(line) + j + 1
  1944. line[j] = strconv.Itoa(p)
  1945. expectedPorts[p-1] = p
  1946. }
  1947. if i == len(portList)-1 {
  1948. portList[i] = strings.Join(line, " ")
  1949. } else {
  1950. portList[i] = strings.Join(line, " ") + ` \`
  1951. }
  1952. }
  1953. dockerfile := `FROM scratch
  1954. EXPOSE {{range .}} {{.}}
  1955. {{end}}`
  1956. tmpl := template.Must(template.New("dockerfile").Parse(dockerfile))
  1957. buf := bytes.NewBuffer(nil)
  1958. tmpl.Execute(buf, portList)
  1959. name := "testbuildexpose"
  1960. defer deleteImages(name)
  1961. _, err := buildImage(name, buf.String(), true)
  1962. if err != nil {
  1963. t.Fatal(err)
  1964. }
  1965. // check if all the ports are saved inside Config.ExposedPorts
  1966. res, err := inspectFieldJSON(name, "Config.ExposedPorts")
  1967. if err != nil {
  1968. t.Fatal(err)
  1969. }
  1970. var exposedPorts map[string]interface{}
  1971. if err := json.Unmarshal([]byte(res), &exposedPorts); err != nil {
  1972. t.Fatal(err)
  1973. }
  1974. for _, p := range expectedPorts {
  1975. ep := fmt.Sprintf("%d/tcp", p)
  1976. if _, ok := exposedPorts[ep]; !ok {
  1977. t.Errorf("Port(%s) is not exposed", ep)
  1978. } else {
  1979. delete(exposedPorts, ep)
  1980. }
  1981. }
  1982. if len(exposedPorts) != 0 {
  1983. t.Errorf("Unexpected extra exposed ports %v", exposedPorts)
  1984. }
  1985. logDone("build - expose large number of ports")
  1986. }
  1987. func TestBuildExposeOrder(t *testing.T) {
  1988. buildID := func(name, exposed string) string {
  1989. _, err := buildImage(name, fmt.Sprintf(`FROM scratch
  1990. EXPOSE %s`, exposed), true)
  1991. if err != nil {
  1992. t.Fatal(err)
  1993. }
  1994. id, err := inspectField(name, "Id")
  1995. if err != nil {
  1996. t.Fatal(err)
  1997. }
  1998. return id
  1999. }
  2000. id1 := buildID("testbuildexpose1", "80 2375")
  2001. id2 := buildID("testbuildexpose2", "2375 80")
  2002. defer deleteImages("testbuildexpose1", "testbuildexpose2")
  2003. if id1 != id2 {
  2004. t.Errorf("EXPOSE should invalidate the cache only when ports actually changed")
  2005. }
  2006. logDone("build - expose order")
  2007. }
  2008. func TestBuildExposeUpperCaseProto(t *testing.T) {
  2009. name := "testbuildexposeuppercaseproto"
  2010. expected := "map[5678/udp:map[]]"
  2011. defer deleteImages(name)
  2012. _, err := buildImage(name,
  2013. `FROM scratch
  2014. EXPOSE 5678/UDP`,
  2015. true)
  2016. if err != nil {
  2017. t.Fatal(err)
  2018. }
  2019. res, err := inspectField(name, "Config.ExposedPorts")
  2020. if err != nil {
  2021. t.Fatal(err)
  2022. }
  2023. if res != expected {
  2024. t.Fatalf("Exposed ports %s, expected %s", res, expected)
  2025. }
  2026. logDone("build - expose port with upper case proto")
  2027. }
  2028. func TestBuildEmptyEntrypointInheritance(t *testing.T) {
  2029. name := "testbuildentrypointinheritance"
  2030. name2 := "testbuildentrypointinheritance2"
  2031. defer deleteImages(name, name2)
  2032. _, err := buildImage(name,
  2033. `FROM busybox
  2034. ENTRYPOINT ["/bin/echo"]`,
  2035. true)
  2036. if err != nil {
  2037. t.Fatal(err)
  2038. }
  2039. res, err := inspectField(name, "Config.Entrypoint")
  2040. if err != nil {
  2041. t.Fatal(err)
  2042. }
  2043. expected := "[/bin/echo]"
  2044. if res != expected {
  2045. t.Fatalf("Entrypoint %s, expected %s", res, expected)
  2046. }
  2047. _, err = buildImage(name2,
  2048. fmt.Sprintf(`FROM %s
  2049. ENTRYPOINT []`, name),
  2050. true)
  2051. if err != nil {
  2052. t.Fatal(err)
  2053. }
  2054. res, err = inspectField(name2, "Config.Entrypoint")
  2055. if err != nil {
  2056. t.Fatal(err)
  2057. }
  2058. expected = "[]"
  2059. if res != expected {
  2060. t.Fatalf("Entrypoint %s, expected %s", res, expected)
  2061. }
  2062. logDone("build - empty entrypoint inheritance")
  2063. }
  2064. func TestBuildEmptyEntrypoint(t *testing.T) {
  2065. name := "testbuildentrypoint"
  2066. defer deleteImages(name)
  2067. expected := "[]"
  2068. _, err := buildImage(name,
  2069. `FROM busybox
  2070. ENTRYPOINT []`,
  2071. true)
  2072. if err != nil {
  2073. t.Fatal(err)
  2074. }
  2075. res, err := inspectField(name, "Config.Entrypoint")
  2076. if err != nil {
  2077. t.Fatal(err)
  2078. }
  2079. if res != expected {
  2080. t.Fatalf("Entrypoint %s, expected %s", res, expected)
  2081. }
  2082. logDone("build - empty entrypoint")
  2083. }
  2084. func TestBuildEntrypoint(t *testing.T) {
  2085. name := "testbuildentrypoint"
  2086. expected := "[/bin/echo]"
  2087. defer deleteImages(name)
  2088. _, err := buildImage(name,
  2089. `FROM scratch
  2090. ENTRYPOINT ["/bin/echo"]`,
  2091. true)
  2092. if err != nil {
  2093. t.Fatal(err)
  2094. }
  2095. res, err := inspectField(name, "Config.Entrypoint")
  2096. if err != nil {
  2097. t.Fatal(err)
  2098. }
  2099. if res != expected {
  2100. t.Fatalf("Entrypoint %s, expected %s", res, expected)
  2101. }
  2102. logDone("build - entrypoint")
  2103. }
  2104. // #6445 ensure ONBUILD triggers aren't committed to grandchildren
  2105. func TestBuildOnBuildLimitedInheritence(t *testing.T) {
  2106. var (
  2107. out2, out3 string
  2108. )
  2109. {
  2110. name1 := "testonbuildtrigger1"
  2111. dockerfile1 := `
  2112. FROM busybox
  2113. RUN echo "GRANDPARENT"
  2114. ONBUILD RUN echo "ONBUILD PARENT"
  2115. `
  2116. ctx, err := fakeContext(dockerfile1, nil)
  2117. if err != nil {
  2118. t.Fatal(err)
  2119. }
  2120. defer ctx.Close()
  2121. out1, _, err := dockerCmdInDir(t, ctx.Dir, "build", "-t", name1, ".")
  2122. if err != nil {
  2123. t.Fatalf("build failed to complete: %s, %v", out1, err)
  2124. }
  2125. defer deleteImages(name1)
  2126. }
  2127. {
  2128. name2 := "testonbuildtrigger2"
  2129. dockerfile2 := `
  2130. FROM testonbuildtrigger1
  2131. `
  2132. ctx, err := fakeContext(dockerfile2, nil)
  2133. if err != nil {
  2134. t.Fatal(err)
  2135. }
  2136. defer ctx.Close()
  2137. out2, _, err = dockerCmdInDir(t, ctx.Dir, "build", "-t", name2, ".")
  2138. if err != nil {
  2139. t.Fatalf("build failed to complete: %s, %v", out2, err)
  2140. }
  2141. defer deleteImages(name2)
  2142. }
  2143. {
  2144. name3 := "testonbuildtrigger3"
  2145. dockerfile3 := `
  2146. FROM testonbuildtrigger2
  2147. `
  2148. ctx, err := fakeContext(dockerfile3, nil)
  2149. if err != nil {
  2150. t.Fatal(err)
  2151. }
  2152. defer ctx.Close()
  2153. out3, _, err = dockerCmdInDir(t, ctx.Dir, "build", "-t", name3, ".")
  2154. if err != nil {
  2155. t.Fatalf("build failed to complete: %s, %v", out3, err)
  2156. }
  2157. defer deleteImages(name3)
  2158. }
  2159. // ONBUILD should be run in second build.
  2160. if !strings.Contains(out2, "ONBUILD PARENT") {
  2161. t.Fatalf("ONBUILD instruction did not run in child of ONBUILD parent")
  2162. }
  2163. // ONBUILD should *not* be run in third build.
  2164. if strings.Contains(out3, "ONBUILD PARENT") {
  2165. t.Fatalf("ONBUILD instruction ran in grandchild of ONBUILD parent")
  2166. }
  2167. logDone("build - onbuild")
  2168. }
  2169. func TestBuildWithCache(t *testing.T) {
  2170. name := "testbuildwithcache"
  2171. defer deleteImages(name)
  2172. id1, err := buildImage(name,
  2173. `FROM scratch
  2174. MAINTAINER dockerio
  2175. EXPOSE 5432
  2176. ENTRYPOINT ["/bin/echo"]`,
  2177. true)
  2178. if err != nil {
  2179. t.Fatal(err)
  2180. }
  2181. id2, err := buildImage(name,
  2182. `FROM scratch
  2183. MAINTAINER dockerio
  2184. EXPOSE 5432
  2185. ENTRYPOINT ["/bin/echo"]`,
  2186. true)
  2187. if err != nil {
  2188. t.Fatal(err)
  2189. }
  2190. if id1 != id2 {
  2191. t.Fatal("The cache should have been used but hasn't.")
  2192. }
  2193. logDone("build - with cache")
  2194. }
  2195. func TestBuildWithoutCache(t *testing.T) {
  2196. name := "testbuildwithoutcache"
  2197. name2 := "testbuildwithoutcache2"
  2198. defer deleteImages(name, name2)
  2199. id1, err := buildImage(name,
  2200. `FROM scratch
  2201. MAINTAINER dockerio
  2202. EXPOSE 5432
  2203. ENTRYPOINT ["/bin/echo"]`,
  2204. true)
  2205. if err != nil {
  2206. t.Fatal(err)
  2207. }
  2208. id2, err := buildImage(name2,
  2209. `FROM scratch
  2210. MAINTAINER dockerio
  2211. EXPOSE 5432
  2212. ENTRYPOINT ["/bin/echo"]`,
  2213. false)
  2214. if err != nil {
  2215. t.Fatal(err)
  2216. }
  2217. if id1 == id2 {
  2218. t.Fatal("The cache should have been invalided but hasn't.")
  2219. }
  2220. logDone("build - without cache")
  2221. }
  2222. func TestBuildConditionalCache(t *testing.T) {
  2223. name := "testbuildconditionalcache"
  2224. name2 := "testbuildconditionalcache2"
  2225. defer deleteImages(name, name2)
  2226. dockerfile := `
  2227. FROM busybox
  2228. ADD foo /tmp/`
  2229. ctx, err := fakeContext(dockerfile, map[string]string{
  2230. "foo": "hello",
  2231. })
  2232. id1, err := buildImageFromContext(name, ctx, true)
  2233. if err != nil {
  2234. t.Fatalf("Error building #1: %s", err)
  2235. }
  2236. if err := ctx.Add("foo", "bye"); err != nil {
  2237. t.Fatalf("Error modifying foo: %s", err)
  2238. }
  2239. id2, err := buildImageFromContext(name, ctx, false)
  2240. if err != nil {
  2241. t.Fatalf("Error building #2: %s", err)
  2242. }
  2243. if id2 == id1 {
  2244. t.Fatal("Should not have used the cache")
  2245. }
  2246. id3, err := buildImageFromContext(name, ctx, true)
  2247. if err != nil {
  2248. t.Fatalf("Error building #3: %s", err)
  2249. }
  2250. if id3 != id2 {
  2251. t.Fatal("Should have used the cache")
  2252. }
  2253. logDone("build - conditional cache")
  2254. }
  2255. func TestBuildADDLocalFileWithCache(t *testing.T) {
  2256. name := "testbuildaddlocalfilewithcache"
  2257. name2 := "testbuildaddlocalfilewithcache2"
  2258. defer deleteImages(name, name2)
  2259. dockerfile := `
  2260. FROM busybox
  2261. MAINTAINER dockerio
  2262. ADD foo /usr/lib/bla/bar
  2263. RUN [ "$(cat /usr/lib/bla/bar)" = "hello" ]`
  2264. ctx, err := fakeContext(dockerfile, map[string]string{
  2265. "foo": "hello",
  2266. })
  2267. defer ctx.Close()
  2268. if err != nil {
  2269. t.Fatal(err)
  2270. }
  2271. id1, err := buildImageFromContext(name, ctx, true)
  2272. if err != nil {
  2273. t.Fatal(err)
  2274. }
  2275. id2, err := buildImageFromContext(name2, ctx, true)
  2276. if err != nil {
  2277. t.Fatal(err)
  2278. }
  2279. if id1 != id2 {
  2280. t.Fatal("The cache should have been used but hasn't.")
  2281. }
  2282. logDone("build - add local file with cache")
  2283. }
  2284. func TestBuildADDMultipleLocalFileWithCache(t *testing.T) {
  2285. name := "testbuildaddmultiplelocalfilewithcache"
  2286. name2 := "testbuildaddmultiplelocalfilewithcache2"
  2287. defer deleteImages(name, name2)
  2288. dockerfile := `
  2289. FROM busybox
  2290. MAINTAINER dockerio
  2291. ADD foo Dockerfile /usr/lib/bla/
  2292. RUN [ "$(cat /usr/lib/bla/foo)" = "hello" ]`
  2293. ctx, err := fakeContext(dockerfile, map[string]string{
  2294. "foo": "hello",
  2295. })
  2296. defer ctx.Close()
  2297. if err != nil {
  2298. t.Fatal(err)
  2299. }
  2300. id1, err := buildImageFromContext(name, ctx, true)
  2301. if err != nil {
  2302. t.Fatal(err)
  2303. }
  2304. id2, err := buildImageFromContext(name2, ctx, true)
  2305. if err != nil {
  2306. t.Fatal(err)
  2307. }
  2308. if id1 != id2 {
  2309. t.Fatal("The cache should have been used but hasn't.")
  2310. }
  2311. logDone("build - add multiple local files with cache")
  2312. }
  2313. func TestBuildADDLocalFileWithoutCache(t *testing.T) {
  2314. name := "testbuildaddlocalfilewithoutcache"
  2315. name2 := "testbuildaddlocalfilewithoutcache2"
  2316. defer deleteImages(name, name2)
  2317. dockerfile := `
  2318. FROM busybox
  2319. MAINTAINER dockerio
  2320. ADD foo /usr/lib/bla/bar
  2321. RUN [ "$(cat /usr/lib/bla/bar)" = "hello" ]`
  2322. ctx, err := fakeContext(dockerfile, map[string]string{
  2323. "foo": "hello",
  2324. })
  2325. defer ctx.Close()
  2326. if err != nil {
  2327. t.Fatal(err)
  2328. }
  2329. id1, err := buildImageFromContext(name, ctx, true)
  2330. if err != nil {
  2331. t.Fatal(err)
  2332. }
  2333. id2, err := buildImageFromContext(name2, ctx, false)
  2334. if err != nil {
  2335. t.Fatal(err)
  2336. }
  2337. if id1 == id2 {
  2338. t.Fatal("The cache should have been invalided but hasn't.")
  2339. }
  2340. logDone("build - add local file without cache")
  2341. }
  2342. func TestBuildCopyDirButNotFile(t *testing.T) {
  2343. name := "testbuildcopydirbutnotfile"
  2344. name2 := "testbuildcopydirbutnotfile2"
  2345. defer deleteImages(name, name2)
  2346. dockerfile := `
  2347. FROM scratch
  2348. COPY dir /tmp/`
  2349. ctx, err := fakeContext(dockerfile, map[string]string{
  2350. "dir/foo": "hello",
  2351. })
  2352. defer ctx.Close()
  2353. if err != nil {
  2354. t.Fatal(err)
  2355. }
  2356. id1, err := buildImageFromContext(name, ctx, true)
  2357. if err != nil {
  2358. t.Fatal(err)
  2359. }
  2360. // Check that adding file with similar name doesn't mess with cache
  2361. if err := ctx.Add("dir_file", "hello2"); err != nil {
  2362. t.Fatal(err)
  2363. }
  2364. id2, err := buildImageFromContext(name2, ctx, true)
  2365. if err != nil {
  2366. t.Fatal(err)
  2367. }
  2368. if id1 != id2 {
  2369. t.Fatal("The cache should have been used but wasn't")
  2370. }
  2371. logDone("build - add current directory but not file")
  2372. }
  2373. func TestBuildADDCurrentDirWithCache(t *testing.T) {
  2374. name := "testbuildaddcurrentdirwithcache"
  2375. name2 := name + "2"
  2376. name3 := name + "3"
  2377. name4 := name + "4"
  2378. name5 := name + "5"
  2379. defer deleteImages(name, name2, name3, name4, name5)
  2380. dockerfile := `
  2381. FROM scratch
  2382. MAINTAINER dockerio
  2383. ADD . /usr/lib/bla`
  2384. ctx, err := fakeContext(dockerfile, map[string]string{
  2385. "foo": "hello",
  2386. })
  2387. defer ctx.Close()
  2388. if err != nil {
  2389. t.Fatal(err)
  2390. }
  2391. id1, err := buildImageFromContext(name, ctx, true)
  2392. if err != nil {
  2393. t.Fatal(err)
  2394. }
  2395. // Check that adding file invalidate cache of "ADD ."
  2396. if err := ctx.Add("bar", "hello2"); err != nil {
  2397. t.Fatal(err)
  2398. }
  2399. id2, err := buildImageFromContext(name2, ctx, true)
  2400. if err != nil {
  2401. t.Fatal(err)
  2402. }
  2403. if id1 == id2 {
  2404. t.Fatal("The cache should have been invalided but hasn't.")
  2405. }
  2406. // Check that changing file invalidate cache of "ADD ."
  2407. if err := ctx.Add("foo", "hello1"); err != nil {
  2408. t.Fatal(err)
  2409. }
  2410. id3, err := buildImageFromContext(name3, ctx, true)
  2411. if err != nil {
  2412. t.Fatal(err)
  2413. }
  2414. if id2 == id3 {
  2415. t.Fatal("The cache should have been invalided but hasn't.")
  2416. }
  2417. // Check that changing file to same content invalidate cache of "ADD ."
  2418. time.Sleep(1 * time.Second) // wait second because of mtime precision
  2419. if err := ctx.Add("foo", "hello1"); err != nil {
  2420. t.Fatal(err)
  2421. }
  2422. id4, err := buildImageFromContext(name4, ctx, true)
  2423. if err != nil {
  2424. t.Fatal(err)
  2425. }
  2426. if id3 == id4 {
  2427. t.Fatal("The cache should have been invalided but hasn't.")
  2428. }
  2429. id5, err := buildImageFromContext(name5, ctx, true)
  2430. if err != nil {
  2431. t.Fatal(err)
  2432. }
  2433. if id4 != id5 {
  2434. t.Fatal("The cache should have been used but hasn't.")
  2435. }
  2436. logDone("build - add current directory with cache")
  2437. }
  2438. func TestBuildADDCurrentDirWithoutCache(t *testing.T) {
  2439. name := "testbuildaddcurrentdirwithoutcache"
  2440. name2 := "testbuildaddcurrentdirwithoutcache2"
  2441. defer deleteImages(name, name2)
  2442. dockerfile := `
  2443. FROM scratch
  2444. MAINTAINER dockerio
  2445. ADD . /usr/lib/bla`
  2446. ctx, err := fakeContext(dockerfile, map[string]string{
  2447. "foo": "hello",
  2448. })
  2449. defer ctx.Close()
  2450. if err != nil {
  2451. t.Fatal(err)
  2452. }
  2453. id1, err := buildImageFromContext(name, ctx, true)
  2454. if err != nil {
  2455. t.Fatal(err)
  2456. }
  2457. id2, err := buildImageFromContext(name2, ctx, false)
  2458. if err != nil {
  2459. t.Fatal(err)
  2460. }
  2461. if id1 == id2 {
  2462. t.Fatal("The cache should have been invalided but hasn't.")
  2463. }
  2464. logDone("build - add current directory without cache")
  2465. }
  2466. func TestBuildADDRemoteFileWithCache(t *testing.T) {
  2467. name := "testbuildaddremotefilewithcache"
  2468. defer deleteImages(name)
  2469. server, err := fakeStorage(map[string]string{
  2470. "baz": "hello",
  2471. })
  2472. if err != nil {
  2473. t.Fatal(err)
  2474. }
  2475. defer server.Close()
  2476. id1, err := buildImage(name,
  2477. fmt.Sprintf(`FROM scratch
  2478. MAINTAINER dockerio
  2479. ADD %s/baz /usr/lib/baz/quux`, server.URL),
  2480. true)
  2481. if err != nil {
  2482. t.Fatal(err)
  2483. }
  2484. id2, err := buildImage(name,
  2485. fmt.Sprintf(`FROM scratch
  2486. MAINTAINER dockerio
  2487. ADD %s/baz /usr/lib/baz/quux`, server.URL),
  2488. true)
  2489. if err != nil {
  2490. t.Fatal(err)
  2491. }
  2492. if id1 != id2 {
  2493. t.Fatal("The cache should have been used but hasn't.")
  2494. }
  2495. logDone("build - add remote file with cache")
  2496. }
  2497. func TestBuildADDRemoteFileWithoutCache(t *testing.T) {
  2498. name := "testbuildaddremotefilewithoutcache"
  2499. name2 := "testbuildaddremotefilewithoutcache2"
  2500. defer deleteImages(name, name2)
  2501. server, err := fakeStorage(map[string]string{
  2502. "baz": "hello",
  2503. })
  2504. if err != nil {
  2505. t.Fatal(err)
  2506. }
  2507. defer server.Close()
  2508. id1, err := buildImage(name,
  2509. fmt.Sprintf(`FROM scratch
  2510. MAINTAINER dockerio
  2511. ADD %s/baz /usr/lib/baz/quux`, server.URL),
  2512. true)
  2513. if err != nil {
  2514. t.Fatal(err)
  2515. }
  2516. id2, err := buildImage(name2,
  2517. fmt.Sprintf(`FROM scratch
  2518. MAINTAINER dockerio
  2519. ADD %s/baz /usr/lib/baz/quux`, server.URL),
  2520. false)
  2521. if err != nil {
  2522. t.Fatal(err)
  2523. }
  2524. if id1 == id2 {
  2525. t.Fatal("The cache should have been invalided but hasn't.")
  2526. }
  2527. logDone("build - add remote file without cache")
  2528. }
  2529. func TestBuildADDRemoteFileMTime(t *testing.T) {
  2530. name := "testbuildaddremotefilemtime"
  2531. name2 := name + "2"
  2532. name3 := name + "3"
  2533. name4 := name + "4"
  2534. defer deleteImages(name, name2, name3, name4)
  2535. server, err := fakeStorage(map[string]string{"baz": "hello"})
  2536. if err != nil {
  2537. t.Fatal(err)
  2538. }
  2539. defer server.Close()
  2540. ctx, err := fakeContext(fmt.Sprintf(`FROM scratch
  2541. MAINTAINER dockerio
  2542. ADD %s/baz /usr/lib/baz/quux`, server.URL), nil)
  2543. if err != nil {
  2544. t.Fatal(err)
  2545. }
  2546. defer ctx.Close()
  2547. id1, err := buildImageFromContext(name, ctx, true)
  2548. if err != nil {
  2549. t.Fatal(err)
  2550. }
  2551. id2, err := buildImageFromContext(name2, ctx, true)
  2552. if err != nil {
  2553. t.Fatal(err)
  2554. }
  2555. if id1 != id2 {
  2556. t.Fatal("The cache should have been used but wasn't - #1")
  2557. }
  2558. // Now set baz's times to anything else and redo the build
  2559. // This time the cache should not be used
  2560. bazPath := path.Join(server.FakeContext.Dir, "baz")
  2561. err = syscall.UtimesNano(bazPath, make([]syscall.Timespec, 2))
  2562. if err != nil {
  2563. t.Fatalf("Error setting mtime on %q: %v", bazPath, err)
  2564. }
  2565. id3, err := buildImageFromContext(name3, ctx, true)
  2566. if err != nil {
  2567. t.Fatal(err)
  2568. }
  2569. if id1 == id3 {
  2570. t.Fatal("The cache should not have been used but was")
  2571. }
  2572. // And for good measure do it again and make sure cache is used this time
  2573. id4, err := buildImageFromContext(name4, ctx, true)
  2574. if err != nil {
  2575. t.Fatal(err)
  2576. }
  2577. if id3 != id4 {
  2578. t.Fatal("The cache should have been used but wasn't - #2")
  2579. }
  2580. logDone("build - add remote file testing mtime")
  2581. }
  2582. func TestBuildADDLocalAndRemoteFilesWithCache(t *testing.T) {
  2583. name := "testbuildaddlocalandremotefilewithcache"
  2584. defer deleteImages(name)
  2585. server, err := fakeStorage(map[string]string{
  2586. "baz": "hello",
  2587. })
  2588. if err != nil {
  2589. t.Fatal(err)
  2590. }
  2591. defer server.Close()
  2592. ctx, err := fakeContext(fmt.Sprintf(`FROM scratch
  2593. MAINTAINER dockerio
  2594. ADD foo /usr/lib/bla/bar
  2595. ADD %s/baz /usr/lib/baz/quux`, server.URL),
  2596. map[string]string{
  2597. "foo": "hello world",
  2598. })
  2599. if err != nil {
  2600. t.Fatal(err)
  2601. }
  2602. defer ctx.Close()
  2603. id1, err := buildImageFromContext(name, ctx, true)
  2604. if err != nil {
  2605. t.Fatal(err)
  2606. }
  2607. id2, err := buildImageFromContext(name, ctx, true)
  2608. if err != nil {
  2609. t.Fatal(err)
  2610. }
  2611. if id1 != id2 {
  2612. t.Fatal("The cache should have been used but hasn't.")
  2613. }
  2614. logDone("build - add local and remote file with cache")
  2615. }
  2616. func testContextTar(t *testing.T, compression archive.Compression) {
  2617. ctx, err := fakeContext(
  2618. `FROM busybox
  2619. ADD foo /foo
  2620. CMD ["cat", "/foo"]`,
  2621. map[string]string{
  2622. "foo": "bar",
  2623. },
  2624. )
  2625. defer ctx.Close()
  2626. if err != nil {
  2627. t.Fatal(err)
  2628. }
  2629. context, err := archive.Tar(ctx.Dir, compression)
  2630. if err != nil {
  2631. t.Fatalf("failed to build context tar: %v", err)
  2632. }
  2633. name := "contexttar"
  2634. buildCmd := exec.Command(dockerBinary, "build", "-t", name, "-")
  2635. defer deleteImages(name)
  2636. buildCmd.Stdin = context
  2637. if out, _, err := runCommandWithOutput(buildCmd); err != nil {
  2638. t.Fatalf("build failed to complete: %v %v", out, err)
  2639. }
  2640. logDone(fmt.Sprintf("build - build an image with a context tar, compression: %v", compression))
  2641. }
  2642. func TestBuildContextTarGzip(t *testing.T) {
  2643. testContextTar(t, archive.Gzip)
  2644. }
  2645. func TestBuildContextTarNoCompression(t *testing.T) {
  2646. testContextTar(t, archive.Uncompressed)
  2647. }
  2648. func TestBuildNoContext(t *testing.T) {
  2649. buildCmd := exec.Command(dockerBinary, "build", "-t", "nocontext", "-")
  2650. buildCmd.Stdin = strings.NewReader("FROM busybox\nCMD echo ok\n")
  2651. if out, _, err := runCommandWithOutput(buildCmd); err != nil {
  2652. t.Fatalf("build failed to complete: %v %v", out, err)
  2653. }
  2654. if out, _, err := dockerCmd(t, "run", "--rm", "nocontext"); out != "ok\n" || err != nil {
  2655. t.Fatalf("run produced invalid output: %q, expected %q", out, "ok")
  2656. }
  2657. deleteImages("nocontext")
  2658. logDone("build - build an image with no context")
  2659. }
  2660. // TODO: TestCaching
  2661. func TestBuildADDLocalAndRemoteFilesWithoutCache(t *testing.T) {
  2662. name := "testbuildaddlocalandremotefilewithoutcache"
  2663. name2 := "testbuildaddlocalandremotefilewithoutcache2"
  2664. defer deleteImages(name, name2)
  2665. server, err := fakeStorage(map[string]string{
  2666. "baz": "hello",
  2667. })
  2668. if err != nil {
  2669. t.Fatal(err)
  2670. }
  2671. defer server.Close()
  2672. ctx, err := fakeContext(fmt.Sprintf(`FROM scratch
  2673. MAINTAINER dockerio
  2674. ADD foo /usr/lib/bla/bar
  2675. ADD %s/baz /usr/lib/baz/quux`, server.URL),
  2676. map[string]string{
  2677. "foo": "hello world",
  2678. })
  2679. if err != nil {
  2680. t.Fatal(err)
  2681. }
  2682. defer ctx.Close()
  2683. id1, err := buildImageFromContext(name, ctx, true)
  2684. if err != nil {
  2685. t.Fatal(err)
  2686. }
  2687. id2, err := buildImageFromContext(name2, ctx, false)
  2688. if err != nil {
  2689. t.Fatal(err)
  2690. }
  2691. if id1 == id2 {
  2692. t.Fatal("The cache should have been invalided but hasn't.")
  2693. }
  2694. logDone("build - add local and remote file without cache")
  2695. }
  2696. func TestBuildWithVolumeOwnership(t *testing.T) {
  2697. name := "testbuildimg"
  2698. defer deleteImages(name)
  2699. _, err := buildImage(name,
  2700. `FROM busybox:latest
  2701. RUN mkdir /test && chown daemon:daemon /test && chmod 0600 /test
  2702. VOLUME /test`,
  2703. true)
  2704. if err != nil {
  2705. t.Fatal(err)
  2706. }
  2707. cmd := exec.Command(dockerBinary, "run", "--rm", "testbuildimg", "ls", "-la", "/test")
  2708. out, _, err := runCommandWithOutput(cmd)
  2709. if err != nil {
  2710. t.Fatal(out, err)
  2711. }
  2712. if expected := "drw-------"; !strings.Contains(out, expected) {
  2713. t.Fatalf("expected %s received %s", expected, out)
  2714. }
  2715. if expected := "daemon daemon"; !strings.Contains(out, expected) {
  2716. t.Fatalf("expected %s received %s", expected, out)
  2717. }
  2718. logDone("build - volume ownership")
  2719. }
  2720. // testing #1405 - config.Cmd does not get cleaned up if
  2721. // utilizing cache
  2722. func TestBuildEntrypointRunCleanup(t *testing.T) {
  2723. name := "testbuildcmdcleanup"
  2724. defer deleteImages(name)
  2725. if _, err := buildImage(name,
  2726. `FROM busybox
  2727. RUN echo "hello"`,
  2728. true); err != nil {
  2729. t.Fatal(err)
  2730. }
  2731. ctx, err := fakeContext(`FROM busybox
  2732. RUN echo "hello"
  2733. ADD foo /foo
  2734. ENTRYPOINT ["/bin/echo"]`,
  2735. map[string]string{
  2736. "foo": "hello",
  2737. })
  2738. defer ctx.Close()
  2739. if err != nil {
  2740. t.Fatal(err)
  2741. }
  2742. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2743. t.Fatal(err)
  2744. }
  2745. res, err := inspectField(name, "Config.Cmd")
  2746. if err != nil {
  2747. t.Fatal(err)
  2748. }
  2749. // Cmd must be cleaned up
  2750. if expected := "<no value>"; res != expected {
  2751. t.Fatalf("Cmd %s, expected %s", res, expected)
  2752. }
  2753. logDone("build - cleanup cmd after RUN")
  2754. }
  2755. func TestBuildForbiddenContextPath(t *testing.T) {
  2756. name := "testbuildforbidpath"
  2757. defer deleteImages(name)
  2758. ctx, err := fakeContext(`FROM scratch
  2759. ADD ../../ test/
  2760. `,
  2761. map[string]string{
  2762. "test.txt": "test1",
  2763. "other.txt": "other",
  2764. })
  2765. defer ctx.Close()
  2766. if err != nil {
  2767. t.Fatal(err)
  2768. }
  2769. expected := "Forbidden path outside the build context: ../../ "
  2770. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  2771. t.Fatalf("Wrong error: (should contain \"%s\") got:\n%v", expected, err)
  2772. }
  2773. logDone("build - forbidden context path")
  2774. }
  2775. func TestBuildADDFileNotFound(t *testing.T) {
  2776. name := "testbuildaddnotfound"
  2777. defer deleteImages(name)
  2778. ctx, err := fakeContext(`FROM scratch
  2779. ADD foo /usr/local/bar`,
  2780. map[string]string{"bar": "hello"})
  2781. defer ctx.Close()
  2782. if err != nil {
  2783. t.Fatal(err)
  2784. }
  2785. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2786. if !strings.Contains(err.Error(), "foo: no such file or directory") {
  2787. t.Fatalf("Wrong error %v, must be about missing foo file or directory", err)
  2788. }
  2789. } else {
  2790. t.Fatal("Error must not be nil")
  2791. }
  2792. logDone("build - add file not found")
  2793. }
  2794. func TestBuildInheritance(t *testing.T) {
  2795. name := "testbuildinheritance"
  2796. defer deleteImages(name)
  2797. _, err := buildImage(name,
  2798. `FROM scratch
  2799. EXPOSE 2375`,
  2800. true)
  2801. if err != nil {
  2802. t.Fatal(err)
  2803. }
  2804. ports1, err := inspectField(name, "Config.ExposedPorts")
  2805. if err != nil {
  2806. t.Fatal(err)
  2807. }
  2808. _, err = buildImage(name,
  2809. fmt.Sprintf(`FROM %s
  2810. ENTRYPOINT ["/bin/echo"]`, name),
  2811. true)
  2812. if err != nil {
  2813. t.Fatal(err)
  2814. }
  2815. res, err := inspectField(name, "Config.Entrypoint")
  2816. if err != nil {
  2817. t.Fatal(err)
  2818. }
  2819. if expected := "[/bin/echo]"; res != expected {
  2820. t.Fatalf("Entrypoint %s, expected %s", res, expected)
  2821. }
  2822. ports2, err := inspectField(name, "Config.ExposedPorts")
  2823. if err != nil {
  2824. t.Fatal(err)
  2825. }
  2826. if ports1 != ports2 {
  2827. t.Fatalf("Ports must be same: %s != %s", ports1, ports2)
  2828. }
  2829. logDone("build - inheritance")
  2830. }
  2831. func TestBuildFails(t *testing.T) {
  2832. name := "testbuildfails"
  2833. defer deleteImages(name)
  2834. defer deleteAllContainers()
  2835. _, err := buildImage(name,
  2836. `FROM busybox
  2837. RUN sh -c "exit 23"`,
  2838. true)
  2839. if err != nil {
  2840. if !strings.Contains(err.Error(), "returned a non-zero code: 23") {
  2841. t.Fatalf("Wrong error %v, must be about non-zero code 23", err)
  2842. }
  2843. } else {
  2844. t.Fatal("Error must not be nil")
  2845. }
  2846. logDone("build - unsuccessful")
  2847. }
  2848. func TestBuildFailsDockerfileEmpty(t *testing.T) {
  2849. name := "testbuildfails"
  2850. defer deleteImages(name)
  2851. _, err := buildImage(name, ``, true)
  2852. if err != nil {
  2853. if !strings.Contains(err.Error(), "Dockerfile cannot be empty") {
  2854. t.Fatalf("Wrong error %v, must be about empty Dockerfile", err)
  2855. }
  2856. } else {
  2857. t.Fatal("Error must not be nil")
  2858. }
  2859. logDone("build - unsuccessful with empty dockerfile")
  2860. }
  2861. func TestBuildOnBuild(t *testing.T) {
  2862. name := "testbuildonbuild"
  2863. defer deleteImages(name)
  2864. _, err := buildImage(name,
  2865. `FROM busybox
  2866. ONBUILD RUN touch foobar`,
  2867. true)
  2868. if err != nil {
  2869. t.Fatal(err)
  2870. }
  2871. _, err = buildImage(name,
  2872. fmt.Sprintf(`FROM %s
  2873. RUN [ -f foobar ]`, name),
  2874. true)
  2875. if err != nil {
  2876. t.Fatal(err)
  2877. }
  2878. logDone("build - onbuild")
  2879. }
  2880. func TestBuildOnBuildForbiddenChained(t *testing.T) {
  2881. name := "testbuildonbuildforbiddenchained"
  2882. defer deleteImages(name)
  2883. _, err := buildImage(name,
  2884. `FROM busybox
  2885. ONBUILD ONBUILD RUN touch foobar`,
  2886. true)
  2887. if err != nil {
  2888. if !strings.Contains(err.Error(), "Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed") {
  2889. t.Fatalf("Wrong error %v, must be about chaining ONBUILD", err)
  2890. }
  2891. } else {
  2892. t.Fatal("Error must not be nil")
  2893. }
  2894. logDone("build - onbuild forbidden chained")
  2895. }
  2896. func TestBuildOnBuildForbiddenFrom(t *testing.T) {
  2897. name := "testbuildonbuildforbiddenfrom"
  2898. defer deleteImages(name)
  2899. _, err := buildImage(name,
  2900. `FROM busybox
  2901. ONBUILD FROM scratch`,
  2902. true)
  2903. if err != nil {
  2904. if !strings.Contains(err.Error(), "FROM isn't allowed as an ONBUILD trigger") {
  2905. t.Fatalf("Wrong error %v, must be about FROM forbidden", err)
  2906. }
  2907. } else {
  2908. t.Fatal("Error must not be nil")
  2909. }
  2910. logDone("build - onbuild forbidden from")
  2911. }
  2912. func TestBuildOnBuildForbiddenMaintainer(t *testing.T) {
  2913. name := "testbuildonbuildforbiddenmaintainer"
  2914. defer deleteImages(name)
  2915. _, err := buildImage(name,
  2916. `FROM busybox
  2917. ONBUILD MAINTAINER docker.io`,
  2918. true)
  2919. if err != nil {
  2920. if !strings.Contains(err.Error(), "MAINTAINER isn't allowed as an ONBUILD trigger") {
  2921. t.Fatalf("Wrong error %v, must be about MAINTAINER forbidden", err)
  2922. }
  2923. } else {
  2924. t.Fatal("Error must not be nil")
  2925. }
  2926. logDone("build - onbuild forbidden maintainer")
  2927. }
  2928. // gh #2446
  2929. func TestBuildAddToSymlinkDest(t *testing.T) {
  2930. name := "testbuildaddtosymlinkdest"
  2931. defer deleteImages(name)
  2932. ctx, err := fakeContext(`FROM busybox
  2933. RUN mkdir /foo
  2934. RUN ln -s /foo /bar
  2935. ADD foo /bar/
  2936. RUN [ -f /bar/foo ]
  2937. RUN [ -f /foo/foo ]`,
  2938. map[string]string{
  2939. "foo": "hello",
  2940. })
  2941. if err != nil {
  2942. t.Fatal(err)
  2943. }
  2944. defer ctx.Close()
  2945. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2946. t.Fatal(err)
  2947. }
  2948. logDone("build - add to symlink destination")
  2949. }
  2950. func TestBuildEscapeWhitespace(t *testing.T) {
  2951. name := "testbuildescaping"
  2952. defer deleteImages(name)
  2953. _, err := buildImage(name, `
  2954. FROM busybox
  2955. MAINTAINER "Docker \
  2956. IO <io@\
  2957. docker.com>"
  2958. `, true)
  2959. res, err := inspectField(name, "Author")
  2960. if err != nil {
  2961. t.Fatal(err)
  2962. }
  2963. if res != "\"Docker IO <io@docker.com>\"" {
  2964. t.Fatalf("Parsed string did not match the escaped string. Got: %q", res)
  2965. }
  2966. logDone("build - validate escaping whitespace")
  2967. }
  2968. func TestBuildVerifyIntString(t *testing.T) {
  2969. // Verify that strings that look like ints are still passed as strings
  2970. name := "testbuildstringing"
  2971. defer deleteImages(name)
  2972. _, err := buildImage(name, `
  2973. FROM busybox
  2974. MAINTAINER 123
  2975. `, true)
  2976. out, rc, err := runCommandWithOutput(exec.Command(dockerBinary, "inspect", name))
  2977. if rc != 0 || err != nil {
  2978. t.Fatalf("Unexcepted error from inspect: rc: %v err: %v", rc, err)
  2979. }
  2980. if !strings.Contains(out, "\"123\"") {
  2981. t.Fatalf("Output does not contain the int as a string:\n%s", out)
  2982. }
  2983. logDone("build - verify int/strings as strings")
  2984. }
  2985. func TestBuildDockerignore(t *testing.T) {
  2986. name := "testbuilddockerignore"
  2987. defer deleteImages(name)
  2988. dockerfile := `
  2989. FROM busybox
  2990. ADD . /bla
  2991. RUN [[ -f /bla/src/x.go ]]
  2992. RUN [[ -f /bla/Makefile ]]
  2993. RUN [[ ! -e /bla/src/_vendor ]]
  2994. RUN [[ ! -e /bla/.gitignore ]]
  2995. RUN [[ ! -e /bla/README.md ]]
  2996. RUN [[ ! -e /bla/.git ]]`
  2997. ctx, err := fakeContext(dockerfile, map[string]string{
  2998. "Makefile": "all:",
  2999. ".git/HEAD": "ref: foo",
  3000. "src/x.go": "package main",
  3001. "src/_vendor/v.go": "package main",
  3002. ".gitignore": "",
  3003. "README.md": "readme",
  3004. ".dockerignore": ".git\npkg\n.gitignore\nsrc/_vendor\n*.md",
  3005. })
  3006. defer ctx.Close()
  3007. if err != nil {
  3008. t.Fatal(err)
  3009. }
  3010. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3011. t.Fatal(err)
  3012. }
  3013. logDone("build - test .dockerignore")
  3014. }
  3015. func TestBuildDockerignoreCleanPaths(t *testing.T) {
  3016. name := "testbuilddockerignorecleanpaths"
  3017. defer deleteImages(name)
  3018. dockerfile := `
  3019. FROM busybox
  3020. ADD . /tmp/
  3021. RUN (! ls /tmp/foo) && (! ls /tmp/foo2) && (! ls /tmp/dir1/foo)`
  3022. ctx, err := fakeContext(dockerfile, map[string]string{
  3023. "foo": "foo",
  3024. "foo2": "foo2",
  3025. "dir1/foo": "foo in dir1",
  3026. ".dockerignore": "./foo\ndir1//foo\n./dir1/../foo2",
  3027. })
  3028. if err != nil {
  3029. t.Fatal(err)
  3030. }
  3031. defer ctx.Close()
  3032. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3033. t.Fatal(err)
  3034. }
  3035. logDone("build - test .dockerignore with clean paths")
  3036. }
  3037. func TestBuildDockerignoringDockerfile(t *testing.T) {
  3038. name := "testbuilddockerignoredockerfile"
  3039. defer deleteImages(name)
  3040. dockerfile := `
  3041. FROM busybox
  3042. ADD . /tmp/
  3043. RUN ! ls /tmp/Dockerfile
  3044. RUN ls /tmp/.dockerignore`
  3045. ctx, err := fakeContext(dockerfile, map[string]string{
  3046. "Dockerfile": dockerfile,
  3047. ".dockerignore": "Dockerfile\n",
  3048. })
  3049. if err != nil {
  3050. t.Fatal(err)
  3051. }
  3052. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3053. t.Fatalf("Didn't ignore Dockerfile correctly:%s", err)
  3054. }
  3055. // now try it with ./Dockerfile
  3056. ctx.Add(".dockerignore", "./Dockerfile\n")
  3057. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3058. t.Fatalf("Didn't ignore ./Dockerfile correctly:%s", err)
  3059. }
  3060. logDone("build - test .dockerignore of Dockerfile")
  3061. }
  3062. func TestBuildDockerignoringRenamedDockerfile(t *testing.T) {
  3063. name := "testbuilddockerignoredockerfile"
  3064. defer deleteImages(name)
  3065. dockerfile := `
  3066. FROM busybox
  3067. ADD . /tmp/
  3068. RUN ls /tmp/Dockerfile
  3069. RUN ! ls /tmp/MyDockerfile
  3070. RUN ls /tmp/.dockerignore`
  3071. ctx, err := fakeContext(dockerfile, map[string]string{
  3072. "Dockerfile": "Should not use me",
  3073. "MyDockerfile": dockerfile,
  3074. ".dockerignore": "MyDockerfile\n",
  3075. })
  3076. if err != nil {
  3077. t.Fatal(err)
  3078. }
  3079. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3080. t.Fatalf("Didn't ignore MyDockerfile correctly:%s", err)
  3081. }
  3082. // now try it with ./MyDockerfile
  3083. ctx.Add(".dockerignore", "./MyDockerfile\n")
  3084. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3085. t.Fatalf("Didn't ignore ./MyDockerfile correctly:%s", err)
  3086. }
  3087. logDone("build - test .dockerignore of renamed Dockerfile")
  3088. }
  3089. func TestBuildDockerignoringDockerignore(t *testing.T) {
  3090. name := "testbuilddockerignoredockerignore"
  3091. defer deleteImages(name)
  3092. dockerfile := `
  3093. FROM busybox
  3094. ADD . /tmp/
  3095. RUN ! ls /tmp/.dockerignore
  3096. RUN ls /tmp/Dockerfile`
  3097. ctx, err := fakeContext(dockerfile, map[string]string{
  3098. "Dockerfile": dockerfile,
  3099. ".dockerignore": ".dockerignore\n",
  3100. })
  3101. defer ctx.Close()
  3102. if err != nil {
  3103. t.Fatal(err)
  3104. }
  3105. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3106. t.Fatalf("Didn't ignore .dockerignore correctly:%s", err)
  3107. }
  3108. logDone("build - test .dockerignore of .dockerignore")
  3109. }
  3110. func TestBuildDockerignoreTouchDockerfile(t *testing.T) {
  3111. var id1 string
  3112. var id2 string
  3113. name := "testbuilddockerignoretouchdockerfile"
  3114. defer deleteImages(name)
  3115. dockerfile := `
  3116. FROM busybox
  3117. ADD . /tmp/`
  3118. ctx, err := fakeContext(dockerfile, map[string]string{
  3119. "Dockerfile": dockerfile,
  3120. ".dockerignore": "Dockerfile\n",
  3121. })
  3122. defer ctx.Close()
  3123. if err != nil {
  3124. t.Fatal(err)
  3125. }
  3126. if id1, err = buildImageFromContext(name, ctx, true); err != nil {
  3127. t.Fatalf("Didn't build it correctly:%s", err)
  3128. }
  3129. if id2, err = buildImageFromContext(name, ctx, true); err != nil {
  3130. t.Fatalf("Didn't build it correctly:%s", err)
  3131. }
  3132. if id1 != id2 {
  3133. t.Fatalf("Didn't use the cache - 1")
  3134. }
  3135. // Now make sure touching Dockerfile doesn't invalidate the cache
  3136. if err = ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil {
  3137. t.Fatalf("Didn't add Dockerfile: %s", err)
  3138. }
  3139. if id2, err = buildImageFromContext(name, ctx, true); err != nil {
  3140. t.Fatalf("Didn't build it correctly:%s", err)
  3141. }
  3142. if id1 != id2 {
  3143. t.Fatalf("Didn't use the cache - 2")
  3144. }
  3145. // One more time but just 'touch' it instead of changing the content
  3146. if err = ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil {
  3147. t.Fatalf("Didn't add Dockerfile: %s", err)
  3148. }
  3149. if id2, err = buildImageFromContext(name, ctx, true); err != nil {
  3150. t.Fatalf("Didn't build it correctly:%s", err)
  3151. }
  3152. if id1 != id2 {
  3153. t.Fatalf("Didn't use the cache - 3")
  3154. }
  3155. logDone("build - test .dockerignore touch dockerfile")
  3156. }
  3157. func TestBuildDockerignoringWholeDir(t *testing.T) {
  3158. name := "testbuilddockerignorewholedir"
  3159. defer deleteImages(name)
  3160. dockerfile := `
  3161. FROM busybox
  3162. COPY . /
  3163. RUN [[ ! -e /.gitignore ]]
  3164. RUN [[ -f /Makefile ]]`
  3165. ctx, err := fakeContext(dockerfile, map[string]string{
  3166. "Dockerfile": "FROM scratch",
  3167. "Makefile": "all:",
  3168. ".dockerignore": ".*\n",
  3169. })
  3170. defer ctx.Close()
  3171. if err != nil {
  3172. t.Fatal(err)
  3173. }
  3174. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3175. t.Fatal(err)
  3176. }
  3177. logDone("build - test .dockerignore whole dir with .*")
  3178. }
  3179. func TestBuildLineBreak(t *testing.T) {
  3180. name := "testbuildlinebreak"
  3181. defer deleteImages(name)
  3182. _, err := buildImage(name,
  3183. `FROM busybox
  3184. RUN sh -c 'echo root:testpass \
  3185. > /tmp/passwd'
  3186. RUN mkdir -p /var/run/sshd
  3187. RUN [ "$(cat /tmp/passwd)" = "root:testpass" ]
  3188. RUN [ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]`,
  3189. true)
  3190. if err != nil {
  3191. t.Fatal(err)
  3192. }
  3193. logDone("build - line break with \\")
  3194. }
  3195. func TestBuildEOLInLine(t *testing.T) {
  3196. name := "testbuildeolinline"
  3197. defer deleteImages(name)
  3198. _, err := buildImage(name,
  3199. `FROM busybox
  3200. RUN sh -c 'echo root:testpass > /tmp/passwd'
  3201. RUN echo "foo \n bar"; echo "baz"
  3202. RUN mkdir -p /var/run/sshd
  3203. RUN [ "$(cat /tmp/passwd)" = "root:testpass" ]
  3204. RUN [ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]`,
  3205. true)
  3206. if err != nil {
  3207. t.Fatal(err)
  3208. }
  3209. logDone("build - end of line in dockerfile instruction")
  3210. }
  3211. func TestBuildCommentsShebangs(t *testing.T) {
  3212. name := "testbuildcomments"
  3213. defer deleteImages(name)
  3214. _, err := buildImage(name,
  3215. `FROM busybox
  3216. # This is an ordinary comment.
  3217. RUN { echo '#!/bin/sh'; echo 'echo hello world'; } > /hello.sh
  3218. RUN [ ! -x /hello.sh ]
  3219. # comment with line break \
  3220. RUN chmod +x /hello.sh
  3221. RUN [ -x /hello.sh ]
  3222. RUN [ "$(cat /hello.sh)" = $'#!/bin/sh\necho hello world' ]
  3223. RUN [ "$(/hello.sh)" = "hello world" ]`,
  3224. true)
  3225. if err != nil {
  3226. t.Fatal(err)
  3227. }
  3228. logDone("build - comments and shebangs")
  3229. }
  3230. func TestBuildUsersAndGroups(t *testing.T) {
  3231. name := "testbuildusers"
  3232. defer deleteImages(name)
  3233. _, err := buildImage(name,
  3234. `FROM busybox
  3235. # Make sure our defaults work
  3236. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)" = '0:0/root:root' ]
  3237. # 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)
  3238. USER root
  3239. RUN [ "$(id -G):$(id -Gn)" = '0 10:root wheel' ]
  3240. # Setup dockerio user and group
  3241. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  3242. RUN echo 'dockerio:x:1001:' >> /etc/group
  3243. # Make sure we can switch to our user and all the information is exactly as we expect it to be
  3244. USER dockerio
  3245. RUN id -G
  3246. RUN id -Gn
  3247. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3248. # Switch back to root and double check that worked exactly as we might expect it to
  3249. USER root
  3250. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '0:0/root:root/0 10:root wheel' ]
  3251. # Add a "supplementary" group for our dockerio user
  3252. RUN echo 'supplementary:x:1002:dockerio' >> /etc/group
  3253. # ... and then go verify that we get it like we expect
  3254. USER dockerio
  3255. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  3256. USER 1001
  3257. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  3258. # super test the new "user:group" syntax
  3259. USER dockerio:dockerio
  3260. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3261. USER 1001:dockerio
  3262. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3263. USER dockerio:1001
  3264. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3265. USER 1001:1001
  3266. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3267. USER dockerio:supplementary
  3268. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3269. USER dockerio:1002
  3270. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3271. USER 1001:supplementary
  3272. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3273. USER 1001:1002
  3274. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3275. # make sure unknown uid/gid still works properly
  3276. USER 1042:1043
  3277. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1042:1043/1042:1043/1043:1043' ]`,
  3278. true)
  3279. if err != nil {
  3280. t.Fatal(err)
  3281. }
  3282. logDone("build - users and groups")
  3283. }
  3284. func TestBuildEnvUsage(t *testing.T) {
  3285. name := "testbuildenvusage"
  3286. defer deleteImages(name)
  3287. dockerfile := `FROM busybox
  3288. ENV HOME /root
  3289. ENV PATH $HOME/bin:$PATH
  3290. ENV PATH /tmp:$PATH
  3291. RUN [ "$PATH" = "/tmp:$HOME/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ]
  3292. ENV FOO /foo/baz
  3293. ENV BAR /bar
  3294. ENV BAZ $BAR
  3295. ENV FOOPATH $PATH:$FOO
  3296. RUN [ "$BAR" = "$BAZ" ]
  3297. RUN [ "$FOOPATH" = "$PATH:/foo/baz" ]
  3298. ENV FROM hello/docker/world
  3299. ENV TO /docker/world/hello
  3300. ADD $FROM $TO
  3301. RUN [ "$(cat $TO)" = "hello" ]
  3302. ENV abc=def
  3303. ENV ghi=$abc
  3304. RUN [ "$ghi" = "def" ]
  3305. `
  3306. ctx, err := fakeContext(dockerfile, map[string]string{
  3307. "hello/docker/world": "hello",
  3308. })
  3309. if err != nil {
  3310. t.Fatal(err)
  3311. }
  3312. defer ctx.Close()
  3313. _, err = buildImageFromContext(name, ctx, true)
  3314. if err != nil {
  3315. t.Fatal(err)
  3316. }
  3317. logDone("build - environment variables usage")
  3318. }
  3319. func TestBuildEnvUsage2(t *testing.T) {
  3320. name := "testbuildenvusage2"
  3321. defer deleteImages(name)
  3322. dockerfile := `FROM busybox
  3323. ENV abc=def
  3324. RUN [ "$abc" = "def" ]
  3325. ENV def="hello world"
  3326. RUN [ "$def" = "hello world" ]
  3327. ENV def=hello\ world
  3328. RUN [ "$def" = "hello world" ]
  3329. ENV v1=abc v2="hi there"
  3330. RUN [ "$v1" = "abc" ]
  3331. RUN [ "$v2" = "hi there" ]
  3332. ENV v3='boogie nights' v4="with'quotes too"
  3333. RUN [ "$v3" = "boogie nights" ]
  3334. RUN [ "$v4" = "with'quotes too" ]
  3335. ENV abc=zzz FROM=hello/docker/world
  3336. ENV abc=zzz TO=/docker/world/hello
  3337. ADD $FROM $TO
  3338. RUN [ "$(cat $TO)" = "hello" ]
  3339. ENV abc "zzz"
  3340. RUN [ $abc = \"zzz\" ]
  3341. ENV abc 'yyy'
  3342. RUN [ $abc = \'yyy\' ]
  3343. ENV abc=
  3344. RUN [ "$abc" = "" ]
  3345. # use grep to make sure if the builder substitutes \$foo by mistake
  3346. # we don't get a false positive
  3347. ENV abc=\$foo
  3348. RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep foo)
  3349. ENV abc \$foo
  3350. RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep 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. ENV abc \"foo\"
  3362. RUN [ "$abc" = "\\\"foo\\\"" ]
  3363. `
  3364. ctx, err := fakeContext(dockerfile, map[string]string{
  3365. "hello/docker/world": "hello",
  3366. })
  3367. if err != nil {
  3368. t.Fatal(err)
  3369. }
  3370. _, err = buildImageFromContext(name, ctx, true)
  3371. if err != nil {
  3372. t.Fatal(err)
  3373. }
  3374. logDone("build - environment variables usage2")
  3375. }
  3376. func TestBuildAddScript(t *testing.T) {
  3377. name := "testbuildaddscript"
  3378. defer deleteImages(name)
  3379. dockerfile := `
  3380. FROM busybox
  3381. ADD test /test
  3382. RUN ["chmod","+x","/test"]
  3383. RUN ["/test"]
  3384. RUN [ "$(cat /testfile)" = 'test!' ]`
  3385. ctx, err := fakeContext(dockerfile, map[string]string{
  3386. "test": "#!/bin/sh\necho 'test!' > /testfile",
  3387. })
  3388. if err != nil {
  3389. t.Fatal(err)
  3390. }
  3391. defer ctx.Close()
  3392. _, err = buildImageFromContext(name, ctx, true)
  3393. if err != nil {
  3394. t.Fatal(err)
  3395. }
  3396. logDone("build - add and run script")
  3397. }
  3398. func TestBuildAddTar(t *testing.T) {
  3399. name := "testbuildaddtar"
  3400. defer deleteImages(name)
  3401. ctx := func() *FakeContext {
  3402. dockerfile := `
  3403. FROM busybox
  3404. ADD test.tar /
  3405. RUN cat /test/foo | grep Hi
  3406. ADD test.tar /test.tar
  3407. RUN cat /test.tar/test/foo | grep Hi
  3408. ADD test.tar /unlikely-to-exist
  3409. RUN cat /unlikely-to-exist/test/foo | grep Hi
  3410. ADD test.tar /unlikely-to-exist-trailing-slash/
  3411. RUN cat /unlikely-to-exist-trailing-slash/test/foo | grep Hi
  3412. RUN mkdir /existing-directory
  3413. ADD test.tar /existing-directory
  3414. RUN cat /existing-directory/test/foo | grep Hi
  3415. ADD test.tar /existing-directory-trailing-slash/
  3416. RUN cat /existing-directory-trailing-slash/test/foo | grep Hi`
  3417. tmpDir, err := ioutil.TempDir("", "fake-context")
  3418. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3419. if err != nil {
  3420. t.Fatalf("failed to create test.tar archive: %v", err)
  3421. }
  3422. defer testTar.Close()
  3423. tw := tar.NewWriter(testTar)
  3424. if err := tw.WriteHeader(&tar.Header{
  3425. Name: "test/foo",
  3426. Size: 2,
  3427. }); err != nil {
  3428. t.Fatalf("failed to write tar file header: %v", err)
  3429. }
  3430. if _, err := tw.Write([]byte("Hi")); err != nil {
  3431. t.Fatalf("failed to write tar file content: %v", err)
  3432. }
  3433. if err := tw.Close(); err != nil {
  3434. t.Fatalf("failed to close tar archive: %v", err)
  3435. }
  3436. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3437. t.Fatalf("failed to open destination dockerfile: %v", err)
  3438. }
  3439. return &FakeContext{Dir: tmpDir}
  3440. }()
  3441. defer ctx.Close()
  3442. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3443. t.Fatalf("build failed to complete for TestBuildAddTar: %v", err)
  3444. }
  3445. logDone("build - ADD tar")
  3446. }
  3447. func TestBuildAddTarXz(t *testing.T) {
  3448. name := "testbuildaddtarxz"
  3449. defer deleteImages(name)
  3450. ctx := func() *FakeContext {
  3451. dockerfile := `
  3452. FROM busybox
  3453. ADD test.tar.xz /
  3454. RUN cat /test/foo | grep Hi`
  3455. tmpDir, err := ioutil.TempDir("", "fake-context")
  3456. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3457. if err != nil {
  3458. t.Fatalf("failed to create test.tar archive: %v", err)
  3459. }
  3460. defer testTar.Close()
  3461. tw := tar.NewWriter(testTar)
  3462. if err := tw.WriteHeader(&tar.Header{
  3463. Name: "test/foo",
  3464. Size: 2,
  3465. }); err != nil {
  3466. t.Fatalf("failed to write tar file header: %v", err)
  3467. }
  3468. if _, err := tw.Write([]byte("Hi")); err != nil {
  3469. t.Fatalf("failed to write tar file content: %v", err)
  3470. }
  3471. if err := tw.Close(); err != nil {
  3472. t.Fatalf("failed to close tar archive: %v", err)
  3473. }
  3474. xzCompressCmd := exec.Command("xz", "-k", "test.tar")
  3475. xzCompressCmd.Dir = tmpDir
  3476. out, _, err := runCommandWithOutput(xzCompressCmd)
  3477. if err != nil {
  3478. t.Fatal(err, out)
  3479. }
  3480. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3481. t.Fatalf("failed to open destination dockerfile: %v", err)
  3482. }
  3483. return &FakeContext{Dir: tmpDir}
  3484. }()
  3485. defer ctx.Close()
  3486. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3487. t.Fatalf("build failed to complete for TestBuildAddTarXz: %v", err)
  3488. }
  3489. logDone("build - ADD tar.xz")
  3490. }
  3491. func TestBuildAddTarXzGz(t *testing.T) {
  3492. name := "testbuildaddtarxzgz"
  3493. defer deleteImages(name)
  3494. ctx := func() *FakeContext {
  3495. dockerfile := `
  3496. FROM busybox
  3497. ADD test.tar.xz.gz /
  3498. RUN ls /test.tar.xz.gz`
  3499. tmpDir, err := ioutil.TempDir("", "fake-context")
  3500. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3501. if err != nil {
  3502. t.Fatalf("failed to create test.tar archive: %v", err)
  3503. }
  3504. defer testTar.Close()
  3505. tw := tar.NewWriter(testTar)
  3506. if err := tw.WriteHeader(&tar.Header{
  3507. Name: "test/foo",
  3508. Size: 2,
  3509. }); err != nil {
  3510. t.Fatalf("failed to write tar file header: %v", err)
  3511. }
  3512. if _, err := tw.Write([]byte("Hi")); err != nil {
  3513. t.Fatalf("failed to write tar file content: %v", err)
  3514. }
  3515. if err := tw.Close(); err != nil {
  3516. t.Fatalf("failed to close tar archive: %v", err)
  3517. }
  3518. xzCompressCmd := exec.Command("xz", "-k", "test.tar")
  3519. xzCompressCmd.Dir = tmpDir
  3520. out, _, err := runCommandWithOutput(xzCompressCmd)
  3521. if err != nil {
  3522. t.Fatal(err, out)
  3523. }
  3524. gzipCompressCmd := exec.Command("gzip", "test.tar.xz")
  3525. gzipCompressCmd.Dir = tmpDir
  3526. out, _, err = runCommandWithOutput(gzipCompressCmd)
  3527. if err != nil {
  3528. t.Fatal(err, out)
  3529. }
  3530. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3531. t.Fatalf("failed to open destination dockerfile: %v", err)
  3532. }
  3533. return &FakeContext{Dir: tmpDir}
  3534. }()
  3535. defer ctx.Close()
  3536. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3537. t.Fatalf("build failed to complete for TestBuildAddTarXz: %v", err)
  3538. }
  3539. logDone("build - ADD tar.xz.gz")
  3540. }
  3541. func TestBuildFromGIT(t *testing.T) {
  3542. name := "testbuildfromgit"
  3543. defer deleteImages(name)
  3544. git, err := fakeGIT("repo", map[string]string{
  3545. "Dockerfile": `FROM busybox
  3546. ADD first /first
  3547. RUN [ -f /first ]
  3548. MAINTAINER docker`,
  3549. "first": "test git data",
  3550. })
  3551. if err != nil {
  3552. t.Fatal(err)
  3553. }
  3554. defer git.Close()
  3555. _, err = buildImageFromPath(name, git.RepoURL, true)
  3556. if err != nil {
  3557. t.Fatal(err)
  3558. }
  3559. res, err := inspectField(name, "Author")
  3560. if err != nil {
  3561. t.Fatal(err)
  3562. }
  3563. if res != "docker" {
  3564. t.Fatalf("Maintainer should be docker, got %s", res)
  3565. }
  3566. logDone("build - build from GIT")
  3567. }
  3568. func TestBuildCleanupCmdOnEntrypoint(t *testing.T) {
  3569. name := "testbuildcmdcleanuponentrypoint"
  3570. defer deleteImages(name)
  3571. if _, err := buildImage(name,
  3572. `FROM scratch
  3573. CMD ["test"]
  3574. ENTRYPOINT ["echo"]`,
  3575. true); err != nil {
  3576. t.Fatal(err)
  3577. }
  3578. if _, err := buildImage(name,
  3579. fmt.Sprintf(`FROM %s
  3580. ENTRYPOINT ["cat"]`, name),
  3581. true); err != nil {
  3582. t.Fatal(err)
  3583. }
  3584. res, err := inspectField(name, "Config.Cmd")
  3585. if err != nil {
  3586. t.Fatal(err)
  3587. }
  3588. if expected := "<no value>"; res != expected {
  3589. t.Fatalf("Cmd %s, expected %s", res, expected)
  3590. }
  3591. res, err = inspectField(name, "Config.Entrypoint")
  3592. if err != nil {
  3593. t.Fatal(err)
  3594. }
  3595. if expected := "[cat]"; res != expected {
  3596. t.Fatalf("Entrypoint %s, expected %s", res, expected)
  3597. }
  3598. logDone("build - cleanup cmd on ENTRYPOINT")
  3599. }
  3600. func TestBuildClearCmd(t *testing.T) {
  3601. name := "testbuildclearcmd"
  3602. defer deleteImages(name)
  3603. _, err := buildImage(name,
  3604. `From scratch
  3605. ENTRYPOINT ["/bin/bash"]
  3606. CMD []`,
  3607. true)
  3608. if err != nil {
  3609. t.Fatal(err)
  3610. }
  3611. res, err := inspectFieldJSON(name, "Config.Cmd")
  3612. if err != nil {
  3613. t.Fatal(err)
  3614. }
  3615. if res != "[]" {
  3616. t.Fatalf("Cmd %s, expected %s", res, "[]")
  3617. }
  3618. logDone("build - clearcmd")
  3619. }
  3620. func TestBuildEmptyCmd(t *testing.T) {
  3621. name := "testbuildemptycmd"
  3622. defer deleteImages(name)
  3623. if _, err := buildImage(name, "FROM scratch\nMAINTAINER quux\n", true); err != nil {
  3624. t.Fatal(err)
  3625. }
  3626. res, err := inspectFieldJSON(name, "Config.Cmd")
  3627. if err != nil {
  3628. t.Fatal(err)
  3629. }
  3630. if res != "null" {
  3631. t.Fatalf("Cmd %s, expected %s", res, "null")
  3632. }
  3633. logDone("build - empty cmd")
  3634. }
  3635. func TestBuildOnBuildOutput(t *testing.T) {
  3636. name := "testbuildonbuildparent"
  3637. defer deleteImages(name)
  3638. if _, err := buildImage(name, "FROM busybox\nONBUILD RUN echo foo\n", true); err != nil {
  3639. t.Fatal(err)
  3640. }
  3641. childname := "testbuildonbuildchild"
  3642. defer deleteImages(childname)
  3643. _, out, err := buildImageWithOut(name, "FROM "+name+"\nMAINTAINER quux\n", true)
  3644. if err != nil {
  3645. t.Fatal(err)
  3646. }
  3647. if !strings.Contains(out, "Trigger 0, RUN echo foo") {
  3648. t.Fatal("failed to find the ONBUILD output", out)
  3649. }
  3650. logDone("build - onbuild output")
  3651. }
  3652. func TestBuildInvalidTag(t *testing.T) {
  3653. name := "abcd:" + makeRandomString(200)
  3654. defer deleteImages(name)
  3655. _, out, err := buildImageWithOut(name, "FROM scratch\nMAINTAINER quux\n", true)
  3656. // if the error doesnt check for illegal tag name, or the image is built
  3657. // then this should fail
  3658. if !strings.Contains(out, "Illegal tag name") || strings.Contains(out, "Sending build context to Docker daemon") {
  3659. t.Fatalf("failed to stop before building. Error: %s, Output: %s", err, out)
  3660. }
  3661. logDone("build - invalid tag")
  3662. }
  3663. func TestBuildCmdShDashC(t *testing.T) {
  3664. name := "testbuildcmdshc"
  3665. defer deleteImages(name)
  3666. if _, err := buildImage(name, "FROM busybox\nCMD echo cmd\n", true); err != nil {
  3667. t.Fatal(err)
  3668. }
  3669. res, err := inspectFieldJSON(name, "Config.Cmd")
  3670. if err != nil {
  3671. t.Fatal(err, res)
  3672. }
  3673. expected := `["/bin/sh","-c","echo cmd"]`
  3674. if res != expected {
  3675. t.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  3676. }
  3677. logDone("build - cmd should have sh -c for non-json")
  3678. }
  3679. func TestBuildCmdSpaces(t *testing.T) {
  3680. // Test to make sure that when we strcat arrays we take into account
  3681. // the arg separator to make sure ["echo","hi"] and ["echo hi"] don't
  3682. // look the same
  3683. name := "testbuildcmdspaces"
  3684. defer deleteImages(name)
  3685. var id1 string
  3686. var id2 string
  3687. var err error
  3688. if id1, err = buildImage(name, "FROM busybox\nCMD [\"echo hi\"]\n", true); err != nil {
  3689. t.Fatal(err)
  3690. }
  3691. if id2, err = buildImage(name, "FROM busybox\nCMD [\"echo\", \"hi\"]\n", true); err != nil {
  3692. t.Fatal(err)
  3693. }
  3694. if id1 == id2 {
  3695. t.Fatal("Should not have resulted in the same CMD")
  3696. }
  3697. // Now do the same with ENTRYPOINT
  3698. if id1, err = buildImage(name, "FROM busybox\nENTRYPOINT [\"echo hi\"]\n", true); err != nil {
  3699. t.Fatal(err)
  3700. }
  3701. if id2, err = buildImage(name, "FROM busybox\nENTRYPOINT [\"echo\", \"hi\"]\n", true); err != nil {
  3702. t.Fatal(err)
  3703. }
  3704. if id1 == id2 {
  3705. t.Fatal("Should not have resulted in the same ENTRYPOINT")
  3706. }
  3707. logDone("build - cmd with spaces")
  3708. }
  3709. func TestBuildCmdJSONNoShDashC(t *testing.T) {
  3710. name := "testbuildcmdjson"
  3711. defer deleteImages(name)
  3712. if _, err := buildImage(name, "FROM busybox\nCMD [\"echo\", \"cmd\"]", true); err != nil {
  3713. t.Fatal(err)
  3714. }
  3715. res, err := inspectFieldJSON(name, "Config.Cmd")
  3716. if err != nil {
  3717. t.Fatal(err, res)
  3718. }
  3719. expected := `["echo","cmd"]`
  3720. if res != expected {
  3721. t.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  3722. }
  3723. logDone("build - cmd should not have /bin/sh -c for json")
  3724. }
  3725. func TestBuildIgnoreInvalidInstruction(t *testing.T) {
  3726. name := "testbuildignoreinvalidinstruction"
  3727. defer deleteImages(name)
  3728. out, _, err := buildImageWithOut(name, "FROM busybox\nfoo bar", true)
  3729. if err != nil {
  3730. t.Fatal(err, out)
  3731. }
  3732. logDone("build - ignore invalid Dockerfile instruction")
  3733. }
  3734. func TestBuildEntrypointInheritance(t *testing.T) {
  3735. defer deleteImages("parent", "child")
  3736. defer deleteAllContainers()
  3737. if _, err := buildImage("parent", `
  3738. FROM busybox
  3739. ENTRYPOINT exit 130
  3740. `, true); err != nil {
  3741. t.Fatal(err)
  3742. }
  3743. status, _ := runCommand(exec.Command(dockerBinary, "run", "parent"))
  3744. if status != 130 {
  3745. t.Fatalf("expected exit code 130 but received %d", status)
  3746. }
  3747. if _, err := buildImage("child", `
  3748. FROM parent
  3749. ENTRYPOINT exit 5
  3750. `, true); err != nil {
  3751. t.Fatal(err)
  3752. }
  3753. status, _ = runCommand(exec.Command(dockerBinary, "run", "child"))
  3754. if status != 5 {
  3755. t.Fatalf("expected exit code 5 but received %d", status)
  3756. }
  3757. logDone("build - clear entrypoint")
  3758. }
  3759. func TestBuildEntrypointInheritanceInspect(t *testing.T) {
  3760. var (
  3761. name = "testbuildepinherit"
  3762. name2 = "testbuildepinherit2"
  3763. expected = `["/bin/sh","-c","echo quux"]`
  3764. )
  3765. defer deleteImages(name, name2)
  3766. defer deleteAllContainers()
  3767. if _, err := buildImage(name, "FROM busybox\nENTRYPOINT /foo/bar", true); err != nil {
  3768. t.Fatal(err)
  3769. }
  3770. if _, err := buildImage(name2, fmt.Sprintf("FROM %s\nENTRYPOINT echo quux", name), true); err != nil {
  3771. t.Fatal(err)
  3772. }
  3773. res, err := inspectFieldJSON(name2, "Config.Entrypoint")
  3774. if err != nil {
  3775. t.Fatal(err, res)
  3776. }
  3777. if res != expected {
  3778. t.Fatalf("Expected value %s not in Config.Entrypoint: %s", expected, res)
  3779. }
  3780. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-t", name2))
  3781. if err != nil {
  3782. t.Fatal(err, out)
  3783. }
  3784. expected = "quux"
  3785. if strings.TrimSpace(out) != expected {
  3786. t.Fatalf("Expected output is %s, got %s", expected, out)
  3787. }
  3788. logDone("build - entrypoint override inheritance properly")
  3789. }
  3790. func TestBuildRunShEntrypoint(t *testing.T) {
  3791. name := "testbuildentrypoint"
  3792. defer deleteImages(name)
  3793. _, err := buildImage(name,
  3794. `FROM busybox
  3795. ENTRYPOINT /bin/echo`,
  3796. true)
  3797. if err != nil {
  3798. t.Fatal(err)
  3799. }
  3800. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--rm", name))
  3801. if err != nil {
  3802. t.Fatal(err, out)
  3803. }
  3804. logDone("build - entrypoint with /bin/echo running successfully")
  3805. }
  3806. func TestBuildExoticShellInterpolation(t *testing.T) {
  3807. name := "testbuildexoticshellinterpolation"
  3808. defer deleteImages(name)
  3809. _, err := buildImage(name, `
  3810. FROM busybox
  3811. ENV SOME_VAR a.b.c
  3812. RUN [ "$SOME_VAR" = 'a.b.c' ]
  3813. RUN [ "${SOME_VAR}" = 'a.b.c' ]
  3814. RUN [ "${SOME_VAR%.*}" = 'a.b' ]
  3815. RUN [ "${SOME_VAR%%.*}" = 'a' ]
  3816. RUN [ "${SOME_VAR#*.}" = 'b.c' ]
  3817. RUN [ "${SOME_VAR##*.}" = 'c' ]
  3818. RUN [ "${SOME_VAR/c/d}" = 'a.b.d' ]
  3819. RUN [ "${#SOME_VAR}" = '5' ]
  3820. RUN [ "${SOME_UNSET_VAR:-$SOME_VAR}" = 'a.b.c' ]
  3821. RUN [ "${SOME_VAR:+Version: ${SOME_VAR}}" = 'Version: a.b.c' ]
  3822. RUN [ "${SOME_UNSET_VAR:+${SOME_VAR}}" = '' ]
  3823. RUN [ "${SOME_UNSET_VAR:-${SOME_VAR:-d.e.f}}" = 'a.b.c' ]
  3824. `, false)
  3825. if err != nil {
  3826. t.Fatal(err)
  3827. }
  3828. logDone("build - exotic shell interpolation")
  3829. }
  3830. func TestBuildVerifySingleQuoteFails(t *testing.T) {
  3831. // This testcase is supposed to generate an error because the
  3832. // JSON array we're passing in on the CMD uses single quotes instead
  3833. // of double quotes (per the JSON spec). This means we interpret it
  3834. // as a "string" insead of "JSON array" and pass it on to "sh -c" and
  3835. // it should barf on it.
  3836. name := "testbuildsinglequotefails"
  3837. defer deleteImages(name)
  3838. defer deleteAllContainers()
  3839. _, err := buildImage(name,
  3840. `FROM busybox
  3841. CMD [ '/bin/sh', '-c', 'echo hi' ]`,
  3842. true)
  3843. _, _, err = runCommandWithOutput(exec.Command(dockerBinary, "run", "--rm", name))
  3844. if err == nil {
  3845. t.Fatal("The image was not supposed to be able to run")
  3846. }
  3847. logDone("build - verify single quotes break the build")
  3848. }
  3849. func TestBuildVerboseOut(t *testing.T) {
  3850. name := "testbuildverboseout"
  3851. defer deleteImages(name)
  3852. _, out, err := buildImageWithOut(name,
  3853. `FROM busybox
  3854. RUN echo 123`,
  3855. false)
  3856. if err != nil {
  3857. t.Fatal(err)
  3858. }
  3859. if !strings.Contains(out, "\n123\n") {
  3860. t.Fatalf("Output should contain %q: %q", "123", out)
  3861. }
  3862. logDone("build - verbose output from commands")
  3863. }
  3864. func TestBuildWithTabs(t *testing.T) {
  3865. name := "testbuildwithtabs"
  3866. defer deleteImages(name)
  3867. _, err := buildImage(name,
  3868. "FROM busybox\nRUN echo\tone\t\ttwo", true)
  3869. if err != nil {
  3870. t.Fatal(err)
  3871. }
  3872. res, err := inspectFieldJSON(name, "ContainerConfig.Cmd")
  3873. if err != nil {
  3874. t.Fatal(err)
  3875. }
  3876. expected1 := `["/bin/sh","-c","echo\tone\t\ttwo"]`
  3877. expected2 := `["/bin/sh","-c","echo\u0009one\u0009\u0009two"]` // syntactically equivalent, and what Go 1.3 generates
  3878. if res != expected1 && res != expected2 {
  3879. t.Fatalf("Missing tabs.\nGot: %s\nExp: %s or %s", res, expected1, expected2)
  3880. }
  3881. logDone("build - with tabs")
  3882. }
  3883. func TestBuildStderr(t *testing.T) {
  3884. // This test just makes sure that no non-error output goes
  3885. // to stderr
  3886. name := "testbuildstderr"
  3887. defer deleteImages(name)
  3888. _, _, stderr, err := buildImageWithStdoutStderr(name,
  3889. "FROM busybox\nRUN echo one", true)
  3890. if err != nil {
  3891. t.Fatal(err)
  3892. }
  3893. if stderr != "" {
  3894. t.Fatalf("Stderr should have been empty, instead its: %q", stderr)
  3895. }
  3896. logDone("build - testing stderr")
  3897. }
  3898. func TestBuildChownSingleFile(t *testing.T) {
  3899. testRequires(t, UnixCli) // test uses chown: not available on windows
  3900. name := "testbuildchownsinglefile"
  3901. defer deleteImages(name)
  3902. ctx, err := fakeContext(`
  3903. FROM busybox
  3904. COPY test /
  3905. RUN ls -l /test
  3906. RUN [ $(ls -l /test | awk '{print $3":"$4}') = 'root:root' ]
  3907. `, map[string]string{
  3908. "test": "test",
  3909. })
  3910. if err != nil {
  3911. t.Fatal(err)
  3912. }
  3913. defer ctx.Close()
  3914. if err := os.Chown(filepath.Join(ctx.Dir, "test"), 4242, 4242); err != nil {
  3915. t.Fatal(err)
  3916. }
  3917. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3918. t.Fatal(err)
  3919. }
  3920. logDone("build - change permission on single file")
  3921. }
  3922. func TestBuildSymlinkBreakout(t *testing.T) {
  3923. name := "testbuildsymlinkbreakout"
  3924. tmpdir, err := ioutil.TempDir("", name)
  3925. if err != nil {
  3926. t.Fatal(err)
  3927. }
  3928. defer os.RemoveAll(tmpdir)
  3929. ctx := filepath.Join(tmpdir, "context")
  3930. if err := os.MkdirAll(ctx, 0755); err != nil {
  3931. t.Fatal(err)
  3932. }
  3933. if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte(`
  3934. from busybox
  3935. add symlink.tar /
  3936. add inject /symlink/
  3937. `), 0644); err != nil {
  3938. t.Fatal(err)
  3939. }
  3940. inject := filepath.Join(ctx, "inject")
  3941. if err := ioutil.WriteFile(inject, nil, 0644); err != nil {
  3942. t.Fatal(err)
  3943. }
  3944. f, err := os.Create(filepath.Join(ctx, "symlink.tar"))
  3945. if err != nil {
  3946. t.Fatal(err)
  3947. }
  3948. w := tar.NewWriter(f)
  3949. w.WriteHeader(&tar.Header{
  3950. Name: "symlink2",
  3951. Typeflag: tar.TypeSymlink,
  3952. Linkname: "/../../../../../../../../../../../../../../",
  3953. Uid: os.Getuid(),
  3954. Gid: os.Getgid(),
  3955. })
  3956. w.WriteHeader(&tar.Header{
  3957. Name: "symlink",
  3958. Typeflag: tar.TypeSymlink,
  3959. Linkname: filepath.Join("symlink2", tmpdir),
  3960. Uid: os.Getuid(),
  3961. Gid: os.Getgid(),
  3962. })
  3963. w.Close()
  3964. f.Close()
  3965. if _, err := buildImageFromContext(name, &FakeContext{Dir: ctx}, false); err != nil {
  3966. t.Fatal(err)
  3967. }
  3968. if _, err := os.Lstat(filepath.Join(tmpdir, "inject")); err == nil {
  3969. t.Fatal("symlink breakout - inject")
  3970. } else if !os.IsNotExist(err) {
  3971. t.Fatalf("unexpected error: %v", err)
  3972. }
  3973. logDone("build - symlink breakout")
  3974. }
  3975. func TestBuildXZHost(t *testing.T) {
  3976. name := "testbuildxzhost"
  3977. defer deleteImages(name)
  3978. ctx, err := fakeContext(`
  3979. FROM busybox
  3980. ADD xz /usr/local/sbin/
  3981. RUN chmod 755 /usr/local/sbin/xz
  3982. ADD test.xz /
  3983. RUN [ ! -e /injected ]`,
  3984. map[string]string{
  3985. "test.xz": "\xfd\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00" +
  3986. "\x21\x01\x16\x00\x00\x00\x74\x2f\xe5\xa3\x01\x00\x3f\xfd" +
  3987. "\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00\x21",
  3988. "xz": "#!/bin/sh\ntouch /injected",
  3989. })
  3990. if err != nil {
  3991. t.Fatal(err)
  3992. }
  3993. defer ctx.Close()
  3994. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3995. t.Fatal(err)
  3996. }
  3997. logDone("build - xz host is being used")
  3998. }
  3999. func TestBuildVolumesRetainContents(t *testing.T) {
  4000. var (
  4001. name = "testbuildvolumescontent"
  4002. expected = "some text"
  4003. )
  4004. defer deleteImages(name)
  4005. ctx, err := fakeContext(`
  4006. FROM busybox
  4007. COPY content /foo/file
  4008. VOLUME /foo
  4009. CMD cat /foo/file`,
  4010. map[string]string{
  4011. "content": expected,
  4012. })
  4013. if err != nil {
  4014. t.Fatal(err)
  4015. }
  4016. defer ctx.Close()
  4017. if _, err := buildImageFromContext(name, ctx, false); err != nil {
  4018. t.Fatal(err)
  4019. }
  4020. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--rm", name))
  4021. if err != nil {
  4022. t.Fatal(err)
  4023. }
  4024. if out != expected {
  4025. t.Fatalf("expected file contents for /foo/file to be %q but received %q", expected, out)
  4026. }
  4027. logDone("build - volumes retain contents in build")
  4028. }
  4029. func TestBuildRenamedDockerfile(t *testing.T) {
  4030. defer deleteAllContainers()
  4031. ctx, err := fakeContext(`FROM busybox
  4032. RUN echo from Dockerfile`,
  4033. map[string]string{
  4034. "Dockerfile": "FROM busybox\nRUN echo from Dockerfile",
  4035. "files/Dockerfile": "FROM busybox\nRUN echo from files/Dockerfile",
  4036. "files/dFile": "FROM busybox\nRUN echo from files/dFile",
  4037. "dFile": "FROM busybox\nRUN echo from dFile",
  4038. "files/dFile2": "FROM busybox\nRUN echo from files/dFile2",
  4039. })
  4040. defer ctx.Close()
  4041. if err != nil {
  4042. t.Fatal(err)
  4043. }
  4044. out, _, err := dockerCmdInDir(t, ctx.Dir, "build", "-t", "test1", ".")
  4045. if err != nil {
  4046. t.Fatalf("Failed to build: %s\n%s", out, err)
  4047. }
  4048. if !strings.Contains(out, "from Dockerfile") {
  4049. t.Fatalf("test1 should have used Dockerfile, output:%s", out)
  4050. }
  4051. out, _, err = dockerCmdInDir(t, ctx.Dir, "build", "-f", filepath.Join("files", "Dockerfile"), "-t", "test2", ".")
  4052. if err != nil {
  4053. t.Fatal(err)
  4054. }
  4055. if !strings.Contains(out, "from files/Dockerfile") {
  4056. t.Fatalf("test2 should have used files/Dockerfile, output:%s", out)
  4057. }
  4058. out, _, err = dockerCmdInDir(t, ctx.Dir, "build", fmt.Sprintf("--file=%s", filepath.Join("files", "dFile")), "-t", "test3", ".")
  4059. if err != nil {
  4060. t.Fatal(err)
  4061. }
  4062. if !strings.Contains(out, "from files/dFile") {
  4063. t.Fatalf("test3 should have used files/dFile, output:%s", out)
  4064. }
  4065. out, _, err = dockerCmdInDir(t, ctx.Dir, "build", "--file=dFile", "-t", "test4", ".")
  4066. if err != nil {
  4067. t.Fatal(err)
  4068. }
  4069. if !strings.Contains(out, "from dFile") {
  4070. t.Fatalf("test4 should have used dFile, output:%s", out)
  4071. }
  4072. dirWithNoDockerfile, _ := ioutil.TempDir(os.TempDir(), "test5")
  4073. nonDockerfileFile := filepath.Join(dirWithNoDockerfile, "notDockerfile")
  4074. if _, err = os.Create(nonDockerfileFile); err != nil {
  4075. t.Fatal(err)
  4076. }
  4077. out, _, err = dockerCmdInDir(t, ctx.Dir, "build", fmt.Sprintf("--file=%s", nonDockerfileFile), "-t", "test5", ".")
  4078. if err == nil {
  4079. t.Fatalf("test5 was supposed to fail to find passwd")
  4080. }
  4081. if expected := fmt.Sprintf("The Dockerfile (%s) must be within the build context (.)", strings.Replace(nonDockerfileFile, `\`, `\\`, -1)); !strings.Contains(out, expected) {
  4082. t.Fatalf("wrong error messsage:%v\nexpected to contain=%v", out, expected)
  4083. }
  4084. out, _, err = dockerCmdInDir(t, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join("..", "Dockerfile"), "-t", "test6", "..")
  4085. if err != nil {
  4086. t.Fatalf("test6 failed: %s", err)
  4087. }
  4088. if !strings.Contains(out, "from Dockerfile") {
  4089. t.Fatalf("test6 should have used root Dockerfile, output:%s", out)
  4090. }
  4091. out, _, err = dockerCmdInDir(t, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join(ctx.Dir, "files", "Dockerfile"), "-t", "test7", "..")
  4092. if err != nil {
  4093. t.Fatalf("test7 failed: %s", err)
  4094. }
  4095. if !strings.Contains(out, "from files/Dockerfile") {
  4096. t.Fatalf("test7 should have used files Dockerfile, output:%s", out)
  4097. }
  4098. out, _, err = dockerCmdInDir(t, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join("..", "Dockerfile"), "-t", "test8", ".")
  4099. if err == nil || !strings.Contains(out, "must be within the build context") {
  4100. t.Fatalf("test8 should have failed with Dockerfile out of context: %s", err)
  4101. }
  4102. tmpDir := os.TempDir()
  4103. out, _, err = dockerCmdInDir(t, tmpDir, "build", "-t", "test9", ctx.Dir)
  4104. if err != nil {
  4105. t.Fatalf("test9 - failed: %s", err)
  4106. }
  4107. if !strings.Contains(out, "from Dockerfile") {
  4108. t.Fatalf("test9 should have used root Dockerfile, output:%s", out)
  4109. }
  4110. out, _, err = dockerCmdInDir(t, filepath.Join(ctx.Dir, "files"), "build", "-f", "dFile2", "-t", "test10", ".")
  4111. if err != nil {
  4112. t.Fatalf("test10 should have worked: %s", err)
  4113. }
  4114. if !strings.Contains(out, "from files/dFile2") {
  4115. t.Fatalf("test10 should have used files/dFile2, output:%s", out)
  4116. }
  4117. logDone("build - rename dockerfile")
  4118. }
  4119. func TestBuildFromOfficialNames(t *testing.T) {
  4120. name := "testbuildfromofficial"
  4121. fromNames := []string{
  4122. "busybox",
  4123. "docker.io/busybox",
  4124. "index.docker.io/busybox",
  4125. "library/busybox",
  4126. "docker.io/library/busybox",
  4127. "index.docker.io/library/busybox",
  4128. }
  4129. for idx, fromName := range fromNames {
  4130. imgName := fmt.Sprintf("%s%d", name, idx)
  4131. _, err := buildImage(imgName, "FROM "+fromName, true)
  4132. if err != nil {
  4133. t.Errorf("Build failed using FROM %s: %s", fromName, err)
  4134. }
  4135. deleteImages(imgName)
  4136. }
  4137. logDone("build - from official names")
  4138. }
  4139. func TestBuildDockerfileOutsideContext(t *testing.T) {
  4140. testRequires(t, UnixCli) // uses os.Symlink: not implemented in windows at the time of writing (go-1.4.2)
  4141. name := "testbuilddockerfileoutsidecontext"
  4142. tmpdir, err := ioutil.TempDir("", name)
  4143. if err != nil {
  4144. t.Fatal(err)
  4145. }
  4146. defer os.RemoveAll(tmpdir)
  4147. ctx := filepath.Join(tmpdir, "context")
  4148. if err := os.MkdirAll(ctx, 0755); err != nil {
  4149. t.Fatal(err)
  4150. }
  4151. if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte("FROM scratch\nENV X Y"), 0644); err != nil {
  4152. t.Fatal(err)
  4153. }
  4154. wd, err := os.Getwd()
  4155. if err != nil {
  4156. t.Fatal(err)
  4157. }
  4158. defer os.Chdir(wd)
  4159. if err := os.Chdir(ctx); err != nil {
  4160. t.Fatal(err)
  4161. }
  4162. if err := ioutil.WriteFile(filepath.Join(tmpdir, "outsideDockerfile"), []byte("FROM scratch\nENV x y"), 0644); err != nil {
  4163. t.Fatal(err)
  4164. }
  4165. if err := os.Symlink(filepath.Join("..", "outsideDockerfile"), filepath.Join(ctx, "dockerfile1")); err != nil {
  4166. t.Fatal(err)
  4167. }
  4168. if err := os.Symlink(filepath.Join(tmpdir, "outsideDockerfile"), filepath.Join(ctx, "dockerfile2")); err != nil {
  4169. t.Fatal(err)
  4170. }
  4171. for _, dockerfilePath := range []string{
  4172. filepath.Join("..", "outsideDockerfile"),
  4173. filepath.Join(ctx, "dockerfile1"),
  4174. filepath.Join(ctx, "dockerfile2"),
  4175. } {
  4176. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "build", "-t", name, "--no-cache", "-f", dockerfilePath, "."))
  4177. if err == nil {
  4178. t.Fatalf("Expected error with %s. Out: %s", dockerfilePath, out)
  4179. }
  4180. if !strings.Contains(out, "must be within the build context") && !strings.Contains(out, "Cannot locate Dockerfile") {
  4181. t.Fatalf("Unexpected error with %s. Out: %s", dockerfilePath, out)
  4182. }
  4183. deleteImages(name)
  4184. }
  4185. os.Chdir(tmpdir)
  4186. // Path to Dockerfile should be resolved relative to working directory, not relative to context.
  4187. // There is a Dockerfile in the context, but since there is no Dockerfile in the current directory, the following should fail
  4188. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "build", "-t", name, "--no-cache", "-f", "Dockerfile", ctx))
  4189. if err == nil {
  4190. t.Fatalf("Expected error. Out: %s", out)
  4191. }
  4192. deleteImages(name)
  4193. logDone("build - Dockerfile outside context")
  4194. }
  4195. func TestBuildSpaces(t *testing.T) {
  4196. // Test to make sure that leading/trailing spaces on a command
  4197. // doesn't change the error msg we get
  4198. var (
  4199. err1 error
  4200. err2 error
  4201. )
  4202. name := "testspaces"
  4203. defer deleteImages(name)
  4204. ctx, err := fakeContext("FROM busybox\nCOPY\n",
  4205. map[string]string{
  4206. "Dockerfile": "FROM busybox\nCOPY\n",
  4207. })
  4208. if err != nil {
  4209. t.Fatal(err)
  4210. }
  4211. defer ctx.Close()
  4212. if _, err1 = buildImageFromContext(name, ctx, false); err1 == nil {
  4213. t.Fatal("Build 1 was supposed to fail, but didn't")
  4214. }
  4215. ctx.Add("Dockerfile", "FROM busybox\nCOPY ")
  4216. if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil {
  4217. t.Fatal("Build 2 was supposed to fail, but didn't")
  4218. }
  4219. // Skip over the times
  4220. e1 := err1.Error()[strings.Index(err1.Error(), `level="`):]
  4221. e2 := err2.Error()[strings.Index(err1.Error(), `level="`):]
  4222. // Ignore whitespace since that's what were verifying doesn't change stuff
  4223. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  4224. t.Fatalf("Build 2's error wasn't the same as build 1's\n1:%s\n2:%s", err1, err2)
  4225. }
  4226. ctx.Add("Dockerfile", "FROM busybox\n COPY")
  4227. if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil {
  4228. t.Fatal("Build 3 was supposed to fail, but didn't")
  4229. }
  4230. // Skip over the times
  4231. e1 = err1.Error()[strings.Index(err1.Error(), `level="`):]
  4232. e2 = err2.Error()[strings.Index(err1.Error(), `level="`):]
  4233. // Ignore whitespace since that's what were verifying doesn't change stuff
  4234. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  4235. t.Fatalf("Build 3's error wasn't the same as build 1's\n1:%s\n3:%s", err1, err2)
  4236. }
  4237. ctx.Add("Dockerfile", "FROM busybox\n COPY ")
  4238. if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil {
  4239. t.Fatal("Build 4 was supposed to fail, but didn't")
  4240. }
  4241. // Skip over the times
  4242. e1 = err1.Error()[strings.Index(err1.Error(), `level="`):]
  4243. e2 = err2.Error()[strings.Index(err1.Error(), `level="`):]
  4244. // Ignore whitespace since that's what were verifying doesn't change stuff
  4245. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  4246. t.Fatalf("Build 4's error wasn't the same as build 1's\n1:%s\n4:%s", err1, err2)
  4247. }
  4248. logDone("build - test spaces")
  4249. }
  4250. func TestBuildSpacesWithQuotes(t *testing.T) {
  4251. // Test to make sure that spaces in quotes aren't lost
  4252. name := "testspacesquotes"
  4253. defer deleteImages(name)
  4254. dockerfile := `FROM busybox
  4255. RUN echo " \
  4256. foo "`
  4257. _, out, err := buildImageWithOut(name, dockerfile, false)
  4258. if err != nil {
  4259. t.Fatal("Build failed:", err)
  4260. }
  4261. expecting := "\n foo \n"
  4262. if !strings.Contains(out, expecting) {
  4263. t.Fatalf("Bad output: %q expecting to contian %q", out, expecting)
  4264. }
  4265. logDone("build - test spaces with quotes")
  4266. }
  4267. // #4393
  4268. func TestBuildVolumeFileExistsinContainer(t *testing.T) {
  4269. buildCmd := exec.Command(dockerBinary, "build", "-t", "docker-test-errcreatevolumewithfile", "-")
  4270. buildCmd.Stdin = strings.NewReader(`
  4271. FROM busybox
  4272. RUN touch /foo
  4273. VOLUME /foo
  4274. `)
  4275. out, _, err := runCommandWithOutput(buildCmd)
  4276. if err == nil || !strings.Contains(out, "file exists") {
  4277. t.Fatalf("expected build to fail when file exists in container at requested volume path")
  4278. }
  4279. logDone("build - errors when volume is specified where a file exists")
  4280. }
  4281. func TestBuildMissingArgs(t *testing.T) {
  4282. // Test to make sure that all Dockerfile commands (except the ones listed
  4283. // in skipCmds) will generate an error if no args are provided.
  4284. // Note: INSERT is deprecated so we exclude it because of that.
  4285. skipCmds := map[string]struct{}{
  4286. "CMD": {},
  4287. "RUN": {},
  4288. "ENTRYPOINT": {},
  4289. "INSERT": {},
  4290. }
  4291. defer deleteAllContainers()
  4292. for cmd := range command.Commands {
  4293. cmd = strings.ToUpper(cmd)
  4294. if _, ok := skipCmds[cmd]; ok {
  4295. continue
  4296. }
  4297. var dockerfile string
  4298. if cmd == "FROM" {
  4299. dockerfile = cmd
  4300. } else {
  4301. // Add FROM to make sure we don't complain about it missing
  4302. dockerfile = "FROM busybox\n" + cmd
  4303. }
  4304. ctx, err := fakeContext(dockerfile, map[string]string{})
  4305. if err != nil {
  4306. t.Fatal(err)
  4307. }
  4308. defer ctx.Close()
  4309. var out string
  4310. if out, err = buildImageFromContext("args", ctx, true); err == nil {
  4311. t.Fatalf("%s was supposed to fail. Out:%s", cmd, out)
  4312. }
  4313. if !strings.Contains(err.Error(), cmd+" requires") {
  4314. t.Fatalf("%s returned the wrong type of error:%s", cmd, err)
  4315. }
  4316. }
  4317. logDone("build - verify missing args")
  4318. }
  4319. func TestBuildEmptyScratch(t *testing.T) {
  4320. defer deleteImages("sc")
  4321. _, out, err := buildImageWithOut("sc", "FROM scratch", true)
  4322. if err == nil {
  4323. t.Fatalf("Build was supposed to fail")
  4324. }
  4325. if !strings.Contains(out, "No image was generated") {
  4326. t.Fatalf("Wrong error message: %v", out)
  4327. }
  4328. logDone("build - empty scratch Dockerfile")
  4329. }
  4330. func TestBuildDotDotFile(t *testing.T) {
  4331. defer deleteImages("sc")
  4332. ctx, err := fakeContext("FROM busybox\n",
  4333. map[string]string{
  4334. "..gitme": "",
  4335. })
  4336. if err != nil {
  4337. t.Fatal(err)
  4338. }
  4339. defer ctx.Close()
  4340. if _, err = buildImageFromContext("sc", ctx, false); err != nil {
  4341. t.Fatalf("Build was supposed to work: %s", err)
  4342. }
  4343. logDone("build - ..file")
  4344. }
  4345. func TestBuildNotVerbose(t *testing.T) {
  4346. defer deleteAllContainers()
  4347. defer deleteImages("verbose")
  4348. ctx, err := fakeContext("FROM busybox\nENV abc=hi\nRUN echo $abc there", map[string]string{})
  4349. if err != nil {
  4350. t.Fatal(err)
  4351. }
  4352. defer ctx.Close()
  4353. // First do it w/verbose - baseline
  4354. buildCmd := exec.Command(dockerBinary, "build", "--no-cache", "-t", "verbose", ".")
  4355. buildCmd.Dir = ctx.Dir
  4356. out, _, err := runCommandWithOutput(buildCmd)
  4357. if err != nil {
  4358. t.Fatalf("failed to build the image w/o -q: %s, %v", out, err)
  4359. }
  4360. if !strings.Contains(out, "hi there") {
  4361. t.Fatalf("missing output:%s\n", out)
  4362. }
  4363. // Now do it w/o verbose
  4364. buildCmd = exec.Command(dockerBinary, "build", "--no-cache", "-q", "-t", "verbose", ".")
  4365. buildCmd.Dir = ctx.Dir
  4366. out, _, err = runCommandWithOutput(buildCmd)
  4367. if err != nil {
  4368. t.Fatalf("failed to build the image w/ -q: %s, %v", out, err)
  4369. }
  4370. if strings.Contains(out, "hi there") {
  4371. t.Fatalf("Bad output, should not contain 'hi there':%s", out)
  4372. }
  4373. logDone("build - not verbose")
  4374. }