docker_cli_build_test.go 207 KB

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