docker_cli_build_test.go 192 KB

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