docker_cli_build_test.go 181 KB

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