docker_cli_build_test.go 160 KB

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