docker_cli_build_test.go 179 KB

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