docker_cli_build_test.go 172 KB

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