docker_cli_build_test.go 136 KB

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