docker_cli_build_test.go 177 KB

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