docker_cli_build_test.go 175 KB

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