docker_cli_build_test.go 203 KB

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