docker_cli_build_test.go 203 KB

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