docker_cli_build_test.go 182 KB

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