docker_cli_build_test.go 143 KB

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