docker_cli_build_test.go 183 KB

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