docker_cli_build_test.go 141 KB

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