docker_cli_build_test.go 205 KB

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