docker_cli_build_test.go 196 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205
  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. if testEnv.OSType == "windows" {
  2903. expectedExitCode = 127
  2904. }
  2905. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2906. CMD [ '/bin/sh', '-c', 'echo hi' ]`))
  2907. icmd.RunCommand(dockerBinary, "run", "--rm", name).Assert(c, icmd.Expected{
  2908. ExitCode: expectedExitCode,
  2909. })
  2910. }
  2911. func (s *DockerSuite) TestBuildVerboseOut(c *check.C) {
  2912. name := "testbuildverboseout"
  2913. expected := "\n123\n"
  2914. if testEnv.OSType == "windows" {
  2915. expected = "\n123\r\n"
  2916. }
  2917. buildImage(name, build.WithDockerfile(`FROM busybox
  2918. RUN echo 123`)).Assert(c, icmd.Expected{
  2919. Out: expected,
  2920. })
  2921. }
  2922. func (s *DockerSuite) TestBuildWithTabs(c *check.C) {
  2923. name := "testbuildwithtabs"
  2924. buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nRUN echo\tone\t\ttwo"))
  2925. res := inspectFieldJSON(c, name, "ContainerConfig.Cmd")
  2926. expected1 := `["/bin/sh","-c","echo\tone\t\ttwo"]`
  2927. expected2 := `["/bin/sh","-c","echo\u0009one\u0009\u0009two"]` // syntactically equivalent, and what Go 1.3 generates
  2928. if testEnv.OSType == "windows" {
  2929. expected1 = `["cmd","/S","/C","echo\tone\t\ttwo"]`
  2930. expected2 = `["cmd","/S","/C","echo\u0009one\u0009\u0009two"]` // syntactically equivalent, and what Go 1.3 generates
  2931. }
  2932. if res != expected1 && res != expected2 {
  2933. c.Fatalf("Missing tabs.\nGot: %s\nExp: %s or %s", res, expected1, expected2)
  2934. }
  2935. }
  2936. func (s *DockerSuite) TestBuildLabels(c *check.C) {
  2937. name := "testbuildlabel"
  2938. expected := `{"License":"GPL","Vendor":"Acme"}`
  2939. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2940. LABEL Vendor=Acme
  2941. LABEL License GPL`))
  2942. res := inspectFieldJSON(c, name, "Config.Labels")
  2943. if res != expected {
  2944. c.Fatalf("Labels %s, expected %s", res, expected)
  2945. }
  2946. }
  2947. func (s *DockerSuite) TestBuildLabelsCache(c *check.C) {
  2948. name := "testbuildlabelcache"
  2949. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2950. LABEL Vendor=Acme`))
  2951. id1 := getIDByName(c, name)
  2952. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2953. LABEL Vendor=Acme`))
  2954. id2 := getIDByName(c, name)
  2955. if id1 != id2 {
  2956. c.Fatalf("Build 2 should have worked & used cache(%s,%s)", id1, id2)
  2957. }
  2958. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2959. LABEL Vendor=Acme1`))
  2960. id2 = getIDByName(c, name)
  2961. if id1 == id2 {
  2962. c.Fatalf("Build 3 should have worked & NOT used cache(%s,%s)", id1, id2)
  2963. }
  2964. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2965. LABEL Vendor Acme`))
  2966. id2 = getIDByName(c, name)
  2967. if id1 != id2 {
  2968. c.Fatalf("Build 4 should have worked & used cache(%s,%s)", id1, id2)
  2969. }
  2970. // Now make sure the cache isn't used by mistake
  2971. buildImageSuccessfully(c, name, build.WithoutCache, build.WithDockerfile(`FROM busybox
  2972. LABEL f1=b1 f2=b2`))
  2973. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  2974. LABEL f1=b1 f2=b2`))
  2975. id2 = getIDByName(c, name)
  2976. if id1 == id2 {
  2977. c.Fatalf("Build 6 should have worked & NOT used the cache(%s,%s)", id1, id2)
  2978. }
  2979. }
  2980. // FIXME(vdemeester) port to docker/cli e2e tests (api tests should test suppressOutput option though)
  2981. func (s *DockerSuite) TestBuildNotVerboseSuccess(c *check.C) {
  2982. // This test makes sure that -q works correctly when build is successful:
  2983. // stdout has only the image ID (long image ID) and stderr is empty.
  2984. outRegexp := regexp.MustCompile("^(sha256:|)[a-z0-9]{64}\\n$")
  2985. buildFlags := cli.WithFlags("-q")
  2986. tt := []struct {
  2987. Name string
  2988. BuildFunc func(string) *icmd.Result
  2989. }{
  2990. {
  2991. Name: "quiet_build_stdin_success",
  2992. BuildFunc: func(name string) *icmd.Result {
  2993. return buildImage(name, buildFlags, build.WithDockerfile("FROM busybox"))
  2994. },
  2995. },
  2996. {
  2997. Name: "quiet_build_ctx_success",
  2998. BuildFunc: func(name string) *icmd.Result {
  2999. return buildImage(name, buildFlags, build.WithBuildContext(c,
  3000. build.WithFile("Dockerfile", "FROM busybox"),
  3001. build.WithFile("quiet_build_success_fctx", "test"),
  3002. ))
  3003. },
  3004. },
  3005. {
  3006. Name: "quiet_build_git_success",
  3007. BuildFunc: func(name string) *icmd.Result {
  3008. git := fakegit.New(c, "repo", map[string]string{
  3009. "Dockerfile": "FROM busybox",
  3010. }, true)
  3011. return buildImage(name, buildFlags, build.WithContextPath(git.RepoURL))
  3012. },
  3013. },
  3014. }
  3015. for _, te := range tt {
  3016. result := te.BuildFunc(te.Name)
  3017. result.Assert(c, icmd.Success)
  3018. if outRegexp.Find([]byte(result.Stdout())) == nil {
  3019. c.Fatalf("Test %s expected stdout to match the [%v] regexp, but it is [%v]", te.Name, outRegexp, result.Stdout())
  3020. }
  3021. if result.Stderr() != "" {
  3022. c.Fatalf("Test %s expected stderr to be empty, but it is [%#v]", te.Name, result.Stderr())
  3023. }
  3024. }
  3025. }
  3026. // FIXME(vdemeester) migrate to docker/cli tests
  3027. func (s *DockerSuite) TestBuildNotVerboseFailureWithNonExistImage(c *check.C) {
  3028. // This test makes sure that -q works correctly when build fails by
  3029. // comparing between the stderr output in quiet mode and in stdout
  3030. // and stderr output in verbose mode
  3031. testRequires(c, Network)
  3032. testName := "quiet_build_not_exists_image"
  3033. dockerfile := "FROM busybox11"
  3034. quietResult := buildImage(testName, cli.WithFlags("-q"), build.WithDockerfile(dockerfile))
  3035. quietResult.Assert(c, icmd.Expected{
  3036. ExitCode: 1,
  3037. })
  3038. result := buildImage(testName, build.WithDockerfile(dockerfile))
  3039. result.Assert(c, icmd.Expected{
  3040. ExitCode: 1,
  3041. })
  3042. if quietResult.Stderr() != result.Combined() {
  3043. c.Fatal(fmt.Errorf("Test[%s] expected that quiet stderr and verbose stdout are equal; quiet [%v], verbose [%v]", testName, quietResult.Stderr(), result.Combined()))
  3044. }
  3045. }
  3046. // FIXME(vdemeester) migrate to docker/cli tests
  3047. func (s *DockerSuite) TestBuildNotVerboseFailure(c *check.C) {
  3048. // This test makes sure that -q works correctly when build fails by
  3049. // comparing between the stderr output in quiet mode and in stdout
  3050. // and stderr output in verbose mode
  3051. testCases := []struct {
  3052. testName string
  3053. dockerfile string
  3054. }{
  3055. {"quiet_build_no_from_at_the_beginning", "RUN whoami"},
  3056. {"quiet_build_unknown_instr", "FROMD busybox"},
  3057. }
  3058. for _, tc := range testCases {
  3059. quietResult := buildImage(tc.testName, cli.WithFlags("-q"), build.WithDockerfile(tc.dockerfile))
  3060. quietResult.Assert(c, icmd.Expected{
  3061. ExitCode: 1,
  3062. })
  3063. result := buildImage(tc.testName, build.WithDockerfile(tc.dockerfile))
  3064. result.Assert(c, icmd.Expected{
  3065. ExitCode: 1,
  3066. })
  3067. if quietResult.Stderr() != result.Combined() {
  3068. 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()))
  3069. }
  3070. }
  3071. }
  3072. // FIXME(vdemeester) migrate to docker/cli tests
  3073. func (s *DockerSuite) TestBuildNotVerboseFailureRemote(c *check.C) {
  3074. // This test ensures that when given a wrong URL, stderr in quiet mode and
  3075. // stderr in verbose mode are identical.
  3076. // TODO(vdemeester) with cobra, stdout has a carriage return too much so this test should not check stdout
  3077. URL := "http://something.invalid"
  3078. name := "quiet_build_wrong_remote"
  3079. quietResult := buildImage(name, cli.WithFlags("-q"), build.WithContextPath(URL))
  3080. quietResult.Assert(c, icmd.Expected{
  3081. ExitCode: 1,
  3082. })
  3083. result := buildImage(name, build.WithContextPath(URL))
  3084. result.Assert(c, icmd.Expected{
  3085. ExitCode: 1,
  3086. })
  3087. // An error message should contain name server IP and port, like this:
  3088. // "dial tcp: lookup something.invalid on 172.29.128.11:53: no such host"
  3089. // The IP:port need to be removed in order to not trigger a test failur
  3090. // when more than one nameserver is configured.
  3091. // While at it, also strip excessive newlines.
  3092. normalize := func(msg string) string {
  3093. return strings.TrimSpace(regexp.MustCompile("[1-9][0-9.]+:[0-9]+").ReplaceAllLiteralString(msg, "<ip:port>"))
  3094. }
  3095. if normalize(quietResult.Stderr()) != normalize(result.Combined()) {
  3096. c.Fatal(fmt.Errorf("Test[%s] expected that quiet stderr and verbose stdout are equal; quiet [%v], verbose [%v]", name, quietResult.Stderr(), result.Combined()))
  3097. }
  3098. }
  3099. // FIXME(vdemeester) migrate to docker/cli tests
  3100. func (s *DockerSuite) TestBuildStderr(c *check.C) {
  3101. // This test just makes sure that no non-error output goes
  3102. // to stderr
  3103. name := "testbuildstderr"
  3104. result := buildImage(name, build.WithDockerfile("FROM busybox\nRUN echo one"))
  3105. result.Assert(c, icmd.Success)
  3106. // Windows to non-Windows should have a security warning
  3107. if runtime.GOOS == "windows" && testEnv.OSType != "windows" && !strings.Contains(result.Stdout(), "SECURITY WARNING:") {
  3108. c.Fatalf("Stdout contains unexpected output: %q", result.Stdout())
  3109. }
  3110. // Stderr should always be empty
  3111. if result.Stderr() != "" {
  3112. c.Fatalf("Stderr should have been empty, instead it's: %q", result.Stderr())
  3113. }
  3114. }
  3115. func (s *DockerSuite) TestBuildChownSingleFile(c *check.C) {
  3116. testRequires(c, UnixCli, DaemonIsLinux) // test uses chown: not available on windows
  3117. name := "testbuildchownsinglefile"
  3118. ctx := fakecontext.New(c, "",
  3119. fakecontext.WithDockerfile(`
  3120. FROM busybox
  3121. COPY test /
  3122. RUN ls -l /test
  3123. RUN [ $(ls -l /test | awk '{print $3":"$4}') = 'root:root' ]
  3124. `),
  3125. fakecontext.WithFiles(map[string]string{
  3126. "test": "test",
  3127. }))
  3128. defer ctx.Close()
  3129. if err := os.Chown(filepath.Join(ctx.Dir, "test"), 4242, 4242); err != nil {
  3130. c.Fatal(err)
  3131. }
  3132. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  3133. }
  3134. func (s *DockerSuite) TestBuildSymlinkBreakout(c *check.C) {
  3135. name := "testbuildsymlinkbreakout"
  3136. tmpdir, err := ioutil.TempDir("", name)
  3137. c.Assert(err, check.IsNil)
  3138. defer os.RemoveAll(tmpdir)
  3139. ctx := filepath.Join(tmpdir, "context")
  3140. if err := os.MkdirAll(ctx, 0755); err != nil {
  3141. c.Fatal(err)
  3142. }
  3143. if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte(`
  3144. from busybox
  3145. add symlink.tar /
  3146. add inject /symlink/
  3147. `), 0644); err != nil {
  3148. c.Fatal(err)
  3149. }
  3150. inject := filepath.Join(ctx, "inject")
  3151. if err := ioutil.WriteFile(inject, nil, 0644); err != nil {
  3152. c.Fatal(err)
  3153. }
  3154. f, err := os.Create(filepath.Join(ctx, "symlink.tar"))
  3155. if err != nil {
  3156. c.Fatal(err)
  3157. }
  3158. w := tar.NewWriter(f)
  3159. w.WriteHeader(&tar.Header{
  3160. Name: "symlink2",
  3161. Typeflag: tar.TypeSymlink,
  3162. Linkname: "/../../../../../../../../../../../../../../",
  3163. Uid: os.Getuid(),
  3164. Gid: os.Getgid(),
  3165. })
  3166. w.WriteHeader(&tar.Header{
  3167. Name: "symlink",
  3168. Typeflag: tar.TypeSymlink,
  3169. Linkname: filepath.Join("symlink2", tmpdir),
  3170. Uid: os.Getuid(),
  3171. Gid: os.Getgid(),
  3172. })
  3173. w.Close()
  3174. f.Close()
  3175. buildImageSuccessfully(c, name, build.WithoutCache, build.WithExternalBuildContext(fakecontext.New(c, ctx)))
  3176. if _, err := os.Lstat(filepath.Join(tmpdir, "inject")); err == nil {
  3177. c.Fatal("symlink breakout - inject")
  3178. } else if !os.IsNotExist(err) {
  3179. c.Fatalf("unexpected error: %v", err)
  3180. }
  3181. }
  3182. func (s *DockerSuite) TestBuildXZHost(c *check.C) {
  3183. // /usr/local/sbin/xz gets permission denied for the user
  3184. testRequires(c, NotUserNamespace)
  3185. testRequires(c, DaemonIsLinux)
  3186. name := "testbuildxzhost"
  3187. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  3188. build.WithFile("Dockerfile", `
  3189. FROM busybox
  3190. ADD xz /usr/local/sbin/
  3191. RUN chmod 755 /usr/local/sbin/xz
  3192. ADD test.xz /
  3193. RUN [ ! -e /injected ]`),
  3194. 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"),
  3195. build.WithFile("xz", "#!/bin/sh\ntouch /injected"),
  3196. ))
  3197. }
  3198. func (s *DockerSuite) TestBuildVolumesRetainContents(c *check.C) {
  3199. // /foo/file gets permission denied for the user
  3200. testRequires(c, NotUserNamespace)
  3201. testRequires(c, DaemonIsLinux) // TODO Windows: Issue #20127
  3202. var (
  3203. name = "testbuildvolumescontent"
  3204. expected = "some text"
  3205. volName = "/foo"
  3206. )
  3207. if testEnv.OSType == "windows" {
  3208. volName = "C:/foo"
  3209. }
  3210. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  3211. build.WithFile("Dockerfile", `
  3212. FROM busybox
  3213. COPY content /foo/file
  3214. VOLUME `+volName+`
  3215. CMD cat /foo/file`),
  3216. build.WithFile("content", expected),
  3217. ))
  3218. out, _ := dockerCmd(c, "run", "--rm", name)
  3219. if out != expected {
  3220. c.Fatalf("expected file contents for /foo/file to be %q but received %q", expected, out)
  3221. }
  3222. }
  3223. func (s *DockerSuite) TestBuildFromMixedcaseDockerfile(c *check.C) {
  3224. testRequires(c, UnixCli) // Dockerfile overwrites dockerfile on windows
  3225. testRequires(c, DaemonIsLinux)
  3226. // If Dockerfile is not present, use dockerfile
  3227. buildImage("test1", build.WithBuildContext(c,
  3228. build.WithFile("dockerfile", `FROM busybox
  3229. RUN echo from dockerfile`),
  3230. )).Assert(c, icmd.Expected{
  3231. Out: "from dockerfile",
  3232. })
  3233. // Prefer Dockerfile in place of dockerfile
  3234. buildImage("test1", build.WithBuildContext(c,
  3235. build.WithFile("dockerfile", `FROM busybox
  3236. RUN echo from dockerfile`),
  3237. build.WithFile("Dockerfile", `FROM busybox
  3238. RUN echo from Dockerfile`),
  3239. )).Assert(c, icmd.Expected{
  3240. Out: "from Dockerfile",
  3241. })
  3242. }
  3243. // FIXME(vdemeester) should migrate to docker/cli tests
  3244. func (s *DockerSuite) TestBuildFromURLWithF(c *check.C) {
  3245. server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{"baz": `FROM busybox
  3246. RUN echo from baz
  3247. COPY * /tmp/
  3248. RUN find /tmp/`}))
  3249. defer server.Close()
  3250. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(`FROM busybox
  3251. RUN echo from Dockerfile`))
  3252. defer ctx.Close()
  3253. // Make sure that -f is ignored and that we don't use the Dockerfile
  3254. // that's in the current dir
  3255. result := cli.BuildCmd(c, "test1", cli.WithFlags("-f", "baz", server.URL()+"/baz"), func(cmd *icmd.Cmd) func() {
  3256. cmd.Dir = ctx.Dir
  3257. return nil
  3258. })
  3259. if !strings.Contains(result.Combined(), "from baz") ||
  3260. strings.Contains(result.Combined(), "/tmp/baz") ||
  3261. !strings.Contains(result.Combined(), "/tmp/Dockerfile") {
  3262. c.Fatalf("Missing proper output: %s", result.Combined())
  3263. }
  3264. }
  3265. // FIXME(vdemeester) should migrate to docker/cli tests
  3266. func (s *DockerSuite) TestBuildFromStdinWithF(c *check.C) {
  3267. testRequires(c, DaemonIsLinux) // TODO Windows: This test is flaky; no idea why
  3268. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(`FROM busybox
  3269. RUN echo "from Dockerfile"`))
  3270. defer ctx.Close()
  3271. // Make sure that -f is ignored and that we don't use the Dockerfile
  3272. // that's in the current dir
  3273. result := cli.BuildCmd(c, "test1", cli.WithFlags("-f", "baz", "-"), func(cmd *icmd.Cmd) func() {
  3274. cmd.Dir = ctx.Dir
  3275. cmd.Stdin = strings.NewReader(`FROM busybox
  3276. RUN echo "from baz"
  3277. COPY * /tmp/
  3278. RUN sh -c "find /tmp/" # sh -c is needed on Windows to use the correct find`)
  3279. return nil
  3280. })
  3281. if !strings.Contains(result.Combined(), "from baz") ||
  3282. strings.Contains(result.Combined(), "/tmp/baz") ||
  3283. !strings.Contains(result.Combined(), "/tmp/Dockerfile") {
  3284. c.Fatalf("Missing proper output: %s", result.Combined())
  3285. }
  3286. }
  3287. func (s *DockerSuite) TestBuildFromOfficialNames(c *check.C) {
  3288. name := "testbuildfromofficial"
  3289. fromNames := []string{
  3290. "busybox",
  3291. "docker.io/busybox",
  3292. "index.docker.io/busybox",
  3293. "library/busybox",
  3294. "docker.io/library/busybox",
  3295. "index.docker.io/library/busybox",
  3296. }
  3297. for idx, fromName := range fromNames {
  3298. imgName := fmt.Sprintf("%s%d", name, idx)
  3299. buildImageSuccessfully(c, imgName, build.WithDockerfile("FROM "+fromName))
  3300. dockerCmd(c, "rmi", imgName)
  3301. }
  3302. }
  3303. // FIXME(vdemeester) should be a unit test
  3304. func (s *DockerSuite) TestBuildSpaces(c *check.C) {
  3305. // Test to make sure that leading/trailing spaces on a command
  3306. // doesn't change the error msg we get
  3307. name := "testspaces"
  3308. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile("FROM busybox\nCOPY\n"))
  3309. defer ctx.Close()
  3310. result1 := cli.Docker(cli.Build(name), build.WithExternalBuildContext(ctx))
  3311. result1.Assert(c, icmd.Expected{
  3312. ExitCode: 1,
  3313. })
  3314. ctx.Add("Dockerfile", "FROM busybox\nCOPY ")
  3315. result2 := cli.Docker(cli.Build(name), build.WithExternalBuildContext(ctx))
  3316. result2.Assert(c, icmd.Expected{
  3317. ExitCode: 1,
  3318. })
  3319. removeLogTimestamps := func(s string) string {
  3320. return regexp.MustCompile(`time="(.*?)"`).ReplaceAllString(s, `time=[TIMESTAMP]`)
  3321. }
  3322. // Skip over the times
  3323. e1 := removeLogTimestamps(result1.Error.Error())
  3324. e2 := removeLogTimestamps(result2.Error.Error())
  3325. // Ignore whitespace since that's what were verifying doesn't change stuff
  3326. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  3327. c.Fatalf("Build 2's error wasn't the same as build 1's\n1:%s\n2:%s", result1.Error, result2.Error)
  3328. }
  3329. ctx.Add("Dockerfile", "FROM busybox\n COPY")
  3330. result2 = cli.Docker(cli.Build(name), build.WithoutCache, build.WithExternalBuildContext(ctx))
  3331. result2.Assert(c, icmd.Expected{
  3332. ExitCode: 1,
  3333. })
  3334. // Skip over the times
  3335. e1 = removeLogTimestamps(result1.Error.Error())
  3336. e2 = removeLogTimestamps(result2.Error.Error())
  3337. // Ignore whitespace since that's what were verifying doesn't change stuff
  3338. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  3339. c.Fatalf("Build 3's error wasn't the same as build 1's\n1:%s\n3:%s", result1.Error, result2.Error)
  3340. }
  3341. ctx.Add("Dockerfile", "FROM busybox\n COPY ")
  3342. result2 = cli.Docker(cli.Build(name), build.WithoutCache, build.WithExternalBuildContext(ctx))
  3343. result2.Assert(c, icmd.Expected{
  3344. ExitCode: 1,
  3345. })
  3346. // Skip over the times
  3347. e1 = removeLogTimestamps(result1.Error.Error())
  3348. e2 = removeLogTimestamps(result2.Error.Error())
  3349. // Ignore whitespace since that's what were verifying doesn't change stuff
  3350. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  3351. c.Fatalf("Build 4's error wasn't the same as build 1's\n1:%s\n4:%s", result1.Error, result2.Error)
  3352. }
  3353. }
  3354. func (s *DockerSuite) TestBuildSpacesWithQuotes(c *check.C) {
  3355. // Test to make sure that spaces in quotes aren't lost
  3356. name := "testspacesquotes"
  3357. dockerfile := `FROM busybox
  3358. RUN echo " \
  3359. foo "`
  3360. expected := "\n foo \n"
  3361. // Windows uses the builtin echo, which preserves quotes
  3362. if testEnv.OSType == "windows" {
  3363. expected = "\" foo \""
  3364. }
  3365. buildImage(name, build.WithDockerfile(dockerfile)).Assert(c, icmd.Expected{
  3366. Out: expected,
  3367. })
  3368. }
  3369. // #4393
  3370. func (s *DockerSuite) TestBuildVolumeFileExistsinContainer(c *check.C) {
  3371. testRequires(c, DaemonIsLinux) // TODO Windows: This should error out
  3372. buildImage("docker-test-errcreatevolumewithfile", build.WithDockerfile(`
  3373. FROM busybox
  3374. RUN touch /foo
  3375. VOLUME /foo
  3376. `)).Assert(c, icmd.Expected{
  3377. ExitCode: 1,
  3378. Err: "file exists",
  3379. })
  3380. }
  3381. // FIXME(vdemeester) should be a unit test
  3382. func (s *DockerSuite) TestBuildMissingArgs(c *check.C) {
  3383. // Test to make sure that all Dockerfile commands (except the ones listed
  3384. // in skipCmds) will generate an error if no args are provided.
  3385. // Note: INSERT is deprecated so we exclude it because of that.
  3386. skipCmds := map[string]struct{}{
  3387. "CMD": {},
  3388. "RUN": {},
  3389. "ENTRYPOINT": {},
  3390. "INSERT": {},
  3391. }
  3392. if testEnv.OSType == "windows" {
  3393. skipCmds = map[string]struct{}{
  3394. "CMD": {},
  3395. "RUN": {},
  3396. "ENTRYPOINT": {},
  3397. "INSERT": {},
  3398. "STOPSIGNAL": {},
  3399. "ARG": {},
  3400. "USER": {},
  3401. "EXPOSE": {},
  3402. }
  3403. }
  3404. for cmd := range command.Commands {
  3405. cmd = strings.ToUpper(cmd)
  3406. if _, ok := skipCmds[cmd]; ok {
  3407. continue
  3408. }
  3409. var dockerfile string
  3410. if cmd == "FROM" {
  3411. dockerfile = cmd
  3412. } else {
  3413. // Add FROM to make sure we don't complain about it missing
  3414. dockerfile = "FROM busybox\n" + cmd
  3415. }
  3416. buildImage("args", build.WithDockerfile(dockerfile)).Assert(c, icmd.Expected{
  3417. ExitCode: 1,
  3418. Err: cmd + " requires",
  3419. })
  3420. }
  3421. }
  3422. func (s *DockerSuite) TestBuildEmptyScratch(c *check.C) {
  3423. testRequires(c, DaemonIsLinux)
  3424. buildImage("sc", build.WithDockerfile("FROM scratch")).Assert(c, icmd.Expected{
  3425. ExitCode: 1,
  3426. Err: "No image was generated",
  3427. })
  3428. }
  3429. func (s *DockerSuite) TestBuildDotDotFile(c *check.C) {
  3430. buildImageSuccessfully(c, "sc", build.WithBuildContext(c,
  3431. build.WithFile("Dockerfile", "FROM busybox\n"),
  3432. build.WithFile("..gitme", ""),
  3433. ))
  3434. }
  3435. func (s *DockerSuite) TestBuildRUNoneJSON(c *check.C) {
  3436. testRequires(c, DaemonIsLinux) // No hello-world Windows image
  3437. name := "testbuildrunonejson"
  3438. buildImage(name, build.WithDockerfile(`FROM hello-world:frozen
  3439. RUN [ "/hello" ]`)).Assert(c, icmd.Expected{
  3440. Out: "Hello from Docker",
  3441. })
  3442. }
  3443. func (s *DockerSuite) TestBuildEmptyStringVolume(c *check.C) {
  3444. name := "testbuildemptystringvolume"
  3445. buildImage(name, build.WithDockerfile(`
  3446. FROM busybox
  3447. ENV foo=""
  3448. VOLUME $foo
  3449. `)).Assert(c, icmd.Expected{
  3450. ExitCode: 1,
  3451. })
  3452. }
  3453. func (s *DockerSuite) TestBuildContainerWithCgroupParent(c *check.C) {
  3454. testRequires(c, SameHostDaemon, DaemonIsLinux)
  3455. cgroupParent := "test"
  3456. data, err := ioutil.ReadFile("/proc/self/cgroup")
  3457. if err != nil {
  3458. c.Fatalf("failed to read '/proc/self/cgroup - %v", err)
  3459. }
  3460. selfCgroupPaths := ParseCgroupPaths(string(data))
  3461. _, found := selfCgroupPaths["memory"]
  3462. if !found {
  3463. c.Fatalf("unable to find self memory cgroup path. CgroupsPath: %v", selfCgroupPaths)
  3464. }
  3465. result := buildImage("buildcgroupparent",
  3466. cli.WithFlags("--cgroup-parent", cgroupParent),
  3467. build.WithDockerfile(`
  3468. FROM busybox
  3469. RUN cat /proc/self/cgroup
  3470. `))
  3471. result.Assert(c, icmd.Success)
  3472. m, err := regexp.MatchString(fmt.Sprintf("memory:.*/%s/.*", cgroupParent), result.Combined())
  3473. c.Assert(err, check.IsNil)
  3474. if !m {
  3475. c.Fatalf("There is no expected memory cgroup with parent /%s/: %s", cgroupParent, result.Combined())
  3476. }
  3477. }
  3478. // FIXME(vdemeester) could be a unit test
  3479. func (s *DockerSuite) TestBuildNoDupOutput(c *check.C) {
  3480. // Check to make sure our build output prints the Dockerfile cmd
  3481. // property - there was a bug that caused it to be duplicated on the
  3482. // Step X line
  3483. name := "testbuildnodupoutput"
  3484. result := buildImage(name, build.WithDockerfile(`
  3485. FROM busybox
  3486. RUN env`))
  3487. result.Assert(c, icmd.Success)
  3488. exp := "\nStep 2/2 : RUN env\n"
  3489. if !strings.Contains(result.Combined(), exp) {
  3490. c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", result.Combined(), exp)
  3491. }
  3492. }
  3493. // GH15826
  3494. // FIXME(vdemeester) could be a unit test
  3495. func (s *DockerSuite) TestBuildStartsFromOne(c *check.C) {
  3496. // Explicit check to ensure that build starts from step 1 rather than 0
  3497. name := "testbuildstartsfromone"
  3498. result := buildImage(name, build.WithDockerfile(`FROM busybox`))
  3499. result.Assert(c, icmd.Success)
  3500. exp := "\nStep 1/1 : FROM busybox\n"
  3501. if !strings.Contains(result.Combined(), exp) {
  3502. c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", result.Combined(), exp)
  3503. }
  3504. }
  3505. func (s *DockerSuite) TestBuildRUNErrMsg(c *check.C) {
  3506. // Test to make sure the bad command is quoted with just "s and
  3507. // not as a Go []string
  3508. name := "testbuildbadrunerrmsg"
  3509. shell := "/bin/sh -c"
  3510. exitCode := 127
  3511. if testEnv.OSType == "windows" {
  3512. shell = "cmd /S /C"
  3513. // architectural - Windows has to start the container to determine the exe is bad, Linux does not
  3514. exitCode = 1
  3515. }
  3516. exp := fmt.Sprintf(`The command '%s badEXE a1 \& a2 a3' returned a non-zero code: %d`, shell, exitCode)
  3517. buildImage(name, build.WithDockerfile(`
  3518. FROM busybox
  3519. RUN badEXE a1 \& a2 a3`)).Assert(c, icmd.Expected{
  3520. ExitCode: exitCode,
  3521. Err: exp,
  3522. })
  3523. }
  3524. // Issue #15634: COPY fails when path starts with "null"
  3525. func (s *DockerSuite) TestBuildNullStringInAddCopyVolume(c *check.C) {
  3526. name := "testbuildnullstringinaddcopyvolume"
  3527. volName := "nullvolume"
  3528. if testEnv.OSType == "windows" {
  3529. volName = `C:\\nullvolume`
  3530. }
  3531. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  3532. build.WithFile("Dockerfile", `
  3533. FROM busybox
  3534. ADD null /
  3535. COPY nullfile /
  3536. VOLUME `+volName+`
  3537. `),
  3538. build.WithFile("null", "test1"),
  3539. build.WithFile("nullfile", "test2"),
  3540. ))
  3541. }
  3542. func (s *DockerSuite) TestBuildStopSignal(c *check.C) {
  3543. testRequires(c, DaemonIsLinux) // Windows does not support STOPSIGNAL yet
  3544. imgName := "test_build_stop_signal"
  3545. buildImageSuccessfully(c, imgName, build.WithDockerfile(`FROM busybox
  3546. STOPSIGNAL SIGKILL`))
  3547. res := inspectFieldJSON(c, imgName, "Config.StopSignal")
  3548. if res != `"SIGKILL"` {
  3549. c.Fatalf("Signal %s, expected SIGKILL", res)
  3550. }
  3551. containerName := "test-container-stop-signal"
  3552. dockerCmd(c, "run", "-d", "--name", containerName, imgName, "top")
  3553. res = inspectFieldJSON(c, containerName, "Config.StopSignal")
  3554. if res != `"SIGKILL"` {
  3555. c.Fatalf("Signal %s, expected SIGKILL", res)
  3556. }
  3557. }
  3558. func (s *DockerSuite) TestBuildBuildTimeArg(c *check.C) {
  3559. imgName := "bldargtest"
  3560. envKey := "foo"
  3561. envVal := "bar"
  3562. var dockerfile string
  3563. if testEnv.OSType == "windows" {
  3564. // Bugs in Windows busybox port - use the default base image and native cmd stuff
  3565. dockerfile = fmt.Sprintf(`FROM `+minimalBaseImage()+`
  3566. ARG %s
  3567. RUN echo %%%s%%
  3568. CMD setlocal enableextensions && if defined %s (echo %%%s%%)`, envKey, envKey, envKey, envKey)
  3569. } else {
  3570. dockerfile = fmt.Sprintf(`FROM busybox
  3571. ARG %s
  3572. RUN echo $%s
  3573. CMD echo $%s`, envKey, envKey, envKey)
  3574. }
  3575. buildImage(imgName,
  3576. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3577. build.WithDockerfile(dockerfile),
  3578. ).Assert(c, icmd.Expected{
  3579. Out: envVal,
  3580. })
  3581. containerName := "bldargCont"
  3582. out, _ := dockerCmd(c, "run", "--name", containerName, imgName)
  3583. out = strings.Trim(out, " \r\n'")
  3584. if out != "" {
  3585. c.Fatalf("run produced invalid output: %q, expected empty string", out)
  3586. }
  3587. }
  3588. func (s *DockerSuite) TestBuildBuildTimeArgHistory(c *check.C) {
  3589. imgName := "bldargtest"
  3590. envKey := "foo"
  3591. envVal := "bar"
  3592. envDef := "bar1"
  3593. dockerfile := fmt.Sprintf(`FROM busybox
  3594. ARG %s=%s`, envKey, envDef)
  3595. buildImage(imgName,
  3596. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3597. build.WithDockerfile(dockerfile),
  3598. ).Assert(c, icmd.Expected{
  3599. Out: envVal,
  3600. })
  3601. out, _ := dockerCmd(c, "history", "--no-trunc", imgName)
  3602. outputTabs := strings.Split(out, "\n")[1]
  3603. if !strings.Contains(outputTabs, envDef) {
  3604. c.Fatalf("failed to find arg default in image history output: %q expected: %q", outputTabs, envDef)
  3605. }
  3606. }
  3607. func (s *DockerSuite) TestBuildTimeArgHistoryExclusions(c *check.C) {
  3608. imgName := "bldargtest"
  3609. envKey := "foo"
  3610. envVal := "bar"
  3611. proxy := "HTTP_PROXY=http://user:password@proxy.example.com"
  3612. explicitProxyKey := "http_proxy"
  3613. explicitProxyVal := "http://user:password@someproxy.example.com"
  3614. dockerfile := fmt.Sprintf(`FROM busybox
  3615. ARG %s
  3616. ARG %s
  3617. RUN echo "Testing Build Args!"`, envKey, explicitProxyKey)
  3618. buildImage := func(imgName string) string {
  3619. cli.BuildCmd(c, imgName,
  3620. cli.WithFlags("--build-arg", "https_proxy=https://proxy.example.com",
  3621. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  3622. "--build-arg", fmt.Sprintf("%s=%s", explicitProxyKey, explicitProxyVal),
  3623. "--build-arg", proxy),
  3624. build.WithDockerfile(dockerfile),
  3625. )
  3626. return getIDByName(c, imgName)
  3627. }
  3628. origID := buildImage(imgName)
  3629. result := cli.DockerCmd(c, "history", "--no-trunc", imgName)
  3630. out := result.Stdout()
  3631. if strings.Contains(out, proxy) {
  3632. c.Fatalf("failed to exclude proxy settings from history!")
  3633. }
  3634. if strings.Contains(out, "https_proxy") {
  3635. c.Fatalf("failed to exclude proxy settings from history!")
  3636. }
  3637. result.Assert(c, icmd.Expected{Out: fmt.Sprintf("%s=%s", envKey, envVal)})
  3638. result.Assert(c, icmd.Expected{Out: fmt.Sprintf("%s=%s", explicitProxyKey, explicitProxyVal)})
  3639. cacheID := buildImage(imgName + "-two")
  3640. c.Assert(origID, checker.Equals, cacheID)
  3641. }
  3642. func (s *DockerSuite) TestBuildBuildTimeArgCacheHit(c *check.C) {
  3643. imgName := "bldargtest"
  3644. envKey := "foo"
  3645. envVal := "bar"
  3646. dockerfile := fmt.Sprintf(`FROM busybox
  3647. ARG %s
  3648. RUN echo $%s`, envKey, envKey)
  3649. buildImageSuccessfully(c, imgName,
  3650. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3651. build.WithDockerfile(dockerfile),
  3652. )
  3653. origImgID := getIDByName(c, imgName)
  3654. imgNameCache := "bldargtestcachehit"
  3655. buildImageSuccessfully(c, imgNameCache,
  3656. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3657. build.WithDockerfile(dockerfile),
  3658. )
  3659. newImgID := getIDByName(c, imgName)
  3660. if newImgID != origImgID {
  3661. c.Fatalf("build didn't use cache! expected image id: %q built image id: %q", origImgID, newImgID)
  3662. }
  3663. }
  3664. func (s *DockerSuite) TestBuildBuildTimeArgCacheMissExtraArg(c *check.C) {
  3665. imgName := "bldargtest"
  3666. envKey := "foo"
  3667. envVal := "bar"
  3668. extraEnvKey := "foo1"
  3669. extraEnvVal := "bar1"
  3670. dockerfile := fmt.Sprintf(`FROM busybox
  3671. ARG %s
  3672. ARG %s
  3673. RUN echo $%s`, envKey, extraEnvKey, envKey)
  3674. buildImageSuccessfully(c, imgName,
  3675. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3676. build.WithDockerfile(dockerfile),
  3677. )
  3678. origImgID := getIDByName(c, imgName)
  3679. imgNameCache := "bldargtestcachemiss"
  3680. buildImageSuccessfully(c, imgNameCache,
  3681. cli.WithFlags(
  3682. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  3683. "--build-arg", fmt.Sprintf("%s=%s", extraEnvKey, extraEnvVal),
  3684. ),
  3685. build.WithDockerfile(dockerfile),
  3686. )
  3687. newImgID := getIDByName(c, imgNameCache)
  3688. if newImgID == origImgID {
  3689. c.Fatalf("build used cache, expected a miss!")
  3690. }
  3691. }
  3692. func (s *DockerSuite) TestBuildBuildTimeArgCacheMissSameArgDiffVal(c *check.C) {
  3693. imgName := "bldargtest"
  3694. envKey := "foo"
  3695. envVal := "bar"
  3696. newEnvVal := "bar1"
  3697. dockerfile := fmt.Sprintf(`FROM busybox
  3698. ARG %s
  3699. RUN echo $%s`, envKey, envKey)
  3700. buildImageSuccessfully(c, imgName,
  3701. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3702. build.WithDockerfile(dockerfile),
  3703. )
  3704. origImgID := getIDByName(c, imgName)
  3705. imgNameCache := "bldargtestcachemiss"
  3706. buildImageSuccessfully(c, imgNameCache,
  3707. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, newEnvVal)),
  3708. build.WithDockerfile(dockerfile),
  3709. )
  3710. newImgID := getIDByName(c, imgNameCache)
  3711. if newImgID == origImgID {
  3712. c.Fatalf("build used cache, expected a miss!")
  3713. }
  3714. }
  3715. func (s *DockerSuite) TestBuildBuildTimeArgOverrideArgDefinedBeforeEnv(c *check.C) {
  3716. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3717. imgName := "bldargtest"
  3718. envKey := "foo"
  3719. envVal := "bar"
  3720. envValOverride := "barOverride"
  3721. dockerfile := fmt.Sprintf(`FROM busybox
  3722. ARG %s
  3723. ENV %s %s
  3724. RUN echo $%s
  3725. CMD echo $%s
  3726. `, envKey, envKey, envValOverride, envKey, envKey)
  3727. result := buildImage(imgName,
  3728. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3729. build.WithDockerfile(dockerfile),
  3730. )
  3731. result.Assert(c, icmd.Success)
  3732. if strings.Count(result.Combined(), envValOverride) != 2 {
  3733. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envValOverride)
  3734. }
  3735. containerName := "bldargCont"
  3736. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOverride) {
  3737. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOverride)
  3738. }
  3739. }
  3740. // FIXME(vdemeester) might be useful to merge with the one above ?
  3741. func (s *DockerSuite) TestBuildBuildTimeArgOverrideEnvDefinedBeforeArg(c *check.C) {
  3742. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3743. imgName := "bldargtest"
  3744. envKey := "foo"
  3745. envVal := "bar"
  3746. envValOverride := "barOverride"
  3747. dockerfile := fmt.Sprintf(`FROM busybox
  3748. ENV %s %s
  3749. ARG %s
  3750. RUN echo $%s
  3751. CMD echo $%s
  3752. `, envKey, envValOverride, envKey, envKey, envKey)
  3753. result := buildImage(imgName,
  3754. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3755. build.WithDockerfile(dockerfile),
  3756. )
  3757. result.Assert(c, icmd.Success)
  3758. if strings.Count(result.Combined(), envValOverride) != 2 {
  3759. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envValOverride)
  3760. }
  3761. containerName := "bldargCont"
  3762. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOverride) {
  3763. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOverride)
  3764. }
  3765. }
  3766. func (s *DockerSuite) TestBuildBuildTimeArgExpansion(c *check.C) {
  3767. imgName := "bldvarstest"
  3768. wdVar := "WDIR"
  3769. wdVal := "/tmp/"
  3770. addVar := "AFILE"
  3771. addVal := "addFile"
  3772. copyVar := "CFILE"
  3773. copyVal := "copyFile"
  3774. envVar := "foo"
  3775. envVal := "bar"
  3776. exposeVar := "EPORT"
  3777. exposeVal := "9999"
  3778. userVar := "USER"
  3779. userVal := "testUser"
  3780. volVar := "VOL"
  3781. volVal := "/testVol/"
  3782. if DaemonIsWindows() {
  3783. volVal = "C:\\testVol"
  3784. wdVal = "C:\\tmp"
  3785. }
  3786. buildImageSuccessfully(c, imgName,
  3787. cli.WithFlags(
  3788. "--build-arg", fmt.Sprintf("%s=%s", wdVar, wdVal),
  3789. "--build-arg", fmt.Sprintf("%s=%s", addVar, addVal),
  3790. "--build-arg", fmt.Sprintf("%s=%s", copyVar, copyVal),
  3791. "--build-arg", fmt.Sprintf("%s=%s", envVar, envVal),
  3792. "--build-arg", fmt.Sprintf("%s=%s", exposeVar, exposeVal),
  3793. "--build-arg", fmt.Sprintf("%s=%s", userVar, userVal),
  3794. "--build-arg", fmt.Sprintf("%s=%s", volVar, volVal),
  3795. ),
  3796. build.WithBuildContext(c,
  3797. build.WithFile("Dockerfile", fmt.Sprintf(`FROM busybox
  3798. ARG %s
  3799. WORKDIR ${%s}
  3800. ARG %s
  3801. ADD ${%s} testDir/
  3802. ARG %s
  3803. COPY $%s testDir/
  3804. ARG %s
  3805. ENV %s=${%s}
  3806. ARG %s
  3807. EXPOSE $%s
  3808. ARG %s
  3809. USER $%s
  3810. ARG %s
  3811. VOLUME ${%s}`,
  3812. wdVar, wdVar, addVar, addVar, copyVar, copyVar, envVar, envVar,
  3813. envVar, exposeVar, exposeVar, userVar, userVar, volVar, volVar)),
  3814. build.WithFile(addVal, "some stuff"),
  3815. build.WithFile(copyVal, "some stuff"),
  3816. ),
  3817. )
  3818. res := inspectField(c, imgName, "Config.WorkingDir")
  3819. c.Check(filepath.ToSlash(res), check.Equals, filepath.ToSlash(wdVal))
  3820. var resArr []string
  3821. inspectFieldAndUnmarshall(c, imgName, "Config.Env", &resArr)
  3822. found := false
  3823. for _, v := range resArr {
  3824. if fmt.Sprintf("%s=%s", envVar, envVal) == v {
  3825. found = true
  3826. break
  3827. }
  3828. }
  3829. if !found {
  3830. c.Fatalf("Config.Env value mismatch. Expected <key=value> to exist: %s=%s, got: %v",
  3831. envVar, envVal, resArr)
  3832. }
  3833. var resMap map[string]interface{}
  3834. inspectFieldAndUnmarshall(c, imgName, "Config.ExposedPorts", &resMap)
  3835. if _, ok := resMap[fmt.Sprintf("%s/tcp", exposeVal)]; !ok {
  3836. c.Fatalf("Config.ExposedPorts value mismatch. Expected exposed port: %s/tcp, got: %v", exposeVal, resMap)
  3837. }
  3838. res = inspectField(c, imgName, "Config.User")
  3839. if res != userVal {
  3840. c.Fatalf("Config.User value mismatch. Expected: %s, got: %s", userVal, res)
  3841. }
  3842. inspectFieldAndUnmarshall(c, imgName, "Config.Volumes", &resMap)
  3843. if _, ok := resMap[volVal]; !ok {
  3844. c.Fatalf("Config.Volumes value mismatch. Expected volume: %s, got: %v", volVal, resMap)
  3845. }
  3846. }
  3847. func (s *DockerSuite) TestBuildBuildTimeArgExpansionOverride(c *check.C) {
  3848. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3849. imgName := "bldvarstest"
  3850. envKey := "foo"
  3851. envVal := "bar"
  3852. envKey1 := "foo1"
  3853. envValOverride := "barOverride"
  3854. dockerfile := fmt.Sprintf(`FROM busybox
  3855. ARG %s
  3856. ENV %s %s
  3857. ENV %s ${%s}
  3858. RUN echo $%s
  3859. CMD echo $%s`, envKey, envKey, envValOverride, envKey1, envKey, envKey1, envKey1)
  3860. result := buildImage(imgName,
  3861. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3862. build.WithDockerfile(dockerfile),
  3863. )
  3864. result.Assert(c, icmd.Success)
  3865. if strings.Count(result.Combined(), envValOverride) != 2 {
  3866. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envValOverride)
  3867. }
  3868. containerName := "bldargCont"
  3869. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOverride) {
  3870. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOverride)
  3871. }
  3872. }
  3873. func (s *DockerSuite) TestBuildBuildTimeArgUntrustedDefinedAfterUse(c *check.C) {
  3874. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3875. imgName := "bldargtest"
  3876. envKey := "foo"
  3877. envVal := "bar"
  3878. dockerfile := fmt.Sprintf(`FROM busybox
  3879. RUN echo $%s
  3880. ARG %s
  3881. CMD echo $%s`, envKey, envKey, envKey)
  3882. result := buildImage(imgName,
  3883. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3884. build.WithDockerfile(dockerfile),
  3885. )
  3886. result.Assert(c, icmd.Success)
  3887. if strings.Contains(result.Combined(), envVal) {
  3888. c.Fatalf("able to access environment variable in output: %q expected to be missing", result.Combined())
  3889. }
  3890. containerName := "bldargCont"
  3891. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); out != "\n" {
  3892. c.Fatalf("run produced invalid output: %q, expected empty string", out)
  3893. }
  3894. }
  3895. func (s *DockerSuite) TestBuildBuildTimeArgBuiltinArg(c *check.C) {
  3896. testRequires(c, DaemonIsLinux) // Windows does not support --build-arg
  3897. imgName := "bldargtest"
  3898. envKey := "HTTP_PROXY"
  3899. envVal := "bar"
  3900. dockerfile := fmt.Sprintf(`FROM busybox
  3901. RUN echo $%s
  3902. CMD echo $%s`, envKey, envKey)
  3903. result := buildImage(imgName,
  3904. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3905. build.WithDockerfile(dockerfile),
  3906. )
  3907. result.Assert(c, icmd.Success)
  3908. if !strings.Contains(result.Combined(), envVal) {
  3909. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envVal)
  3910. }
  3911. containerName := "bldargCont"
  3912. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); out != "\n" {
  3913. c.Fatalf("run produced invalid output: %q, expected empty string", out)
  3914. }
  3915. }
  3916. func (s *DockerSuite) TestBuildBuildTimeArgDefaultOverride(c *check.C) {
  3917. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3918. imgName := "bldargtest"
  3919. envKey := "foo"
  3920. envVal := "bar"
  3921. envValOverride := "barOverride"
  3922. dockerfile := fmt.Sprintf(`FROM busybox
  3923. ARG %s=%s
  3924. ENV %s $%s
  3925. RUN echo $%s
  3926. CMD echo $%s`, envKey, envVal, envKey, envKey, envKey, envKey)
  3927. result := buildImage(imgName,
  3928. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envValOverride)),
  3929. build.WithDockerfile(dockerfile),
  3930. )
  3931. result.Assert(c, icmd.Success)
  3932. if strings.Count(result.Combined(), envValOverride) != 1 {
  3933. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envValOverride)
  3934. }
  3935. containerName := "bldargCont"
  3936. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOverride) {
  3937. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOverride)
  3938. }
  3939. }
  3940. func (s *DockerSuite) TestBuildBuildTimeArgUnconsumedArg(c *check.C) {
  3941. imgName := "bldargtest"
  3942. envKey := "foo"
  3943. envVal := "bar"
  3944. dockerfile := fmt.Sprintf(`FROM busybox
  3945. RUN echo $%s
  3946. CMD echo $%s`, envKey, envKey)
  3947. warnStr := "[Warning] One or more build-args"
  3948. buildImage(imgName,
  3949. cli.WithFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3950. build.WithDockerfile(dockerfile),
  3951. ).Assert(c, icmd.Expected{
  3952. Out: warnStr,
  3953. })
  3954. }
  3955. func (s *DockerSuite) TestBuildBuildTimeArgEnv(c *check.C) {
  3956. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3957. dockerfile := `FROM busybox
  3958. ARG FOO1=fromfile
  3959. ARG FOO2=fromfile
  3960. ARG FOO3=fromfile
  3961. ARG FOO4=fromfile
  3962. ARG FOO5
  3963. ARG FOO6
  3964. ARG FO10
  3965. RUN env
  3966. RUN [ "$FOO1" == "fromcmd" ]
  3967. RUN [ "$FOO2" == "" ]
  3968. RUN [ "$FOO3" == "fromenv" ]
  3969. RUN [ "$FOO4" == "fromfile" ]
  3970. RUN [ "$FOO5" == "fromcmd" ]
  3971. # The following should not exist at all in the env
  3972. RUN [ "$(env | grep FOO6)" == "" ]
  3973. RUN [ "$(env | grep FOO7)" == "" ]
  3974. RUN [ "$(env | grep FOO8)" == "" ]
  3975. RUN [ "$(env | grep FOO9)" == "" ]
  3976. RUN [ "$FO10" == "" ]
  3977. `
  3978. result := buildImage("testbuildtimeargenv",
  3979. cli.WithFlags(
  3980. "--build-arg", fmt.Sprintf("FOO1=fromcmd"),
  3981. "--build-arg", fmt.Sprintf("FOO2="),
  3982. "--build-arg", fmt.Sprintf("FOO3"), // set in env
  3983. "--build-arg", fmt.Sprintf("FOO4"), // not set in env
  3984. "--build-arg", fmt.Sprintf("FOO5=fromcmd"),
  3985. // FOO6 is not set at all
  3986. "--build-arg", fmt.Sprintf("FOO7=fromcmd"), // should produce a warning
  3987. "--build-arg", fmt.Sprintf("FOO8="), // should produce a warning
  3988. "--build-arg", fmt.Sprintf("FOO9"), // should produce a warning
  3989. "--build-arg", fmt.Sprintf("FO10"), // not set in env, empty value
  3990. ),
  3991. cli.WithEnvironmentVariables(append(os.Environ(),
  3992. "FOO1=fromenv",
  3993. "FOO2=fromenv",
  3994. "FOO3=fromenv")...),
  3995. build.WithBuildContext(c,
  3996. build.WithFile("Dockerfile", dockerfile),
  3997. ),
  3998. )
  3999. result.Assert(c, icmd.Success)
  4000. // Now check to make sure we got a warning msg about unused build-args
  4001. i := strings.Index(result.Combined(), "[Warning]")
  4002. if i < 0 {
  4003. c.Fatalf("Missing the build-arg warning in %q", result.Combined())
  4004. }
  4005. out := result.Combined()[i:] // "out" should contain just the warning message now
  4006. // These were specified on a --build-arg but no ARG was in the Dockerfile
  4007. c.Assert(out, checker.Contains, "FOO7")
  4008. c.Assert(out, checker.Contains, "FOO8")
  4009. c.Assert(out, checker.Contains, "FOO9")
  4010. }
  4011. func (s *DockerSuite) TestBuildBuildTimeArgQuotedValVariants(c *check.C) {
  4012. imgName := "bldargtest"
  4013. envKey := "foo"
  4014. envKey1 := "foo1"
  4015. envKey2 := "foo2"
  4016. envKey3 := "foo3"
  4017. dockerfile := fmt.Sprintf(`FROM busybox
  4018. ARG %s=""
  4019. ARG %s=''
  4020. ARG %s="''"
  4021. ARG %s='""'
  4022. RUN [ "$%s" != "$%s" ]
  4023. RUN [ "$%s" != "$%s" ]
  4024. RUN [ "$%s" != "$%s" ]
  4025. RUN [ "$%s" != "$%s" ]
  4026. RUN [ "$%s" != "$%s" ]`, envKey, envKey1, envKey2, envKey3,
  4027. envKey, envKey2, envKey, envKey3, envKey1, envKey2, envKey1, envKey3,
  4028. envKey2, envKey3)
  4029. buildImageSuccessfully(c, imgName, build.WithDockerfile(dockerfile))
  4030. }
  4031. func (s *DockerSuite) TestBuildBuildTimeArgEmptyValVariants(c *check.C) {
  4032. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  4033. imgName := "bldargtest"
  4034. envKey := "foo"
  4035. envKey1 := "foo1"
  4036. envKey2 := "foo2"
  4037. dockerfile := fmt.Sprintf(`FROM busybox
  4038. ARG %s=
  4039. ARG %s=""
  4040. ARG %s=''
  4041. RUN [ "$%s" == "$%s" ]
  4042. RUN [ "$%s" == "$%s" ]
  4043. RUN [ "$%s" == "$%s" ]`, envKey, envKey1, envKey2, envKey, envKey1, envKey1, envKey2, envKey, envKey2)
  4044. buildImageSuccessfully(c, imgName, build.WithDockerfile(dockerfile))
  4045. }
  4046. func (s *DockerSuite) TestBuildBuildTimeArgDefinitionWithNoEnvInjection(c *check.C) {
  4047. imgName := "bldargtest"
  4048. envKey := "foo"
  4049. dockerfile := fmt.Sprintf(`FROM busybox
  4050. ARG %s
  4051. RUN env`, envKey)
  4052. result := cli.BuildCmd(c, imgName, build.WithDockerfile(dockerfile))
  4053. result.Assert(c, icmd.Success)
  4054. if strings.Count(result.Combined(), envKey) != 1 {
  4055. c.Fatalf("unexpected number of occurrences of the arg in output: %q expected: 1", result.Combined())
  4056. }
  4057. }
  4058. func (s *DockerSuite) TestBuildMultiStageArg(c *check.C) {
  4059. imgName := "multifrombldargtest"
  4060. dockerfile := `FROM busybox
  4061. ARG foo=abc
  4062. LABEL multifromtest=1
  4063. RUN env > /out
  4064. FROM busybox
  4065. ARG bar=def
  4066. RUN env > /out`
  4067. result := cli.BuildCmd(c, imgName, build.WithDockerfile(dockerfile))
  4068. result.Assert(c, icmd.Success)
  4069. result = cli.DockerCmd(c, "images", "-q", "-f", "label=multifromtest=1")
  4070. parentID := strings.TrimSpace(result.Stdout())
  4071. result = cli.DockerCmd(c, "run", "--rm", parentID, "cat", "/out")
  4072. c.Assert(result.Stdout(), checker.Contains, "foo=abc")
  4073. result = cli.DockerCmd(c, "run", "--rm", imgName, "cat", "/out")
  4074. c.Assert(result.Stdout(), checker.Not(checker.Contains), "foo")
  4075. c.Assert(result.Stdout(), checker.Contains, "bar=def")
  4076. }
  4077. func (s *DockerSuite) TestBuildMultiStageGlobalArg(c *check.C) {
  4078. imgName := "multifrombldargtest"
  4079. dockerfile := `ARG tag=nosuchtag
  4080. FROM busybox:${tag}
  4081. LABEL multifromtest=1
  4082. RUN env > /out
  4083. FROM busybox:${tag}
  4084. ARG tag
  4085. RUN env > /out`
  4086. result := cli.BuildCmd(c, imgName,
  4087. build.WithDockerfile(dockerfile),
  4088. cli.WithFlags("--build-arg", fmt.Sprintf("tag=latest")))
  4089. result.Assert(c, icmd.Success)
  4090. result = cli.DockerCmd(c, "images", "-q", "-f", "label=multifromtest=1")
  4091. parentID := strings.TrimSpace(result.Stdout())
  4092. result = cli.DockerCmd(c, "run", "--rm", parentID, "cat", "/out")
  4093. c.Assert(result.Stdout(), checker.Not(checker.Contains), "tag")
  4094. result = cli.DockerCmd(c, "run", "--rm", imgName, "cat", "/out")
  4095. c.Assert(result.Stdout(), checker.Contains, "tag=latest")
  4096. }
  4097. func (s *DockerSuite) TestBuildMultiStageUnusedArg(c *check.C) {
  4098. imgName := "multifromunusedarg"
  4099. dockerfile := `FROM busybox
  4100. ARG foo
  4101. FROM busybox
  4102. ARG bar
  4103. RUN env > /out`
  4104. result := cli.BuildCmd(c, imgName,
  4105. build.WithDockerfile(dockerfile),
  4106. cli.WithFlags("--build-arg", fmt.Sprintf("baz=abc")))
  4107. result.Assert(c, icmd.Success)
  4108. c.Assert(result.Combined(), checker.Contains, "[Warning]")
  4109. c.Assert(result.Combined(), checker.Contains, "[baz] were not consumed")
  4110. result = cli.DockerCmd(c, "run", "--rm", imgName, "cat", "/out")
  4111. c.Assert(result.Stdout(), checker.Not(checker.Contains), "bar")
  4112. c.Assert(result.Stdout(), checker.Not(checker.Contains), "baz")
  4113. }
  4114. func (s *DockerSuite) TestBuildNoNamedVolume(c *check.C) {
  4115. volName := "testname:/foo"
  4116. if testEnv.OSType == "windows" {
  4117. volName = "testname:C:\\foo"
  4118. }
  4119. dockerCmd(c, "run", "-v", volName, "busybox", "sh", "-c", "touch /foo/oops")
  4120. dockerFile := `FROM busybox
  4121. VOLUME ` + volName + `
  4122. RUN ls /foo/oops
  4123. `
  4124. buildImage("test", build.WithDockerfile(dockerFile)).Assert(c, icmd.Expected{
  4125. ExitCode: 1,
  4126. })
  4127. }
  4128. func (s *DockerSuite) TestBuildTagEvent(c *check.C) {
  4129. since := daemonUnixTime(c)
  4130. dockerFile := `FROM busybox
  4131. RUN echo events
  4132. `
  4133. buildImageSuccessfully(c, "test", build.WithDockerfile(dockerFile))
  4134. until := daemonUnixTime(c)
  4135. out, _ := dockerCmd(c, "events", "--since", since, "--until", until, "--filter", "type=image")
  4136. events := strings.Split(strings.TrimSpace(out), "\n")
  4137. actions := eventActionsByIDAndType(c, events, "test:latest", "image")
  4138. var foundTag bool
  4139. for _, a := range actions {
  4140. if a == "tag" {
  4141. foundTag = true
  4142. break
  4143. }
  4144. }
  4145. c.Assert(foundTag, checker.True, check.Commentf("No tag event found:\n%s", out))
  4146. }
  4147. // #15780
  4148. func (s *DockerSuite) TestBuildMultipleTags(c *check.C) {
  4149. dockerfile := `
  4150. FROM busybox
  4151. MAINTAINER test-15780
  4152. `
  4153. buildImageSuccessfully(c, "tag1", cli.WithFlags("-t", "tag2:v2", "-t", "tag1:latest", "-t", "tag1"), build.WithDockerfile(dockerfile))
  4154. id1 := getIDByName(c, "tag1")
  4155. id2 := getIDByName(c, "tag2:v2")
  4156. c.Assert(id1, check.Equals, id2)
  4157. }
  4158. // #17290
  4159. func (s *DockerSuite) TestBuildCacheBrokenSymlink(c *check.C) {
  4160. name := "testbuildbrokensymlink"
  4161. ctx := fakecontext.New(c, "",
  4162. fakecontext.WithDockerfile(`
  4163. FROM busybox
  4164. COPY . ./`),
  4165. fakecontext.WithFiles(map[string]string{
  4166. "foo": "bar",
  4167. }))
  4168. defer ctx.Close()
  4169. err := os.Symlink(filepath.Join(ctx.Dir, "nosuchfile"), filepath.Join(ctx.Dir, "asymlink"))
  4170. c.Assert(err, checker.IsNil)
  4171. // warm up cache
  4172. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4173. // add new file to context, should invalidate cache
  4174. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "newfile"), []byte("foo"), 0644)
  4175. c.Assert(err, checker.IsNil)
  4176. result := cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4177. if strings.Contains(result.Combined(), "Using cache") {
  4178. c.Fatal("2nd build used cache on ADD, it shouldn't")
  4179. }
  4180. }
  4181. func (s *DockerSuite) TestBuildFollowSymlinkToFile(c *check.C) {
  4182. name := "testbuildbrokensymlink"
  4183. ctx := fakecontext.New(c, "",
  4184. fakecontext.WithDockerfile(`
  4185. FROM busybox
  4186. COPY asymlink target`),
  4187. fakecontext.WithFiles(map[string]string{
  4188. "foo": "bar",
  4189. }))
  4190. defer ctx.Close()
  4191. err := os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink"))
  4192. c.Assert(err, checker.IsNil)
  4193. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4194. out := cli.DockerCmd(c, "run", "--rm", name, "cat", "target").Combined()
  4195. c.Assert(out, checker.Matches, "bar")
  4196. // change target file should invalidate cache
  4197. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "foo"), []byte("baz"), 0644)
  4198. c.Assert(err, checker.IsNil)
  4199. result := cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4200. c.Assert(result.Combined(), checker.Not(checker.Contains), "Using cache")
  4201. out = cli.DockerCmd(c, "run", "--rm", name, "cat", "target").Combined()
  4202. c.Assert(out, checker.Matches, "baz")
  4203. }
  4204. func (s *DockerSuite) TestBuildFollowSymlinkToDir(c *check.C) {
  4205. name := "testbuildbrokensymlink"
  4206. ctx := fakecontext.New(c, "",
  4207. fakecontext.WithDockerfile(`
  4208. FROM busybox
  4209. COPY asymlink /`),
  4210. fakecontext.WithFiles(map[string]string{
  4211. "foo/abc": "bar",
  4212. "foo/def": "baz",
  4213. }))
  4214. defer ctx.Close()
  4215. err := os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink"))
  4216. c.Assert(err, checker.IsNil)
  4217. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4218. out := cli.DockerCmd(c, "run", "--rm", name, "cat", "abc", "def").Combined()
  4219. c.Assert(out, checker.Matches, "barbaz")
  4220. // change target file should invalidate cache
  4221. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "foo/def"), []byte("bax"), 0644)
  4222. c.Assert(err, checker.IsNil)
  4223. result := cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4224. c.Assert(result.Combined(), checker.Not(checker.Contains), "Using cache")
  4225. out = cli.DockerCmd(c, "run", "--rm", name, "cat", "abc", "def").Combined()
  4226. c.Assert(out, checker.Matches, "barbax")
  4227. }
  4228. // TestBuildSymlinkBasename tests that target file gets basename from symlink,
  4229. // not from the target file.
  4230. func (s *DockerSuite) TestBuildSymlinkBasename(c *check.C) {
  4231. name := "testbuildbrokensymlink"
  4232. ctx := fakecontext.New(c, "",
  4233. fakecontext.WithDockerfile(`
  4234. FROM busybox
  4235. COPY asymlink /`),
  4236. fakecontext.WithFiles(map[string]string{
  4237. "foo": "bar",
  4238. }))
  4239. defer ctx.Close()
  4240. err := os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink"))
  4241. c.Assert(err, checker.IsNil)
  4242. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4243. out := cli.DockerCmd(c, "run", "--rm", name, "cat", "asymlink").Combined()
  4244. c.Assert(out, checker.Matches, "bar")
  4245. }
  4246. // #17827
  4247. func (s *DockerSuite) TestBuildCacheRootSource(c *check.C) {
  4248. name := "testbuildrootsource"
  4249. ctx := fakecontext.New(c, "",
  4250. fakecontext.WithDockerfile(`
  4251. FROM busybox
  4252. COPY / /data`),
  4253. fakecontext.WithFiles(map[string]string{
  4254. "foo": "bar",
  4255. }))
  4256. defer ctx.Close()
  4257. // warm up cache
  4258. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4259. // change file, should invalidate cache
  4260. err := ioutil.WriteFile(filepath.Join(ctx.Dir, "foo"), []byte("baz"), 0644)
  4261. c.Assert(err, checker.IsNil)
  4262. result := cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4263. c.Assert(result.Combined(), checker.Not(checker.Contains), "Using cache")
  4264. }
  4265. // #19375
  4266. // FIXME(vdemeester) should migrate to docker/cli tests
  4267. func (s *DockerSuite) TestBuildFailsGitNotCallable(c *check.C) {
  4268. buildImage("gitnotcallable", cli.WithEnvironmentVariables("PATH="),
  4269. build.WithContextPath("github.com/docker/v1.10-migrator.git")).Assert(c, icmd.Expected{
  4270. ExitCode: 1,
  4271. Err: "unable to prepare context: unable to find 'git': ",
  4272. })
  4273. buildImage("gitnotcallable", cli.WithEnvironmentVariables("PATH="),
  4274. build.WithContextPath("https://github.com/docker/v1.10-migrator.git")).Assert(c, icmd.Expected{
  4275. ExitCode: 1,
  4276. Err: "unable to prepare context: unable to find 'git': ",
  4277. })
  4278. }
  4279. // TestBuildWorkdirWindowsPath tests that a Windows style path works as a workdir
  4280. func (s *DockerSuite) TestBuildWorkdirWindowsPath(c *check.C) {
  4281. testRequires(c, DaemonIsWindows)
  4282. name := "testbuildworkdirwindowspath"
  4283. buildImageSuccessfully(c, name, build.WithDockerfile(`
  4284. FROM `+testEnv.PlatformDefaults.BaseImage+`
  4285. RUN mkdir C:\\work
  4286. WORKDIR C:\\work
  4287. RUN if "%CD%" NEQ "C:\work" exit -1
  4288. `))
  4289. }
  4290. func (s *DockerSuite) TestBuildLabel(c *check.C) {
  4291. name := "testbuildlabel"
  4292. testLabel := "foo"
  4293. buildImageSuccessfully(c, name, cli.WithFlags("--label", testLabel),
  4294. build.WithDockerfile(`
  4295. FROM `+minimalBaseImage()+`
  4296. LABEL default foo
  4297. `))
  4298. var labels map[string]string
  4299. inspectFieldAndUnmarshall(c, name, "Config.Labels", &labels)
  4300. if _, ok := labels[testLabel]; !ok {
  4301. c.Fatal("label not found in image")
  4302. }
  4303. }
  4304. func (s *DockerSuite) TestBuildLabelOneNode(c *check.C) {
  4305. name := "testbuildlabel"
  4306. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo=bar"),
  4307. build.WithDockerfile("FROM busybox"))
  4308. var labels map[string]string
  4309. inspectFieldAndUnmarshall(c, name, "Config.Labels", &labels)
  4310. v, ok := labels["foo"]
  4311. if !ok {
  4312. c.Fatal("label `foo` not found in image")
  4313. }
  4314. c.Assert(v, checker.Equals, "bar")
  4315. }
  4316. func (s *DockerSuite) TestBuildLabelCacheCommit(c *check.C) {
  4317. name := "testbuildlabelcachecommit"
  4318. testLabel := "foo"
  4319. buildImageSuccessfully(c, name, build.WithDockerfile(`
  4320. FROM `+minimalBaseImage()+`
  4321. LABEL default foo
  4322. `))
  4323. buildImageSuccessfully(c, name, cli.WithFlags("--label", testLabel),
  4324. build.WithDockerfile(`
  4325. FROM `+minimalBaseImage()+`
  4326. LABEL default foo
  4327. `))
  4328. var labels map[string]string
  4329. inspectFieldAndUnmarshall(c, name, "Config.Labels", &labels)
  4330. if _, ok := labels[testLabel]; !ok {
  4331. c.Fatal("label not found in image")
  4332. }
  4333. }
  4334. func (s *DockerSuite) TestBuildLabelMultiple(c *check.C) {
  4335. name := "testbuildlabelmultiple"
  4336. testLabels := map[string]string{
  4337. "foo": "bar",
  4338. "123": "456",
  4339. }
  4340. var labelArgs []string
  4341. for k, v := range testLabels {
  4342. labelArgs = append(labelArgs, "--label", k+"="+v)
  4343. }
  4344. buildImageSuccessfully(c, name, cli.WithFlags(labelArgs...),
  4345. build.WithDockerfile(`
  4346. FROM `+minimalBaseImage()+`
  4347. LABEL default foo
  4348. `))
  4349. var labels map[string]string
  4350. inspectFieldAndUnmarshall(c, name, "Config.Labels", &labels)
  4351. for k, v := range testLabels {
  4352. if x, ok := labels[k]; !ok || x != v {
  4353. c.Fatalf("label %s=%s not found in image", k, v)
  4354. }
  4355. }
  4356. }
  4357. func (s *DockerRegistryAuthHtpasswdSuite) TestBuildFromAuthenticatedRegistry(c *check.C) {
  4358. dockerCmd(c, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL)
  4359. baseImage := privateRegistryURL + "/baseimage"
  4360. buildImageSuccessfully(c, baseImage, build.WithDockerfile(`
  4361. FROM busybox
  4362. ENV env1 val1
  4363. `))
  4364. dockerCmd(c, "push", baseImage)
  4365. dockerCmd(c, "rmi", baseImage)
  4366. buildImageSuccessfully(c, baseImage, build.WithDockerfile(fmt.Sprintf(`
  4367. FROM %s
  4368. ENV env2 val2
  4369. `, baseImage)))
  4370. }
  4371. func (s *DockerRegistryAuthHtpasswdSuite) TestBuildWithExternalAuth(c *check.C) {
  4372. osPath := os.Getenv("PATH")
  4373. defer os.Setenv("PATH", osPath)
  4374. workingDir, err := os.Getwd()
  4375. c.Assert(err, checker.IsNil)
  4376. absolute, err := filepath.Abs(filepath.Join(workingDir, "fixtures", "auth"))
  4377. c.Assert(err, checker.IsNil)
  4378. testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute)
  4379. os.Setenv("PATH", testPath)
  4380. repoName := fmt.Sprintf("%v/dockercli/busybox:authtest", privateRegistryURL)
  4381. tmp, err := ioutil.TempDir("", "integration-cli-")
  4382. c.Assert(err, checker.IsNil)
  4383. externalAuthConfig := `{ "credsStore": "shell-test" }`
  4384. configPath := filepath.Join(tmp, "config.json")
  4385. err = ioutil.WriteFile(configPath, []byte(externalAuthConfig), 0644)
  4386. c.Assert(err, checker.IsNil)
  4387. dockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL)
  4388. b, err := ioutil.ReadFile(configPath)
  4389. c.Assert(err, checker.IsNil)
  4390. c.Assert(string(b), checker.Not(checker.Contains), "\"auth\":")
  4391. dockerCmd(c, "--config", tmp, "tag", "busybox", repoName)
  4392. dockerCmd(c, "--config", tmp, "push", repoName)
  4393. // make sure the image is pulled when building
  4394. dockerCmd(c, "rmi", repoName)
  4395. icmd.RunCmd(icmd.Cmd{
  4396. Command: []string{dockerBinary, "--config", tmp, "build", "-"},
  4397. Stdin: strings.NewReader(fmt.Sprintf("FROM %s", repoName)),
  4398. }).Assert(c, icmd.Success)
  4399. }
  4400. // Test cases in #22036
  4401. func (s *DockerSuite) TestBuildLabelsOverride(c *check.C) {
  4402. // Command line option labels will always override
  4403. name := "scratchy"
  4404. expected := `{"bar":"from-flag","foo":"from-flag"}`
  4405. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo=from-flag", "--label", "bar=from-flag"),
  4406. build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4407. LABEL foo=from-dockerfile`))
  4408. res := inspectFieldJSON(c, name, "Config.Labels")
  4409. if res != expected {
  4410. c.Fatalf("Labels %s, expected %s", res, expected)
  4411. }
  4412. name = "from"
  4413. expected = `{"foo":"from-dockerfile"}`
  4414. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4415. LABEL foo from-dockerfile`))
  4416. res = inspectFieldJSON(c, name, "Config.Labels")
  4417. if res != expected {
  4418. c.Fatalf("Labels %s, expected %s", res, expected)
  4419. }
  4420. // Command line option label will override even via `FROM`
  4421. name = "new"
  4422. expected = `{"bar":"from-dockerfile2","foo":"new"}`
  4423. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo=new"),
  4424. build.WithDockerfile(`FROM from
  4425. LABEL bar from-dockerfile2`))
  4426. res = inspectFieldJSON(c, name, "Config.Labels")
  4427. if res != expected {
  4428. c.Fatalf("Labels %s, expected %s", res, expected)
  4429. }
  4430. // Command line option without a value set (--label foo, --label bar=)
  4431. // will be treated as --label foo="", --label bar=""
  4432. name = "scratchy2"
  4433. expected = `{"bar":"","foo":""}`
  4434. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo", "--label", "bar="),
  4435. build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4436. LABEL foo=from-dockerfile`))
  4437. res = inspectFieldJSON(c, name, "Config.Labels")
  4438. if res != expected {
  4439. c.Fatalf("Labels %s, expected %s", res, expected)
  4440. }
  4441. // Command line option without a value set (--label foo, --label bar=)
  4442. // will be treated as --label foo="", --label bar=""
  4443. // This time is for inherited images
  4444. name = "new2"
  4445. expected = `{"bar":"","foo":""}`
  4446. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo=", "--label", "bar"),
  4447. build.WithDockerfile(`FROM from
  4448. LABEL bar from-dockerfile2`))
  4449. res = inspectFieldJSON(c, name, "Config.Labels")
  4450. if res != expected {
  4451. c.Fatalf("Labels %s, expected %s", res, expected)
  4452. }
  4453. // Command line option labels with only `FROM`
  4454. name = "scratchy"
  4455. expected = `{"bar":"from-flag","foo":"from-flag"}`
  4456. buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo=from-flag", "--label", "bar=from-flag"),
  4457. build.WithDockerfile(`FROM `+minimalBaseImage()))
  4458. res = inspectFieldJSON(c, name, "Config.Labels")
  4459. if res != expected {
  4460. c.Fatalf("Labels %s, expected %s", res, expected)
  4461. }
  4462. // Command line option labels with env var
  4463. name = "scratchz"
  4464. expected = `{"bar":"$PATH"}`
  4465. buildImageSuccessfully(c, name, cli.WithFlags("--label", "bar=$PATH"),
  4466. build.WithDockerfile(`FROM `+minimalBaseImage()))
  4467. res = inspectFieldJSON(c, name, "Config.Labels")
  4468. if res != expected {
  4469. c.Fatalf("Labels %s, expected %s", res, expected)
  4470. }
  4471. }
  4472. // Test case for #22855
  4473. func (s *DockerSuite) TestBuildDeleteCommittedFile(c *check.C) {
  4474. name := "test-delete-committed-file"
  4475. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  4476. RUN echo test > file
  4477. RUN test -e file
  4478. RUN rm file
  4479. RUN sh -c "! test -e file"`))
  4480. }
  4481. // #20083
  4482. func (s *DockerSuite) TestBuildDockerignoreComment(c *check.C) {
  4483. // TODO Windows: Figure out why this test is flakey on TP5. If you add
  4484. // something like RUN sleep 5, or even RUN ls /tmp after the ADD line,
  4485. // it is more reliable, but that's not a good fix.
  4486. testRequires(c, DaemonIsLinux)
  4487. name := "testbuilddockerignorecleanpaths"
  4488. dockerfile := `
  4489. FROM busybox
  4490. ADD . /tmp/
  4491. RUN sh -c "(ls -la /tmp/#1)"
  4492. RUN sh -c "(! ls -la /tmp/#2)"
  4493. RUN sh -c "(! ls /tmp/foo) && (! ls /tmp/foo2) && (ls /tmp/dir1/foo)"`
  4494. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  4495. build.WithFile("Dockerfile", dockerfile),
  4496. build.WithFile("foo", "foo"),
  4497. build.WithFile("foo2", "foo2"),
  4498. build.WithFile("dir1/foo", "foo in dir1"),
  4499. build.WithFile("#1", "# file 1"),
  4500. build.WithFile("#2", "# file 2"),
  4501. build.WithFile(".dockerignore", `# Visual C++ cache files
  4502. # because we have git ;-)
  4503. # The above comment is from #20083
  4504. foo
  4505. #dir1/foo
  4506. foo2
  4507. # The following is considered as comment as # is at the beginning
  4508. #1
  4509. # The following is not considered as comment as # is not at the beginning
  4510. #2
  4511. `)))
  4512. }
  4513. // Test case for #23221
  4514. func (s *DockerSuite) TestBuildWithUTF8BOM(c *check.C) {
  4515. name := "test-with-utf8-bom"
  4516. dockerfile := []byte(`FROM busybox`)
  4517. bomDockerfile := append([]byte{0xEF, 0xBB, 0xBF}, dockerfile...)
  4518. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  4519. build.WithFile("Dockerfile", string(bomDockerfile)),
  4520. ))
  4521. }
  4522. // Test case for UTF-8 BOM in .dockerignore, related to #23221
  4523. func (s *DockerSuite) TestBuildWithUTF8BOMDockerignore(c *check.C) {
  4524. name := "test-with-utf8-bom-dockerignore"
  4525. dockerfile := `
  4526. FROM busybox
  4527. ADD . /tmp/
  4528. RUN ls -la /tmp
  4529. RUN sh -c "! ls /tmp/Dockerfile"
  4530. RUN ls /tmp/.dockerignore`
  4531. dockerignore := []byte("./Dockerfile\n")
  4532. bomDockerignore := append([]byte{0xEF, 0xBB, 0xBF}, dockerignore...)
  4533. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  4534. build.WithFile("Dockerfile", dockerfile),
  4535. build.WithFile(".dockerignore", string(bomDockerignore)),
  4536. ))
  4537. }
  4538. // #22489 Shell test to confirm config gets updated correctly
  4539. func (s *DockerSuite) TestBuildShellUpdatesConfig(c *check.C) {
  4540. name := "testbuildshellupdatesconfig"
  4541. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4542. SHELL ["foo", "-bar"]`))
  4543. expected := `["foo","-bar","#(nop) ","SHELL [foo -bar]"]`
  4544. res := inspectFieldJSON(c, name, "ContainerConfig.Cmd")
  4545. if res != expected {
  4546. c.Fatalf("%s, expected %s", res, expected)
  4547. }
  4548. res = inspectFieldJSON(c, name, "ContainerConfig.Shell")
  4549. if res != `["foo","-bar"]` {
  4550. c.Fatalf(`%s, expected ["foo","-bar"]`, res)
  4551. }
  4552. }
  4553. // #22489 Changing the shell multiple times and CMD after.
  4554. func (s *DockerSuite) TestBuildShellMultiple(c *check.C) {
  4555. name := "testbuildshellmultiple"
  4556. result := buildImage(name, build.WithDockerfile(`FROM busybox
  4557. RUN echo defaultshell
  4558. SHELL ["echo"]
  4559. RUN echoshell
  4560. SHELL ["ls"]
  4561. RUN -l
  4562. CMD -l`))
  4563. result.Assert(c, icmd.Success)
  4564. // Must contain 'defaultshell' twice
  4565. if len(strings.Split(result.Combined(), "defaultshell")) != 3 {
  4566. c.Fatalf("defaultshell should have appeared twice in %s", result.Combined())
  4567. }
  4568. // Must contain 'echoshell' twice
  4569. if len(strings.Split(result.Combined(), "echoshell")) != 3 {
  4570. c.Fatalf("echoshell should have appeared twice in %s", result.Combined())
  4571. }
  4572. // Must contain "total " (part of ls -l)
  4573. if !strings.Contains(result.Combined(), "total ") {
  4574. c.Fatalf("%s should have contained 'total '", result.Combined())
  4575. }
  4576. // A container started from the image uses the shell-form CMD.
  4577. // Last shell is ls. CMD is -l. So should contain 'total '.
  4578. outrun, _ := dockerCmd(c, "run", "--rm", name)
  4579. if !strings.Contains(outrun, "total ") {
  4580. c.Fatalf("Expected started container to run ls -l. %s", outrun)
  4581. }
  4582. }
  4583. // #22489. Changed SHELL with ENTRYPOINT
  4584. func (s *DockerSuite) TestBuildShellEntrypoint(c *check.C) {
  4585. name := "testbuildshellentrypoint"
  4586. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  4587. SHELL ["ls"]
  4588. ENTRYPOINT -l`))
  4589. // A container started from the image uses the shell-form ENTRYPOINT.
  4590. // Shell is ls. ENTRYPOINT is -l. So should contain 'total '.
  4591. outrun, _ := dockerCmd(c, "run", "--rm", name)
  4592. if !strings.Contains(outrun, "total ") {
  4593. c.Fatalf("Expected started container to run ls -l. %s", outrun)
  4594. }
  4595. }
  4596. // #22489 Shell test to confirm shell is inherited in a subsequent build
  4597. func (s *DockerSuite) TestBuildShellInherited(c *check.C) {
  4598. name1 := "testbuildshellinherited1"
  4599. buildImageSuccessfully(c, name1, build.WithDockerfile(`FROM busybox
  4600. SHELL ["ls"]`))
  4601. name2 := "testbuildshellinherited2"
  4602. buildImage(name2, build.WithDockerfile(`FROM `+name1+`
  4603. RUN -l`)).Assert(c, icmd.Expected{
  4604. // ls -l has "total " followed by some number in it, ls without -l does not.
  4605. Out: "total ",
  4606. })
  4607. }
  4608. // #22489 Shell test to confirm non-JSON doesn't work
  4609. func (s *DockerSuite) TestBuildShellNotJSON(c *check.C) {
  4610. name := "testbuildshellnotjson"
  4611. buildImage(name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4612. sHeLl exec -form`, // Casing explicit to ensure error is upper-cased.
  4613. )).Assert(c, icmd.Expected{
  4614. ExitCode: 1,
  4615. Err: "SHELL requires the arguments to be in JSON form",
  4616. })
  4617. }
  4618. // #22489 Windows shell test to confirm native is powershell if executing a PS command
  4619. // This would error if the default shell were still cmd.
  4620. func (s *DockerSuite) TestBuildShellWindowsPowershell(c *check.C) {
  4621. testRequires(c, DaemonIsWindows)
  4622. name := "testbuildshellpowershell"
  4623. buildImage(name, build.WithDockerfile(`FROM `+minimalBaseImage()+`
  4624. SHELL ["powershell", "-command"]
  4625. RUN Write-Host John`)).Assert(c, icmd.Expected{
  4626. Out: "\nJohn\n",
  4627. })
  4628. }
  4629. // Verify that escape is being correctly applied to words when escape directive is not \.
  4630. // Tests WORKDIR, ADD
  4631. func (s *DockerSuite) TestBuildEscapeNotBackslashWordTest(c *check.C) {
  4632. testRequires(c, DaemonIsWindows)
  4633. name := "testbuildescapenotbackslashwordtesta"
  4634. buildImage(name, build.WithDockerfile(`# escape= `+"`"+`
  4635. FROM `+minimalBaseImage()+`
  4636. WORKDIR c:\windows
  4637. RUN dir /w`)).Assert(c, icmd.Expected{
  4638. Out: "[System32]",
  4639. })
  4640. name = "testbuildescapenotbackslashwordtestb"
  4641. buildImage(name, build.WithDockerfile(`# escape= `+"`"+`
  4642. FROM `+minimalBaseImage()+`
  4643. SHELL ["powershell.exe"]
  4644. WORKDIR c:\foo
  4645. ADD Dockerfile c:\foo\
  4646. RUN dir Dockerfile`)).Assert(c, icmd.Expected{
  4647. Out: "-a----",
  4648. })
  4649. }
  4650. // #22868. Make sure shell-form CMD is marked as escaped in the config of the image
  4651. func (s *DockerSuite) TestBuildCmdShellArgsEscaped(c *check.C) {
  4652. testRequires(c, DaemonIsWindows)
  4653. name := "testbuildcmdshellescaped"
  4654. buildImageSuccessfully(c, name, build.WithDockerfile(`
  4655. FROM `+minimalBaseImage()+`
  4656. CMD "ipconfig"
  4657. `))
  4658. res := inspectFieldJSON(c, name, "Config.ArgsEscaped")
  4659. if res != "true" {
  4660. c.Fatalf("CMD did not update Config.ArgsEscaped on image: %v", res)
  4661. }
  4662. dockerCmd(c, "run", "--name", "inspectme", name)
  4663. dockerCmd(c, "wait", "inspectme")
  4664. res = inspectFieldJSON(c, name, "Config.Cmd")
  4665. if res != `["cmd","/S","/C","\"ipconfig\""]` {
  4666. c.Fatalf("CMD was not escaped Config.Cmd: got %v", res)
  4667. }
  4668. }
  4669. // Test case for #24912.
  4670. func (s *DockerSuite) TestBuildStepsWithProgress(c *check.C) {
  4671. name := "testbuildstepswithprogress"
  4672. totalRun := 5
  4673. result := buildImage(name, build.WithDockerfile("FROM busybox\n"+strings.Repeat("RUN echo foo\n", totalRun)))
  4674. result.Assert(c, icmd.Success)
  4675. c.Assert(result.Combined(), checker.Contains, fmt.Sprintf("Step 1/%d : FROM busybox", 1+totalRun))
  4676. for i := 2; i <= 1+totalRun; i++ {
  4677. c.Assert(result.Combined(), checker.Contains, fmt.Sprintf("Step %d/%d : RUN echo foo", i, 1+totalRun))
  4678. }
  4679. }
  4680. func (s *DockerSuite) TestBuildWithFailure(c *check.C) {
  4681. name := "testbuildwithfailure"
  4682. // First test case can only detect `nobody` in runtime so all steps will show up
  4683. dockerfile := "FROM busybox\nRUN nobody"
  4684. result := buildImage(name, build.WithDockerfile(dockerfile))
  4685. c.Assert(result.Error, checker.NotNil)
  4686. c.Assert(result.Stdout(), checker.Contains, "Step 1/2 : FROM busybox")
  4687. c.Assert(result.Stdout(), checker.Contains, "Step 2/2 : RUN nobody")
  4688. // Second test case `FFOM` should have been detected before build runs so no steps
  4689. dockerfile = "FFOM nobody\nRUN nobody"
  4690. result = buildImage(name, build.WithDockerfile(dockerfile))
  4691. c.Assert(result.Error, checker.NotNil)
  4692. c.Assert(result.Stdout(), checker.Not(checker.Contains), "Step 1/2 : FROM busybox")
  4693. c.Assert(result.Stdout(), checker.Not(checker.Contains), "Step 2/2 : RUN nobody")
  4694. }
  4695. func (s *DockerSuite) TestBuildCacheFromEqualDiffIDsLength(c *check.C) {
  4696. dockerfile := `
  4697. FROM busybox
  4698. RUN echo "test"
  4699. ENTRYPOINT ["sh"]`
  4700. ctx := fakecontext.New(c, "",
  4701. fakecontext.WithDockerfile(dockerfile),
  4702. fakecontext.WithFiles(map[string]string{
  4703. "Dockerfile": dockerfile,
  4704. }))
  4705. defer ctx.Close()
  4706. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  4707. id1 := getIDByName(c, "build1")
  4708. // rebuild with cache-from
  4709. result := cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4710. id2 := getIDByName(c, "build2")
  4711. c.Assert(id1, checker.Equals, id2)
  4712. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 2)
  4713. }
  4714. func (s *DockerSuite) TestBuildCacheFrom(c *check.C) {
  4715. testRequires(c, DaemonIsLinux) // All tests that do save are skipped in windows
  4716. dockerfile := `
  4717. FROM busybox
  4718. ENV FOO=bar
  4719. ADD baz /
  4720. RUN touch bax`
  4721. ctx := fakecontext.New(c, "",
  4722. fakecontext.WithDockerfile(dockerfile),
  4723. fakecontext.WithFiles(map[string]string{
  4724. "Dockerfile": dockerfile,
  4725. "baz": "baz",
  4726. }))
  4727. defer ctx.Close()
  4728. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  4729. id1 := getIDByName(c, "build1")
  4730. // rebuild with cache-from
  4731. result := cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4732. id2 := getIDByName(c, "build2")
  4733. c.Assert(id1, checker.Equals, id2)
  4734. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 3)
  4735. cli.DockerCmd(c, "rmi", "build2")
  4736. // no cache match with unknown source
  4737. result = cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=nosuchtag"), build.WithExternalBuildContext(ctx))
  4738. id2 = getIDByName(c, "build2")
  4739. c.Assert(id1, checker.Not(checker.Equals), id2)
  4740. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 0)
  4741. cli.DockerCmd(c, "rmi", "build2")
  4742. // clear parent images
  4743. tempDir, err := ioutil.TempDir("", "test-build-cache-from-")
  4744. if err != nil {
  4745. c.Fatalf("failed to create temporary directory: %s", tempDir)
  4746. }
  4747. defer os.RemoveAll(tempDir)
  4748. tempFile := filepath.Join(tempDir, "img.tar")
  4749. cli.DockerCmd(c, "save", "-o", tempFile, "build1")
  4750. cli.DockerCmd(c, "rmi", "build1")
  4751. cli.DockerCmd(c, "load", "-i", tempFile)
  4752. parentID := cli.DockerCmd(c, "inspect", "-f", "{{.Parent}}", "build1").Combined()
  4753. c.Assert(strings.TrimSpace(parentID), checker.Equals, "")
  4754. // cache still applies without parents
  4755. result = cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4756. id2 = getIDByName(c, "build2")
  4757. c.Assert(id1, checker.Equals, id2)
  4758. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 3)
  4759. history1 := cli.DockerCmd(c, "history", "-q", "build2").Combined()
  4760. // Retry, no new intermediate images
  4761. result = cli.BuildCmd(c, "build3", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4762. id3 := getIDByName(c, "build3")
  4763. c.Assert(id1, checker.Equals, id3)
  4764. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 3)
  4765. history2 := cli.DockerCmd(c, "history", "-q", "build3").Combined()
  4766. c.Assert(history1, checker.Equals, history2)
  4767. cli.DockerCmd(c, "rmi", "build2")
  4768. cli.DockerCmd(c, "rmi", "build3")
  4769. cli.DockerCmd(c, "rmi", "build1")
  4770. cli.DockerCmd(c, "load", "-i", tempFile)
  4771. // Modify file, everything up to last command and layers are reused
  4772. dockerfile = `
  4773. FROM busybox
  4774. ENV FOO=bar
  4775. ADD baz /
  4776. RUN touch newfile`
  4777. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "Dockerfile"), []byte(dockerfile), 0644)
  4778. c.Assert(err, checker.IsNil)
  4779. result = cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4780. id2 = getIDByName(c, "build2")
  4781. c.Assert(id1, checker.Not(checker.Equals), id2)
  4782. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 2)
  4783. layers1Str := cli.DockerCmd(c, "inspect", "-f", "{{json .RootFS.Layers}}", "build1").Combined()
  4784. layers2Str := cli.DockerCmd(c, "inspect", "-f", "{{json .RootFS.Layers}}", "build2").Combined()
  4785. var layers1 []string
  4786. var layers2 []string
  4787. c.Assert(json.Unmarshal([]byte(layers1Str), &layers1), checker.IsNil)
  4788. c.Assert(json.Unmarshal([]byte(layers2Str), &layers2), checker.IsNil)
  4789. c.Assert(len(layers1), checker.Equals, len(layers2))
  4790. for i := 0; i < len(layers1)-1; i++ {
  4791. c.Assert(layers1[i], checker.Equals, layers2[i])
  4792. }
  4793. c.Assert(layers1[len(layers1)-1], checker.Not(checker.Equals), layers2[len(layers1)-1])
  4794. }
  4795. func (s *DockerSuite) TestBuildMultiStageCache(c *check.C) {
  4796. testRequires(c, DaemonIsLinux) // All tests that do save are skipped in windows
  4797. dockerfile := `
  4798. FROM busybox
  4799. ADD baz /
  4800. FROM busybox
  4801. ADD baz /`
  4802. ctx := fakecontext.New(c, "",
  4803. fakecontext.WithDockerfile(dockerfile),
  4804. fakecontext.WithFiles(map[string]string{
  4805. "Dockerfile": dockerfile,
  4806. "baz": "baz",
  4807. }))
  4808. defer ctx.Close()
  4809. result := cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  4810. // second part of dockerfile was a repeat of first so should be cached
  4811. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 1)
  4812. result = cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx))
  4813. // now both parts of dockerfile should be cached
  4814. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 2)
  4815. }
  4816. func (s *DockerSuite) TestBuildNetNone(c *check.C) {
  4817. testRequires(c, DaemonIsLinux)
  4818. name := "testbuildnetnone"
  4819. buildImage(name, cli.WithFlags("--network=none"), build.WithDockerfile(`
  4820. FROM busybox
  4821. RUN ping -c 1 8.8.8.8
  4822. `)).Assert(c, icmd.Expected{
  4823. ExitCode: 1,
  4824. Out: "unreachable",
  4825. })
  4826. }
  4827. func (s *DockerSuite) TestBuildNetContainer(c *check.C) {
  4828. testRequires(c, DaemonIsLinux)
  4829. id, _ := dockerCmd(c, "run", "--hostname", "foobar", "-d", "busybox", "nc", "-ll", "-p", "1234", "-e", "hostname")
  4830. name := "testbuildnetcontainer"
  4831. buildImageSuccessfully(c, name, cli.WithFlags("--network=container:"+strings.TrimSpace(id)),
  4832. build.WithDockerfile(`
  4833. FROM busybox
  4834. RUN nc localhost 1234 > /otherhost
  4835. `))
  4836. host, _ := dockerCmd(c, "run", "testbuildnetcontainer", "cat", "/otherhost")
  4837. c.Assert(strings.TrimSpace(host), check.Equals, "foobar")
  4838. }
  4839. func (s *DockerSuite) TestBuildWithExtraHost(c *check.C) {
  4840. testRequires(c, DaemonIsLinux)
  4841. name := "testbuildwithextrahost"
  4842. buildImageSuccessfully(c, name,
  4843. cli.WithFlags(
  4844. "--add-host", "foo:127.0.0.1",
  4845. "--add-host", "bar:127.0.0.1",
  4846. ),
  4847. build.WithDockerfile(`
  4848. FROM busybox
  4849. RUN ping -c 1 foo
  4850. RUN ping -c 1 bar
  4851. `))
  4852. }
  4853. func (s *DockerSuite) TestBuildWithExtraHostInvalidFormat(c *check.C) {
  4854. testRequires(c, DaemonIsLinux)
  4855. dockerfile := `
  4856. FROM busybox
  4857. RUN ping -c 1 foo`
  4858. testCases := []struct {
  4859. testName string
  4860. dockerfile string
  4861. buildFlag string
  4862. }{
  4863. {"extra_host_missing_ip", dockerfile, "--add-host=foo"},
  4864. {"extra_host_missing_ip_with_delimiter", dockerfile, "--add-host=foo:"},
  4865. {"extra_host_missing_hostname", dockerfile, "--add-host=:127.0.0.1"},
  4866. {"extra_host_invalid_ipv4", dockerfile, "--add-host=foo:101.10.2"},
  4867. {"extra_host_invalid_ipv6", dockerfile, "--add-host=foo:2001::1::3F"},
  4868. }
  4869. for _, tc := range testCases {
  4870. result := buildImage(tc.testName, cli.WithFlags(tc.buildFlag), build.WithDockerfile(tc.dockerfile))
  4871. result.Assert(c, icmd.Expected{
  4872. ExitCode: 125,
  4873. })
  4874. }
  4875. }
  4876. func (s *DockerSuite) TestBuildContChar(c *check.C) {
  4877. name := "testbuildcontchar"
  4878. buildImage(name, build.WithDockerfile(`FROM busybox\`)).Assert(c, icmd.Expected{
  4879. Out: "Step 1/1 : FROM busybox",
  4880. })
  4881. result := buildImage(name, build.WithDockerfile(`FROM busybox
  4882. RUN echo hi \`))
  4883. result.Assert(c, icmd.Success)
  4884. c.Assert(result.Combined(), checker.Contains, "Step 1/2 : FROM busybox")
  4885. c.Assert(result.Combined(), checker.Contains, "Step 2/2 : RUN echo hi\n")
  4886. result = buildImage(name, build.WithDockerfile(`FROM busybox
  4887. RUN echo hi \\`))
  4888. result.Assert(c, icmd.Success)
  4889. c.Assert(result.Combined(), checker.Contains, "Step 1/2 : FROM busybox")
  4890. c.Assert(result.Combined(), checker.Contains, "Step 2/2 : RUN echo hi \\\n")
  4891. result = buildImage(name, build.WithDockerfile(`FROM busybox
  4892. RUN echo hi \\\`))
  4893. result.Assert(c, icmd.Success)
  4894. c.Assert(result.Combined(), checker.Contains, "Step 1/2 : FROM busybox")
  4895. c.Assert(result.Combined(), checker.Contains, "Step 2/2 : RUN echo hi \\\\\n")
  4896. }
  4897. func (s *DockerSuite) TestBuildMultiStageCopyFromSyntax(c *check.C) {
  4898. dockerfile := `
  4899. FROM busybox AS first
  4900. COPY foo bar
  4901. FROM busybox
  4902. %s
  4903. COPY baz baz
  4904. RUN echo mno > baz/cc
  4905. FROM busybox
  4906. COPY bar /
  4907. COPY --from=1 baz sub/
  4908. COPY --from=0 bar baz
  4909. COPY --from=first bar bay`
  4910. ctx := fakecontext.New(c, "",
  4911. fakecontext.WithDockerfile(fmt.Sprintf(dockerfile, "")),
  4912. fakecontext.WithFiles(map[string]string{
  4913. "foo": "abc",
  4914. "bar": "def",
  4915. "baz/aa": "ghi",
  4916. "baz/bb": "jkl",
  4917. }))
  4918. defer ctx.Close()
  4919. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  4920. cli.DockerCmd(c, "run", "build1", "cat", "bar").Assert(c, icmd.Expected{Out: "def"})
  4921. cli.DockerCmd(c, "run", "build1", "cat", "sub/aa").Assert(c, icmd.Expected{Out: "ghi"})
  4922. cli.DockerCmd(c, "run", "build1", "cat", "sub/cc").Assert(c, icmd.Expected{Out: "mno"})
  4923. cli.DockerCmd(c, "run", "build1", "cat", "baz").Assert(c, icmd.Expected{Out: "abc"})
  4924. cli.DockerCmd(c, "run", "build1", "cat", "bay").Assert(c, icmd.Expected{Out: "abc"})
  4925. result := cli.BuildCmd(c, "build2", build.WithExternalBuildContext(ctx))
  4926. // all commands should be cached
  4927. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 7)
  4928. c.Assert(getIDByName(c, "build1"), checker.Equals, getIDByName(c, "build2"))
  4929. err := ioutil.WriteFile(filepath.Join(ctx.Dir, "Dockerfile"), []byte(fmt.Sprintf(dockerfile, "COPY baz/aa foo")), 0644)
  4930. c.Assert(err, checker.IsNil)
  4931. // changing file in parent block should not affect last block
  4932. result = cli.BuildCmd(c, "build3", build.WithExternalBuildContext(ctx))
  4933. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 5)
  4934. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "foo"), []byte("pqr"), 0644)
  4935. c.Assert(err, checker.IsNil)
  4936. // changing file in parent block should affect both first and last block
  4937. result = cli.BuildCmd(c, "build4", build.WithExternalBuildContext(ctx))
  4938. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 5)
  4939. cli.DockerCmd(c, "run", "build4", "cat", "bay").Assert(c, icmd.Expected{Out: "pqr"})
  4940. cli.DockerCmd(c, "run", "build4", "cat", "baz").Assert(c, icmd.Expected{Out: "pqr"})
  4941. }
  4942. func (s *DockerSuite) TestBuildMultiStageCopyFromErrors(c *check.C) {
  4943. testCases := []struct {
  4944. dockerfile string
  4945. expectedError string
  4946. }{
  4947. {
  4948. dockerfile: `
  4949. FROM busybox
  4950. COPY --from=foo foo bar`,
  4951. expectedError: "invalid from flag value foo",
  4952. },
  4953. {
  4954. dockerfile: `
  4955. FROM busybox
  4956. COPY --from=0 foo bar`,
  4957. expectedError: "invalid from flag value 0: refers to current build stage",
  4958. },
  4959. {
  4960. dockerfile: `
  4961. FROM busybox AS foo
  4962. COPY --from=bar foo bar`,
  4963. expectedError: "invalid from flag value bar",
  4964. },
  4965. {
  4966. dockerfile: `
  4967. FROM busybox AS 1
  4968. COPY --from=1 foo bar`,
  4969. expectedError: "invalid name for build stage",
  4970. },
  4971. }
  4972. for _, tc := range testCases {
  4973. ctx := fakecontext.New(c, "",
  4974. fakecontext.WithDockerfile(tc.dockerfile),
  4975. fakecontext.WithFiles(map[string]string{
  4976. "foo": "abc",
  4977. }))
  4978. cli.Docker(cli.Build("build1"), build.WithExternalBuildContext(ctx)).Assert(c, icmd.Expected{
  4979. ExitCode: 1,
  4980. Err: tc.expectedError,
  4981. })
  4982. ctx.Close()
  4983. }
  4984. }
  4985. func (s *DockerSuite) TestBuildMultiStageMultipleBuilds(c *check.C) {
  4986. dockerfile := `
  4987. FROM busybox
  4988. COPY foo bar`
  4989. ctx := fakecontext.New(c, "",
  4990. fakecontext.WithDockerfile(dockerfile),
  4991. fakecontext.WithFiles(map[string]string{
  4992. "foo": "abc",
  4993. }))
  4994. defer ctx.Close()
  4995. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  4996. dockerfile = `
  4997. FROM build1:latest AS foo
  4998. FROM busybox
  4999. COPY --from=foo bar /
  5000. COPY foo /`
  5001. ctx = fakecontext.New(c, "",
  5002. fakecontext.WithDockerfile(dockerfile),
  5003. fakecontext.WithFiles(map[string]string{
  5004. "foo": "def",
  5005. }))
  5006. defer ctx.Close()
  5007. cli.BuildCmd(c, "build2", build.WithExternalBuildContext(ctx))
  5008. out := cli.DockerCmd(c, "run", "build2", "cat", "bar").Combined()
  5009. c.Assert(strings.TrimSpace(out), check.Equals, "abc")
  5010. out = cli.DockerCmd(c, "run", "build2", "cat", "foo").Combined()
  5011. c.Assert(strings.TrimSpace(out), check.Equals, "def")
  5012. }
  5013. func (s *DockerSuite) TestBuildMultiStageImplicitFrom(c *check.C) {
  5014. dockerfile := `
  5015. FROM busybox
  5016. COPY --from=busybox /etc/passwd /mypasswd
  5017. RUN cmp /etc/passwd /mypasswd`
  5018. if DaemonIsWindows() {
  5019. dockerfile = `
  5020. FROM busybox
  5021. COPY --from=busybox License.txt foo`
  5022. }
  5023. ctx := fakecontext.New(c, "",
  5024. fakecontext.WithDockerfile(dockerfile),
  5025. )
  5026. defer ctx.Close()
  5027. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5028. if DaemonIsWindows() {
  5029. out := cli.DockerCmd(c, "run", "build1", "cat", "License.txt").Combined()
  5030. c.Assert(len(out), checker.GreaterThan, 10)
  5031. out2 := cli.DockerCmd(c, "run", "build1", "cat", "foo").Combined()
  5032. c.Assert(out, check.Equals, out2)
  5033. }
  5034. }
  5035. func (s *DockerRegistrySuite) TestBuildMultiStageImplicitPull(c *check.C) {
  5036. repoName := fmt.Sprintf("%v/dockercli/testf", privateRegistryURL)
  5037. dockerfile := `
  5038. FROM busybox
  5039. COPY foo bar`
  5040. ctx := fakecontext.New(c, "",
  5041. fakecontext.WithDockerfile(dockerfile),
  5042. fakecontext.WithFiles(map[string]string{
  5043. "foo": "abc",
  5044. }))
  5045. defer ctx.Close()
  5046. cli.BuildCmd(c, repoName, build.WithExternalBuildContext(ctx))
  5047. cli.DockerCmd(c, "push", repoName)
  5048. cli.DockerCmd(c, "rmi", repoName)
  5049. dockerfile = `
  5050. FROM busybox
  5051. COPY --from=%s bar baz`
  5052. ctx = fakecontext.New(c, "", fakecontext.WithDockerfile(fmt.Sprintf(dockerfile, repoName)))
  5053. defer ctx.Close()
  5054. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5055. cli.Docker(cli.Args("run", "build1", "cat", "baz")).Assert(c, icmd.Expected{Out: "abc"})
  5056. }
  5057. func (s *DockerSuite) TestBuildMultiStageNameVariants(c *check.C) {
  5058. dockerfile := `
  5059. FROM busybox as foo
  5060. COPY foo /
  5061. FROM foo as foo1
  5062. RUN echo 1 >> foo
  5063. FROM foo as foO2
  5064. RUN echo 2 >> foo
  5065. FROM foo
  5066. COPY --from=foo1 foo f1
  5067. COPY --from=FOo2 foo f2
  5068. ` // foo2 case also tests that names are case insensitive
  5069. ctx := fakecontext.New(c, "",
  5070. fakecontext.WithDockerfile(dockerfile),
  5071. fakecontext.WithFiles(map[string]string{
  5072. "foo": "bar",
  5073. }))
  5074. defer ctx.Close()
  5075. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5076. cli.Docker(cli.Args("run", "build1", "cat", "foo")).Assert(c, icmd.Expected{Out: "bar"})
  5077. cli.Docker(cli.Args("run", "build1", "cat", "f1")).Assert(c, icmd.Expected{Out: "bar1"})
  5078. cli.Docker(cli.Args("run", "build1", "cat", "f2")).Assert(c, icmd.Expected{Out: "bar2"})
  5079. }
  5080. func (s *DockerSuite) TestBuildMultiStageMultipleBuildsWindows(c *check.C) {
  5081. testRequires(c, DaemonIsWindows)
  5082. dockerfile := `
  5083. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5084. COPY foo c:\\bar`
  5085. ctx := fakecontext.New(c, "",
  5086. fakecontext.WithDockerfile(dockerfile),
  5087. fakecontext.WithFiles(map[string]string{
  5088. "foo": "abc",
  5089. }))
  5090. defer ctx.Close()
  5091. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5092. dockerfile = `
  5093. FROM build1:latest
  5094. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5095. COPY --from=0 c:\\bar /
  5096. COPY foo /`
  5097. ctx = fakecontext.New(c, "",
  5098. fakecontext.WithDockerfile(dockerfile),
  5099. fakecontext.WithFiles(map[string]string{
  5100. "foo": "def",
  5101. }))
  5102. defer ctx.Close()
  5103. cli.BuildCmd(c, "build2", build.WithExternalBuildContext(ctx))
  5104. out := cli.DockerCmd(c, "run", "build2", "cmd.exe", "/s", "/c", "type", "c:\\bar").Combined()
  5105. c.Assert(strings.TrimSpace(out), check.Equals, "abc")
  5106. out = cli.DockerCmd(c, "run", "build2", "cmd.exe", "/s", "/c", "type", "c:\\foo").Combined()
  5107. c.Assert(strings.TrimSpace(out), check.Equals, "def")
  5108. }
  5109. func (s *DockerSuite) TestBuildCopyFromForbidWindowsSystemPaths(c *check.C) {
  5110. testRequires(c, DaemonIsWindows)
  5111. dockerfile := `
  5112. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5113. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5114. COPY --from=0 %s c:\\oscopy
  5115. `
  5116. exp := icmd.Expected{
  5117. ExitCode: 1,
  5118. Err: "copy from c:\\ or c:\\windows is not allowed on windows",
  5119. }
  5120. buildImage("testforbidsystempaths1", build.WithDockerfile(fmt.Sprintf(dockerfile, "c:\\\\"))).Assert(c, exp)
  5121. buildImage("testforbidsystempaths2", build.WithDockerfile(fmt.Sprintf(dockerfile, "C:\\\\"))).Assert(c, exp)
  5122. buildImage("testforbidsystempaths3", build.WithDockerfile(fmt.Sprintf(dockerfile, "c:\\\\windows"))).Assert(c, exp)
  5123. buildImage("testforbidsystempaths4", build.WithDockerfile(fmt.Sprintf(dockerfile, "c:\\\\wInDows"))).Assert(c, exp)
  5124. }
  5125. func (s *DockerSuite) TestBuildCopyFromForbidWindowsRelativePaths(c *check.C) {
  5126. testRequires(c, DaemonIsWindows)
  5127. dockerfile := `
  5128. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5129. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5130. COPY --from=0 %s c:\\oscopy
  5131. `
  5132. exp := icmd.Expected{
  5133. ExitCode: 1,
  5134. Err: "copy from c:\\ or c:\\windows is not allowed on windows",
  5135. }
  5136. buildImage("testforbidsystempaths1", build.WithDockerfile(fmt.Sprintf(dockerfile, "c:"))).Assert(c, exp)
  5137. buildImage("testforbidsystempaths2", build.WithDockerfile(fmt.Sprintf(dockerfile, "."))).Assert(c, exp)
  5138. buildImage("testforbidsystempaths3", build.WithDockerfile(fmt.Sprintf(dockerfile, "..\\\\"))).Assert(c, exp)
  5139. buildImage("testforbidsystempaths4", build.WithDockerfile(fmt.Sprintf(dockerfile, ".\\\\windows"))).Assert(c, exp)
  5140. buildImage("testforbidsystempaths5", build.WithDockerfile(fmt.Sprintf(dockerfile, "\\\\windows"))).Assert(c, exp)
  5141. }
  5142. func (s *DockerSuite) TestBuildCopyFromWindowsIsCaseInsensitive(c *check.C) {
  5143. testRequires(c, DaemonIsWindows)
  5144. dockerfile := `
  5145. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5146. COPY foo /
  5147. FROM ` + testEnv.PlatformDefaults.BaseImage + `
  5148. COPY --from=0 c:\\fOo c:\\copied
  5149. RUN type c:\\copied
  5150. `
  5151. cli.Docker(cli.Build("copyfrom-windows-insensitive"), build.WithBuildContext(c,
  5152. build.WithFile("Dockerfile", dockerfile),
  5153. build.WithFile("foo", "hello world"),
  5154. )).Assert(c, icmd.Expected{
  5155. ExitCode: 0,
  5156. Out: "hello world",
  5157. })
  5158. }
  5159. // #33176
  5160. func (s *DockerSuite) TestBuildMulitStageResetScratch(c *check.C) {
  5161. testRequires(c, DaemonIsLinux)
  5162. dockerfile := `
  5163. FROM busybox
  5164. WORKDIR /foo/bar
  5165. FROM scratch
  5166. ENV FOO=bar
  5167. `
  5168. ctx := fakecontext.New(c, "",
  5169. fakecontext.WithDockerfile(dockerfile),
  5170. )
  5171. defer ctx.Close()
  5172. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx))
  5173. res := cli.InspectCmd(c, "build1", cli.Format(".Config.WorkingDir")).Combined()
  5174. c.Assert(strings.TrimSpace(res), checker.Equals, "")
  5175. }
  5176. func (s *DockerSuite) TestBuildIntermediateTarget(c *check.C) {
  5177. //todo: need to be removed after 18.06 release
  5178. if strings.Contains(testEnv.DaemonInfo.ServerVersion, "18.05.0") {
  5179. c.Skip(fmt.Sprintf("Bug fixed in 18.06 or higher.Skipping it for %s", testEnv.DaemonInfo.ServerVersion))
  5180. }
  5181. dockerfile := `
  5182. FROM busybox AS build-env
  5183. CMD ["/dev"]
  5184. FROM busybox
  5185. CMD ["/dist"]
  5186. `
  5187. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(dockerfile))
  5188. defer ctx.Close()
  5189. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx),
  5190. cli.WithFlags("--target", "build-env"))
  5191. res := cli.InspectCmd(c, "build1", cli.Format("json .Config.Cmd")).Combined()
  5192. c.Assert(strings.TrimSpace(res), checker.Equals, `["/dev"]`)
  5193. // Stage name is case-insensitive by design
  5194. cli.BuildCmd(c, "build1", build.WithExternalBuildContext(ctx),
  5195. cli.WithFlags("--target", "BUIld-EnV"))
  5196. res = cli.InspectCmd(c, "build1", cli.Format("json .Config.Cmd")).Combined()
  5197. c.Assert(strings.TrimSpace(res), checker.Equals, `["/dev"]`)
  5198. result := cli.Docker(cli.Build("build1"), build.WithExternalBuildContext(ctx),
  5199. cli.WithFlags("--target", "nosuchtarget"))
  5200. result.Assert(c, icmd.Expected{
  5201. ExitCode: 1,
  5202. Err: "failed to reach build target",
  5203. })
  5204. }
  5205. // TestBuildOpaqueDirectory tests that a build succeeds which
  5206. // creates opaque directories.
  5207. // See https://github.com/docker/docker/issues/25244
  5208. func (s *DockerSuite) TestBuildOpaqueDirectory(c *check.C) {
  5209. testRequires(c, DaemonIsLinux)
  5210. dockerFile := `
  5211. FROM busybox
  5212. RUN mkdir /dir1 && touch /dir1/f1
  5213. RUN rm -rf /dir1 && mkdir /dir1 && touch /dir1/f2
  5214. RUN touch /dir1/f3
  5215. RUN [ -f /dir1/f2 ]
  5216. `
  5217. // Test that build succeeds, last command fails if opaque directory
  5218. // was not handled correctly
  5219. buildImageSuccessfully(c, "testopaquedirectory", build.WithDockerfile(dockerFile))
  5220. }
  5221. // Windows test for USER in dockerfile
  5222. func (s *DockerSuite) TestBuildWindowsUser(c *check.C) {
  5223. testRequires(c, DaemonIsWindows)
  5224. name := "testbuildwindowsuser"
  5225. buildImage(name, build.WithDockerfile(`FROM `+testEnv.PlatformDefaults.BaseImage+`
  5226. RUN net user user /add
  5227. USER user
  5228. RUN set username
  5229. `)).Assert(c, icmd.Expected{
  5230. Out: "USERNAME=user",
  5231. })
  5232. }
  5233. // Verifies if COPY file . when WORKDIR is set to a non-existing directory,
  5234. // the directory is created and the file is copied into the directory,
  5235. // as opposed to the file being copied as a file with the name of the
  5236. // directory. Fix for 27545 (found on Windows, but regression good for Linux too).
  5237. // Note 27545 was reverted in 28505, but a new fix was added subsequently in 28514.
  5238. func (s *DockerSuite) TestBuildCopyFileDotWithWorkdir(c *check.C) {
  5239. name := "testbuildcopyfiledotwithworkdir"
  5240. buildImageSuccessfully(c, name, build.WithBuildContext(c,
  5241. build.WithFile("Dockerfile", `FROM busybox
  5242. WORKDIR /foo
  5243. COPY file .
  5244. RUN ["cat", "/foo/file"]
  5245. `),
  5246. build.WithFile("file", "content"),
  5247. ))
  5248. }
  5249. // Case-insensitive environment variables on Windows
  5250. func (s *DockerSuite) TestBuildWindowsEnvCaseInsensitive(c *check.C) {
  5251. testRequires(c, DaemonIsWindows)
  5252. name := "testbuildwindowsenvcaseinsensitive"
  5253. buildImageSuccessfully(c, name, build.WithDockerfile(`
  5254. FROM `+testEnv.PlatformDefaults.BaseImage+`
  5255. ENV FOO=bar foo=baz
  5256. `))
  5257. res := inspectFieldJSON(c, name, "Config.Env")
  5258. if res != `["foo=baz"]` { // Should not have FOO=bar in it - takes the last one processed. And only one entry as deduped.
  5259. c.Fatalf("Case insensitive environment variables on Windows failed. Got %s", res)
  5260. }
  5261. }
  5262. // Test case for 29667
  5263. func (s *DockerSuite) TestBuildWorkdirImageCmd(c *check.C) {
  5264. image := "testworkdirimagecmd"
  5265. buildImageSuccessfully(c, image, build.WithDockerfile(`
  5266. FROM busybox
  5267. WORKDIR /foo/bar
  5268. `))
  5269. out, _ := dockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", image)
  5270. // The Windows busybox image has a blank `cmd`
  5271. lookingFor := `["sh"]`
  5272. if testEnv.OSType == "windows" {
  5273. lookingFor = "null"
  5274. }
  5275. c.Assert(strings.TrimSpace(out), checker.Equals, lookingFor)
  5276. image = "testworkdirlabelimagecmd"
  5277. buildImageSuccessfully(c, image, build.WithDockerfile(`
  5278. FROM busybox
  5279. WORKDIR /foo/bar
  5280. LABEL a=b
  5281. `))
  5282. out, _ = dockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", image)
  5283. c.Assert(strings.TrimSpace(out), checker.Equals, lookingFor)
  5284. }
  5285. // Test case for 28902/28909
  5286. func (s *DockerSuite) TestBuildWorkdirCmd(c *check.C) {
  5287. testRequires(c, DaemonIsLinux)
  5288. name := "testbuildworkdircmd"
  5289. dockerFile := `
  5290. FROM busybox
  5291. WORKDIR /
  5292. `
  5293. buildImageSuccessfully(c, name, build.WithDockerfile(dockerFile))
  5294. result := buildImage(name, build.WithDockerfile(dockerFile))
  5295. result.Assert(c, icmd.Success)
  5296. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 1)
  5297. }
  5298. // FIXME(vdemeester) should be a unit test
  5299. func (s *DockerSuite) TestBuildLineErrorOnBuild(c *check.C) {
  5300. name := "test_build_line_error_onbuild"
  5301. buildImage(name, build.WithDockerfile(`FROM busybox
  5302. ONBUILD
  5303. `)).Assert(c, icmd.Expected{
  5304. ExitCode: 1,
  5305. Err: "Dockerfile parse error line 2: ONBUILD requires at least one argument",
  5306. })
  5307. }
  5308. // FIXME(vdemeester) should be a unit test
  5309. func (s *DockerSuite) TestBuildLineErrorUnknownInstruction(c *check.C) {
  5310. name := "test_build_line_error_unknown_instruction"
  5311. cli.Docker(cli.Build(name), build.WithDockerfile(`FROM busybox
  5312. RUN echo hello world
  5313. NOINSTRUCTION echo ba
  5314. RUN echo hello
  5315. ERROR
  5316. `)).Assert(c, icmd.Expected{
  5317. ExitCode: 1,
  5318. Err: "Dockerfile parse error line 3: unknown instruction: NOINSTRUCTION",
  5319. })
  5320. }
  5321. // FIXME(vdemeester) should be a unit test
  5322. func (s *DockerSuite) TestBuildLineErrorWithEmptyLines(c *check.C) {
  5323. name := "test_build_line_error_with_empty_lines"
  5324. cli.Docker(cli.Build(name), build.WithDockerfile(`
  5325. FROM busybox
  5326. RUN echo hello world
  5327. NOINSTRUCTION echo ba
  5328. CMD ["/bin/init"]
  5329. `)).Assert(c, icmd.Expected{
  5330. ExitCode: 1,
  5331. Err: "Dockerfile parse error line 6: unknown instruction: NOINSTRUCTION",
  5332. })
  5333. }
  5334. // FIXME(vdemeester) should be a unit test
  5335. func (s *DockerSuite) TestBuildLineErrorWithComments(c *check.C) {
  5336. name := "test_build_line_error_with_comments"
  5337. cli.Docker(cli.Build(name), build.WithDockerfile(`FROM busybox
  5338. # This will print hello world
  5339. # and then ba
  5340. RUN echo hello world
  5341. NOINSTRUCTION echo ba
  5342. `)).Assert(c, icmd.Expected{
  5343. ExitCode: 1,
  5344. Err: "Dockerfile parse error line 5: unknown instruction: NOINSTRUCTION",
  5345. })
  5346. }
  5347. // #31957
  5348. func (s *DockerSuite) TestBuildSetCommandWithDefinedShell(c *check.C) {
  5349. buildImageSuccessfully(c, "build1", build.WithDockerfile(`
  5350. FROM busybox
  5351. SHELL ["/bin/sh", "-c"]
  5352. `))
  5353. buildImageSuccessfully(c, "build2", build.WithDockerfile(`
  5354. FROM build1
  5355. CMD echo foo
  5356. `))
  5357. out, _ := dockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", "build2")
  5358. c.Assert(strings.TrimSpace(out), checker.Equals, `["/bin/sh","-c","echo foo"]`)
  5359. }
  5360. // FIXME(vdemeester) should migrate to docker/cli tests
  5361. func (s *DockerSuite) TestBuildIidFile(c *check.C) {
  5362. tmpDir, err := ioutil.TempDir("", "TestBuildIidFile")
  5363. if err != nil {
  5364. c.Fatal(err)
  5365. }
  5366. defer os.RemoveAll(tmpDir)
  5367. tmpIidFile := filepath.Join(tmpDir, "iid")
  5368. name := "testbuildiidfile"
  5369. // Use a Dockerfile with multiple stages to ensure we get the last one
  5370. cli.BuildCmd(c, name,
  5371. build.WithDockerfile(`FROM `+minimalBaseImage()+` AS stage1
  5372. ENV FOO FOO
  5373. FROM `+minimalBaseImage()+`
  5374. ENV BAR BAZ`),
  5375. cli.WithFlags("--iidfile", tmpIidFile))
  5376. id, err := ioutil.ReadFile(tmpIidFile)
  5377. c.Assert(err, check.IsNil)
  5378. d, err := digest.Parse(string(id))
  5379. c.Assert(err, check.IsNil)
  5380. c.Assert(d.String(), checker.Equals, getIDByName(c, name))
  5381. }
  5382. // FIXME(vdemeester) should migrate to docker/cli tests
  5383. func (s *DockerSuite) TestBuildIidFileCleanupOnFail(c *check.C) {
  5384. tmpDir, err := ioutil.TempDir("", "TestBuildIidFileCleanupOnFail")
  5385. if err != nil {
  5386. c.Fatal(err)
  5387. }
  5388. defer os.RemoveAll(tmpDir)
  5389. tmpIidFile := filepath.Join(tmpDir, "iid")
  5390. err = ioutil.WriteFile(tmpIidFile, []byte("Dummy"), 0666)
  5391. c.Assert(err, check.IsNil)
  5392. cli.Docker(cli.Build("testbuildiidfilecleanuponfail"),
  5393. build.WithDockerfile(`FROM `+minimalBaseImage()+`
  5394. RUN /non/existing/command`),
  5395. cli.WithFlags("--iidfile", tmpIidFile)).Assert(c, icmd.Expected{
  5396. ExitCode: 1,
  5397. })
  5398. _, err = os.Stat(tmpIidFile)
  5399. c.Assert(err, check.NotNil)
  5400. c.Assert(os.IsNotExist(err), check.Equals, true)
  5401. }