docker_cli_build_test.go 161 KB

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