docker_cli_build_test.go 172 KB

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