docker_cli_build_test.go 184 KB

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