docker_cli_build_test.go 171 KB

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