docker_cli_build_test.go 198 KB

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