docker_cli_build_test.go 163 KB

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