docker_cli_build_test.go 206 KB

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