docker_cli_build_test.go 200 KB

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