docker_cli_build_test.go 171 KB

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