docker_cli_build_test.go 131 KB

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