docker_cli_build_test.go 197 KB

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