docker_cli_build_test.go 196 KB

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