docker_cli_build_test.go 127 KB

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