docker_cli_build_test.go 137 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428
  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 is accessible") {
  1456. c.Fatalf("output should've contained the string: Error checking context is accessible")
  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 is accessible") {
  1489. c.Fatalf("output should've contained the string: Error checking context is accessible")
  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) TestBuildExposeHostPort(c *check.C) {
  2066. // start building docker file with ip:hostPort:containerPort
  2067. name := "testbuildexpose"
  2068. expected := "map[5678/tcp:{}]"
  2069. _, out, err := buildImageWithOut(name,
  2070. `FROM scratch
  2071. EXPOSE 192.168.1.2:2375:5678`,
  2072. true)
  2073. if err != nil {
  2074. c.Fatal(err)
  2075. }
  2076. if !strings.Contains(out, "to map host ports to container ports (ip:hostPort:containerPort) is deprecated.") {
  2077. c.Fatal("Missing warning message")
  2078. }
  2079. res, err := inspectField(name, "Config.ExposedPorts")
  2080. if err != nil {
  2081. c.Fatal(err)
  2082. }
  2083. if res != expected {
  2084. c.Fatalf("Exposed ports %s, expected %s", res, expected)
  2085. }
  2086. }
  2087. func (s *DockerSuite) TestBuildEmptyEntrypointInheritance(c *check.C) {
  2088. name := "testbuildentrypointinheritance"
  2089. name2 := "testbuildentrypointinheritance2"
  2090. _, err := buildImage(name,
  2091. `FROM busybox
  2092. ENTRYPOINT ["/bin/echo"]`,
  2093. true)
  2094. if err != nil {
  2095. c.Fatal(err)
  2096. }
  2097. res, err := inspectField(name, "Config.Entrypoint")
  2098. if err != nil {
  2099. c.Fatal(err)
  2100. }
  2101. expected := "{[/bin/echo]}"
  2102. if res != expected {
  2103. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  2104. }
  2105. _, err = buildImage(name2,
  2106. fmt.Sprintf(`FROM %s
  2107. ENTRYPOINT []`, name),
  2108. true)
  2109. if err != nil {
  2110. c.Fatal(err)
  2111. }
  2112. res, err = inspectField(name2, "Config.Entrypoint")
  2113. if err != nil {
  2114. c.Fatal(err)
  2115. }
  2116. expected = "{[]}"
  2117. if res != expected {
  2118. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  2119. }
  2120. }
  2121. func (s *DockerSuite) TestBuildEmptyEntrypoint(c *check.C) {
  2122. name := "testbuildentrypoint"
  2123. expected := "{[]}"
  2124. _, err := buildImage(name,
  2125. `FROM busybox
  2126. ENTRYPOINT []`,
  2127. true)
  2128. if err != nil {
  2129. c.Fatal(err)
  2130. }
  2131. res, err := inspectField(name, "Config.Entrypoint")
  2132. if err != nil {
  2133. c.Fatal(err)
  2134. }
  2135. if res != expected {
  2136. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  2137. }
  2138. }
  2139. func (s *DockerSuite) TestBuildEntrypoint(c *check.C) {
  2140. name := "testbuildentrypoint"
  2141. expected := "{[/bin/echo]}"
  2142. _, err := buildImage(name,
  2143. `FROM scratch
  2144. ENTRYPOINT ["/bin/echo"]`,
  2145. true)
  2146. if err != nil {
  2147. c.Fatal(err)
  2148. }
  2149. res, err := inspectField(name, "Config.Entrypoint")
  2150. if err != nil {
  2151. c.Fatal(err)
  2152. }
  2153. if res != expected {
  2154. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  2155. }
  2156. }
  2157. // #6445 ensure ONBUILD triggers aren't committed to grandchildren
  2158. func (s *DockerSuite) TestBuildOnBuildLimitedInheritence(c *check.C) {
  2159. var (
  2160. out2, out3 string
  2161. )
  2162. {
  2163. name1 := "testonbuildtrigger1"
  2164. dockerfile1 := `
  2165. FROM busybox
  2166. RUN echo "GRANDPARENT"
  2167. ONBUILD RUN echo "ONBUILD PARENT"
  2168. `
  2169. ctx, err := fakeContext(dockerfile1, nil)
  2170. if err != nil {
  2171. c.Fatal(err)
  2172. }
  2173. defer ctx.Close()
  2174. out1, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", name1, ".")
  2175. if err != nil {
  2176. c.Fatalf("build failed to complete: %s, %v", out1, err)
  2177. }
  2178. }
  2179. {
  2180. name2 := "testonbuildtrigger2"
  2181. dockerfile2 := `
  2182. FROM testonbuildtrigger1
  2183. `
  2184. ctx, err := fakeContext(dockerfile2, nil)
  2185. if err != nil {
  2186. c.Fatal(err)
  2187. }
  2188. defer ctx.Close()
  2189. out2, _, err = dockerCmdInDir(c, ctx.Dir, "build", "-t", name2, ".")
  2190. if err != nil {
  2191. c.Fatalf("build failed to complete: %s, %v", out2, err)
  2192. }
  2193. }
  2194. {
  2195. name3 := "testonbuildtrigger3"
  2196. dockerfile3 := `
  2197. FROM testonbuildtrigger2
  2198. `
  2199. ctx, err := fakeContext(dockerfile3, nil)
  2200. if err != nil {
  2201. c.Fatal(err)
  2202. }
  2203. defer ctx.Close()
  2204. out3, _, err = dockerCmdInDir(c, ctx.Dir, "build", "-t", name3, ".")
  2205. if err != nil {
  2206. c.Fatalf("build failed to complete: %s, %v", out3, err)
  2207. }
  2208. }
  2209. // ONBUILD should be run in second build.
  2210. if !strings.Contains(out2, "ONBUILD PARENT") {
  2211. c.Fatalf("ONBUILD instruction did not run in child of ONBUILD parent")
  2212. }
  2213. // ONBUILD should *not* be run in third build.
  2214. if strings.Contains(out3, "ONBUILD PARENT") {
  2215. c.Fatalf("ONBUILD instruction ran in grandchild of ONBUILD parent")
  2216. }
  2217. }
  2218. func (s *DockerSuite) TestBuildWithCache(c *check.C) {
  2219. name := "testbuildwithcache"
  2220. id1, err := buildImage(name,
  2221. `FROM scratch
  2222. MAINTAINER dockerio
  2223. EXPOSE 5432
  2224. ENTRYPOINT ["/bin/echo"]`,
  2225. true)
  2226. if err != nil {
  2227. c.Fatal(err)
  2228. }
  2229. id2, err := buildImage(name,
  2230. `FROM scratch
  2231. MAINTAINER dockerio
  2232. EXPOSE 5432
  2233. ENTRYPOINT ["/bin/echo"]`,
  2234. true)
  2235. if err != nil {
  2236. c.Fatal(err)
  2237. }
  2238. if id1 != id2 {
  2239. c.Fatal("The cache should have been used but hasn't.")
  2240. }
  2241. }
  2242. func (s *DockerSuite) TestBuildWithoutCache(c *check.C) {
  2243. name := "testbuildwithoutcache"
  2244. name2 := "testbuildwithoutcache2"
  2245. id1, err := buildImage(name,
  2246. `FROM scratch
  2247. MAINTAINER dockerio
  2248. EXPOSE 5432
  2249. ENTRYPOINT ["/bin/echo"]`,
  2250. true)
  2251. if err != nil {
  2252. c.Fatal(err)
  2253. }
  2254. id2, err := buildImage(name2,
  2255. `FROM scratch
  2256. MAINTAINER dockerio
  2257. EXPOSE 5432
  2258. ENTRYPOINT ["/bin/echo"]`,
  2259. false)
  2260. if err != nil {
  2261. c.Fatal(err)
  2262. }
  2263. if id1 == id2 {
  2264. c.Fatal("The cache should have been invalided but hasn't.")
  2265. }
  2266. }
  2267. func (s *DockerSuite) TestBuildConditionalCache(c *check.C) {
  2268. name := "testbuildconditionalcache"
  2269. dockerfile := `
  2270. FROM busybox
  2271. ADD foo /tmp/`
  2272. ctx, err := fakeContext(dockerfile, map[string]string{
  2273. "foo": "hello",
  2274. })
  2275. if err != nil {
  2276. c.Fatal(err)
  2277. }
  2278. defer ctx.Close()
  2279. id1, err := buildImageFromContext(name, ctx, true)
  2280. if err != nil {
  2281. c.Fatalf("Error building #1: %s", err)
  2282. }
  2283. if err := ctx.Add("foo", "bye"); err != nil {
  2284. c.Fatalf("Error modifying foo: %s", err)
  2285. }
  2286. id2, err := buildImageFromContext(name, ctx, false)
  2287. if err != nil {
  2288. c.Fatalf("Error building #2: %s", err)
  2289. }
  2290. if id2 == id1 {
  2291. c.Fatal("Should not have used the cache")
  2292. }
  2293. id3, err := buildImageFromContext(name, ctx, true)
  2294. if err != nil {
  2295. c.Fatalf("Error building #3: %s", err)
  2296. }
  2297. if id3 != id2 {
  2298. c.Fatal("Should have used the cache")
  2299. }
  2300. }
  2301. func (s *DockerSuite) TestBuildAddLocalFileWithCache(c *check.C) {
  2302. name := "testbuildaddlocalfilewithcache"
  2303. name2 := "testbuildaddlocalfilewithcache2"
  2304. dockerfile := `
  2305. FROM busybox
  2306. MAINTAINER dockerio
  2307. ADD foo /usr/lib/bla/bar
  2308. RUN [ "$(cat /usr/lib/bla/bar)" = "hello" ]`
  2309. ctx, err := fakeContext(dockerfile, map[string]string{
  2310. "foo": "hello",
  2311. })
  2312. defer ctx.Close()
  2313. if err != nil {
  2314. c.Fatal(err)
  2315. }
  2316. id1, err := buildImageFromContext(name, ctx, true)
  2317. if err != nil {
  2318. c.Fatal(err)
  2319. }
  2320. id2, err := buildImageFromContext(name2, ctx, true)
  2321. if err != nil {
  2322. c.Fatal(err)
  2323. }
  2324. if id1 != id2 {
  2325. c.Fatal("The cache should have been used but hasn't.")
  2326. }
  2327. }
  2328. func (s *DockerSuite) TestBuildAddMultipleLocalFileWithCache(c *check.C) {
  2329. name := "testbuildaddmultiplelocalfilewithcache"
  2330. name2 := "testbuildaddmultiplelocalfilewithcache2"
  2331. dockerfile := `
  2332. FROM busybox
  2333. MAINTAINER dockerio
  2334. ADD foo Dockerfile /usr/lib/bla/
  2335. RUN [ "$(cat /usr/lib/bla/foo)" = "hello" ]`
  2336. ctx, err := fakeContext(dockerfile, map[string]string{
  2337. "foo": "hello",
  2338. })
  2339. defer ctx.Close()
  2340. if err != nil {
  2341. c.Fatal(err)
  2342. }
  2343. id1, err := buildImageFromContext(name, ctx, true)
  2344. if err != nil {
  2345. c.Fatal(err)
  2346. }
  2347. id2, err := buildImageFromContext(name2, ctx, true)
  2348. if err != nil {
  2349. c.Fatal(err)
  2350. }
  2351. if id1 != id2 {
  2352. c.Fatal("The cache should have been used but hasn't.")
  2353. }
  2354. }
  2355. func (s *DockerSuite) TestBuildAddLocalFileWithoutCache(c *check.C) {
  2356. name := "testbuildaddlocalfilewithoutcache"
  2357. name2 := "testbuildaddlocalfilewithoutcache2"
  2358. dockerfile := `
  2359. FROM busybox
  2360. MAINTAINER dockerio
  2361. ADD foo /usr/lib/bla/bar
  2362. RUN [ "$(cat /usr/lib/bla/bar)" = "hello" ]`
  2363. ctx, err := fakeContext(dockerfile, map[string]string{
  2364. "foo": "hello",
  2365. })
  2366. defer ctx.Close()
  2367. if err != nil {
  2368. c.Fatal(err)
  2369. }
  2370. id1, err := buildImageFromContext(name, ctx, true)
  2371. if err != nil {
  2372. c.Fatal(err)
  2373. }
  2374. id2, err := buildImageFromContext(name2, ctx, false)
  2375. if err != nil {
  2376. c.Fatal(err)
  2377. }
  2378. if id1 == id2 {
  2379. c.Fatal("The cache should have been invalided but hasn't.")
  2380. }
  2381. }
  2382. func (s *DockerSuite) TestBuildCopyDirButNotFile(c *check.C) {
  2383. name := "testbuildcopydirbutnotfile"
  2384. name2 := "testbuildcopydirbutnotfile2"
  2385. dockerfile := `
  2386. FROM scratch
  2387. COPY dir /tmp/`
  2388. ctx, err := fakeContext(dockerfile, map[string]string{
  2389. "dir/foo": "hello",
  2390. })
  2391. defer ctx.Close()
  2392. if err != nil {
  2393. c.Fatal(err)
  2394. }
  2395. id1, err := buildImageFromContext(name, ctx, true)
  2396. if err != nil {
  2397. c.Fatal(err)
  2398. }
  2399. // Check that adding file with similar name doesn't mess with cache
  2400. if err := ctx.Add("dir_file", "hello2"); err != nil {
  2401. c.Fatal(err)
  2402. }
  2403. id2, err := buildImageFromContext(name2, ctx, true)
  2404. if err != nil {
  2405. c.Fatal(err)
  2406. }
  2407. if id1 != id2 {
  2408. c.Fatal("The cache should have been used but wasn't")
  2409. }
  2410. }
  2411. func (s *DockerSuite) TestBuildAddCurrentDirWithCache(c *check.C) {
  2412. name := "testbuildaddcurrentdirwithcache"
  2413. name2 := name + "2"
  2414. name3 := name + "3"
  2415. name4 := name + "4"
  2416. name5 := name + "5"
  2417. dockerfile := `
  2418. FROM scratch
  2419. MAINTAINER dockerio
  2420. ADD . /usr/lib/bla`
  2421. ctx, err := fakeContext(dockerfile, map[string]string{
  2422. "foo": "hello",
  2423. })
  2424. defer ctx.Close()
  2425. if err != nil {
  2426. c.Fatal(err)
  2427. }
  2428. id1, err := buildImageFromContext(name, ctx, true)
  2429. if err != nil {
  2430. c.Fatal(err)
  2431. }
  2432. // Check that adding file invalidate cache of "ADD ."
  2433. if err := ctx.Add("bar", "hello2"); err != nil {
  2434. c.Fatal(err)
  2435. }
  2436. id2, err := buildImageFromContext(name2, ctx, true)
  2437. if err != nil {
  2438. c.Fatal(err)
  2439. }
  2440. if id1 == id2 {
  2441. c.Fatal("The cache should have been invalided but hasn't.")
  2442. }
  2443. // Check that changing file invalidate cache of "ADD ."
  2444. if err := ctx.Add("foo", "hello1"); err != nil {
  2445. c.Fatal(err)
  2446. }
  2447. id3, err := buildImageFromContext(name3, ctx, true)
  2448. if err != nil {
  2449. c.Fatal(err)
  2450. }
  2451. if id2 == id3 {
  2452. c.Fatal("The cache should have been invalided but hasn't.")
  2453. }
  2454. // Check that changing file to same content invalidate cache of "ADD ."
  2455. time.Sleep(1 * time.Second) // wait second because of mtime precision
  2456. if err := ctx.Add("foo", "hello1"); err != nil {
  2457. c.Fatal(err)
  2458. }
  2459. id4, err := buildImageFromContext(name4, ctx, true)
  2460. if err != nil {
  2461. c.Fatal(err)
  2462. }
  2463. if id3 == id4 {
  2464. c.Fatal("The cache should have been invalided but hasn't.")
  2465. }
  2466. id5, err := buildImageFromContext(name5, ctx, true)
  2467. if err != nil {
  2468. c.Fatal(err)
  2469. }
  2470. if id4 != id5 {
  2471. c.Fatal("The cache should have been used but hasn't.")
  2472. }
  2473. }
  2474. func (s *DockerSuite) TestBuildAddCurrentDirWithoutCache(c *check.C) {
  2475. name := "testbuildaddcurrentdirwithoutcache"
  2476. name2 := "testbuildaddcurrentdirwithoutcache2"
  2477. dockerfile := `
  2478. FROM scratch
  2479. MAINTAINER dockerio
  2480. ADD . /usr/lib/bla`
  2481. ctx, err := fakeContext(dockerfile, map[string]string{
  2482. "foo": "hello",
  2483. })
  2484. defer ctx.Close()
  2485. if err != nil {
  2486. c.Fatal(err)
  2487. }
  2488. id1, err := buildImageFromContext(name, ctx, true)
  2489. if err != nil {
  2490. c.Fatal(err)
  2491. }
  2492. id2, err := buildImageFromContext(name2, ctx, false)
  2493. if err != nil {
  2494. c.Fatal(err)
  2495. }
  2496. if id1 == id2 {
  2497. c.Fatal("The cache should have been invalided but hasn't.")
  2498. }
  2499. }
  2500. func (s *DockerSuite) TestBuildAddRemoteFileWithCache(c *check.C) {
  2501. name := "testbuildaddremotefilewithcache"
  2502. server, err := fakeStorage(map[string]string{
  2503. "baz": "hello",
  2504. })
  2505. if err != nil {
  2506. c.Fatal(err)
  2507. }
  2508. defer server.Close()
  2509. id1, err := buildImage(name,
  2510. fmt.Sprintf(`FROM scratch
  2511. MAINTAINER dockerio
  2512. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2513. true)
  2514. if err != nil {
  2515. c.Fatal(err)
  2516. }
  2517. id2, 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. if id1 != id2 {
  2526. c.Fatal("The cache should have been used but hasn't.")
  2527. }
  2528. }
  2529. func (s *DockerSuite) TestBuildAddRemoteFileWithoutCache(c *check.C) {
  2530. name := "testbuildaddremotefilewithoutcache"
  2531. name2 := "testbuildaddremotefilewithoutcache2"
  2532. server, err := fakeStorage(map[string]string{
  2533. "baz": "hello",
  2534. })
  2535. if err != nil {
  2536. c.Fatal(err)
  2537. }
  2538. defer server.Close()
  2539. id1, err := buildImage(name,
  2540. fmt.Sprintf(`FROM scratch
  2541. MAINTAINER dockerio
  2542. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2543. true)
  2544. if err != nil {
  2545. c.Fatal(err)
  2546. }
  2547. id2, err := buildImage(name2,
  2548. fmt.Sprintf(`FROM scratch
  2549. MAINTAINER dockerio
  2550. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2551. false)
  2552. if err != nil {
  2553. c.Fatal(err)
  2554. }
  2555. if id1 == id2 {
  2556. c.Fatal("The cache should have been invalided but hasn't.")
  2557. }
  2558. }
  2559. func (s *DockerSuite) TestBuildAddRemoteFileMTime(c *check.C) {
  2560. name := "testbuildaddremotefilemtime"
  2561. name2 := name + "2"
  2562. name3 := name + "3"
  2563. name4 := name + "4"
  2564. files := map[string]string{"baz": "hello"}
  2565. server, err := fakeStorage(files)
  2566. if err != nil {
  2567. c.Fatal(err)
  2568. }
  2569. defer server.Close()
  2570. ctx, err := fakeContext(fmt.Sprintf(`FROM scratch
  2571. MAINTAINER dockerio
  2572. ADD %s/baz /usr/lib/baz/quux`, server.URL()), nil)
  2573. if err != nil {
  2574. c.Fatal(err)
  2575. }
  2576. defer ctx.Close()
  2577. id1, err := buildImageFromContext(name, ctx, true)
  2578. if err != nil {
  2579. c.Fatal(err)
  2580. }
  2581. id2, err := buildImageFromContext(name2, ctx, true)
  2582. if err != nil {
  2583. c.Fatal(err)
  2584. }
  2585. if id1 != id2 {
  2586. c.Fatal("The cache should have been used but wasn't - #1")
  2587. }
  2588. // Now create a different server withsame contents (causes different mtim)
  2589. // This time the cache should not be used
  2590. // allow some time for clock to pass as mtime precision is only 1s
  2591. time.Sleep(2 * time.Second)
  2592. server2, err := fakeStorage(files)
  2593. if err != nil {
  2594. c.Fatal(err)
  2595. }
  2596. defer server2.Close()
  2597. ctx2, err := fakeContext(fmt.Sprintf(`FROM scratch
  2598. MAINTAINER dockerio
  2599. ADD %s/baz /usr/lib/baz/quux`, server2.URL()), nil)
  2600. if err != nil {
  2601. c.Fatal(err)
  2602. }
  2603. defer ctx2.Close()
  2604. id3, err := buildImageFromContext(name3, ctx2, true)
  2605. if err != nil {
  2606. c.Fatal(err)
  2607. }
  2608. if id1 == id3 {
  2609. c.Fatal("The cache should not have been used but was")
  2610. }
  2611. // And for good measure do it again and make sure cache is used this time
  2612. id4, err := buildImageFromContext(name4, ctx2, true)
  2613. if err != nil {
  2614. c.Fatal(err)
  2615. }
  2616. if id3 != id4 {
  2617. c.Fatal("The cache should have been used but wasn't - #2")
  2618. }
  2619. }
  2620. func (s *DockerSuite) TestBuildAddLocalAndRemoteFilesWithCache(c *check.C) {
  2621. name := "testbuildaddlocalandremotefilewithcache"
  2622. server, err := fakeStorage(map[string]string{
  2623. "baz": "hello",
  2624. })
  2625. if err != nil {
  2626. c.Fatal(err)
  2627. }
  2628. defer server.Close()
  2629. ctx, err := fakeContext(fmt.Sprintf(`FROM scratch
  2630. MAINTAINER dockerio
  2631. ADD foo /usr/lib/bla/bar
  2632. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2633. map[string]string{
  2634. "foo": "hello world",
  2635. })
  2636. if err != nil {
  2637. c.Fatal(err)
  2638. }
  2639. defer ctx.Close()
  2640. id1, err := buildImageFromContext(name, ctx, true)
  2641. if err != nil {
  2642. c.Fatal(err)
  2643. }
  2644. id2, err := buildImageFromContext(name, ctx, true)
  2645. if err != nil {
  2646. c.Fatal(err)
  2647. }
  2648. if id1 != id2 {
  2649. c.Fatal("The cache should have been used but hasn't.")
  2650. }
  2651. }
  2652. func testContextTar(c *check.C, compression archive.Compression) {
  2653. ctx, err := fakeContext(
  2654. `FROM busybox
  2655. ADD foo /foo
  2656. CMD ["cat", "/foo"]`,
  2657. map[string]string{
  2658. "foo": "bar",
  2659. },
  2660. )
  2661. defer ctx.Close()
  2662. if err != nil {
  2663. c.Fatal(err)
  2664. }
  2665. context, err := archive.Tar(ctx.Dir, compression)
  2666. if err != nil {
  2667. c.Fatalf("failed to build context tar: %v", err)
  2668. }
  2669. name := "contexttar"
  2670. buildCmd := exec.Command(dockerBinary, "build", "-t", name, "-")
  2671. buildCmd.Stdin = context
  2672. if out, _, err := runCommandWithOutput(buildCmd); err != nil {
  2673. c.Fatalf("build failed to complete: %v %v", out, err)
  2674. }
  2675. }
  2676. func (s *DockerSuite) TestBuildContextTarGzip(c *check.C) {
  2677. testContextTar(c, archive.Gzip)
  2678. }
  2679. func (s *DockerSuite) TestBuildContextTarNoCompression(c *check.C) {
  2680. testContextTar(c, archive.Uncompressed)
  2681. }
  2682. func (s *DockerSuite) TestBuildNoContext(c *check.C) {
  2683. buildCmd := exec.Command(dockerBinary, "build", "-t", "nocontext", "-")
  2684. buildCmd.Stdin = strings.NewReader("FROM busybox\nCMD echo ok\n")
  2685. if out, _, err := runCommandWithOutput(buildCmd); err != nil {
  2686. c.Fatalf("build failed to complete: %v %v", out, err)
  2687. }
  2688. if out, _ := dockerCmd(c, "run", "--rm", "nocontext"); out != "ok\n" {
  2689. c.Fatalf("run produced invalid output: %q, expected %q", out, "ok")
  2690. }
  2691. }
  2692. // TODO: TestCaching
  2693. func (s *DockerSuite) TestBuildAddLocalAndRemoteFilesWithoutCache(c *check.C) {
  2694. name := "testbuildaddlocalandremotefilewithoutcache"
  2695. name2 := "testbuildaddlocalandremotefilewithoutcache2"
  2696. server, err := fakeStorage(map[string]string{
  2697. "baz": "hello",
  2698. })
  2699. if err != nil {
  2700. c.Fatal(err)
  2701. }
  2702. defer server.Close()
  2703. ctx, err := fakeContext(fmt.Sprintf(`FROM scratch
  2704. MAINTAINER dockerio
  2705. ADD foo /usr/lib/bla/bar
  2706. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2707. map[string]string{
  2708. "foo": "hello world",
  2709. })
  2710. if err != nil {
  2711. c.Fatal(err)
  2712. }
  2713. defer ctx.Close()
  2714. id1, err := buildImageFromContext(name, ctx, true)
  2715. if err != nil {
  2716. c.Fatal(err)
  2717. }
  2718. id2, err := buildImageFromContext(name2, ctx, false)
  2719. if err != nil {
  2720. c.Fatal(err)
  2721. }
  2722. if id1 == id2 {
  2723. c.Fatal("The cache should have been invalided but hasn't.")
  2724. }
  2725. }
  2726. func (s *DockerSuite) TestBuildWithVolumeOwnership(c *check.C) {
  2727. name := "testbuildimg"
  2728. _, err := buildImage(name,
  2729. `FROM busybox:latest
  2730. RUN mkdir /test && chown daemon:daemon /test && chmod 0600 /test
  2731. VOLUME /test`,
  2732. true)
  2733. if err != nil {
  2734. c.Fatal(err)
  2735. }
  2736. cmd := exec.Command(dockerBinary, "run", "--rm", "testbuildimg", "ls", "-la", "/test")
  2737. out, _, err := runCommandWithOutput(cmd)
  2738. if err != nil {
  2739. c.Fatal(out, err)
  2740. }
  2741. if expected := "drw-------"; !strings.Contains(out, expected) {
  2742. c.Fatalf("expected %s received %s", expected, out)
  2743. }
  2744. if expected := "daemon daemon"; !strings.Contains(out, expected) {
  2745. c.Fatalf("expected %s received %s", expected, out)
  2746. }
  2747. }
  2748. // testing #1405 - config.Cmd does not get cleaned up if
  2749. // utilizing cache
  2750. func (s *DockerSuite) TestBuildEntrypointRunCleanup(c *check.C) {
  2751. name := "testbuildcmdcleanup"
  2752. if _, err := buildImage(name,
  2753. `FROM busybox
  2754. RUN echo "hello"`,
  2755. true); err != nil {
  2756. c.Fatal(err)
  2757. }
  2758. ctx, err := fakeContext(`FROM busybox
  2759. RUN echo "hello"
  2760. ADD foo /foo
  2761. ENTRYPOINT ["/bin/echo"]`,
  2762. map[string]string{
  2763. "foo": "hello",
  2764. })
  2765. defer ctx.Close()
  2766. if err != nil {
  2767. c.Fatal(err)
  2768. }
  2769. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2770. c.Fatal(err)
  2771. }
  2772. res, err := inspectField(name, "Config.Cmd")
  2773. if err != nil {
  2774. c.Fatal(err)
  2775. }
  2776. // Cmd must be cleaned up
  2777. if res != "<nil>" {
  2778. c.Fatalf("Cmd %s, expected nil", res)
  2779. }
  2780. }
  2781. func (s *DockerSuite) TestBuildForbiddenContextPath(c *check.C) {
  2782. name := "testbuildforbidpath"
  2783. ctx, err := fakeContext(`FROM scratch
  2784. ADD ../../ test/
  2785. `,
  2786. map[string]string{
  2787. "test.txt": "test1",
  2788. "other.txt": "other",
  2789. })
  2790. defer ctx.Close()
  2791. if err != nil {
  2792. c.Fatal(err)
  2793. }
  2794. expected := "Forbidden path outside the build context: ../../ "
  2795. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  2796. c.Fatalf("Wrong error: (should contain \"%s\") got:\n%v", expected, err)
  2797. }
  2798. }
  2799. func (s *DockerSuite) TestBuildAddFileNotFound(c *check.C) {
  2800. name := "testbuildaddnotfound"
  2801. ctx, err := fakeContext(`FROM scratch
  2802. ADD foo /usr/local/bar`,
  2803. map[string]string{"bar": "hello"})
  2804. defer ctx.Close()
  2805. if err != nil {
  2806. c.Fatal(err)
  2807. }
  2808. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2809. if !strings.Contains(err.Error(), "foo: no such file or directory") {
  2810. c.Fatalf("Wrong error %v, must be about missing foo file or directory", err)
  2811. }
  2812. } else {
  2813. c.Fatal("Error must not be nil")
  2814. }
  2815. }
  2816. func (s *DockerSuite) TestBuildInheritance(c *check.C) {
  2817. name := "testbuildinheritance"
  2818. _, err := buildImage(name,
  2819. `FROM scratch
  2820. EXPOSE 2375`,
  2821. true)
  2822. if err != nil {
  2823. c.Fatal(err)
  2824. }
  2825. ports1, err := inspectField(name, "Config.ExposedPorts")
  2826. if err != nil {
  2827. c.Fatal(err)
  2828. }
  2829. _, err = buildImage(name,
  2830. fmt.Sprintf(`FROM %s
  2831. ENTRYPOINT ["/bin/echo"]`, name),
  2832. true)
  2833. if err != nil {
  2834. c.Fatal(err)
  2835. }
  2836. res, err := inspectField(name, "Config.Entrypoint")
  2837. if err != nil {
  2838. c.Fatal(err)
  2839. }
  2840. if expected := "{[/bin/echo]}"; res != expected {
  2841. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  2842. }
  2843. ports2, err := inspectField(name, "Config.ExposedPorts")
  2844. if err != nil {
  2845. c.Fatal(err)
  2846. }
  2847. if ports1 != ports2 {
  2848. c.Fatalf("Ports must be same: %s != %s", ports1, ports2)
  2849. }
  2850. }
  2851. func (s *DockerSuite) TestBuildFails(c *check.C) {
  2852. name := "testbuildfails"
  2853. _, err := buildImage(name,
  2854. `FROM busybox
  2855. RUN sh -c "exit 23"`,
  2856. true)
  2857. if err != nil {
  2858. if !strings.Contains(err.Error(), "returned a non-zero code: 23") {
  2859. c.Fatalf("Wrong error %v, must be about non-zero code 23", err)
  2860. }
  2861. } else {
  2862. c.Fatal("Error must not be nil")
  2863. }
  2864. }
  2865. func (s *DockerSuite) TestBuildFailsDockerfileEmpty(c *check.C) {
  2866. name := "testbuildfails"
  2867. _, err := buildImage(name, ``, true)
  2868. if err != nil {
  2869. if !strings.Contains(err.Error(), "The Dockerfile (Dockerfile) cannot be empty") {
  2870. c.Fatalf("Wrong error %v, must be about empty Dockerfile", err)
  2871. }
  2872. } else {
  2873. c.Fatal("Error must not be nil")
  2874. }
  2875. }
  2876. func (s *DockerSuite) TestBuildOnBuild(c *check.C) {
  2877. name := "testbuildonbuild"
  2878. _, err := buildImage(name,
  2879. `FROM busybox
  2880. ONBUILD RUN touch foobar`,
  2881. true)
  2882. if err != nil {
  2883. c.Fatal(err)
  2884. }
  2885. _, err = buildImage(name,
  2886. fmt.Sprintf(`FROM %s
  2887. RUN [ -f foobar ]`, name),
  2888. true)
  2889. if err != nil {
  2890. c.Fatal(err)
  2891. }
  2892. }
  2893. func (s *DockerSuite) TestBuildOnBuildForbiddenChained(c *check.C) {
  2894. name := "testbuildonbuildforbiddenchained"
  2895. _, err := buildImage(name,
  2896. `FROM busybox
  2897. ONBUILD ONBUILD RUN touch foobar`,
  2898. true)
  2899. if err != nil {
  2900. if !strings.Contains(err.Error(), "Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed") {
  2901. c.Fatalf("Wrong error %v, must be about chaining ONBUILD", err)
  2902. }
  2903. } else {
  2904. c.Fatal("Error must not be nil")
  2905. }
  2906. }
  2907. func (s *DockerSuite) TestBuildOnBuildForbiddenFrom(c *check.C) {
  2908. name := "testbuildonbuildforbiddenfrom"
  2909. _, err := buildImage(name,
  2910. `FROM busybox
  2911. ONBUILD FROM scratch`,
  2912. true)
  2913. if err != nil {
  2914. if !strings.Contains(err.Error(), "FROM isn't allowed as an ONBUILD trigger") {
  2915. c.Fatalf("Wrong error %v, must be about FROM forbidden", err)
  2916. }
  2917. } else {
  2918. c.Fatal("Error must not be nil")
  2919. }
  2920. }
  2921. func (s *DockerSuite) TestBuildOnBuildForbiddenMaintainer(c *check.C) {
  2922. name := "testbuildonbuildforbiddenmaintainer"
  2923. _, err := buildImage(name,
  2924. `FROM busybox
  2925. ONBUILD MAINTAINER docker.io`,
  2926. true)
  2927. if err != nil {
  2928. if !strings.Contains(err.Error(), "MAINTAINER isn't allowed as an ONBUILD trigger") {
  2929. c.Fatalf("Wrong error %v, must be about MAINTAINER forbidden", err)
  2930. }
  2931. } else {
  2932. c.Fatal("Error must not be nil")
  2933. }
  2934. }
  2935. // gh #2446
  2936. func (s *DockerSuite) TestBuildAddToSymlinkDest(c *check.C) {
  2937. name := "testbuildaddtosymlinkdest"
  2938. ctx, err := fakeContext(`FROM busybox
  2939. RUN mkdir /foo
  2940. RUN ln -s /foo /bar
  2941. ADD foo /bar/
  2942. RUN [ -f /bar/foo ]
  2943. RUN [ -f /foo/foo ]`,
  2944. map[string]string{
  2945. "foo": "hello",
  2946. })
  2947. if err != nil {
  2948. c.Fatal(err)
  2949. }
  2950. defer ctx.Close()
  2951. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2952. c.Fatal(err)
  2953. }
  2954. }
  2955. func (s *DockerSuite) TestBuildEscapeWhitespace(c *check.C) {
  2956. name := "testbuildescaping"
  2957. _, err := buildImage(name, `
  2958. FROM busybox
  2959. MAINTAINER "Docker \
  2960. IO <io@\
  2961. docker.com>"
  2962. `, true)
  2963. res, err := inspectField(name, "Author")
  2964. if err != nil {
  2965. c.Fatal(err)
  2966. }
  2967. if res != "\"Docker IO <io@docker.com>\"" {
  2968. c.Fatalf("Parsed string did not match the escaped string. Got: %q", res)
  2969. }
  2970. }
  2971. func (s *DockerSuite) TestBuildVerifyIntString(c *check.C) {
  2972. // Verify that strings that look like ints are still passed as strings
  2973. name := "testbuildstringing"
  2974. _, err := buildImage(name, `
  2975. FROM busybox
  2976. MAINTAINER 123
  2977. `, true)
  2978. out, rc, err := runCommandWithOutput(exec.Command(dockerBinary, "inspect", name))
  2979. if rc != 0 || err != nil {
  2980. c.Fatalf("Unexpected error from inspect: rc: %v err: %v", rc, err)
  2981. }
  2982. if !strings.Contains(out, "\"123\"") {
  2983. c.Fatalf("Output does not contain the int as a string:\n%s", out)
  2984. }
  2985. }
  2986. func (s *DockerSuite) TestBuildDockerignore(c *check.C) {
  2987. name := "testbuilddockerignore"
  2988. dockerfile := `
  2989. FROM busybox
  2990. ADD . /bla
  2991. RUN [[ -f /bla/src/x.go ]]
  2992. RUN [[ -f /bla/Makefile ]]
  2993. RUN [[ ! -e /bla/src/_vendor ]]
  2994. RUN [[ ! -e /bla/.gitignore ]]
  2995. RUN [[ ! -e /bla/README.md ]]
  2996. RUN [[ ! -e /bla/dir/foo ]]
  2997. RUN [[ ! -e /bla/foo ]]
  2998. RUN [[ ! -e /bla/.git ]]`
  2999. ctx, err := fakeContext(dockerfile, map[string]string{
  3000. "Makefile": "all:",
  3001. ".git/HEAD": "ref: foo",
  3002. "src/x.go": "package main",
  3003. "src/_vendor/v.go": "package main",
  3004. "dir/foo": "",
  3005. ".gitignore": "",
  3006. "README.md": "readme",
  3007. ".dockerignore": `
  3008. .git
  3009. pkg
  3010. .gitignore
  3011. src/_vendor
  3012. *.md
  3013. dir`,
  3014. })
  3015. if err != nil {
  3016. c.Fatal(err)
  3017. }
  3018. defer ctx.Close()
  3019. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3020. c.Fatal(err)
  3021. }
  3022. }
  3023. func (s *DockerSuite) TestBuildDockerignoreCleanPaths(c *check.C) {
  3024. name := "testbuilddockerignorecleanpaths"
  3025. dockerfile := `
  3026. FROM busybox
  3027. ADD . /tmp/
  3028. RUN (! ls /tmp/foo) && (! ls /tmp/foo2) && (! ls /tmp/dir1/foo)`
  3029. ctx, err := fakeContext(dockerfile, map[string]string{
  3030. "foo": "foo",
  3031. "foo2": "foo2",
  3032. "dir1/foo": "foo in dir1",
  3033. ".dockerignore": "./foo\ndir1//foo\n./dir1/../foo2",
  3034. })
  3035. if err != nil {
  3036. c.Fatal(err)
  3037. }
  3038. defer ctx.Close()
  3039. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3040. c.Fatal(err)
  3041. }
  3042. }
  3043. func (s *DockerSuite) TestBuildDockerignoreExceptions(c *check.C) {
  3044. name := "testbuilddockerignoreexceptions"
  3045. defer deleteImages(name)
  3046. dockerfile := `
  3047. FROM busybox
  3048. ADD . /bla
  3049. RUN [[ -f /bla/src/x.go ]]
  3050. RUN [[ -f /bla/Makefile ]]
  3051. RUN [[ ! -e /bla/src/_vendor ]]
  3052. RUN [[ ! -e /bla/.gitignore ]]
  3053. RUN [[ ! -e /bla/README.md ]]
  3054. RUN [[ -e /bla/dir/dir/foo ]]
  3055. RUN [[ ! -e /bla/dir/foo1 ]]
  3056. RUN [[ -f /bla/dir/e ]]
  3057. RUN [[ -f /bla/dir/e-dir/foo ]]
  3058. RUN [[ ! -e /bla/foo ]]
  3059. RUN [[ ! -e /bla/.git ]]`
  3060. ctx, err := fakeContext(dockerfile, map[string]string{
  3061. "Makefile": "all:",
  3062. ".git/HEAD": "ref: foo",
  3063. "src/x.go": "package main",
  3064. "src/_vendor/v.go": "package main",
  3065. "dir/foo": "",
  3066. "dir/foo1": "",
  3067. "dir/dir/f1": "",
  3068. "dir/dir/foo": "",
  3069. "dir/e": "",
  3070. "dir/e-dir/foo": "",
  3071. ".gitignore": "",
  3072. "README.md": "readme",
  3073. ".dockerignore": `
  3074. .git
  3075. pkg
  3076. .gitignore
  3077. src/_vendor
  3078. *.md
  3079. dir
  3080. !dir/e*
  3081. !dir/dir/foo`,
  3082. })
  3083. if err != nil {
  3084. c.Fatal(err)
  3085. }
  3086. defer ctx.Close()
  3087. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3088. c.Fatal(err)
  3089. }
  3090. }
  3091. func (s *DockerSuite) TestBuildDockerignoringDockerfile(c *check.C) {
  3092. name := "testbuilddockerignoredockerfile"
  3093. dockerfile := `
  3094. FROM busybox
  3095. ADD . /tmp/
  3096. RUN ! ls /tmp/Dockerfile
  3097. RUN ls /tmp/.dockerignore`
  3098. ctx, err := fakeContext(dockerfile, map[string]string{
  3099. "Dockerfile": dockerfile,
  3100. ".dockerignore": "Dockerfile\n",
  3101. })
  3102. if err != nil {
  3103. c.Fatal(err)
  3104. }
  3105. defer ctx.Close()
  3106. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3107. c.Fatalf("Didn't ignore Dockerfile correctly:%s", err)
  3108. }
  3109. // now try it with ./Dockerfile
  3110. ctx.Add(".dockerignore", "./Dockerfile\n")
  3111. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3112. c.Fatalf("Didn't ignore ./Dockerfile correctly:%s", err)
  3113. }
  3114. }
  3115. func (s *DockerSuite) TestBuildDockerignoringRenamedDockerfile(c *check.C) {
  3116. name := "testbuilddockerignoredockerfile"
  3117. dockerfile := `
  3118. FROM busybox
  3119. ADD . /tmp/
  3120. RUN ls /tmp/Dockerfile
  3121. RUN ! ls /tmp/MyDockerfile
  3122. RUN ls /tmp/.dockerignore`
  3123. ctx, err := fakeContext(dockerfile, map[string]string{
  3124. "Dockerfile": "Should not use me",
  3125. "MyDockerfile": dockerfile,
  3126. ".dockerignore": "MyDockerfile\n",
  3127. })
  3128. if err != nil {
  3129. c.Fatal(err)
  3130. }
  3131. defer ctx.Close()
  3132. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3133. c.Fatalf("Didn't ignore MyDockerfile correctly:%s", err)
  3134. }
  3135. // now try it with ./MyDockerfile
  3136. ctx.Add(".dockerignore", "./MyDockerfile\n")
  3137. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3138. c.Fatalf("Didn't ignore ./MyDockerfile correctly:%s", err)
  3139. }
  3140. }
  3141. func (s *DockerSuite) TestBuildDockerignoringDockerignore(c *check.C) {
  3142. name := "testbuilddockerignoredockerignore"
  3143. dockerfile := `
  3144. FROM busybox
  3145. ADD . /tmp/
  3146. RUN ! ls /tmp/.dockerignore
  3147. RUN ls /tmp/Dockerfile`
  3148. ctx, err := fakeContext(dockerfile, map[string]string{
  3149. "Dockerfile": dockerfile,
  3150. ".dockerignore": ".dockerignore\n",
  3151. })
  3152. defer ctx.Close()
  3153. if err != nil {
  3154. c.Fatal(err)
  3155. }
  3156. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3157. c.Fatalf("Didn't ignore .dockerignore correctly:%s", err)
  3158. }
  3159. }
  3160. func (s *DockerSuite) TestBuildDockerignoreTouchDockerfile(c *check.C) {
  3161. var id1 string
  3162. var id2 string
  3163. name := "testbuilddockerignoretouchdockerfile"
  3164. dockerfile := `
  3165. FROM busybox
  3166. ADD . /tmp/`
  3167. ctx, err := fakeContext(dockerfile, map[string]string{
  3168. "Dockerfile": dockerfile,
  3169. ".dockerignore": "Dockerfile\n",
  3170. })
  3171. defer ctx.Close()
  3172. if err != nil {
  3173. c.Fatal(err)
  3174. }
  3175. if id1, err = buildImageFromContext(name, ctx, true); err != nil {
  3176. c.Fatalf("Didn't build it correctly:%s", err)
  3177. }
  3178. if id2, err = buildImageFromContext(name, ctx, true); err != nil {
  3179. c.Fatalf("Didn't build it correctly:%s", err)
  3180. }
  3181. if id1 != id2 {
  3182. c.Fatalf("Didn't use the cache - 1")
  3183. }
  3184. // Now make sure touching Dockerfile doesn't invalidate the cache
  3185. if err = ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil {
  3186. c.Fatalf("Didn't add Dockerfile: %s", err)
  3187. }
  3188. if id2, err = buildImageFromContext(name, ctx, true); err != nil {
  3189. c.Fatalf("Didn't build it correctly:%s", err)
  3190. }
  3191. if id1 != id2 {
  3192. c.Fatalf("Didn't use the cache - 2")
  3193. }
  3194. // One more time but just 'touch' it instead of changing the content
  3195. if err = ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil {
  3196. c.Fatalf("Didn't add Dockerfile: %s", err)
  3197. }
  3198. if id2, err = buildImageFromContext(name, ctx, true); err != nil {
  3199. c.Fatalf("Didn't build it correctly:%s", err)
  3200. }
  3201. if id1 != id2 {
  3202. c.Fatalf("Didn't use the cache - 3")
  3203. }
  3204. }
  3205. func (s *DockerSuite) TestBuildDockerignoringWholeDir(c *check.C) {
  3206. name := "testbuilddockerignorewholedir"
  3207. dockerfile := `
  3208. FROM busybox
  3209. COPY . /
  3210. RUN [[ ! -e /.gitignore ]]
  3211. RUN [[ -f /Makefile ]]`
  3212. ctx, err := fakeContext(dockerfile, map[string]string{
  3213. "Dockerfile": "FROM scratch",
  3214. "Makefile": "all:",
  3215. ".gitignore": "",
  3216. ".dockerignore": ".*\n",
  3217. })
  3218. defer ctx.Close()
  3219. if err != nil {
  3220. c.Fatal(err)
  3221. }
  3222. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3223. c.Fatal(err)
  3224. }
  3225. }
  3226. func (s *DockerSuite) TestBuildLineBreak(c *check.C) {
  3227. name := "testbuildlinebreak"
  3228. _, err := buildImage(name,
  3229. `FROM busybox
  3230. RUN sh -c 'echo root:testpass \
  3231. > /tmp/passwd'
  3232. RUN mkdir -p /var/run/sshd
  3233. RUN [ "$(cat /tmp/passwd)" = "root:testpass" ]
  3234. RUN [ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]`,
  3235. true)
  3236. if err != nil {
  3237. c.Fatal(err)
  3238. }
  3239. }
  3240. func (s *DockerSuite) TestBuildEOLInLine(c *check.C) {
  3241. name := "testbuildeolinline"
  3242. _, err := buildImage(name,
  3243. `FROM busybox
  3244. RUN sh -c 'echo root:testpass > /tmp/passwd'
  3245. RUN echo "foo \n bar"; echo "baz"
  3246. RUN mkdir -p /var/run/sshd
  3247. RUN [ "$(cat /tmp/passwd)" = "root:testpass" ]
  3248. RUN [ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]`,
  3249. true)
  3250. if err != nil {
  3251. c.Fatal(err)
  3252. }
  3253. }
  3254. func (s *DockerSuite) TestBuildCommentsShebangs(c *check.C) {
  3255. name := "testbuildcomments"
  3256. _, err := buildImage(name,
  3257. `FROM busybox
  3258. # This is an ordinary comment.
  3259. RUN { echo '#!/bin/sh'; echo 'echo hello world'; } > /hello.sh
  3260. RUN [ ! -x /hello.sh ]
  3261. # comment with line break \
  3262. RUN chmod +x /hello.sh
  3263. RUN [ -x /hello.sh ]
  3264. RUN [ "$(cat /hello.sh)" = $'#!/bin/sh\necho hello world' ]
  3265. RUN [ "$(/hello.sh)" = "hello world" ]`,
  3266. true)
  3267. if err != nil {
  3268. c.Fatal(err)
  3269. }
  3270. }
  3271. func (s *DockerSuite) TestBuildUsersAndGroups(c *check.C) {
  3272. name := "testbuildusers"
  3273. _, err := buildImage(name,
  3274. `FROM busybox
  3275. # Make sure our defaults work
  3276. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)" = '0:0/root:root' ]
  3277. # 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)
  3278. USER root
  3279. RUN [ "$(id -G):$(id -Gn)" = '0 10:root wheel' ]
  3280. # Setup dockerio user and group
  3281. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  3282. RUN echo 'dockerio:x:1001:' >> /etc/group
  3283. # Make sure we can switch to our user and all the information is exactly as we expect it to be
  3284. USER dockerio
  3285. RUN id -G
  3286. RUN id -Gn
  3287. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3288. # Switch back to root and double check that worked exactly as we might expect it to
  3289. USER root
  3290. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '0:0/root:root/0 10:root wheel' ]
  3291. # Add a "supplementary" group for our dockerio user
  3292. RUN echo 'supplementary:x:1002:dockerio' >> /etc/group
  3293. # ... and then go verify that we get it like we expect
  3294. USER dockerio
  3295. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  3296. USER 1001
  3297. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  3298. # super test the new "user:group" syntax
  3299. USER dockerio:dockerio
  3300. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3301. USER 1001:dockerio
  3302. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3303. USER dockerio:1001
  3304. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3305. USER 1001:1001
  3306. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3307. USER dockerio:supplementary
  3308. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3309. USER dockerio:1002
  3310. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3311. USER 1001:supplementary
  3312. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3313. USER 1001:1002
  3314. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3315. # make sure unknown uid/gid still works properly
  3316. USER 1042:1043
  3317. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1042:1043/1042:1043/1043:1043' ]`,
  3318. true)
  3319. if err != nil {
  3320. c.Fatal(err)
  3321. }
  3322. }
  3323. func (s *DockerSuite) TestBuildEnvUsage(c *check.C) {
  3324. name := "testbuildenvusage"
  3325. dockerfile := `FROM busybox
  3326. ENV HOME /root
  3327. ENV PATH $HOME/bin:$PATH
  3328. ENV PATH /tmp:$PATH
  3329. RUN [ "$PATH" = "/tmp:$HOME/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ]
  3330. ENV FOO /foo/baz
  3331. ENV BAR /bar
  3332. ENV BAZ $BAR
  3333. ENV FOOPATH $PATH:$FOO
  3334. RUN [ "$BAR" = "$BAZ" ]
  3335. RUN [ "$FOOPATH" = "$PATH:/foo/baz" ]
  3336. ENV FROM hello/docker/world
  3337. ENV TO /docker/world/hello
  3338. ADD $FROM $TO
  3339. RUN [ "$(cat $TO)" = "hello" ]
  3340. ENV abc=def
  3341. ENV ghi=$abc
  3342. RUN [ "$ghi" = "def" ]
  3343. `
  3344. ctx, err := fakeContext(dockerfile, map[string]string{
  3345. "hello/docker/world": "hello",
  3346. })
  3347. if err != nil {
  3348. c.Fatal(err)
  3349. }
  3350. defer ctx.Close()
  3351. _, err = buildImageFromContext(name, ctx, true)
  3352. if err != nil {
  3353. c.Fatal(err)
  3354. }
  3355. }
  3356. func (s *DockerSuite) TestBuildEnvUsage2(c *check.C) {
  3357. name := "testbuildenvusage2"
  3358. dockerfile := `FROM busybox
  3359. ENV abc=def
  3360. RUN [ "$abc" = "def" ]
  3361. ENV def="hello world"
  3362. RUN [ "$def" = "hello world" ]
  3363. ENV def=hello\ world
  3364. RUN [ "$def" = "hello world" ]
  3365. ENV v1=abc v2="hi there"
  3366. RUN [ "$v1" = "abc" ]
  3367. RUN [ "$v2" = "hi there" ]
  3368. ENV v3='boogie nights' v4="with'quotes too"
  3369. RUN [ "$v3" = "boogie nights" ]
  3370. RUN [ "$v4" = "with'quotes too" ]
  3371. ENV abc=zzz FROM=hello/docker/world
  3372. ENV abc=zzz TO=/docker/world/hello
  3373. ADD $FROM $TO
  3374. RUN [ "$(cat $TO)" = "hello" ]
  3375. ENV abc "zzz"
  3376. RUN [ $abc = "zzz" ]
  3377. ENV abc 'yyy'
  3378. RUN [ $abc = 'yyy' ]
  3379. ENV abc=
  3380. RUN [ "$abc" = "" ]
  3381. # use grep to make sure if the builder substitutes \$foo by mistake
  3382. # we don't get a false positive
  3383. ENV abc=\$foo
  3384. RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep foo)
  3385. ENV abc \$foo
  3386. RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep foo)
  3387. ENV abc=\'foo\'
  3388. RUN [ "$abc" = "'foo'" ]
  3389. ENV abc=\"foo\"
  3390. RUN [ "$abc" = "\"foo\"" ]
  3391. ENV abc "foo"
  3392. RUN [ "$abc" = "foo" ]
  3393. ENV abc 'foo'
  3394. RUN [ "$abc" = 'foo' ]
  3395. ENV abc \'foo\'
  3396. RUN [ "$abc" = "'foo'" ]
  3397. ENV abc \"foo\"
  3398. RUN [ "$abc" = '"foo"' ]
  3399. ENV abc=ABC
  3400. RUN [ "$abc" = "ABC" ]
  3401. ENV def=${abc:-DEF}
  3402. RUN [ "$def" = "ABC" ]
  3403. ENV def=${ccc:-DEF}
  3404. RUN [ "$def" = "DEF" ]
  3405. ENV def=${ccc:-${def}xx}
  3406. RUN [ "$def" = "DEFxx" ]
  3407. ENV def=${def:+ALT}
  3408. RUN [ "$def" = "ALT" ]
  3409. ENV def=${def:+${abc}:}
  3410. RUN [ "$def" = "ABC:" ]
  3411. ENV def=${ccc:-\$abc:}
  3412. RUN [ "$def" = '$abc:' ]
  3413. ENV def=${ccc:-\${abc}:}
  3414. RUN [ "$def" = '${abc:}' ]
  3415. ENV mypath=${mypath:+$mypath:}/home
  3416. RUN [ "$mypath" = '/home' ]
  3417. ENV mypath=${mypath:+$mypath:}/away
  3418. RUN [ "$mypath" = '/home:/away' ]
  3419. ENV e1=bar
  3420. ENV e2=$e1
  3421. ENV e3=$e11
  3422. ENV e4=\$e1
  3423. ENV e5=\$e11
  3424. RUN [ "$e0,$e1,$e2,$e3,$e4,$e5" = ',bar,bar,,$e1,$e11' ]
  3425. ENV ee1 bar
  3426. ENV ee2 $ee1
  3427. ENV ee3 $ee11
  3428. ENV ee4 \$ee1
  3429. ENV ee5 \$ee11
  3430. RUN [ "$ee1,$ee2,$ee3,$ee4,$ee5" = 'bar,bar,,$ee1,$ee11' ]
  3431. ENV eee1="foo"
  3432. ENV eee2='foo'
  3433. ENV eee3 "foo"
  3434. ENV eee4 'foo'
  3435. RUN [ "$eee1,$eee2,$eee3,$eee4" = 'foo,foo,foo,foo' ]
  3436. `
  3437. ctx, err := fakeContext(dockerfile, map[string]string{
  3438. "hello/docker/world": "hello",
  3439. })
  3440. if err != nil {
  3441. c.Fatal(err)
  3442. }
  3443. defer ctx.Close()
  3444. _, err = buildImageFromContext(name, ctx, true)
  3445. if err != nil {
  3446. c.Fatal(err)
  3447. }
  3448. }
  3449. func (s *DockerSuite) TestBuildAddScript(c *check.C) {
  3450. name := "testbuildaddscript"
  3451. dockerfile := `
  3452. FROM busybox
  3453. ADD test /test
  3454. RUN ["chmod","+x","/test"]
  3455. RUN ["/test"]
  3456. RUN [ "$(cat /testfile)" = 'test!' ]`
  3457. ctx, err := fakeContext(dockerfile, map[string]string{
  3458. "test": "#!/bin/sh\necho 'test!' > /testfile",
  3459. })
  3460. if err != nil {
  3461. c.Fatal(err)
  3462. }
  3463. defer ctx.Close()
  3464. _, err = buildImageFromContext(name, ctx, true)
  3465. if err != nil {
  3466. c.Fatal(err)
  3467. }
  3468. }
  3469. func (s *DockerSuite) TestBuildAddTar(c *check.C) {
  3470. name := "testbuildaddtar"
  3471. ctx := func() *FakeContext {
  3472. dockerfile := `
  3473. FROM busybox
  3474. ADD test.tar /
  3475. RUN cat /test/foo | grep Hi
  3476. ADD test.tar /test.tar
  3477. RUN cat /test.tar/test/foo | grep Hi
  3478. ADD test.tar /unlikely-to-exist
  3479. RUN cat /unlikely-to-exist/test/foo | grep Hi
  3480. ADD test.tar /unlikely-to-exist-trailing-slash/
  3481. RUN cat /unlikely-to-exist-trailing-slash/test/foo | grep Hi
  3482. RUN mkdir /existing-directory
  3483. ADD test.tar /existing-directory
  3484. RUN cat /existing-directory/test/foo | grep Hi
  3485. ADD test.tar /existing-directory-trailing-slash/
  3486. RUN cat /existing-directory-trailing-slash/test/foo | grep Hi`
  3487. tmpDir, err := ioutil.TempDir("", "fake-context")
  3488. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3489. if err != nil {
  3490. c.Fatalf("failed to create test.tar archive: %v", err)
  3491. }
  3492. defer testTar.Close()
  3493. tw := tar.NewWriter(testTar)
  3494. if err := tw.WriteHeader(&tar.Header{
  3495. Name: "test/foo",
  3496. Size: 2,
  3497. }); err != nil {
  3498. c.Fatalf("failed to write tar file header: %v", err)
  3499. }
  3500. if _, err := tw.Write([]byte("Hi")); err != nil {
  3501. c.Fatalf("failed to write tar file content: %v", err)
  3502. }
  3503. if err := tw.Close(); err != nil {
  3504. c.Fatalf("failed to close tar archive: %v", err)
  3505. }
  3506. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3507. c.Fatalf("failed to open destination dockerfile: %v", err)
  3508. }
  3509. return fakeContextFromDir(tmpDir)
  3510. }()
  3511. defer ctx.Close()
  3512. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3513. c.Fatalf("build failed to complete for TestBuildAddTar: %v", err)
  3514. }
  3515. }
  3516. func (s *DockerSuite) TestBuildAddTarXz(c *check.C) {
  3517. name := "testbuildaddtarxz"
  3518. ctx := func() *FakeContext {
  3519. dockerfile := `
  3520. FROM busybox
  3521. ADD test.tar.xz /
  3522. RUN cat /test/foo | grep Hi`
  3523. tmpDir, err := ioutil.TempDir("", "fake-context")
  3524. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3525. if err != nil {
  3526. c.Fatalf("failed to create test.tar archive: %v", err)
  3527. }
  3528. defer testTar.Close()
  3529. tw := tar.NewWriter(testTar)
  3530. if err := tw.WriteHeader(&tar.Header{
  3531. Name: "test/foo",
  3532. Size: 2,
  3533. }); err != nil {
  3534. c.Fatalf("failed to write tar file header: %v", err)
  3535. }
  3536. if _, err := tw.Write([]byte("Hi")); err != nil {
  3537. c.Fatalf("failed to write tar file content: %v", err)
  3538. }
  3539. if err := tw.Close(); err != nil {
  3540. c.Fatalf("failed to close tar archive: %v", err)
  3541. }
  3542. xzCompressCmd := exec.Command("xz", "-k", "test.tar")
  3543. xzCompressCmd.Dir = tmpDir
  3544. out, _, err := runCommandWithOutput(xzCompressCmd)
  3545. if err != nil {
  3546. c.Fatal(err, out)
  3547. }
  3548. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3549. c.Fatalf("failed to open destination dockerfile: %v", err)
  3550. }
  3551. return fakeContextFromDir(tmpDir)
  3552. }()
  3553. defer ctx.Close()
  3554. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3555. c.Fatalf("build failed to complete for TestBuildAddTarXz: %v", err)
  3556. }
  3557. }
  3558. func (s *DockerSuite) TestBuildAddTarXzGz(c *check.C) {
  3559. name := "testbuildaddtarxzgz"
  3560. ctx := func() *FakeContext {
  3561. dockerfile := `
  3562. FROM busybox
  3563. ADD test.tar.xz.gz /
  3564. RUN ls /test.tar.xz.gz`
  3565. tmpDir, err := ioutil.TempDir("", "fake-context")
  3566. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3567. if err != nil {
  3568. c.Fatalf("failed to create test.tar archive: %v", err)
  3569. }
  3570. defer testTar.Close()
  3571. tw := tar.NewWriter(testTar)
  3572. if err := tw.WriteHeader(&tar.Header{
  3573. Name: "test/foo",
  3574. Size: 2,
  3575. }); err != nil {
  3576. c.Fatalf("failed to write tar file header: %v", err)
  3577. }
  3578. if _, err := tw.Write([]byte("Hi")); err != nil {
  3579. c.Fatalf("failed to write tar file content: %v", err)
  3580. }
  3581. if err := tw.Close(); err != nil {
  3582. c.Fatalf("failed to close tar archive: %v", err)
  3583. }
  3584. xzCompressCmd := exec.Command("xz", "-k", "test.tar")
  3585. xzCompressCmd.Dir = tmpDir
  3586. out, _, err := runCommandWithOutput(xzCompressCmd)
  3587. if err != nil {
  3588. c.Fatal(err, out)
  3589. }
  3590. gzipCompressCmd := exec.Command("gzip", "test.tar.xz")
  3591. gzipCompressCmd.Dir = tmpDir
  3592. out, _, err = runCommandWithOutput(gzipCompressCmd)
  3593. if err != nil {
  3594. c.Fatal(err, out)
  3595. }
  3596. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3597. c.Fatalf("failed to open destination dockerfile: %v", err)
  3598. }
  3599. return fakeContextFromDir(tmpDir)
  3600. }()
  3601. defer ctx.Close()
  3602. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3603. c.Fatalf("build failed to complete for TestBuildAddTarXz: %v", err)
  3604. }
  3605. }
  3606. func (s *DockerSuite) TestBuildFromGIT(c *check.C) {
  3607. name := "testbuildfromgit"
  3608. git, err := fakeGIT("repo", map[string]string{
  3609. "Dockerfile": `FROM busybox
  3610. ADD first /first
  3611. RUN [ -f /first ]
  3612. MAINTAINER docker`,
  3613. "first": "test git data",
  3614. }, true)
  3615. if err != nil {
  3616. c.Fatal(err)
  3617. }
  3618. defer git.Close()
  3619. _, err = buildImageFromPath(name, git.RepoURL, true)
  3620. if err != nil {
  3621. c.Fatal(err)
  3622. }
  3623. res, err := inspectField(name, "Author")
  3624. if err != nil {
  3625. c.Fatal(err)
  3626. }
  3627. if res != "docker" {
  3628. c.Fatalf("Maintainer should be docker, got %s", res)
  3629. }
  3630. }
  3631. func (s *DockerSuite) TestBuildFromGITWithContext(c *check.C) {
  3632. name := "testbuildfromgit"
  3633. defer deleteImages(name)
  3634. git, err := fakeGIT("repo", map[string]string{
  3635. "docker/Dockerfile": `FROM busybox
  3636. ADD first /first
  3637. RUN [ -f /first ]
  3638. MAINTAINER docker`,
  3639. "docker/first": "test git data",
  3640. }, true)
  3641. if err != nil {
  3642. c.Fatal(err)
  3643. }
  3644. defer git.Close()
  3645. u := fmt.Sprintf("%s#master:docker", git.RepoURL)
  3646. _, err = buildImageFromPath(name, u, true)
  3647. if err != nil {
  3648. c.Fatal(err)
  3649. }
  3650. res, err := inspectField(name, "Author")
  3651. if err != nil {
  3652. c.Fatal(err)
  3653. }
  3654. if res != "docker" {
  3655. c.Fatalf("Maintainer should be docker, got %s", res)
  3656. }
  3657. }
  3658. func (s *DockerSuite) TestBuildCleanupCmdOnEntrypoint(c *check.C) {
  3659. name := "testbuildcmdcleanuponentrypoint"
  3660. if _, err := buildImage(name,
  3661. `FROM scratch
  3662. CMD ["test"]
  3663. ENTRYPOINT ["echo"]`,
  3664. true); err != nil {
  3665. c.Fatal(err)
  3666. }
  3667. if _, err := buildImage(name,
  3668. fmt.Sprintf(`FROM %s
  3669. ENTRYPOINT ["cat"]`, name),
  3670. true); err != nil {
  3671. c.Fatal(err)
  3672. }
  3673. res, err := inspectField(name, "Config.Cmd")
  3674. if err != nil {
  3675. c.Fatal(err)
  3676. }
  3677. if res != "<nil>" {
  3678. c.Fatalf("Cmd %s, expected nil", res)
  3679. }
  3680. res, err = inspectField(name, "Config.Entrypoint")
  3681. if err != nil {
  3682. c.Fatal(err)
  3683. }
  3684. if expected := "{[cat]}"; res != expected {
  3685. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  3686. }
  3687. }
  3688. func (s *DockerSuite) TestBuildClearCmd(c *check.C) {
  3689. name := "testbuildclearcmd"
  3690. _, err := buildImage(name,
  3691. `From scratch
  3692. ENTRYPOINT ["/bin/bash"]
  3693. CMD []`,
  3694. true)
  3695. if err != nil {
  3696. c.Fatal(err)
  3697. }
  3698. res, err := inspectFieldJSON(name, "Config.Cmd")
  3699. if err != nil {
  3700. c.Fatal(err)
  3701. }
  3702. if res != "[]" {
  3703. c.Fatalf("Cmd %s, expected %s", res, "[]")
  3704. }
  3705. }
  3706. func (s *DockerSuite) TestBuildEmptyCmd(c *check.C) {
  3707. name := "testbuildemptycmd"
  3708. if _, err := buildImage(name, "FROM scratch\nMAINTAINER quux\n", true); err != nil {
  3709. c.Fatal(err)
  3710. }
  3711. res, err := inspectFieldJSON(name, "Config.Cmd")
  3712. if err != nil {
  3713. c.Fatal(err)
  3714. }
  3715. if res != "null" {
  3716. c.Fatalf("Cmd %s, expected %s", res, "null")
  3717. }
  3718. }
  3719. func (s *DockerSuite) TestBuildOnBuildOutput(c *check.C) {
  3720. name := "testbuildonbuildparent"
  3721. if _, err := buildImage(name, "FROM busybox\nONBUILD RUN echo foo\n", true); err != nil {
  3722. c.Fatal(err)
  3723. }
  3724. _, out, err := buildImageWithOut(name, "FROM "+name+"\nMAINTAINER quux\n", true)
  3725. if err != nil {
  3726. c.Fatal(err)
  3727. }
  3728. if !strings.Contains(out, "Trigger 0, RUN echo foo") {
  3729. c.Fatal("failed to find the ONBUILD output", out)
  3730. }
  3731. }
  3732. func (s *DockerSuite) TestBuildInvalidTag(c *check.C) {
  3733. name := "abcd:" + stringutils.GenerateRandomAlphaOnlyString(200)
  3734. _, out, err := buildImageWithOut(name, "FROM scratch\nMAINTAINER quux\n", true)
  3735. // if the error doesnt check for illegal tag name, or the image is built
  3736. // then this should fail
  3737. if !strings.Contains(out, "Illegal tag name") || strings.Contains(out, "Sending build context to Docker daemon") {
  3738. c.Fatalf("failed to stop before building. Error: %s, Output: %s", err, out)
  3739. }
  3740. }
  3741. func (s *DockerSuite) TestBuildCmdShDashC(c *check.C) {
  3742. name := "testbuildcmdshc"
  3743. if _, err := buildImage(name, "FROM busybox\nCMD echo cmd\n", true); err != nil {
  3744. c.Fatal(err)
  3745. }
  3746. res, err := inspectFieldJSON(name, "Config.Cmd")
  3747. if err != nil {
  3748. c.Fatal(err, res)
  3749. }
  3750. expected := `["/bin/sh","-c","echo cmd"]`
  3751. if res != expected {
  3752. c.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  3753. }
  3754. }
  3755. func (s *DockerSuite) TestBuildCmdSpaces(c *check.C) {
  3756. // Test to make sure that when we strcat arrays we take into account
  3757. // the arg separator to make sure ["echo","hi"] and ["echo hi"] don't
  3758. // look the same
  3759. name := "testbuildcmdspaces"
  3760. var id1 string
  3761. var id2 string
  3762. var err error
  3763. if id1, err = buildImage(name, "FROM busybox\nCMD [\"echo hi\"]\n", true); err != nil {
  3764. c.Fatal(err)
  3765. }
  3766. if id2, err = buildImage(name, "FROM busybox\nCMD [\"echo\", \"hi\"]\n", true); err != nil {
  3767. c.Fatal(err)
  3768. }
  3769. if id1 == id2 {
  3770. c.Fatal("Should not have resulted in the same CMD")
  3771. }
  3772. // Now do the same with ENTRYPOINT
  3773. if id1, err = buildImage(name, "FROM busybox\nENTRYPOINT [\"echo hi\"]\n", true); err != nil {
  3774. c.Fatal(err)
  3775. }
  3776. if id2, err = buildImage(name, "FROM busybox\nENTRYPOINT [\"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 ENTRYPOINT")
  3781. }
  3782. }
  3783. func (s *DockerSuite) TestBuildCmdJSONNoShDashC(c *check.C) {
  3784. name := "testbuildcmdjson"
  3785. if _, err := buildImage(name, "FROM busybox\nCMD [\"echo\", \"cmd\"]", true); err != nil {
  3786. c.Fatal(err)
  3787. }
  3788. res, err := inspectFieldJSON(name, "Config.Cmd")
  3789. if err != nil {
  3790. c.Fatal(err, res)
  3791. }
  3792. expected := `["echo","cmd"]`
  3793. if res != expected {
  3794. c.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  3795. }
  3796. }
  3797. func (s *DockerSuite) TestBuildErrorInvalidInstruction(c *check.C) {
  3798. name := "testbuildignoreinvalidinstruction"
  3799. out, _, err := buildImageWithOut(name, "FROM busybox\nfoo bar", true)
  3800. if err == nil {
  3801. c.Fatalf("Should have failed: %s", out)
  3802. }
  3803. }
  3804. func (s *DockerSuite) TestBuildEntrypointInheritance(c *check.C) {
  3805. if _, err := buildImage("parent", `
  3806. FROM busybox
  3807. ENTRYPOINT exit 130
  3808. `, true); err != nil {
  3809. c.Fatal(err)
  3810. }
  3811. status, _ := runCommand(exec.Command(dockerBinary, "run", "parent"))
  3812. if status != 130 {
  3813. c.Fatalf("expected exit code 130 but received %d", status)
  3814. }
  3815. if _, err := buildImage("child", `
  3816. FROM parent
  3817. ENTRYPOINT exit 5
  3818. `, true); err != nil {
  3819. c.Fatal(err)
  3820. }
  3821. status, _ = runCommand(exec.Command(dockerBinary, "run", "child"))
  3822. if status != 5 {
  3823. c.Fatalf("expected exit code 5 but received %d", status)
  3824. }
  3825. }
  3826. func (s *DockerSuite) TestBuildEntrypointInheritanceInspect(c *check.C) {
  3827. var (
  3828. name = "testbuildepinherit"
  3829. name2 = "testbuildepinherit2"
  3830. expected = `["/bin/sh","-c","echo quux"]`
  3831. )
  3832. if _, err := buildImage(name, "FROM busybox\nENTRYPOINT /foo/bar", true); err != nil {
  3833. c.Fatal(err)
  3834. }
  3835. if _, err := buildImage(name2, fmt.Sprintf("FROM %s\nENTRYPOINT echo quux", name), true); err != nil {
  3836. c.Fatal(err)
  3837. }
  3838. res, err := inspectFieldJSON(name2, "Config.Entrypoint")
  3839. if err != nil {
  3840. c.Fatal(err, res)
  3841. }
  3842. if res != expected {
  3843. c.Fatalf("Expected value %s not in Config.Entrypoint: %s", expected, res)
  3844. }
  3845. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-t", name2))
  3846. if err != nil {
  3847. c.Fatal(err, out)
  3848. }
  3849. expected = "quux"
  3850. if strings.TrimSpace(out) != expected {
  3851. c.Fatalf("Expected output is %s, got %s", expected, out)
  3852. }
  3853. }
  3854. func (s *DockerSuite) TestBuildRunShEntrypoint(c *check.C) {
  3855. name := "testbuildentrypoint"
  3856. _, err := buildImage(name,
  3857. `FROM busybox
  3858. ENTRYPOINT /bin/echo`,
  3859. true)
  3860. if err != nil {
  3861. c.Fatal(err)
  3862. }
  3863. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--rm", name))
  3864. if err != nil {
  3865. c.Fatal(err, out)
  3866. }
  3867. }
  3868. func (s *DockerSuite) TestBuildExoticShellInterpolation(c *check.C) {
  3869. name := "testbuildexoticshellinterpolation"
  3870. _, err := buildImage(name, `
  3871. FROM busybox
  3872. ENV SOME_VAR a.b.c
  3873. RUN [ "$SOME_VAR" = 'a.b.c' ]
  3874. RUN [ "${SOME_VAR}" = 'a.b.c' ]
  3875. RUN [ "${SOME_VAR%.*}" = 'a.b' ]
  3876. RUN [ "${SOME_VAR%%.*}" = 'a' ]
  3877. RUN [ "${SOME_VAR#*.}" = 'b.c' ]
  3878. RUN [ "${SOME_VAR##*.}" = 'c' ]
  3879. RUN [ "${SOME_VAR/c/d}" = 'a.b.d' ]
  3880. RUN [ "${#SOME_VAR}" = '5' ]
  3881. RUN [ "${SOME_UNSET_VAR:-$SOME_VAR}" = 'a.b.c' ]
  3882. RUN [ "${SOME_VAR:+Version: ${SOME_VAR}}" = 'Version: a.b.c' ]
  3883. RUN [ "${SOME_UNSET_VAR:+${SOME_VAR}}" = '' ]
  3884. RUN [ "${SOME_UNSET_VAR:-${SOME_VAR:-d.e.f}}" = 'a.b.c' ]
  3885. `, false)
  3886. if err != nil {
  3887. c.Fatal(err)
  3888. }
  3889. }
  3890. func (s *DockerSuite) TestBuildVerifySingleQuoteFails(c *check.C) {
  3891. // This testcase is supposed to generate an error because the
  3892. // JSON array we're passing in on the CMD uses single quotes instead
  3893. // of double quotes (per the JSON spec). This means we interpret it
  3894. // as a "string" insead of "JSON array" and pass it on to "sh -c" and
  3895. // it should barf on it.
  3896. name := "testbuildsinglequotefails"
  3897. _, err := buildImage(name,
  3898. `FROM busybox
  3899. CMD [ '/bin/sh', '-c', 'echo hi' ]`,
  3900. true)
  3901. _, _, err = runCommandWithOutput(exec.Command(dockerBinary, "run", "--rm", name))
  3902. if err == nil {
  3903. c.Fatal("The image was not supposed to be able to run")
  3904. }
  3905. }
  3906. func (s *DockerSuite) TestBuildVerboseOut(c *check.C) {
  3907. name := "testbuildverboseout"
  3908. _, out, err := buildImageWithOut(name,
  3909. `FROM busybox
  3910. RUN echo 123`,
  3911. false)
  3912. if err != nil {
  3913. c.Fatal(err)
  3914. }
  3915. if !strings.Contains(out, "\n123\n") {
  3916. c.Fatalf("Output should contain %q: %q", "123", out)
  3917. }
  3918. }
  3919. func (s *DockerSuite) TestBuildWithTabs(c *check.C) {
  3920. name := "testbuildwithtabs"
  3921. _, err := buildImage(name,
  3922. "FROM busybox\nRUN echo\tone\t\ttwo", true)
  3923. if err != nil {
  3924. c.Fatal(err)
  3925. }
  3926. res, err := inspectFieldJSON(name, "ContainerConfig.Cmd")
  3927. if err != nil {
  3928. c.Fatal(err)
  3929. }
  3930. expected1 := `["/bin/sh","-c","echo\tone\t\ttwo"]`
  3931. expected2 := `["/bin/sh","-c","echo\u0009one\u0009\u0009two"]` // syntactically equivalent, and what Go 1.3 generates
  3932. if res != expected1 && res != expected2 {
  3933. c.Fatalf("Missing tabs.\nGot: %s\nExp: %s or %s", res, expected1, expected2)
  3934. }
  3935. }
  3936. func (s *DockerSuite) TestBuildLabels(c *check.C) {
  3937. name := "testbuildlabel"
  3938. expected := `{"License":"GPL","Vendor":"Acme"}`
  3939. _, err := buildImage(name,
  3940. `FROM busybox
  3941. LABEL Vendor=Acme
  3942. LABEL License GPL`,
  3943. true)
  3944. if err != nil {
  3945. c.Fatal(err)
  3946. }
  3947. res, err := inspectFieldJSON(name, "Config.Labels")
  3948. if err != nil {
  3949. c.Fatal(err)
  3950. }
  3951. if res != expected {
  3952. c.Fatalf("Labels %s, expected %s", res, expected)
  3953. }
  3954. }
  3955. func (s *DockerSuite) TestBuildLabelsCache(c *check.C) {
  3956. name := "testbuildlabelcache"
  3957. id1, err := buildImage(name,
  3958. `FROM busybox
  3959. LABEL Vendor=Acme`, false)
  3960. if err != nil {
  3961. c.Fatalf("Build 1 should have worked: %v", err)
  3962. }
  3963. id2, err := buildImage(name,
  3964. `FROM busybox
  3965. LABEL Vendor=Acme`, true)
  3966. if err != nil || id1 != id2 {
  3967. c.Fatalf("Build 2 should have worked & used cache(%s,%s): %v", id1, id2, err)
  3968. }
  3969. id2, err = buildImage(name,
  3970. `FROM busybox
  3971. LABEL Vendor=Acme1`, true)
  3972. if err != nil || id1 == id2 {
  3973. c.Fatalf("Build 3 should have worked & NOT used cache(%s,%s): %v", id1, id2, err)
  3974. }
  3975. id2, err = buildImage(name,
  3976. `FROM busybox
  3977. LABEL Vendor Acme`, true) // Note: " " and "=" should be same
  3978. if err != nil || id1 != id2 {
  3979. c.Fatalf("Build 4 should have worked & used cache(%s,%s): %v", id1, id2, err)
  3980. }
  3981. // Now make sure the cache isn't used by mistake
  3982. id1, err = buildImage(name,
  3983. `FROM busybox
  3984. LABEL f1=b1 f2=b2`, false)
  3985. if err != nil {
  3986. c.Fatalf("Build 5 should have worked: %q", err)
  3987. }
  3988. id2, err = buildImage(name,
  3989. `FROM busybox
  3990. LABEL f1="b1 f2=b2"`, true)
  3991. if err != nil || id1 == id2 {
  3992. c.Fatalf("Build 6 should have worked & NOT used the cache(%s,%s): %q", id1, id2, err)
  3993. }
  3994. }
  3995. func (s *DockerSuite) TestBuildStderr(c *check.C) {
  3996. // This test just makes sure that no non-error output goes
  3997. // to stderr
  3998. name := "testbuildstderr"
  3999. _, _, stderr, err := buildImageWithStdoutStderr(name,
  4000. "FROM busybox\nRUN echo one", true)
  4001. if err != nil {
  4002. c.Fatal(err)
  4003. }
  4004. if runtime.GOOS == "windows" {
  4005. // stderr might contain a security warning on windows
  4006. lines := strings.Split(stderr, "\n")
  4007. for _, v := range lines {
  4008. if v != "" && !strings.Contains(v, "SECURITY WARNING:") {
  4009. c.Fatalf("Stderr contains unexpected output line: %q", v)
  4010. }
  4011. }
  4012. } else {
  4013. if stderr != "" {
  4014. c.Fatalf("Stderr should have been empty, instead its: %q", stderr)
  4015. }
  4016. }
  4017. }
  4018. func (s *DockerSuite) TestBuildChownSingleFile(c *check.C) {
  4019. testRequires(c, UnixCli) // test uses chown: not available on windows
  4020. name := "testbuildchownsinglefile"
  4021. ctx, err := fakeContext(`
  4022. FROM busybox
  4023. COPY test /
  4024. RUN ls -l /test
  4025. RUN [ $(ls -l /test | awk '{print $3":"$4}') = 'root:root' ]
  4026. `, map[string]string{
  4027. "test": "test",
  4028. })
  4029. if err != nil {
  4030. c.Fatal(err)
  4031. }
  4032. defer ctx.Close()
  4033. if err := os.Chown(filepath.Join(ctx.Dir, "test"), 4242, 4242); err != nil {
  4034. c.Fatal(err)
  4035. }
  4036. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  4037. c.Fatal(err)
  4038. }
  4039. }
  4040. func (s *DockerSuite) TestBuildSymlinkBreakout(c *check.C) {
  4041. name := "testbuildsymlinkbreakout"
  4042. tmpdir, err := ioutil.TempDir("", name)
  4043. if err != nil {
  4044. c.Fatal(err)
  4045. }
  4046. defer os.RemoveAll(tmpdir)
  4047. ctx := filepath.Join(tmpdir, "context")
  4048. if err := os.MkdirAll(ctx, 0755); err != nil {
  4049. c.Fatal(err)
  4050. }
  4051. if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte(`
  4052. from busybox
  4053. add symlink.tar /
  4054. add inject /symlink/
  4055. `), 0644); err != nil {
  4056. c.Fatal(err)
  4057. }
  4058. inject := filepath.Join(ctx, "inject")
  4059. if err := ioutil.WriteFile(inject, nil, 0644); err != nil {
  4060. c.Fatal(err)
  4061. }
  4062. f, err := os.Create(filepath.Join(ctx, "symlink.tar"))
  4063. if err != nil {
  4064. c.Fatal(err)
  4065. }
  4066. w := tar.NewWriter(f)
  4067. w.WriteHeader(&tar.Header{
  4068. Name: "symlink2",
  4069. Typeflag: tar.TypeSymlink,
  4070. Linkname: "/../../../../../../../../../../../../../../",
  4071. Uid: os.Getuid(),
  4072. Gid: os.Getgid(),
  4073. })
  4074. w.WriteHeader(&tar.Header{
  4075. Name: "symlink",
  4076. Typeflag: tar.TypeSymlink,
  4077. Linkname: filepath.Join("symlink2", tmpdir),
  4078. Uid: os.Getuid(),
  4079. Gid: os.Getgid(),
  4080. })
  4081. w.Close()
  4082. f.Close()
  4083. if _, err := buildImageFromContext(name, fakeContextFromDir(ctx), false); err != nil {
  4084. c.Fatal(err)
  4085. }
  4086. if _, err := os.Lstat(filepath.Join(tmpdir, "inject")); err == nil {
  4087. c.Fatal("symlink breakout - inject")
  4088. } else if !os.IsNotExist(err) {
  4089. c.Fatalf("unexpected error: %v", err)
  4090. }
  4091. }
  4092. func (s *DockerSuite) TestBuildXZHost(c *check.C) {
  4093. name := "testbuildxzhost"
  4094. ctx, err := fakeContext(`
  4095. FROM busybox
  4096. ADD xz /usr/local/sbin/
  4097. RUN chmod 755 /usr/local/sbin/xz
  4098. ADD test.xz /
  4099. RUN [ ! -e /injected ]`,
  4100. map[string]string{
  4101. "test.xz": "\xfd\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00" +
  4102. "\x21\x01\x16\x00\x00\x00\x74\x2f\xe5\xa3\x01\x00\x3f\xfd" +
  4103. "\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00\x21",
  4104. "xz": "#!/bin/sh\ntouch /injected",
  4105. })
  4106. if err != nil {
  4107. c.Fatal(err)
  4108. }
  4109. defer ctx.Close()
  4110. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  4111. c.Fatal(err)
  4112. }
  4113. }
  4114. func (s *DockerSuite) TestBuildVolumesRetainContents(c *check.C) {
  4115. var (
  4116. name = "testbuildvolumescontent"
  4117. expected = "some text"
  4118. )
  4119. ctx, err := fakeContext(`
  4120. FROM busybox
  4121. COPY content /foo/file
  4122. VOLUME /foo
  4123. CMD cat /foo/file`,
  4124. map[string]string{
  4125. "content": expected,
  4126. })
  4127. if err != nil {
  4128. c.Fatal(err)
  4129. }
  4130. defer ctx.Close()
  4131. if _, err := buildImageFromContext(name, ctx, false); err != nil {
  4132. c.Fatal(err)
  4133. }
  4134. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--rm", name))
  4135. if err != nil {
  4136. c.Fatal(err)
  4137. }
  4138. if out != expected {
  4139. c.Fatalf("expected file contents for /foo/file to be %q but received %q", expected, out)
  4140. }
  4141. }
  4142. func (s *DockerSuite) TestBuildRenamedDockerfile(c *check.C) {
  4143. ctx, err := fakeContext(`FROM busybox
  4144. RUN echo from Dockerfile`,
  4145. map[string]string{
  4146. "Dockerfile": "FROM busybox\nRUN echo from Dockerfile",
  4147. "files/Dockerfile": "FROM busybox\nRUN echo from files/Dockerfile",
  4148. "files/dFile": "FROM busybox\nRUN echo from files/dFile",
  4149. "dFile": "FROM busybox\nRUN echo from dFile",
  4150. "files/dFile2": "FROM busybox\nRUN echo from files/dFile2",
  4151. })
  4152. defer ctx.Close()
  4153. if err != nil {
  4154. c.Fatal(err)
  4155. }
  4156. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", "test1", ".")
  4157. if err != nil {
  4158. c.Fatalf("Failed to build: %s\n%s", out, err)
  4159. }
  4160. if !strings.Contains(out, "from Dockerfile") {
  4161. c.Fatalf("test1 should have used Dockerfile, output:%s", out)
  4162. }
  4163. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", "-f", filepath.Join("files", "Dockerfile"), "-t", "test2", ".")
  4164. if err != nil {
  4165. c.Fatal(err)
  4166. }
  4167. if !strings.Contains(out, "from files/Dockerfile") {
  4168. c.Fatalf("test2 should have used files/Dockerfile, output:%s", out)
  4169. }
  4170. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", fmt.Sprintf("--file=%s", filepath.Join("files", "dFile")), "-t", "test3", ".")
  4171. if err != nil {
  4172. c.Fatal(err)
  4173. }
  4174. if !strings.Contains(out, "from files/dFile") {
  4175. c.Fatalf("test3 should have used files/dFile, output:%s", out)
  4176. }
  4177. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", "--file=dFile", "-t", "test4", ".")
  4178. if err != nil {
  4179. c.Fatal(err)
  4180. }
  4181. if !strings.Contains(out, "from dFile") {
  4182. c.Fatalf("test4 should have used dFile, output:%s", out)
  4183. }
  4184. dirWithNoDockerfile, _ := ioutil.TempDir(os.TempDir(), "test5")
  4185. nonDockerfileFile := filepath.Join(dirWithNoDockerfile, "notDockerfile")
  4186. if _, err = os.Create(nonDockerfileFile); err != nil {
  4187. c.Fatal(err)
  4188. }
  4189. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", fmt.Sprintf("--file=%s", nonDockerfileFile), "-t", "test5", ".")
  4190. if err == nil {
  4191. c.Fatalf("test5 was supposed to fail to find passwd")
  4192. }
  4193. if expected := fmt.Sprintf("The Dockerfile (%s) must be within the build context (.)", nonDockerfileFile); !strings.Contains(out, expected) {
  4194. c.Fatalf("wrong error messsage:%v\nexpected to contain=%v", out, expected)
  4195. }
  4196. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join("..", "Dockerfile"), "-t", "test6", "..")
  4197. if err != nil {
  4198. c.Fatalf("test6 failed: %s", err)
  4199. }
  4200. if !strings.Contains(out, "from Dockerfile") {
  4201. c.Fatalf("test6 should have used root Dockerfile, output:%s", out)
  4202. }
  4203. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join(ctx.Dir, "files", "Dockerfile"), "-t", "test7", "..")
  4204. if err != nil {
  4205. c.Fatalf("test7 failed: %s", err)
  4206. }
  4207. if !strings.Contains(out, "from files/Dockerfile") {
  4208. c.Fatalf("test7 should have used files Dockerfile, output:%s", out)
  4209. }
  4210. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join("..", "Dockerfile"), "-t", "test8", ".")
  4211. if err == nil || !strings.Contains(out, "must be within the build context") {
  4212. c.Fatalf("test8 should have failed with Dockerfile out of context: %s", err)
  4213. }
  4214. tmpDir := os.TempDir()
  4215. out, _, err = dockerCmdInDir(c, tmpDir, "build", "-t", "test9", ctx.Dir)
  4216. if err != nil {
  4217. c.Fatalf("test9 - failed: %s", err)
  4218. }
  4219. if !strings.Contains(out, "from Dockerfile") {
  4220. c.Fatalf("test9 should have used root Dockerfile, output:%s", out)
  4221. }
  4222. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", "dFile2", "-t", "test10", ".")
  4223. if err != nil {
  4224. c.Fatalf("test10 should have worked: %s", err)
  4225. }
  4226. if !strings.Contains(out, "from files/dFile2") {
  4227. c.Fatalf("test10 should have used files/dFile2, output:%s", out)
  4228. }
  4229. }
  4230. func (s *DockerSuite) TestBuildFromMixedcaseDockerfile(c *check.C) {
  4231. testRequires(c, UnixCli) // Dockerfile overwrites dockerfile on windows
  4232. ctx, err := fakeContext(`FROM busybox
  4233. RUN echo from dockerfile`,
  4234. map[string]string{
  4235. "dockerfile": "FROM busybox\nRUN echo from dockerfile",
  4236. })
  4237. defer ctx.Close()
  4238. if err != nil {
  4239. c.Fatal(err)
  4240. }
  4241. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", "test1", ".")
  4242. if err != nil {
  4243. c.Fatalf("Failed to build: %s\n%s", out, err)
  4244. }
  4245. if !strings.Contains(out, "from dockerfile") {
  4246. c.Fatalf("Missing proper output: %s", out)
  4247. }
  4248. }
  4249. func (s *DockerSuite) TestBuildWithTwoDockerfiles(c *check.C) {
  4250. testRequires(c, UnixCli) // Dockerfile overwrites dockerfile on windows
  4251. ctx, err := fakeContext(`FROM busybox
  4252. RUN echo from Dockerfile`,
  4253. map[string]string{
  4254. "dockerfile": "FROM busybox\nRUN echo from dockerfile",
  4255. })
  4256. defer ctx.Close()
  4257. if err != nil {
  4258. c.Fatal(err)
  4259. }
  4260. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", "test1", ".")
  4261. if err != nil {
  4262. c.Fatalf("Failed to build: %s\n%s", out, err)
  4263. }
  4264. if !strings.Contains(out, "from Dockerfile") {
  4265. c.Fatalf("Missing proper output: %s", out)
  4266. }
  4267. }
  4268. func (s *DockerSuite) TestBuildFromURLWithF(c *check.C) {
  4269. server, err := fakeStorage(map[string]string{"baz": `FROM busybox
  4270. RUN echo from baz
  4271. COPY * /tmp/
  4272. RUN find /tmp/`})
  4273. if err != nil {
  4274. c.Fatal(err)
  4275. }
  4276. defer server.Close()
  4277. ctx, err := fakeContext(`FROM busybox
  4278. RUN echo from Dockerfile`,
  4279. map[string]string{})
  4280. defer ctx.Close()
  4281. if err != nil {
  4282. c.Fatal(err)
  4283. }
  4284. // Make sure that -f is ignored and that we don't use the Dockerfile
  4285. // that's in the current dir
  4286. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-f", "baz", "-t", "test1", server.URL()+"/baz")
  4287. if err != nil {
  4288. c.Fatalf("Failed to build: %s\n%s", out, err)
  4289. }
  4290. if !strings.Contains(out, "from baz") ||
  4291. strings.Contains(out, "/tmp/baz") ||
  4292. !strings.Contains(out, "/tmp/Dockerfile") {
  4293. c.Fatalf("Missing proper output: %s", out)
  4294. }
  4295. }
  4296. func (s *DockerSuite) TestBuildFromStdinWithF(c *check.C) {
  4297. ctx, err := fakeContext(`FROM busybox
  4298. RUN echo from Dockerfile`,
  4299. map[string]string{})
  4300. defer ctx.Close()
  4301. if err != nil {
  4302. c.Fatal(err)
  4303. }
  4304. // Make sure that -f is ignored and that we don't use the Dockerfile
  4305. // that's in the current dir
  4306. dockerCommand := exec.Command(dockerBinary, "build", "-f", "baz", "-t", "test1", "-")
  4307. dockerCommand.Dir = ctx.Dir
  4308. dockerCommand.Stdin = strings.NewReader(`FROM busybox
  4309. RUN echo from baz
  4310. COPY * /tmp/
  4311. RUN find /tmp/`)
  4312. out, status, err := runCommandWithOutput(dockerCommand)
  4313. if err != nil || status != 0 {
  4314. c.Fatalf("Error building: %s", err)
  4315. }
  4316. if !strings.Contains(out, "from baz") ||
  4317. strings.Contains(out, "/tmp/baz") ||
  4318. !strings.Contains(out, "/tmp/Dockerfile") {
  4319. c.Fatalf("Missing proper output: %s", out)
  4320. }
  4321. }
  4322. func (s *DockerSuite) TestBuildFromOfficialNames(c *check.C) {
  4323. name := "testbuildfromofficial"
  4324. fromNames := []string{
  4325. "busybox",
  4326. "docker.io/busybox",
  4327. "index.docker.io/busybox",
  4328. "library/busybox",
  4329. "docker.io/library/busybox",
  4330. "index.docker.io/library/busybox",
  4331. }
  4332. for idx, fromName := range fromNames {
  4333. imgName := fmt.Sprintf("%s%d", name, idx)
  4334. _, err := buildImage(imgName, "FROM "+fromName, true)
  4335. if err != nil {
  4336. c.Errorf("Build failed using FROM %s: %s", fromName, err)
  4337. }
  4338. deleteImages(imgName)
  4339. }
  4340. }
  4341. func (s *DockerSuite) TestBuildDockerfileOutsideContext(c *check.C) {
  4342. testRequires(c, UnixCli) // uses os.Symlink: not implemented in windows at the time of writing (go-1.4.2)
  4343. name := "testbuilddockerfileoutsidecontext"
  4344. tmpdir, err := ioutil.TempDir("", name)
  4345. if err != nil {
  4346. c.Fatal(err)
  4347. }
  4348. defer os.RemoveAll(tmpdir)
  4349. ctx := filepath.Join(tmpdir, "context")
  4350. if err := os.MkdirAll(ctx, 0755); err != nil {
  4351. c.Fatal(err)
  4352. }
  4353. if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte("FROM scratch\nENV X Y"), 0644); err != nil {
  4354. c.Fatal(err)
  4355. }
  4356. wd, err := os.Getwd()
  4357. if err != nil {
  4358. c.Fatal(err)
  4359. }
  4360. defer os.Chdir(wd)
  4361. if err := os.Chdir(ctx); err != nil {
  4362. c.Fatal(err)
  4363. }
  4364. if err := ioutil.WriteFile(filepath.Join(tmpdir, "outsideDockerfile"), []byte("FROM scratch\nENV x y"), 0644); err != nil {
  4365. c.Fatal(err)
  4366. }
  4367. if err := os.Symlink(filepath.Join("..", "outsideDockerfile"), filepath.Join(ctx, "dockerfile1")); err != nil {
  4368. c.Fatal(err)
  4369. }
  4370. if err := os.Symlink(filepath.Join(tmpdir, "outsideDockerfile"), filepath.Join(ctx, "dockerfile2")); err != nil {
  4371. c.Fatal(err)
  4372. }
  4373. for _, dockerfilePath := range []string{
  4374. filepath.Join("..", "outsideDockerfile"),
  4375. filepath.Join(ctx, "dockerfile1"),
  4376. filepath.Join(ctx, "dockerfile2"),
  4377. } {
  4378. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "build", "-t", name, "--no-cache", "-f", dockerfilePath, "."))
  4379. if err == nil {
  4380. c.Fatalf("Expected error with %s. Out: %s", dockerfilePath, out)
  4381. }
  4382. if !strings.Contains(out, "must be within the build context") && !strings.Contains(out, "Cannot locate Dockerfile") {
  4383. c.Fatalf("Unexpected error with %s. Out: %s", dockerfilePath, out)
  4384. }
  4385. deleteImages(name)
  4386. }
  4387. os.Chdir(tmpdir)
  4388. // Path to Dockerfile should be resolved relative to working directory, not relative to context.
  4389. // There is a Dockerfile in the context, but since there is no Dockerfile in the current directory, the following should fail
  4390. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "build", "-t", name, "--no-cache", "-f", "Dockerfile", ctx))
  4391. if err == nil {
  4392. c.Fatalf("Expected error. Out: %s", out)
  4393. }
  4394. }
  4395. func (s *DockerSuite) TestBuildSpaces(c *check.C) {
  4396. // Test to make sure that leading/trailing spaces on a command
  4397. // doesn't change the error msg we get
  4398. var (
  4399. err1 error
  4400. err2 error
  4401. )
  4402. name := "testspaces"
  4403. ctx, err := fakeContext("FROM busybox\nCOPY\n",
  4404. map[string]string{
  4405. "Dockerfile": "FROM busybox\nCOPY\n",
  4406. })
  4407. if err != nil {
  4408. c.Fatal(err)
  4409. }
  4410. defer ctx.Close()
  4411. if _, err1 = buildImageFromContext(name, ctx, false); err1 == nil {
  4412. c.Fatal("Build 1 was supposed to fail, but didn't")
  4413. }
  4414. ctx.Add("Dockerfile", "FROM busybox\nCOPY ")
  4415. if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil {
  4416. c.Fatal("Build 2 was supposed to fail, but didn't")
  4417. }
  4418. removeLogTimestamps := func(s string) string {
  4419. return regexp.MustCompile(`time="(.*?)"`).ReplaceAllString(s, `time=[TIMESTAMP]`)
  4420. }
  4421. // Skip over the times
  4422. e1 := removeLogTimestamps(err1.Error())
  4423. e2 := removeLogTimestamps(err2.Error())
  4424. // Ignore whitespace since that's what were verifying doesn't change stuff
  4425. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  4426. c.Fatalf("Build 2's error wasn't the same as build 1's\n1:%s\n2:%s", err1, err2)
  4427. }
  4428. ctx.Add("Dockerfile", "FROM busybox\n COPY")
  4429. if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil {
  4430. c.Fatal("Build 3 was supposed to fail, but didn't")
  4431. }
  4432. // Skip over the times
  4433. e1 = removeLogTimestamps(err1.Error())
  4434. e2 = removeLogTimestamps(err2.Error())
  4435. // Ignore whitespace since that's what were verifying doesn't change stuff
  4436. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  4437. c.Fatalf("Build 3's error wasn't the same as build 1's\n1:%s\n3:%s", err1, err2)
  4438. }
  4439. ctx.Add("Dockerfile", "FROM busybox\n COPY ")
  4440. if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil {
  4441. c.Fatal("Build 4 was supposed to fail, but didn't")
  4442. }
  4443. // Skip over the times
  4444. e1 = removeLogTimestamps(err1.Error())
  4445. e2 = removeLogTimestamps(err2.Error())
  4446. // Ignore whitespace since that's what were verifying doesn't change stuff
  4447. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  4448. c.Fatalf("Build 4's error wasn't the same as build 1's\n1:%s\n4:%s", err1, err2)
  4449. }
  4450. }
  4451. func (s *DockerSuite) TestBuildSpacesWithQuotes(c *check.C) {
  4452. // Test to make sure that spaces in quotes aren't lost
  4453. name := "testspacesquotes"
  4454. dockerfile := `FROM busybox
  4455. RUN echo " \
  4456. foo "`
  4457. _, out, err := buildImageWithOut(name, dockerfile, false)
  4458. if err != nil {
  4459. c.Fatal("Build failed:", err)
  4460. }
  4461. expecting := "\n foo \n"
  4462. if !strings.Contains(out, expecting) {
  4463. c.Fatalf("Bad output: %q expecting to contain %q", out, expecting)
  4464. }
  4465. }
  4466. // #4393
  4467. func (s *DockerSuite) TestBuildVolumeFileExistsinContainer(c *check.C) {
  4468. buildCmd := exec.Command(dockerBinary, "build", "-t", "docker-test-errcreatevolumewithfile", "-")
  4469. buildCmd.Stdin = strings.NewReader(`
  4470. FROM busybox
  4471. RUN touch /foo
  4472. VOLUME /foo
  4473. `)
  4474. out, _, err := runCommandWithOutput(buildCmd)
  4475. if err == nil || !strings.Contains(out, "file exists") {
  4476. c.Fatalf("expected build to fail when file exists in container at requested volume path")
  4477. }
  4478. }
  4479. func (s *DockerSuite) TestBuildMissingArgs(c *check.C) {
  4480. // Test to make sure that all Dockerfile commands (except the ones listed
  4481. // in skipCmds) will generate an error if no args are provided.
  4482. // Note: INSERT is deprecated so we exclude it because of that.
  4483. skipCmds := map[string]struct{}{
  4484. "CMD": {},
  4485. "RUN": {},
  4486. "ENTRYPOINT": {},
  4487. "INSERT": {},
  4488. }
  4489. for cmd := range command.Commands {
  4490. cmd = strings.ToUpper(cmd)
  4491. if _, ok := skipCmds[cmd]; ok {
  4492. continue
  4493. }
  4494. var dockerfile string
  4495. if cmd == "FROM" {
  4496. dockerfile = cmd
  4497. } else {
  4498. // Add FROM to make sure we don't complain about it missing
  4499. dockerfile = "FROM busybox\n" + cmd
  4500. }
  4501. ctx, err := fakeContext(dockerfile, map[string]string{})
  4502. if err != nil {
  4503. c.Fatal(err)
  4504. }
  4505. defer ctx.Close()
  4506. var out string
  4507. if out, err = buildImageFromContext("args", ctx, true); err == nil {
  4508. c.Fatalf("%s was supposed to fail. Out:%s", cmd, out)
  4509. }
  4510. if !strings.Contains(err.Error(), cmd+" requires") {
  4511. c.Fatalf("%s returned the wrong type of error:%s", cmd, err)
  4512. }
  4513. }
  4514. }
  4515. func (s *DockerSuite) TestBuildEmptyScratch(c *check.C) {
  4516. _, out, err := buildImageWithOut("sc", "FROM scratch", true)
  4517. if err == nil {
  4518. c.Fatalf("Build was supposed to fail")
  4519. }
  4520. if !strings.Contains(out, "No image was generated") {
  4521. c.Fatalf("Wrong error message: %v", out)
  4522. }
  4523. }
  4524. func (s *DockerSuite) TestBuildDotDotFile(c *check.C) {
  4525. ctx, err := fakeContext("FROM busybox\n",
  4526. map[string]string{
  4527. "..gitme": "",
  4528. })
  4529. if err != nil {
  4530. c.Fatal(err)
  4531. }
  4532. defer ctx.Close()
  4533. if _, err = buildImageFromContext("sc", ctx, false); err != nil {
  4534. c.Fatalf("Build was supposed to work: %s", err)
  4535. }
  4536. }
  4537. func (s *DockerSuite) TestBuildNotVerbose(c *check.C) {
  4538. ctx, err := fakeContext("FROM busybox\nENV abc=hi\nRUN echo $abc there", map[string]string{})
  4539. if err != nil {
  4540. c.Fatal(err)
  4541. }
  4542. defer ctx.Close()
  4543. // First do it w/verbose - baseline
  4544. buildCmd := exec.Command(dockerBinary, "build", "--no-cache", "-t", "verbose", ".")
  4545. buildCmd.Dir = ctx.Dir
  4546. out, _, err := runCommandWithOutput(buildCmd)
  4547. if err != nil {
  4548. c.Fatalf("failed to build the image w/o -q: %s, %v", out, err)
  4549. }
  4550. if !strings.Contains(out, "hi there") {
  4551. c.Fatalf("missing output:%s\n", out)
  4552. }
  4553. // Now do it w/o verbose
  4554. buildCmd = exec.Command(dockerBinary, "build", "--no-cache", "-q", "-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/ -q: %s, %v", out, err)
  4559. }
  4560. if strings.Contains(out, "hi there") {
  4561. c.Fatalf("Bad output, should not contain 'hi there':%s", out)
  4562. }
  4563. }
  4564. func (s *DockerSuite) TestBuildRUNoneJSON(c *check.C) {
  4565. name := "testbuildrunonejson"
  4566. ctx, err := fakeContext(`FROM hello-world:frozen
  4567. RUN [ "/hello" ]`, map[string]string{})
  4568. if err != nil {
  4569. c.Fatal(err)
  4570. }
  4571. defer ctx.Close()
  4572. buildCmd := exec.Command(dockerBinary, "build", "--no-cache", "-t", name, ".")
  4573. buildCmd.Dir = ctx.Dir
  4574. out, _, err := runCommandWithOutput(buildCmd)
  4575. if err != nil {
  4576. c.Fatalf("failed to build the image: %s, %v", out, err)
  4577. }
  4578. if !strings.Contains(out, "Hello from Docker") {
  4579. c.Fatalf("bad output: %s", out)
  4580. }
  4581. }
  4582. func (s *DockerSuite) TestBuildResourceConstraintsAreUsed(c *check.C) {
  4583. name := "testbuildresourceconstraints"
  4584. ctx, err := fakeContext(`
  4585. FROM hello-world:frozen
  4586. RUN ["/hello"]
  4587. `, map[string]string{})
  4588. if err != nil {
  4589. c.Fatal(err)
  4590. }
  4591. cmd := exec.Command(dockerBinary, "build", "--no-cache", "--rm=false", "--memory=64m", "--memory-swap=-1", "--cpuset-cpus=0", "--cpuset-mems=0", "--cpu-shares=100", "--cpu-quota=8000", "-t", name, ".")
  4592. cmd.Dir = ctx.Dir
  4593. out, _, err := runCommandWithOutput(cmd)
  4594. if err != nil {
  4595. c.Fatal(err, out)
  4596. }
  4597. out, _ = dockerCmd(c, "ps", "-lq")
  4598. cID := strings.TrimSpace(out)
  4599. type hostConfig struct {
  4600. Memory int64
  4601. MemorySwap int64
  4602. CpusetCpus string
  4603. CpusetMems string
  4604. CpuShares int64
  4605. CpuQuota int64
  4606. }
  4607. cfg, err := inspectFieldJSON(cID, "HostConfig")
  4608. if err != nil {
  4609. c.Fatal(err)
  4610. }
  4611. var c1 hostConfig
  4612. if err := json.Unmarshal([]byte(cfg), &c1); err != nil {
  4613. c.Fatal(err, cfg)
  4614. }
  4615. if c1.Memory != 67108864 || c1.MemorySwap != -1 || c1.CpusetCpus != "0" || c1.CpusetMems != "0" || c1.CpuShares != 100 || c1.CpuQuota != 8000 {
  4616. c.Fatalf("resource constraints not set properly:\nMemory: %d, MemSwap: %d, CpusetCpus: %s, CpusetMems: %s, CpuShares: %d, CpuQuota: %d",
  4617. c1.Memory, c1.MemorySwap, c1.CpusetCpus, c1.CpusetMems, c1.CpuShares, c1.CpuQuota)
  4618. }
  4619. // Make sure constraints aren't saved to image
  4620. _, _ = dockerCmd(c, "run", "--name=test", name)
  4621. cfg, err = inspectFieldJSON("test", "HostConfig")
  4622. if err != nil {
  4623. c.Fatal(err)
  4624. }
  4625. var c2 hostConfig
  4626. if err := json.Unmarshal([]byte(cfg), &c2); err != nil {
  4627. c.Fatal(err, cfg)
  4628. }
  4629. if c2.Memory == 67108864 || c2.MemorySwap == -1 || c2.CpusetCpus == "0" || c2.CpusetMems == "0" || c2.CpuShares == 100 || c2.CpuQuota == 8000 {
  4630. c.Fatalf("resource constraints leaked from build:\nMemory: %d, MemSwap: %d, CpusetCpus: %s, CpusetMems: %s, CpuShares: %d, CpuQuota: %d",
  4631. c2.Memory, c2.MemorySwap, c2.CpusetCpus, c2.CpusetMems, c2.CpuShares, c2.CpuQuota)
  4632. }
  4633. }
  4634. func (s *DockerSuite) TestBuildEmptyStringVolume(c *check.C) {
  4635. name := "testbuildemptystringvolume"
  4636. _, err := buildImage(name, `
  4637. FROM busybox
  4638. ENV foo=""
  4639. VOLUME $foo
  4640. `, false)
  4641. if err == nil {
  4642. c.Fatal("Should have failed to build")
  4643. }
  4644. }
  4645. func (s *DockerSuite) TestBuildContainerWithCgroupParent(c *check.C) {
  4646. testRequires(c, NativeExecDriver)
  4647. testRequires(c, SameHostDaemon)
  4648. defer deleteImages()
  4649. cgroupParent := "test"
  4650. data, err := ioutil.ReadFile("/proc/self/cgroup")
  4651. if err != nil {
  4652. c.Fatalf("failed to read '/proc/self/cgroup - %v", err)
  4653. }
  4654. selfCgroupPaths := parseCgroupPaths(string(data))
  4655. _, found := selfCgroupPaths["memory"]
  4656. if !found {
  4657. c.Fatalf("unable to find self cpu cgroup path. CgroupsPath: %v", selfCgroupPaths)
  4658. }
  4659. cmd := exec.Command(dockerBinary, "build", "--cgroup-parent", cgroupParent, "-")
  4660. cmd.Stdin = strings.NewReader(`
  4661. FROM busybox
  4662. RUN cat /proc/self/cgroup
  4663. `)
  4664. out, _, err := runCommandWithOutput(cmd)
  4665. if err != nil {
  4666. c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err)
  4667. }
  4668. }
  4669. func (s *DockerSuite) TestBuildNoDupOutput(c *check.C) {
  4670. // Check to make sure our build output prints the Dockerfile cmd
  4671. // property - there was a bug that caused it to be duplicated on the
  4672. // Step X line
  4673. name := "testbuildnodupoutput"
  4674. _, out, err := buildImageWithOut(name, `
  4675. FROM busybox
  4676. RUN env`, false)
  4677. if err != nil {
  4678. c.Fatalf("Build should have worked: %q", err)
  4679. }
  4680. exp := "\nStep 1 : RUN env\n"
  4681. if !strings.Contains(out, exp) {
  4682. c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", out, exp)
  4683. }
  4684. }
  4685. func (s *DockerSuite) TestBuildBadCmdFlag(c *check.C) {
  4686. name := "testbuildbadcmdflag"
  4687. _, out, err := buildImageWithOut(name, `
  4688. FROM busybox
  4689. MAINTAINER --boo joe@example.com`, false)
  4690. if err == nil {
  4691. c.Fatal("Build should have failed")
  4692. }
  4693. exp := "\nUnknown flag: boo\n"
  4694. if !strings.Contains(out, exp) {
  4695. c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", out, exp)
  4696. }
  4697. }
  4698. func (s *DockerSuite) TestBuildRUNErrMsg(c *check.C) {
  4699. // Test to make sure the bad command is quoted with just "s and
  4700. // not as a Go []string
  4701. name := "testbuildbadrunerrmsg"
  4702. _, out, err := buildImageWithOut(name, `
  4703. FROM busybox
  4704. RUN badEXE a1 \& a2 a3`, false) // tab between a2 and a3
  4705. if err == nil {
  4706. c.Fatal("Should have failed to build")
  4707. }
  4708. exp := `The command '/bin/sh -c badEXE a1 \& a2 a3' returned a non-zero code: 127`
  4709. if !strings.Contains(out, exp) {
  4710. c.Fatalf("RUN doesn't have the correct output:\nGot:%s\nExpected:%s", out, exp)
  4711. }
  4712. }