docker_cli_build_test.go 143 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600
  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. logDone("build - ADD from context with accessible links must work")
  1635. logDone("build - ADD from context with ignored inaccessible files must work")
  1636. }
  1637. func TestBuildForceRm(t *testing.T) {
  1638. containerCountBefore, err := getContainerCount()
  1639. if err != nil {
  1640. t.Fatalf("failed to get the container count: %s", err)
  1641. }
  1642. name := "testbuildforcerm"
  1643. defer deleteImages(name)
  1644. ctx, err := fakeContext("FROM scratch\nRUN true\nRUN thiswillfail", nil)
  1645. if err != nil {
  1646. t.Fatal(err)
  1647. }
  1648. defer ctx.Close()
  1649. buildCmd := exec.Command(dockerBinary, "build", "-t", name, "--force-rm", ".")
  1650. buildCmd.Dir = ctx.Dir
  1651. if out, _, err := runCommandWithOutput(buildCmd); err == nil {
  1652. t.Fatalf("failed to build the image: %s, %v", out, err)
  1653. }
  1654. containerCountAfter, err := getContainerCount()
  1655. if err != nil {
  1656. t.Fatalf("failed to get the container count: %s", err)
  1657. }
  1658. if containerCountBefore != containerCountAfter {
  1659. t.Fatalf("--force-rm shouldn't have left containers behind")
  1660. }
  1661. logDone("build - ensure --force-rm doesn't leave containers behind")
  1662. }
  1663. // Test that an infinite sleep during a build is killed if the client disconnects.
  1664. // This test is fairly hairy because there are lots of ways to race.
  1665. // Strategy:
  1666. // * Monitor the output of docker events starting from before
  1667. // * Run a 1-year-long sleep from a docker build.
  1668. // * When docker events sees container start, close the "docker build" command
  1669. // * Wait for docker events to emit a dying event.
  1670. func TestBuildCancelationKillsSleep(t *testing.T) {
  1671. // TODO(jfrazelle): Make this work on Windows.
  1672. testRequires(t, SameHostDaemon)
  1673. name := "testbuildcancelation"
  1674. defer deleteImages(name)
  1675. defer deleteAllContainers()
  1676. // (Note: one year, will never finish)
  1677. ctx, err := fakeContext("FROM busybox\nRUN sleep 31536000", nil)
  1678. if err != nil {
  1679. t.Fatal(err)
  1680. }
  1681. defer ctx.Close()
  1682. var wg sync.WaitGroup
  1683. defer wg.Wait()
  1684. finish := make(chan struct{})
  1685. defer close(finish)
  1686. eventStart := make(chan struct{})
  1687. eventDie := make(chan struct{})
  1688. // Start one second ago, to avoid rounding problems
  1689. startEpoch := time.Now().Add(-1 * time.Second)
  1690. // Goroutine responsible for watching start/die events from `docker events`
  1691. wg.Add(1)
  1692. go func() {
  1693. defer wg.Done()
  1694. // Watch for events since epoch.
  1695. eventsCmd := exec.Command(dockerBinary, "events",
  1696. "-since", fmt.Sprint(startEpoch.Unix()))
  1697. stdout, err := eventsCmd.StdoutPipe()
  1698. err = eventsCmd.Start()
  1699. if err != nil {
  1700. t.Fatalf("failed to start 'docker events': %s", err)
  1701. }
  1702. go func() {
  1703. <-finish
  1704. eventsCmd.Process.Kill()
  1705. }()
  1706. var started, died bool
  1707. matchStart := regexp.MustCompile(" \\(from busybox\\:latest\\) start$")
  1708. matchDie := regexp.MustCompile(" \\(from busybox\\:latest\\) die$")
  1709. //
  1710. // Read lines of `docker events` looking for container start and stop.
  1711. //
  1712. scanner := bufio.NewScanner(stdout)
  1713. for scanner.Scan() {
  1714. if ok := matchStart.MatchString(scanner.Text()); ok {
  1715. if started {
  1716. t.Fatal("assertion fail: more than one container started")
  1717. }
  1718. close(eventStart)
  1719. started = true
  1720. }
  1721. if ok := matchDie.MatchString(scanner.Text()); ok {
  1722. if died {
  1723. t.Fatal("assertion fail: more than one container died")
  1724. }
  1725. close(eventDie)
  1726. died = true
  1727. }
  1728. }
  1729. err = eventsCmd.Wait()
  1730. if err != nil && !IsKilled(err) {
  1731. t.Fatalf("docker events had bad exit status: %s", err)
  1732. }
  1733. }()
  1734. buildCmd := exec.Command(dockerBinary, "build", "-t", name, ".")
  1735. buildCmd.Dir = ctx.Dir
  1736. buildCmd.Stdout = os.Stdout
  1737. err = buildCmd.Start()
  1738. if err != nil {
  1739. t.Fatalf("failed to run build: %s", err)
  1740. }
  1741. select {
  1742. case <-time.After(30 * time.Second):
  1743. t.Fatal("failed to observe build container start in timely fashion")
  1744. case <-eventStart:
  1745. // Proceeds from here when we see the container fly past in the
  1746. // output of "docker events".
  1747. // Now we know the container is running.
  1748. }
  1749. // Send a kill to the `docker build` command.
  1750. // Causes the underlying build to be cancelled due to socket close.
  1751. err = buildCmd.Process.Kill()
  1752. if err != nil {
  1753. t.Fatalf("error killing build command: %s", err)
  1754. }
  1755. // Get the exit status of `docker build`, check it exited because killed.
  1756. err = buildCmd.Wait()
  1757. if err != nil && !IsKilled(err) {
  1758. t.Fatalf("wait failed during build run: %T %s", err, err)
  1759. }
  1760. select {
  1761. case <-time.After(30 * time.Second):
  1762. // If we don't get here in a timely fashion, it wasn't killed.
  1763. t.Fatal("container cancel did not succeed")
  1764. case <-eventDie:
  1765. // We saw the container shut down in the `docker events` stream,
  1766. // as expected.
  1767. }
  1768. logDone("build - ensure canceled job finishes immediately")
  1769. }
  1770. func TestBuildRm(t *testing.T) {
  1771. name := "testbuildrm"
  1772. defer deleteImages(name)
  1773. ctx, err := fakeContext("FROM scratch\nADD foo /\nADD foo /", map[string]string{"foo": "bar"})
  1774. if err != nil {
  1775. t.Fatal(err)
  1776. }
  1777. defer ctx.Close()
  1778. {
  1779. containerCountBefore, err := getContainerCount()
  1780. if err != nil {
  1781. t.Fatalf("failed to get the container count: %s", err)
  1782. }
  1783. out, _, err := dockerCmdInDir(t, ctx.Dir, "build", "--rm", "-t", name, ".")
  1784. if err != nil {
  1785. t.Fatal("failed to build the image", out)
  1786. }
  1787. containerCountAfter, err := getContainerCount()
  1788. if err != nil {
  1789. t.Fatalf("failed to get the container count: %s", err)
  1790. }
  1791. if containerCountBefore != containerCountAfter {
  1792. t.Fatalf("-rm shouldn't have left containers behind")
  1793. }
  1794. deleteImages(name)
  1795. }
  1796. {
  1797. containerCountBefore, err := getContainerCount()
  1798. if err != nil {
  1799. t.Fatalf("failed to get the container count: %s", err)
  1800. }
  1801. out, _, err := dockerCmdInDir(t, ctx.Dir, "build", "-t", name, ".")
  1802. if err != nil {
  1803. t.Fatal("failed to build the image", out)
  1804. }
  1805. containerCountAfter, err := getContainerCount()
  1806. if err != nil {
  1807. t.Fatalf("failed to get the container count: %s", err)
  1808. }
  1809. if containerCountBefore != containerCountAfter {
  1810. t.Fatalf("--rm shouldn't have left containers behind")
  1811. }
  1812. deleteImages(name)
  1813. }
  1814. {
  1815. containerCountBefore, err := getContainerCount()
  1816. if err != nil {
  1817. t.Fatalf("failed to get the container count: %s", err)
  1818. }
  1819. out, _, err := dockerCmdInDir(t, ctx.Dir, "build", "--rm=false", "-t", name, ".")
  1820. if err != nil {
  1821. t.Fatal("failed to build the image", out)
  1822. }
  1823. containerCountAfter, err := getContainerCount()
  1824. if err != nil {
  1825. t.Fatalf("failed to get the container count: %s", err)
  1826. }
  1827. if containerCountBefore == containerCountAfter {
  1828. t.Fatalf("--rm=false should have left containers behind")
  1829. }
  1830. deleteAllContainers()
  1831. deleteImages(name)
  1832. }
  1833. logDone("build - ensure --rm doesn't leave containers behind and that --rm=true is the default")
  1834. logDone("build - ensure --rm=false overrides the default")
  1835. }
  1836. func TestBuildWithVolumes(t *testing.T) {
  1837. var (
  1838. result map[string]map[string]struct{}
  1839. name = "testbuildvolumes"
  1840. emptyMap = make(map[string]struct{})
  1841. expected = map[string]map[string]struct{}{
  1842. "/test1": emptyMap,
  1843. "/test2": emptyMap,
  1844. "/test3": emptyMap,
  1845. "/test4": emptyMap,
  1846. "/test5": emptyMap,
  1847. "/test6": emptyMap,
  1848. "[/test7": emptyMap,
  1849. "/test8]": emptyMap,
  1850. }
  1851. )
  1852. defer deleteImages(name)
  1853. _, err := buildImage(name,
  1854. `FROM scratch
  1855. VOLUME /test1
  1856. VOLUME /test2
  1857. VOLUME /test3 /test4
  1858. VOLUME ["/test5", "/test6"]
  1859. VOLUME [/test7 /test8]
  1860. `,
  1861. true)
  1862. if err != nil {
  1863. t.Fatal(err)
  1864. }
  1865. res, err := inspectFieldJSON(name, "Config.Volumes")
  1866. if err != nil {
  1867. t.Fatal(err)
  1868. }
  1869. err = unmarshalJSON([]byte(res), &result)
  1870. if err != nil {
  1871. t.Fatal(err)
  1872. }
  1873. equal := reflect.DeepEqual(&result, &expected)
  1874. if !equal {
  1875. t.Fatalf("Volumes %s, expected %s", result, expected)
  1876. }
  1877. logDone("build - with volumes")
  1878. }
  1879. func TestBuildMaintainer(t *testing.T) {
  1880. name := "testbuildmaintainer"
  1881. expected := "dockerio"
  1882. defer deleteImages(name)
  1883. _, err := buildImage(name,
  1884. `FROM scratch
  1885. MAINTAINER dockerio`,
  1886. true)
  1887. if err != nil {
  1888. t.Fatal(err)
  1889. }
  1890. res, err := inspectField(name, "Author")
  1891. if err != nil {
  1892. t.Fatal(err)
  1893. }
  1894. if res != expected {
  1895. t.Fatalf("Maintainer %s, expected %s", res, expected)
  1896. }
  1897. logDone("build - maintainer")
  1898. }
  1899. func TestBuildUser(t *testing.T) {
  1900. name := "testbuilduser"
  1901. expected := "dockerio"
  1902. defer deleteImages(name)
  1903. _, err := buildImage(name,
  1904. `FROM busybox
  1905. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1906. USER dockerio
  1907. RUN [ $(whoami) = 'dockerio' ]`,
  1908. true)
  1909. if err != nil {
  1910. t.Fatal(err)
  1911. }
  1912. res, err := inspectField(name, "Config.User")
  1913. if err != nil {
  1914. t.Fatal(err)
  1915. }
  1916. if res != expected {
  1917. t.Fatalf("User %s, expected %s", res, expected)
  1918. }
  1919. logDone("build - user")
  1920. }
  1921. func TestBuildRelativeWorkdir(t *testing.T) {
  1922. name := "testbuildrelativeworkdir"
  1923. expected := "/test2/test3"
  1924. defer deleteImages(name)
  1925. _, err := buildImage(name,
  1926. `FROM busybox
  1927. RUN [ "$PWD" = '/' ]
  1928. WORKDIR test1
  1929. RUN [ "$PWD" = '/test1' ]
  1930. WORKDIR /test2
  1931. RUN [ "$PWD" = '/test2' ]
  1932. WORKDIR test3
  1933. RUN [ "$PWD" = '/test2/test3' ]`,
  1934. true)
  1935. if err != nil {
  1936. t.Fatal(err)
  1937. }
  1938. res, err := inspectField(name, "Config.WorkingDir")
  1939. if err != nil {
  1940. t.Fatal(err)
  1941. }
  1942. if res != expected {
  1943. t.Fatalf("Workdir %s, expected %s", res, expected)
  1944. }
  1945. logDone("build - relative workdir")
  1946. }
  1947. func TestBuildWorkdirWithEnvVariables(t *testing.T) {
  1948. name := "testbuildworkdirwithenvvariables"
  1949. expected := "/test1/test2"
  1950. defer deleteImages(name)
  1951. _, err := buildImage(name,
  1952. `FROM busybox
  1953. ENV DIRPATH /test1
  1954. ENV SUBDIRNAME test2
  1955. WORKDIR $DIRPATH
  1956. WORKDIR $SUBDIRNAME/$MISSING_VAR`,
  1957. true)
  1958. if err != nil {
  1959. t.Fatal(err)
  1960. }
  1961. res, err := inspectField(name, "Config.WorkingDir")
  1962. if err != nil {
  1963. t.Fatal(err)
  1964. }
  1965. if res != expected {
  1966. t.Fatalf("Workdir %s, expected %s", res, expected)
  1967. }
  1968. logDone("build - workdir with env variables")
  1969. }
  1970. func TestBuildRelativeCopy(t *testing.T) {
  1971. name := "testbuildrelativecopy"
  1972. defer deleteImages(name)
  1973. dockerfile := `
  1974. FROM busybox
  1975. WORKDIR /test1
  1976. WORKDIR test2
  1977. RUN [ "$PWD" = '/test1/test2' ]
  1978. COPY foo ./
  1979. RUN [ "$(cat /test1/test2/foo)" = 'hello' ]
  1980. ADD foo ./bar/baz
  1981. RUN [ "$(cat /test1/test2/bar/baz)" = 'hello' ]
  1982. COPY foo ./bar/baz2
  1983. RUN [ "$(cat /test1/test2/bar/baz2)" = 'hello' ]
  1984. WORKDIR ..
  1985. COPY foo ./
  1986. RUN [ "$(cat /test1/foo)" = 'hello' ]
  1987. COPY foo /test3/
  1988. RUN [ "$(cat /test3/foo)" = 'hello' ]
  1989. WORKDIR /test4
  1990. COPY . .
  1991. RUN [ "$(cat /test4/foo)" = 'hello' ]
  1992. WORKDIR /test5/test6
  1993. COPY foo ../
  1994. RUN [ "$(cat /test5/foo)" = 'hello' ]
  1995. `
  1996. ctx, err := fakeContext(dockerfile, map[string]string{
  1997. "foo": "hello",
  1998. })
  1999. defer ctx.Close()
  2000. if err != nil {
  2001. t.Fatal(err)
  2002. }
  2003. _, err = buildImageFromContext(name, ctx, false)
  2004. if err != nil {
  2005. t.Fatal(err)
  2006. }
  2007. logDone("build - relative copy/add")
  2008. }
  2009. func TestBuildEnv(t *testing.T) {
  2010. name := "testbuildenv"
  2011. expected := "[PATH=/test:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin PORT=2375]"
  2012. defer deleteImages(name)
  2013. _, err := buildImage(name,
  2014. `FROM busybox
  2015. ENV PATH /test:$PATH
  2016. ENV PORT 2375
  2017. RUN [ $(env | grep PORT) = 'PORT=2375' ]`,
  2018. true)
  2019. if err != nil {
  2020. t.Fatal(err)
  2021. }
  2022. res, err := inspectField(name, "Config.Env")
  2023. if err != nil {
  2024. t.Fatal(err)
  2025. }
  2026. if res != expected {
  2027. t.Fatalf("Env %s, expected %s", res, expected)
  2028. }
  2029. logDone("build - env")
  2030. }
  2031. func TestBuildContextCleanup(t *testing.T) {
  2032. testRequires(t, SameHostDaemon)
  2033. name := "testbuildcontextcleanup"
  2034. defer deleteImages(name)
  2035. entries, err := ioutil.ReadDir("/var/lib/docker/tmp")
  2036. if err != nil {
  2037. t.Fatalf("failed to list contents of tmp dir: %s", err)
  2038. }
  2039. _, err = buildImage(name,
  2040. `FROM scratch
  2041. ENTRYPOINT ["/bin/echo"]`,
  2042. true)
  2043. if err != nil {
  2044. t.Fatal(err)
  2045. }
  2046. entriesFinal, err := ioutil.ReadDir("/var/lib/docker/tmp")
  2047. if err != nil {
  2048. t.Fatalf("failed to list contents of tmp dir: %s", err)
  2049. }
  2050. if err = compareDirectoryEntries(entries, entriesFinal); err != nil {
  2051. t.Fatalf("context should have been deleted, but wasn't")
  2052. }
  2053. logDone("build - verify context cleanup works properly")
  2054. }
  2055. func TestBuildContextCleanupFailedBuild(t *testing.T) {
  2056. testRequires(t, SameHostDaemon)
  2057. name := "testbuildcontextcleanup"
  2058. defer deleteImages(name)
  2059. defer deleteAllContainers()
  2060. entries, err := ioutil.ReadDir("/var/lib/docker/tmp")
  2061. if err != nil {
  2062. t.Fatalf("failed to list contents of tmp dir: %s", err)
  2063. }
  2064. _, err = buildImage(name,
  2065. `FROM scratch
  2066. RUN /non/existing/command`,
  2067. true)
  2068. if err == nil {
  2069. t.Fatalf("expected build to fail, but it didn't")
  2070. }
  2071. entriesFinal, err := ioutil.ReadDir("/var/lib/docker/tmp")
  2072. if err != nil {
  2073. t.Fatalf("failed to list contents of tmp dir: %s", err)
  2074. }
  2075. if err = compareDirectoryEntries(entries, entriesFinal); err != nil {
  2076. t.Fatalf("context should have been deleted, but wasn't")
  2077. }
  2078. logDone("build - verify context cleanup works properly after an unsuccessful build")
  2079. }
  2080. func TestBuildCmd(t *testing.T) {
  2081. name := "testbuildcmd"
  2082. expected := "[/bin/echo Hello World]"
  2083. defer deleteImages(name)
  2084. _, err := buildImage(name,
  2085. `FROM scratch
  2086. CMD ["/bin/echo", "Hello World"]`,
  2087. true)
  2088. if err != nil {
  2089. t.Fatal(err)
  2090. }
  2091. res, err := inspectField(name, "Config.Cmd")
  2092. if err != nil {
  2093. t.Fatal(err)
  2094. }
  2095. if res != expected {
  2096. t.Fatalf("Cmd %s, expected %s", res, expected)
  2097. }
  2098. logDone("build - cmd")
  2099. }
  2100. func TestBuildExpose(t *testing.T) {
  2101. name := "testbuildexpose"
  2102. expected := "map[2375/tcp:map[]]"
  2103. defer deleteImages(name)
  2104. _, err := buildImage(name,
  2105. `FROM scratch
  2106. EXPOSE 2375`,
  2107. true)
  2108. if err != nil {
  2109. t.Fatal(err)
  2110. }
  2111. res, err := inspectField(name, "Config.ExposedPorts")
  2112. if err != nil {
  2113. t.Fatal(err)
  2114. }
  2115. if res != expected {
  2116. t.Fatalf("Exposed ports %s, expected %s", res, expected)
  2117. }
  2118. logDone("build - expose")
  2119. }
  2120. func TestBuildExposeMorePorts(t *testing.T) {
  2121. // start building docker file with a large number of ports
  2122. portList := make([]string, 50)
  2123. line := make([]string, 100)
  2124. expectedPorts := make([]int, len(portList)*len(line))
  2125. for i := 0; i < len(portList); i++ {
  2126. for j := 0; j < len(line); j++ {
  2127. p := i*len(line) + j + 1
  2128. line[j] = strconv.Itoa(p)
  2129. expectedPorts[p-1] = p
  2130. }
  2131. if i == len(portList)-1 {
  2132. portList[i] = strings.Join(line, " ")
  2133. } else {
  2134. portList[i] = strings.Join(line, " ") + ` \`
  2135. }
  2136. }
  2137. dockerfile := `FROM scratch
  2138. EXPOSE {{range .}} {{.}}
  2139. {{end}}`
  2140. tmpl := template.Must(template.New("dockerfile").Parse(dockerfile))
  2141. buf := bytes.NewBuffer(nil)
  2142. tmpl.Execute(buf, portList)
  2143. name := "testbuildexpose"
  2144. defer deleteImages(name)
  2145. _, err := buildImage(name, buf.String(), true)
  2146. if err != nil {
  2147. t.Fatal(err)
  2148. }
  2149. // check if all the ports are saved inside Config.ExposedPorts
  2150. res, err := inspectFieldJSON(name, "Config.ExposedPorts")
  2151. if err != nil {
  2152. t.Fatal(err)
  2153. }
  2154. var exposedPorts map[string]interface{}
  2155. if err := json.Unmarshal([]byte(res), &exposedPorts); err != nil {
  2156. t.Fatal(err)
  2157. }
  2158. for _, p := range expectedPorts {
  2159. ep := fmt.Sprintf("%d/tcp", p)
  2160. if _, ok := exposedPorts[ep]; !ok {
  2161. t.Errorf("Port(%s) is not exposed", ep)
  2162. } else {
  2163. delete(exposedPorts, ep)
  2164. }
  2165. }
  2166. if len(exposedPorts) != 0 {
  2167. t.Errorf("Unexpected extra exposed ports %v", exposedPorts)
  2168. }
  2169. logDone("build - expose large number of ports")
  2170. }
  2171. func TestBuildExposeOrder(t *testing.T) {
  2172. buildID := func(name, exposed string) string {
  2173. _, err := buildImage(name, fmt.Sprintf(`FROM scratch
  2174. EXPOSE %s`, exposed), true)
  2175. if err != nil {
  2176. t.Fatal(err)
  2177. }
  2178. id, err := inspectField(name, "Id")
  2179. if err != nil {
  2180. t.Fatal(err)
  2181. }
  2182. return id
  2183. }
  2184. id1 := buildID("testbuildexpose1", "80 2375")
  2185. id2 := buildID("testbuildexpose2", "2375 80")
  2186. defer deleteImages("testbuildexpose1", "testbuildexpose2")
  2187. if id1 != id2 {
  2188. t.Errorf("EXPOSE should invalidate the cache only when ports actually changed")
  2189. }
  2190. logDone("build - expose order")
  2191. }
  2192. func TestBuildExposeUpperCaseProto(t *testing.T) {
  2193. name := "testbuildexposeuppercaseproto"
  2194. expected := "map[5678/udp:map[]]"
  2195. defer deleteImages(name)
  2196. _, err := buildImage(name,
  2197. `FROM scratch
  2198. EXPOSE 5678/UDP`,
  2199. true)
  2200. if err != nil {
  2201. t.Fatal(err)
  2202. }
  2203. res, err := inspectField(name, "Config.ExposedPorts")
  2204. if err != nil {
  2205. t.Fatal(err)
  2206. }
  2207. if res != expected {
  2208. t.Fatalf("Exposed ports %s, expected %s", res, expected)
  2209. }
  2210. logDone("build - expose port with upper case proto")
  2211. }
  2212. func TestBuildExposeHostPort(t *testing.T) {
  2213. // start building docker file with ip:hostPort:containerPort
  2214. name := "testbuildexpose"
  2215. expected := "map[5678/tcp:map[]]"
  2216. defer deleteImages(name)
  2217. _, out, err := buildImageWithOut(name,
  2218. `FROM scratch
  2219. EXPOSE 192.168.1.2:2375:5678`,
  2220. true)
  2221. if err != nil {
  2222. t.Fatal(err)
  2223. }
  2224. if !strings.Contains(out, "to map host ports to container ports (ip:hostPort:containerPort) is deprecated.") {
  2225. t.Fatal("Missing warning message")
  2226. }
  2227. res, err := inspectField(name, "Config.ExposedPorts")
  2228. if err != nil {
  2229. t.Fatal(err)
  2230. }
  2231. if res != expected {
  2232. t.Fatalf("Exposed ports %s, expected %s", res, expected)
  2233. }
  2234. logDone("build - ignore exposing host's port")
  2235. }
  2236. func TestBuildEmptyEntrypointInheritance(t *testing.T) {
  2237. name := "testbuildentrypointinheritance"
  2238. name2 := "testbuildentrypointinheritance2"
  2239. defer deleteImages(name, name2)
  2240. _, err := buildImage(name,
  2241. `FROM busybox
  2242. ENTRYPOINT ["/bin/echo"]`,
  2243. true)
  2244. if err != nil {
  2245. t.Fatal(err)
  2246. }
  2247. res, err := inspectField(name, "Config.Entrypoint")
  2248. if err != nil {
  2249. t.Fatal(err)
  2250. }
  2251. expected := "[/bin/echo]"
  2252. if res != expected {
  2253. t.Fatalf("Entrypoint %s, expected %s", res, expected)
  2254. }
  2255. _, err = buildImage(name2,
  2256. fmt.Sprintf(`FROM %s
  2257. ENTRYPOINT []`, name),
  2258. true)
  2259. if err != nil {
  2260. t.Fatal(err)
  2261. }
  2262. res, err = inspectField(name2, "Config.Entrypoint")
  2263. if err != nil {
  2264. t.Fatal(err)
  2265. }
  2266. expected = "[]"
  2267. if res != expected {
  2268. t.Fatalf("Entrypoint %s, expected %s", res, expected)
  2269. }
  2270. logDone("build - empty entrypoint inheritance")
  2271. }
  2272. func TestBuildEmptyEntrypoint(t *testing.T) {
  2273. name := "testbuildentrypoint"
  2274. defer deleteImages(name)
  2275. expected := "[]"
  2276. _, err := buildImage(name,
  2277. `FROM busybox
  2278. ENTRYPOINT []`,
  2279. true)
  2280. if err != nil {
  2281. t.Fatal(err)
  2282. }
  2283. res, err := inspectField(name, "Config.Entrypoint")
  2284. if err != nil {
  2285. t.Fatal(err)
  2286. }
  2287. if res != expected {
  2288. t.Fatalf("Entrypoint %s, expected %s", res, expected)
  2289. }
  2290. logDone("build - empty entrypoint")
  2291. }
  2292. func TestBuildEntrypoint(t *testing.T) {
  2293. name := "testbuildentrypoint"
  2294. expected := "[/bin/echo]"
  2295. defer deleteImages(name)
  2296. _, err := buildImage(name,
  2297. `FROM scratch
  2298. ENTRYPOINT ["/bin/echo"]`,
  2299. true)
  2300. if err != nil {
  2301. t.Fatal(err)
  2302. }
  2303. res, err := inspectField(name, "Config.Entrypoint")
  2304. if err != nil {
  2305. t.Fatal(err)
  2306. }
  2307. if res != expected {
  2308. t.Fatalf("Entrypoint %s, expected %s", res, expected)
  2309. }
  2310. logDone("build - entrypoint")
  2311. }
  2312. // #6445 ensure ONBUILD triggers aren't committed to grandchildren
  2313. func TestBuildOnBuildLimitedInheritence(t *testing.T) {
  2314. var (
  2315. out2, out3 string
  2316. )
  2317. {
  2318. name1 := "testonbuildtrigger1"
  2319. dockerfile1 := `
  2320. FROM busybox
  2321. RUN echo "GRANDPARENT"
  2322. ONBUILD RUN echo "ONBUILD PARENT"
  2323. `
  2324. ctx, err := fakeContext(dockerfile1, nil)
  2325. if err != nil {
  2326. t.Fatal(err)
  2327. }
  2328. defer ctx.Close()
  2329. out1, _, err := dockerCmdInDir(t, ctx.Dir, "build", "-t", name1, ".")
  2330. if err != nil {
  2331. t.Fatalf("build failed to complete: %s, %v", out1, err)
  2332. }
  2333. defer deleteImages(name1)
  2334. }
  2335. {
  2336. name2 := "testonbuildtrigger2"
  2337. dockerfile2 := `
  2338. FROM testonbuildtrigger1
  2339. `
  2340. ctx, err := fakeContext(dockerfile2, nil)
  2341. if err != nil {
  2342. t.Fatal(err)
  2343. }
  2344. defer ctx.Close()
  2345. out2, _, err = dockerCmdInDir(t, ctx.Dir, "build", "-t", name2, ".")
  2346. if err != nil {
  2347. t.Fatalf("build failed to complete: %s, %v", out2, err)
  2348. }
  2349. defer deleteImages(name2)
  2350. }
  2351. {
  2352. name3 := "testonbuildtrigger3"
  2353. dockerfile3 := `
  2354. FROM testonbuildtrigger2
  2355. `
  2356. ctx, err := fakeContext(dockerfile3, nil)
  2357. if err != nil {
  2358. t.Fatal(err)
  2359. }
  2360. defer ctx.Close()
  2361. out3, _, err = dockerCmdInDir(t, ctx.Dir, "build", "-t", name3, ".")
  2362. if err != nil {
  2363. t.Fatalf("build failed to complete: %s, %v", out3, err)
  2364. }
  2365. defer deleteImages(name3)
  2366. }
  2367. // ONBUILD should be run in second build.
  2368. if !strings.Contains(out2, "ONBUILD PARENT") {
  2369. t.Fatalf("ONBUILD instruction did not run in child of ONBUILD parent")
  2370. }
  2371. // ONBUILD should *not* be run in third build.
  2372. if strings.Contains(out3, "ONBUILD PARENT") {
  2373. t.Fatalf("ONBUILD instruction ran in grandchild of ONBUILD parent")
  2374. }
  2375. logDone("build - onbuild")
  2376. }
  2377. func TestBuildWithCache(t *testing.T) {
  2378. name := "testbuildwithcache"
  2379. defer deleteImages(name)
  2380. id1, err := buildImage(name,
  2381. `FROM scratch
  2382. MAINTAINER dockerio
  2383. EXPOSE 5432
  2384. ENTRYPOINT ["/bin/echo"]`,
  2385. true)
  2386. if err != nil {
  2387. t.Fatal(err)
  2388. }
  2389. id2, err := buildImage(name,
  2390. `FROM scratch
  2391. MAINTAINER dockerio
  2392. EXPOSE 5432
  2393. ENTRYPOINT ["/bin/echo"]`,
  2394. true)
  2395. if err != nil {
  2396. t.Fatal(err)
  2397. }
  2398. if id1 != id2 {
  2399. t.Fatal("The cache should have been used but hasn't.")
  2400. }
  2401. logDone("build - with cache")
  2402. }
  2403. func TestBuildWithoutCache(t *testing.T) {
  2404. name := "testbuildwithoutcache"
  2405. name2 := "testbuildwithoutcache2"
  2406. defer deleteImages(name, name2)
  2407. id1, err := buildImage(name,
  2408. `FROM scratch
  2409. MAINTAINER dockerio
  2410. EXPOSE 5432
  2411. ENTRYPOINT ["/bin/echo"]`,
  2412. true)
  2413. if err != nil {
  2414. t.Fatal(err)
  2415. }
  2416. id2, err := buildImage(name2,
  2417. `FROM scratch
  2418. MAINTAINER dockerio
  2419. EXPOSE 5432
  2420. ENTRYPOINT ["/bin/echo"]`,
  2421. false)
  2422. if err != nil {
  2423. t.Fatal(err)
  2424. }
  2425. if id1 == id2 {
  2426. t.Fatal("The cache should have been invalided but hasn't.")
  2427. }
  2428. logDone("build - without cache")
  2429. }
  2430. func TestBuildConditionalCache(t *testing.T) {
  2431. name := "testbuildconditionalcache"
  2432. name2 := "testbuildconditionalcache2"
  2433. defer deleteImages(name, name2)
  2434. dockerfile := `
  2435. FROM busybox
  2436. ADD foo /tmp/`
  2437. ctx, err := fakeContext(dockerfile, map[string]string{
  2438. "foo": "hello",
  2439. })
  2440. if err != nil {
  2441. t.Fatal(err)
  2442. }
  2443. defer ctx.Close()
  2444. id1, err := buildImageFromContext(name, ctx, true)
  2445. if err != nil {
  2446. t.Fatalf("Error building #1: %s", err)
  2447. }
  2448. if err := ctx.Add("foo", "bye"); err != nil {
  2449. t.Fatalf("Error modifying foo: %s", err)
  2450. }
  2451. id2, err := buildImageFromContext(name, ctx, false)
  2452. if err != nil {
  2453. t.Fatalf("Error building #2: %s", err)
  2454. }
  2455. if id2 == id1 {
  2456. t.Fatal("Should not have used the cache")
  2457. }
  2458. id3, err := buildImageFromContext(name, ctx, true)
  2459. if err != nil {
  2460. t.Fatalf("Error building #3: %s", err)
  2461. }
  2462. if id3 != id2 {
  2463. t.Fatal("Should have used the cache")
  2464. }
  2465. logDone("build - conditional cache")
  2466. }
  2467. func TestBuildADDLocalFileWithCache(t *testing.T) {
  2468. name := "testbuildaddlocalfilewithcache"
  2469. name2 := "testbuildaddlocalfilewithcache2"
  2470. defer deleteImages(name, name2)
  2471. dockerfile := `
  2472. FROM busybox
  2473. MAINTAINER dockerio
  2474. ADD foo /usr/lib/bla/bar
  2475. RUN [ "$(cat /usr/lib/bla/bar)" = "hello" ]`
  2476. ctx, err := fakeContext(dockerfile, map[string]string{
  2477. "foo": "hello",
  2478. })
  2479. defer ctx.Close()
  2480. if err != nil {
  2481. t.Fatal(err)
  2482. }
  2483. id1, err := buildImageFromContext(name, ctx, true)
  2484. if err != nil {
  2485. t.Fatal(err)
  2486. }
  2487. id2, err := buildImageFromContext(name2, ctx, true)
  2488. if err != nil {
  2489. t.Fatal(err)
  2490. }
  2491. if id1 != id2 {
  2492. t.Fatal("The cache should have been used but hasn't.")
  2493. }
  2494. logDone("build - add local file with cache")
  2495. }
  2496. func TestBuildADDMultipleLocalFileWithCache(t *testing.T) {
  2497. name := "testbuildaddmultiplelocalfilewithcache"
  2498. name2 := "testbuildaddmultiplelocalfilewithcache2"
  2499. defer deleteImages(name, name2)
  2500. dockerfile := `
  2501. FROM busybox
  2502. MAINTAINER dockerio
  2503. ADD foo Dockerfile /usr/lib/bla/
  2504. RUN [ "$(cat /usr/lib/bla/foo)" = "hello" ]`
  2505. ctx, err := fakeContext(dockerfile, map[string]string{
  2506. "foo": "hello",
  2507. })
  2508. defer ctx.Close()
  2509. if err != nil {
  2510. t.Fatal(err)
  2511. }
  2512. id1, err := buildImageFromContext(name, ctx, true)
  2513. if err != nil {
  2514. t.Fatal(err)
  2515. }
  2516. id2, err := buildImageFromContext(name2, ctx, true)
  2517. if err != nil {
  2518. t.Fatal(err)
  2519. }
  2520. if id1 != id2 {
  2521. t.Fatal("The cache should have been used but hasn't.")
  2522. }
  2523. logDone("build - add multiple local files with cache")
  2524. }
  2525. func TestBuildADDLocalFileWithoutCache(t *testing.T) {
  2526. name := "testbuildaddlocalfilewithoutcache"
  2527. name2 := "testbuildaddlocalfilewithoutcache2"
  2528. defer deleteImages(name, name2)
  2529. dockerfile := `
  2530. FROM busybox
  2531. MAINTAINER dockerio
  2532. ADD foo /usr/lib/bla/bar
  2533. RUN [ "$(cat /usr/lib/bla/bar)" = "hello" ]`
  2534. ctx, err := fakeContext(dockerfile, map[string]string{
  2535. "foo": "hello",
  2536. })
  2537. defer ctx.Close()
  2538. if err != nil {
  2539. t.Fatal(err)
  2540. }
  2541. id1, err := buildImageFromContext(name, ctx, true)
  2542. if err != nil {
  2543. t.Fatal(err)
  2544. }
  2545. id2, err := buildImageFromContext(name2, ctx, false)
  2546. if err != nil {
  2547. t.Fatal(err)
  2548. }
  2549. if id1 == id2 {
  2550. t.Fatal("The cache should have been invalided but hasn't.")
  2551. }
  2552. logDone("build - add local file without cache")
  2553. }
  2554. func TestBuildCopyDirButNotFile(t *testing.T) {
  2555. name := "testbuildcopydirbutnotfile"
  2556. name2 := "testbuildcopydirbutnotfile2"
  2557. defer deleteImages(name, name2)
  2558. dockerfile := `
  2559. FROM scratch
  2560. COPY dir /tmp/`
  2561. ctx, err := fakeContext(dockerfile, map[string]string{
  2562. "dir/foo": "hello",
  2563. })
  2564. defer ctx.Close()
  2565. if err != nil {
  2566. t.Fatal(err)
  2567. }
  2568. id1, err := buildImageFromContext(name, ctx, true)
  2569. if err != nil {
  2570. t.Fatal(err)
  2571. }
  2572. // Check that adding file with similar name doesn't mess with cache
  2573. if err := ctx.Add("dir_file", "hello2"); err != nil {
  2574. t.Fatal(err)
  2575. }
  2576. id2, err := buildImageFromContext(name2, ctx, true)
  2577. if err != nil {
  2578. t.Fatal(err)
  2579. }
  2580. if id1 != id2 {
  2581. t.Fatal("The cache should have been used but wasn't")
  2582. }
  2583. logDone("build - add current directory but not file")
  2584. }
  2585. func TestBuildADDCurrentDirWithCache(t *testing.T) {
  2586. name := "testbuildaddcurrentdirwithcache"
  2587. name2 := name + "2"
  2588. name3 := name + "3"
  2589. name4 := name + "4"
  2590. name5 := name + "5"
  2591. defer deleteImages(name, name2, name3, name4, name5)
  2592. dockerfile := `
  2593. FROM scratch
  2594. MAINTAINER dockerio
  2595. ADD . /usr/lib/bla`
  2596. ctx, err := fakeContext(dockerfile, map[string]string{
  2597. "foo": "hello",
  2598. })
  2599. defer ctx.Close()
  2600. if err != nil {
  2601. t.Fatal(err)
  2602. }
  2603. id1, err := buildImageFromContext(name, ctx, true)
  2604. if err != nil {
  2605. t.Fatal(err)
  2606. }
  2607. // Check that adding file invalidate cache of "ADD ."
  2608. if err := ctx.Add("bar", "hello2"); err != nil {
  2609. t.Fatal(err)
  2610. }
  2611. id2, err := buildImageFromContext(name2, ctx, true)
  2612. if err != nil {
  2613. t.Fatal(err)
  2614. }
  2615. if id1 == id2 {
  2616. t.Fatal("The cache should have been invalided but hasn't.")
  2617. }
  2618. // Check that changing file invalidate cache of "ADD ."
  2619. if err := ctx.Add("foo", "hello1"); err != nil {
  2620. t.Fatal(err)
  2621. }
  2622. id3, err := buildImageFromContext(name3, ctx, true)
  2623. if err != nil {
  2624. t.Fatal(err)
  2625. }
  2626. if id2 == id3 {
  2627. t.Fatal("The cache should have been invalided but hasn't.")
  2628. }
  2629. // Check that changing file to same content invalidate cache of "ADD ."
  2630. time.Sleep(1 * time.Second) // wait second because of mtime precision
  2631. if err := ctx.Add("foo", "hello1"); err != nil {
  2632. t.Fatal(err)
  2633. }
  2634. id4, err := buildImageFromContext(name4, ctx, true)
  2635. if err != nil {
  2636. t.Fatal(err)
  2637. }
  2638. if id3 == id4 {
  2639. t.Fatal("The cache should have been invalided but hasn't.")
  2640. }
  2641. id5, err := buildImageFromContext(name5, ctx, true)
  2642. if err != nil {
  2643. t.Fatal(err)
  2644. }
  2645. if id4 != id5 {
  2646. t.Fatal("The cache should have been used but hasn't.")
  2647. }
  2648. logDone("build - add current directory with cache")
  2649. }
  2650. func TestBuildADDCurrentDirWithoutCache(t *testing.T) {
  2651. name := "testbuildaddcurrentdirwithoutcache"
  2652. name2 := "testbuildaddcurrentdirwithoutcache2"
  2653. defer deleteImages(name, name2)
  2654. dockerfile := `
  2655. FROM scratch
  2656. MAINTAINER dockerio
  2657. ADD . /usr/lib/bla`
  2658. ctx, err := fakeContext(dockerfile, map[string]string{
  2659. "foo": "hello",
  2660. })
  2661. defer ctx.Close()
  2662. if err != nil {
  2663. t.Fatal(err)
  2664. }
  2665. id1, err := buildImageFromContext(name, ctx, true)
  2666. if err != nil {
  2667. t.Fatal(err)
  2668. }
  2669. id2, err := buildImageFromContext(name2, ctx, false)
  2670. if err != nil {
  2671. t.Fatal(err)
  2672. }
  2673. if id1 == id2 {
  2674. t.Fatal("The cache should have been invalided but hasn't.")
  2675. }
  2676. logDone("build - add current directory without cache")
  2677. }
  2678. func TestBuildADDRemoteFileWithCache(t *testing.T) {
  2679. name := "testbuildaddremotefilewithcache"
  2680. defer deleteImages(name)
  2681. server, err := fakeStorage(map[string]string{
  2682. "baz": "hello",
  2683. })
  2684. if err != nil {
  2685. t.Fatal(err)
  2686. }
  2687. defer server.Close()
  2688. id1, err := buildImage(name,
  2689. fmt.Sprintf(`FROM scratch
  2690. MAINTAINER dockerio
  2691. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2692. true)
  2693. if err != nil {
  2694. t.Fatal(err)
  2695. }
  2696. id2, err := buildImage(name,
  2697. fmt.Sprintf(`FROM scratch
  2698. MAINTAINER dockerio
  2699. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2700. true)
  2701. if err != nil {
  2702. t.Fatal(err)
  2703. }
  2704. if id1 != id2 {
  2705. t.Fatal("The cache should have been used but hasn't.")
  2706. }
  2707. logDone("build - add remote file with cache")
  2708. }
  2709. func TestBuildADDRemoteFileWithoutCache(t *testing.T) {
  2710. name := "testbuildaddremotefilewithoutcache"
  2711. name2 := "testbuildaddremotefilewithoutcache2"
  2712. defer deleteImages(name, name2)
  2713. server, err := fakeStorage(map[string]string{
  2714. "baz": "hello",
  2715. })
  2716. if err != nil {
  2717. t.Fatal(err)
  2718. }
  2719. defer server.Close()
  2720. id1, err := buildImage(name,
  2721. fmt.Sprintf(`FROM scratch
  2722. MAINTAINER dockerio
  2723. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2724. true)
  2725. if err != nil {
  2726. t.Fatal(err)
  2727. }
  2728. id2, err := buildImage(name2,
  2729. fmt.Sprintf(`FROM scratch
  2730. MAINTAINER dockerio
  2731. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2732. false)
  2733. if err != nil {
  2734. t.Fatal(err)
  2735. }
  2736. if id1 == id2 {
  2737. t.Fatal("The cache should have been invalided but hasn't.")
  2738. }
  2739. logDone("build - add remote file without cache")
  2740. }
  2741. func TestBuildADDRemoteFileMTime(t *testing.T) {
  2742. name := "testbuildaddremotefilemtime"
  2743. name2 := name + "2"
  2744. name3 := name + "3"
  2745. name4 := name + "4"
  2746. defer deleteImages(name, name2, name3, name4)
  2747. files := map[string]string{"baz": "hello"}
  2748. server, err := fakeStorage(files)
  2749. if err != nil {
  2750. t.Fatal(err)
  2751. }
  2752. defer server.Close()
  2753. ctx, err := fakeContext(fmt.Sprintf(`FROM scratch
  2754. MAINTAINER dockerio
  2755. ADD %s/baz /usr/lib/baz/quux`, server.URL()), nil)
  2756. if err != nil {
  2757. t.Fatal(err)
  2758. }
  2759. defer ctx.Close()
  2760. id1, err := buildImageFromContext(name, ctx, true)
  2761. if err != nil {
  2762. t.Fatal(err)
  2763. }
  2764. id2, err := buildImageFromContext(name2, ctx, true)
  2765. if err != nil {
  2766. t.Fatal(err)
  2767. }
  2768. if id1 != id2 {
  2769. t.Fatal("The cache should have been used but wasn't - #1")
  2770. }
  2771. // Now create a different server withsame contents (causes different mtim)
  2772. // This time the cache should not be used
  2773. // allow some time for clock to pass as mtime precision is only 1s
  2774. time.Sleep(2 * time.Second)
  2775. server2, err := fakeStorage(files)
  2776. if err != nil {
  2777. t.Fatal(err)
  2778. }
  2779. defer server2.Close()
  2780. ctx2, err := fakeContext(fmt.Sprintf(`FROM scratch
  2781. MAINTAINER dockerio
  2782. ADD %s/baz /usr/lib/baz/quux`, server2.URL()), nil)
  2783. if err != nil {
  2784. t.Fatal(err)
  2785. }
  2786. defer ctx2.Close()
  2787. id3, err := buildImageFromContext(name3, ctx2, true)
  2788. if err != nil {
  2789. t.Fatal(err)
  2790. }
  2791. if id1 == id3 {
  2792. t.Fatal("The cache should not have been used but was")
  2793. }
  2794. // And for good measure do it again and make sure cache is used this time
  2795. id4, err := buildImageFromContext(name4, ctx2, true)
  2796. if err != nil {
  2797. t.Fatal(err)
  2798. }
  2799. if id3 != id4 {
  2800. t.Fatal("The cache should have been used but wasn't - #2")
  2801. }
  2802. logDone("build - add remote file testing mtime")
  2803. }
  2804. func TestBuildADDLocalAndRemoteFilesWithCache(t *testing.T) {
  2805. name := "testbuildaddlocalandremotefilewithcache"
  2806. defer deleteImages(name)
  2807. server, err := fakeStorage(map[string]string{
  2808. "baz": "hello",
  2809. })
  2810. if err != nil {
  2811. t.Fatal(err)
  2812. }
  2813. defer server.Close()
  2814. ctx, err := fakeContext(fmt.Sprintf(`FROM scratch
  2815. MAINTAINER dockerio
  2816. ADD foo /usr/lib/bla/bar
  2817. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2818. map[string]string{
  2819. "foo": "hello world",
  2820. })
  2821. if err != nil {
  2822. t.Fatal(err)
  2823. }
  2824. defer ctx.Close()
  2825. id1, err := buildImageFromContext(name, ctx, true)
  2826. if err != nil {
  2827. t.Fatal(err)
  2828. }
  2829. id2, err := buildImageFromContext(name, ctx, true)
  2830. if err != nil {
  2831. t.Fatal(err)
  2832. }
  2833. if id1 != id2 {
  2834. t.Fatal("The cache should have been used but hasn't.")
  2835. }
  2836. logDone("build - add local and remote file with cache")
  2837. }
  2838. func testContextTar(t *testing.T, compression archive.Compression) {
  2839. ctx, err := fakeContext(
  2840. `FROM busybox
  2841. ADD foo /foo
  2842. CMD ["cat", "/foo"]`,
  2843. map[string]string{
  2844. "foo": "bar",
  2845. },
  2846. )
  2847. defer ctx.Close()
  2848. if err != nil {
  2849. t.Fatal(err)
  2850. }
  2851. context, err := archive.Tar(ctx.Dir, compression)
  2852. if err != nil {
  2853. t.Fatalf("failed to build context tar: %v", err)
  2854. }
  2855. name := "contexttar"
  2856. buildCmd := exec.Command(dockerBinary, "build", "-t", name, "-")
  2857. defer deleteImages(name)
  2858. buildCmd.Stdin = context
  2859. if out, _, err := runCommandWithOutput(buildCmd); err != nil {
  2860. t.Fatalf("build failed to complete: %v %v", out, err)
  2861. }
  2862. logDone(fmt.Sprintf("build - build an image with a context tar, compression: %v", compression))
  2863. }
  2864. func TestBuildContextTarGzip(t *testing.T) {
  2865. testContextTar(t, archive.Gzip)
  2866. }
  2867. func TestBuildContextTarNoCompression(t *testing.T) {
  2868. testContextTar(t, archive.Uncompressed)
  2869. }
  2870. func TestBuildNoContext(t *testing.T) {
  2871. buildCmd := exec.Command(dockerBinary, "build", "-t", "nocontext", "-")
  2872. buildCmd.Stdin = strings.NewReader("FROM busybox\nCMD echo ok\n")
  2873. if out, _, err := runCommandWithOutput(buildCmd); err != nil {
  2874. t.Fatalf("build failed to complete: %v %v", out, err)
  2875. }
  2876. if out, _, err := dockerCmd(t, "run", "--rm", "nocontext"); out != "ok\n" || err != nil {
  2877. t.Fatalf("run produced invalid output: %q, expected %q", out, "ok")
  2878. }
  2879. deleteImages("nocontext")
  2880. logDone("build - build an image with no context")
  2881. }
  2882. // TODO: TestCaching
  2883. func TestBuildADDLocalAndRemoteFilesWithoutCache(t *testing.T) {
  2884. name := "testbuildaddlocalandremotefilewithoutcache"
  2885. name2 := "testbuildaddlocalandremotefilewithoutcache2"
  2886. defer deleteImages(name, name2)
  2887. server, err := fakeStorage(map[string]string{
  2888. "baz": "hello",
  2889. })
  2890. if err != nil {
  2891. t.Fatal(err)
  2892. }
  2893. defer server.Close()
  2894. ctx, err := fakeContext(fmt.Sprintf(`FROM scratch
  2895. MAINTAINER dockerio
  2896. ADD foo /usr/lib/bla/bar
  2897. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  2898. map[string]string{
  2899. "foo": "hello world",
  2900. })
  2901. if err != nil {
  2902. t.Fatal(err)
  2903. }
  2904. defer ctx.Close()
  2905. id1, err := buildImageFromContext(name, ctx, true)
  2906. if err != nil {
  2907. t.Fatal(err)
  2908. }
  2909. id2, err := buildImageFromContext(name2, ctx, false)
  2910. if err != nil {
  2911. t.Fatal(err)
  2912. }
  2913. if id1 == id2 {
  2914. t.Fatal("The cache should have been invalided but hasn't.")
  2915. }
  2916. logDone("build - add local and remote file without cache")
  2917. }
  2918. func TestBuildWithVolumeOwnership(t *testing.T) {
  2919. name := "testbuildimg"
  2920. defer deleteImages(name)
  2921. _, err := buildImage(name,
  2922. `FROM busybox:latest
  2923. RUN mkdir /test && chown daemon:daemon /test && chmod 0600 /test
  2924. VOLUME /test`,
  2925. true)
  2926. if err != nil {
  2927. t.Fatal(err)
  2928. }
  2929. cmd := exec.Command(dockerBinary, "run", "--rm", "testbuildimg", "ls", "-la", "/test")
  2930. out, _, err := runCommandWithOutput(cmd)
  2931. if err != nil {
  2932. t.Fatal(out, err)
  2933. }
  2934. if expected := "drw-------"; !strings.Contains(out, expected) {
  2935. t.Fatalf("expected %s received %s", expected, out)
  2936. }
  2937. if expected := "daemon daemon"; !strings.Contains(out, expected) {
  2938. t.Fatalf("expected %s received %s", expected, out)
  2939. }
  2940. logDone("build - volume ownership")
  2941. }
  2942. // testing #1405 - config.Cmd does not get cleaned up if
  2943. // utilizing cache
  2944. func TestBuildEntrypointRunCleanup(t *testing.T) {
  2945. name := "testbuildcmdcleanup"
  2946. defer deleteImages(name)
  2947. if _, err := buildImage(name,
  2948. `FROM busybox
  2949. RUN echo "hello"`,
  2950. true); err != nil {
  2951. t.Fatal(err)
  2952. }
  2953. ctx, err := fakeContext(`FROM busybox
  2954. RUN echo "hello"
  2955. ADD foo /foo
  2956. ENTRYPOINT ["/bin/echo"]`,
  2957. map[string]string{
  2958. "foo": "hello",
  2959. })
  2960. defer ctx.Close()
  2961. if err != nil {
  2962. t.Fatal(err)
  2963. }
  2964. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2965. t.Fatal(err)
  2966. }
  2967. res, err := inspectField(name, "Config.Cmd")
  2968. if err != nil {
  2969. t.Fatal(err)
  2970. }
  2971. // Cmd must be cleaned up
  2972. if expected := "<no value>"; res != expected {
  2973. t.Fatalf("Cmd %s, expected %s", res, expected)
  2974. }
  2975. logDone("build - cleanup cmd after RUN")
  2976. }
  2977. func TestBuildForbiddenContextPath(t *testing.T) {
  2978. name := "testbuildforbidpath"
  2979. defer deleteImages(name)
  2980. ctx, err := fakeContext(`FROM scratch
  2981. ADD ../../ test/
  2982. `,
  2983. map[string]string{
  2984. "test.txt": "test1",
  2985. "other.txt": "other",
  2986. })
  2987. defer ctx.Close()
  2988. if err != nil {
  2989. t.Fatal(err)
  2990. }
  2991. expected := "Forbidden path outside the build context: ../../ "
  2992. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  2993. t.Fatalf("Wrong error: (should contain \"%s\") got:\n%v", expected, err)
  2994. }
  2995. logDone("build - forbidden context path")
  2996. }
  2997. func TestBuildADDFileNotFound(t *testing.T) {
  2998. name := "testbuildaddnotfound"
  2999. defer deleteImages(name)
  3000. ctx, err := fakeContext(`FROM scratch
  3001. ADD foo /usr/local/bar`,
  3002. map[string]string{"bar": "hello"})
  3003. defer ctx.Close()
  3004. if err != nil {
  3005. t.Fatal(err)
  3006. }
  3007. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3008. if !strings.Contains(err.Error(), "foo: no such file or directory") {
  3009. t.Fatalf("Wrong error %v, must be about missing foo file or directory", err)
  3010. }
  3011. } else {
  3012. t.Fatal("Error must not be nil")
  3013. }
  3014. logDone("build - add file not found")
  3015. }
  3016. func TestBuildInheritance(t *testing.T) {
  3017. name := "testbuildinheritance"
  3018. defer deleteImages(name)
  3019. _, err := buildImage(name,
  3020. `FROM scratch
  3021. EXPOSE 2375`,
  3022. true)
  3023. if err != nil {
  3024. t.Fatal(err)
  3025. }
  3026. ports1, err := inspectField(name, "Config.ExposedPorts")
  3027. if err != nil {
  3028. t.Fatal(err)
  3029. }
  3030. _, err = buildImage(name,
  3031. fmt.Sprintf(`FROM %s
  3032. ENTRYPOINT ["/bin/echo"]`, name),
  3033. true)
  3034. if err != nil {
  3035. t.Fatal(err)
  3036. }
  3037. res, err := inspectField(name, "Config.Entrypoint")
  3038. if err != nil {
  3039. t.Fatal(err)
  3040. }
  3041. if expected := "[/bin/echo]"; res != expected {
  3042. t.Fatalf("Entrypoint %s, expected %s", res, expected)
  3043. }
  3044. ports2, err := inspectField(name, "Config.ExposedPorts")
  3045. if err != nil {
  3046. t.Fatal(err)
  3047. }
  3048. if ports1 != ports2 {
  3049. t.Fatalf("Ports must be same: %s != %s", ports1, ports2)
  3050. }
  3051. logDone("build - inheritance")
  3052. }
  3053. func TestBuildFails(t *testing.T) {
  3054. name := "testbuildfails"
  3055. defer deleteImages(name)
  3056. defer deleteAllContainers()
  3057. _, err := buildImage(name,
  3058. `FROM busybox
  3059. RUN sh -c "exit 23"`,
  3060. true)
  3061. if err != nil {
  3062. if !strings.Contains(err.Error(), "returned a non-zero code: 23") {
  3063. t.Fatalf("Wrong error %v, must be about non-zero code 23", err)
  3064. }
  3065. } else {
  3066. t.Fatal("Error must not be nil")
  3067. }
  3068. logDone("build - unsuccessful")
  3069. }
  3070. func TestBuildFailsDockerfileEmpty(t *testing.T) {
  3071. name := "testbuildfails"
  3072. defer deleteImages(name)
  3073. _, err := buildImage(name, ``, true)
  3074. if err != nil {
  3075. if !strings.Contains(err.Error(), "The Dockerfile (Dockerfile) cannot be empty") {
  3076. t.Fatalf("Wrong error %v, must be about empty Dockerfile", err)
  3077. }
  3078. } else {
  3079. t.Fatal("Error must not be nil")
  3080. }
  3081. logDone("build - unsuccessful with empty dockerfile")
  3082. }
  3083. func TestBuildOnBuild(t *testing.T) {
  3084. name := "testbuildonbuild"
  3085. defer deleteImages(name)
  3086. _, err := buildImage(name,
  3087. `FROM busybox
  3088. ONBUILD RUN touch foobar`,
  3089. true)
  3090. if err != nil {
  3091. t.Fatal(err)
  3092. }
  3093. _, err = buildImage(name,
  3094. fmt.Sprintf(`FROM %s
  3095. RUN [ -f foobar ]`, name),
  3096. true)
  3097. if err != nil {
  3098. t.Fatal(err)
  3099. }
  3100. logDone("build - onbuild")
  3101. }
  3102. func TestBuildOnBuildForbiddenChained(t *testing.T) {
  3103. name := "testbuildonbuildforbiddenchained"
  3104. defer deleteImages(name)
  3105. _, err := buildImage(name,
  3106. `FROM busybox
  3107. ONBUILD ONBUILD RUN touch foobar`,
  3108. true)
  3109. if err != nil {
  3110. if !strings.Contains(err.Error(), "Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed") {
  3111. t.Fatalf("Wrong error %v, must be about chaining ONBUILD", err)
  3112. }
  3113. } else {
  3114. t.Fatal("Error must not be nil")
  3115. }
  3116. logDone("build - onbuild forbidden chained")
  3117. }
  3118. func TestBuildOnBuildForbiddenFrom(t *testing.T) {
  3119. name := "testbuildonbuildforbiddenfrom"
  3120. defer deleteImages(name)
  3121. _, err := buildImage(name,
  3122. `FROM busybox
  3123. ONBUILD FROM scratch`,
  3124. true)
  3125. if err != nil {
  3126. if !strings.Contains(err.Error(), "FROM isn't allowed as an ONBUILD trigger") {
  3127. t.Fatalf("Wrong error %v, must be about FROM forbidden", err)
  3128. }
  3129. } else {
  3130. t.Fatal("Error must not be nil")
  3131. }
  3132. logDone("build - onbuild forbidden from")
  3133. }
  3134. func TestBuildOnBuildForbiddenMaintainer(t *testing.T) {
  3135. name := "testbuildonbuildforbiddenmaintainer"
  3136. defer deleteImages(name)
  3137. _, err := buildImage(name,
  3138. `FROM busybox
  3139. ONBUILD MAINTAINER docker.io`,
  3140. true)
  3141. if err != nil {
  3142. if !strings.Contains(err.Error(), "MAINTAINER isn't allowed as an ONBUILD trigger") {
  3143. t.Fatalf("Wrong error %v, must be about MAINTAINER forbidden", err)
  3144. }
  3145. } else {
  3146. t.Fatal("Error must not be nil")
  3147. }
  3148. logDone("build - onbuild forbidden maintainer")
  3149. }
  3150. // gh #2446
  3151. func TestBuildAddToSymlinkDest(t *testing.T) {
  3152. name := "testbuildaddtosymlinkdest"
  3153. defer deleteImages(name)
  3154. ctx, err := fakeContext(`FROM busybox
  3155. RUN mkdir /foo
  3156. RUN ln -s /foo /bar
  3157. ADD foo /bar/
  3158. RUN [ -f /bar/foo ]
  3159. RUN [ -f /foo/foo ]`,
  3160. map[string]string{
  3161. "foo": "hello",
  3162. })
  3163. if err != nil {
  3164. t.Fatal(err)
  3165. }
  3166. defer ctx.Close()
  3167. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3168. t.Fatal(err)
  3169. }
  3170. logDone("build - add to symlink destination")
  3171. }
  3172. func TestBuildEscapeWhitespace(t *testing.T) {
  3173. name := "testbuildescaping"
  3174. defer deleteImages(name)
  3175. _, err := buildImage(name, `
  3176. FROM busybox
  3177. MAINTAINER "Docker \
  3178. IO <io@\
  3179. docker.com>"
  3180. `, true)
  3181. res, err := inspectField(name, "Author")
  3182. if err != nil {
  3183. t.Fatal(err)
  3184. }
  3185. if res != "\"Docker IO <io@docker.com>\"" {
  3186. t.Fatalf("Parsed string did not match the escaped string. Got: %q", res)
  3187. }
  3188. logDone("build - validate escaping whitespace")
  3189. }
  3190. func TestBuildVerifyIntString(t *testing.T) {
  3191. // Verify that strings that look like ints are still passed as strings
  3192. name := "testbuildstringing"
  3193. defer deleteImages(name)
  3194. _, err := buildImage(name, `
  3195. FROM busybox
  3196. MAINTAINER 123
  3197. `, true)
  3198. out, rc, err := runCommandWithOutput(exec.Command(dockerBinary, "inspect", name))
  3199. if rc != 0 || err != nil {
  3200. t.Fatalf("Unexcepted error from inspect: rc: %v err: %v", rc, err)
  3201. }
  3202. if !strings.Contains(out, "\"123\"") {
  3203. t.Fatalf("Output does not contain the int as a string:\n%s", out)
  3204. }
  3205. logDone("build - verify int/strings as strings")
  3206. }
  3207. func TestBuildDockerignore(t *testing.T) {
  3208. name := "testbuilddockerignore"
  3209. defer deleteImages(name)
  3210. dockerfile := `
  3211. FROM busybox
  3212. ADD . /bla
  3213. RUN [[ -f /bla/src/x.go ]]
  3214. RUN [[ -f /bla/Makefile ]]
  3215. RUN [[ ! -e /bla/src/_vendor ]]
  3216. RUN [[ ! -e /bla/.gitignore ]]
  3217. RUN [[ ! -e /bla/README.md ]]
  3218. RUN [[ ! -e /bla/.git ]]`
  3219. ctx, err := fakeContext(dockerfile, map[string]string{
  3220. "Makefile": "all:",
  3221. ".git/HEAD": "ref: foo",
  3222. "src/x.go": "package main",
  3223. "src/_vendor/v.go": "package main",
  3224. ".gitignore": "",
  3225. "README.md": "readme",
  3226. ".dockerignore": ".git\npkg\n.gitignore\nsrc/_vendor\n*.md",
  3227. })
  3228. defer ctx.Close()
  3229. if err != nil {
  3230. t.Fatal(err)
  3231. }
  3232. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3233. t.Fatal(err)
  3234. }
  3235. logDone("build - test .dockerignore")
  3236. }
  3237. func TestBuildDockerignoreCleanPaths(t *testing.T) {
  3238. name := "testbuilddockerignorecleanpaths"
  3239. defer deleteImages(name)
  3240. dockerfile := `
  3241. FROM busybox
  3242. ADD . /tmp/
  3243. RUN (! ls /tmp/foo) && (! ls /tmp/foo2) && (! ls /tmp/dir1/foo)`
  3244. ctx, err := fakeContext(dockerfile, map[string]string{
  3245. "foo": "foo",
  3246. "foo2": "foo2",
  3247. "dir1/foo": "foo in dir1",
  3248. ".dockerignore": "./foo\ndir1//foo\n./dir1/../foo2",
  3249. })
  3250. if err != nil {
  3251. t.Fatal(err)
  3252. }
  3253. defer ctx.Close()
  3254. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3255. t.Fatal(err)
  3256. }
  3257. logDone("build - test .dockerignore with clean paths")
  3258. }
  3259. func TestBuildDockerignoringDockerfile(t *testing.T) {
  3260. name := "testbuilddockerignoredockerfile"
  3261. defer deleteImages(name)
  3262. dockerfile := `
  3263. FROM busybox
  3264. ADD . /tmp/
  3265. RUN ! ls /tmp/Dockerfile
  3266. RUN ls /tmp/.dockerignore`
  3267. ctx, err := fakeContext(dockerfile, map[string]string{
  3268. "Dockerfile": dockerfile,
  3269. ".dockerignore": "Dockerfile\n",
  3270. })
  3271. if err != nil {
  3272. t.Fatal(err)
  3273. }
  3274. defer ctx.Close()
  3275. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3276. t.Fatalf("Didn't ignore Dockerfile correctly:%s", err)
  3277. }
  3278. // now try it with ./Dockerfile
  3279. ctx.Add(".dockerignore", "./Dockerfile\n")
  3280. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3281. t.Fatalf("Didn't ignore ./Dockerfile correctly:%s", err)
  3282. }
  3283. logDone("build - test .dockerignore of Dockerfile")
  3284. }
  3285. func TestBuildDockerignoringRenamedDockerfile(t *testing.T) {
  3286. name := "testbuilddockerignoredockerfile"
  3287. defer deleteImages(name)
  3288. dockerfile := `
  3289. FROM busybox
  3290. ADD . /tmp/
  3291. RUN ls /tmp/Dockerfile
  3292. RUN ! ls /tmp/MyDockerfile
  3293. RUN ls /tmp/.dockerignore`
  3294. ctx, err := fakeContext(dockerfile, map[string]string{
  3295. "Dockerfile": "Should not use me",
  3296. "MyDockerfile": dockerfile,
  3297. ".dockerignore": "MyDockerfile\n",
  3298. })
  3299. if err != nil {
  3300. t.Fatal(err)
  3301. }
  3302. defer ctx.Close()
  3303. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3304. t.Fatalf("Didn't ignore MyDockerfile correctly:%s", err)
  3305. }
  3306. // now try it with ./MyDockerfile
  3307. ctx.Add(".dockerignore", "./MyDockerfile\n")
  3308. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3309. t.Fatalf("Didn't ignore ./MyDockerfile correctly:%s", err)
  3310. }
  3311. logDone("build - test .dockerignore of renamed Dockerfile")
  3312. }
  3313. func TestBuildDockerignoringDockerignore(t *testing.T) {
  3314. name := "testbuilddockerignoredockerignore"
  3315. defer deleteImages(name)
  3316. dockerfile := `
  3317. FROM busybox
  3318. ADD . /tmp/
  3319. RUN ! ls /tmp/.dockerignore
  3320. RUN ls /tmp/Dockerfile`
  3321. ctx, err := fakeContext(dockerfile, map[string]string{
  3322. "Dockerfile": dockerfile,
  3323. ".dockerignore": ".dockerignore\n",
  3324. })
  3325. defer ctx.Close()
  3326. if err != nil {
  3327. t.Fatal(err)
  3328. }
  3329. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3330. t.Fatalf("Didn't ignore .dockerignore correctly:%s", err)
  3331. }
  3332. logDone("build - test .dockerignore of .dockerignore")
  3333. }
  3334. func TestBuildDockerignoreTouchDockerfile(t *testing.T) {
  3335. var id1 string
  3336. var id2 string
  3337. name := "testbuilddockerignoretouchdockerfile"
  3338. defer deleteImages(name)
  3339. dockerfile := `
  3340. FROM busybox
  3341. ADD . /tmp/`
  3342. ctx, err := fakeContext(dockerfile, map[string]string{
  3343. "Dockerfile": dockerfile,
  3344. ".dockerignore": "Dockerfile\n",
  3345. })
  3346. defer ctx.Close()
  3347. if err != nil {
  3348. t.Fatal(err)
  3349. }
  3350. if id1, err = buildImageFromContext(name, ctx, true); err != nil {
  3351. t.Fatalf("Didn't build it correctly:%s", err)
  3352. }
  3353. if id2, err = buildImageFromContext(name, ctx, true); err != nil {
  3354. t.Fatalf("Didn't build it correctly:%s", err)
  3355. }
  3356. if id1 != id2 {
  3357. t.Fatalf("Didn't use the cache - 1")
  3358. }
  3359. // Now make sure touching Dockerfile doesn't invalidate the cache
  3360. if err = ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil {
  3361. t.Fatalf("Didn't add Dockerfile: %s", err)
  3362. }
  3363. if id2, err = buildImageFromContext(name, ctx, true); err != nil {
  3364. t.Fatalf("Didn't build it correctly:%s", err)
  3365. }
  3366. if id1 != id2 {
  3367. t.Fatalf("Didn't use the cache - 2")
  3368. }
  3369. // One more time but just 'touch' it instead of changing the content
  3370. if err = ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil {
  3371. t.Fatalf("Didn't add Dockerfile: %s", err)
  3372. }
  3373. if id2, err = buildImageFromContext(name, ctx, true); err != nil {
  3374. t.Fatalf("Didn't build it correctly:%s", err)
  3375. }
  3376. if id1 != id2 {
  3377. t.Fatalf("Didn't use the cache - 3")
  3378. }
  3379. logDone("build - test .dockerignore touch dockerfile")
  3380. }
  3381. func TestBuildDockerignoringWholeDir(t *testing.T) {
  3382. name := "testbuilddockerignorewholedir"
  3383. defer deleteImages(name)
  3384. dockerfile := `
  3385. FROM busybox
  3386. COPY . /
  3387. RUN [[ ! -e /.gitignore ]]
  3388. RUN [[ -f /Makefile ]]`
  3389. ctx, err := fakeContext(dockerfile, map[string]string{
  3390. "Dockerfile": "FROM scratch",
  3391. "Makefile": "all:",
  3392. ".dockerignore": ".*\n",
  3393. })
  3394. defer ctx.Close()
  3395. if err != nil {
  3396. t.Fatal(err)
  3397. }
  3398. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  3399. t.Fatal(err)
  3400. }
  3401. logDone("build - test .dockerignore whole dir with .*")
  3402. }
  3403. func TestBuildLineBreak(t *testing.T) {
  3404. name := "testbuildlinebreak"
  3405. defer deleteImages(name)
  3406. _, err := buildImage(name,
  3407. `FROM busybox
  3408. RUN sh -c 'echo root:testpass \
  3409. > /tmp/passwd'
  3410. RUN mkdir -p /var/run/sshd
  3411. RUN [ "$(cat /tmp/passwd)" = "root:testpass" ]
  3412. RUN [ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]`,
  3413. true)
  3414. if err != nil {
  3415. t.Fatal(err)
  3416. }
  3417. logDone("build - line break with \\")
  3418. }
  3419. func TestBuildEOLInLine(t *testing.T) {
  3420. name := "testbuildeolinline"
  3421. defer deleteImages(name)
  3422. _, err := buildImage(name,
  3423. `FROM busybox
  3424. RUN sh -c 'echo root:testpass > /tmp/passwd'
  3425. RUN echo "foo \n bar"; echo "baz"
  3426. RUN mkdir -p /var/run/sshd
  3427. RUN [ "$(cat /tmp/passwd)" = "root:testpass" ]
  3428. RUN [ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]`,
  3429. true)
  3430. if err != nil {
  3431. t.Fatal(err)
  3432. }
  3433. logDone("build - end of line in dockerfile instruction")
  3434. }
  3435. func TestBuildCommentsShebangs(t *testing.T) {
  3436. name := "testbuildcomments"
  3437. defer deleteImages(name)
  3438. _, err := buildImage(name,
  3439. `FROM busybox
  3440. # This is an ordinary comment.
  3441. RUN { echo '#!/bin/sh'; echo 'echo hello world'; } > /hello.sh
  3442. RUN [ ! -x /hello.sh ]
  3443. # comment with line break \
  3444. RUN chmod +x /hello.sh
  3445. RUN [ -x /hello.sh ]
  3446. RUN [ "$(cat /hello.sh)" = $'#!/bin/sh\necho hello world' ]
  3447. RUN [ "$(/hello.sh)" = "hello world" ]`,
  3448. true)
  3449. if err != nil {
  3450. t.Fatal(err)
  3451. }
  3452. logDone("build - comments and shebangs")
  3453. }
  3454. func TestBuildUsersAndGroups(t *testing.T) {
  3455. name := "testbuildusers"
  3456. defer deleteImages(name)
  3457. _, err := buildImage(name,
  3458. `FROM busybox
  3459. # Make sure our defaults work
  3460. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)" = '0:0/root:root' ]
  3461. # 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)
  3462. USER root
  3463. RUN [ "$(id -G):$(id -Gn)" = '0 10:root wheel' ]
  3464. # Setup dockerio user and group
  3465. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  3466. RUN echo 'dockerio:x:1001:' >> /etc/group
  3467. # Make sure we can switch to our user and all the information is exactly as we expect it to be
  3468. USER dockerio
  3469. RUN id -G
  3470. RUN id -Gn
  3471. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3472. # Switch back to root and double check that worked exactly as we might expect it to
  3473. USER root
  3474. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '0:0/root:root/0 10:root wheel' ]
  3475. # Add a "supplementary" group for our dockerio user
  3476. RUN echo 'supplementary:x:1002:dockerio' >> /etc/group
  3477. # ... and then go verify that we get it like we expect
  3478. USER dockerio
  3479. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  3480. USER 1001
  3481. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  3482. # super test the new "user:group" syntax
  3483. USER dockerio:dockerio
  3484. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3485. USER 1001:dockerio
  3486. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3487. USER dockerio:1001
  3488. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3489. USER 1001:1001
  3490. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3491. USER dockerio:supplementary
  3492. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3493. USER dockerio:1002
  3494. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3495. USER 1001:supplementary
  3496. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3497. USER 1001:1002
  3498. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3499. # make sure unknown uid/gid still works properly
  3500. USER 1042:1043
  3501. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1042:1043/1042:1043/1043:1043' ]`,
  3502. true)
  3503. if err != nil {
  3504. t.Fatal(err)
  3505. }
  3506. logDone("build - users and groups")
  3507. }
  3508. func TestBuildEnvUsage(t *testing.T) {
  3509. name := "testbuildenvusage"
  3510. defer deleteImages(name)
  3511. dockerfile := `FROM busybox
  3512. ENV HOME /root
  3513. ENV PATH $HOME/bin:$PATH
  3514. ENV PATH /tmp:$PATH
  3515. RUN [ "$PATH" = "/tmp:$HOME/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ]
  3516. ENV FOO /foo/baz
  3517. ENV BAR /bar
  3518. ENV BAZ $BAR
  3519. ENV FOOPATH $PATH:$FOO
  3520. RUN [ "$BAR" = "$BAZ" ]
  3521. RUN [ "$FOOPATH" = "$PATH:/foo/baz" ]
  3522. ENV FROM hello/docker/world
  3523. ENV TO /docker/world/hello
  3524. ADD $FROM $TO
  3525. RUN [ "$(cat $TO)" = "hello" ]
  3526. ENV abc=def
  3527. ENV ghi=$abc
  3528. RUN [ "$ghi" = "def" ]
  3529. `
  3530. ctx, err := fakeContext(dockerfile, map[string]string{
  3531. "hello/docker/world": "hello",
  3532. })
  3533. if err != nil {
  3534. t.Fatal(err)
  3535. }
  3536. defer ctx.Close()
  3537. _, err = buildImageFromContext(name, ctx, true)
  3538. if err != nil {
  3539. t.Fatal(err)
  3540. }
  3541. logDone("build - environment variables usage")
  3542. }
  3543. func TestBuildEnvUsage2(t *testing.T) {
  3544. name := "testbuildenvusage2"
  3545. defer deleteImages(name)
  3546. dockerfile := `FROM busybox
  3547. ENV abc=def
  3548. RUN [ "$abc" = "def" ]
  3549. ENV def="hello world"
  3550. RUN [ "$def" = "hello world" ]
  3551. ENV def=hello\ world
  3552. RUN [ "$def" = "hello world" ]
  3553. ENV v1=abc v2="hi there"
  3554. RUN [ "$v1" = "abc" ]
  3555. RUN [ "$v2" = "hi there" ]
  3556. ENV v3='boogie nights' v4="with'quotes too"
  3557. RUN [ "$v3" = "boogie nights" ]
  3558. RUN [ "$v4" = "with'quotes too" ]
  3559. ENV abc=zzz FROM=hello/docker/world
  3560. ENV abc=zzz TO=/docker/world/hello
  3561. ADD $FROM $TO
  3562. RUN [ "$(cat $TO)" = "hello" ]
  3563. ENV abc "zzz"
  3564. RUN [ $abc = "zzz" ]
  3565. ENV abc 'yyy'
  3566. RUN [ $abc = 'yyy' ]
  3567. ENV abc=
  3568. RUN [ "$abc" = "" ]
  3569. # use grep to make sure if the builder substitutes \$foo by mistake
  3570. # we don't get a false positive
  3571. ENV abc=\$foo
  3572. RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep foo)
  3573. ENV abc \$foo
  3574. RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep foo)
  3575. ENV abc=\'foo\'
  3576. RUN [ "$abc" = "'foo'" ]
  3577. ENV abc=\"foo\"
  3578. RUN [ "$abc" = "\"foo\"" ]
  3579. ENV abc "foo"
  3580. RUN [ "$abc" = "foo" ]
  3581. ENV abc 'foo'
  3582. RUN [ "$abc" = 'foo' ]
  3583. ENV abc \'foo\'
  3584. RUN [ "$abc" = "'foo'" ]
  3585. ENV abc \"foo\"
  3586. RUN [ "$abc" = '"foo"' ]
  3587. ENV e1=bar
  3588. ENV e2=$e1
  3589. ENV e3=$e11
  3590. ENV e4=\$e1
  3591. ENV e5=\$e11
  3592. RUN [ "$e0,$e1,$e2,$e3,$e4,$e5" = ',bar,bar,,$e1,$e11' ]
  3593. ENV ee1 bar
  3594. ENV ee2 $ee1
  3595. ENV ee3 $ee11
  3596. ENV ee4 \$ee1
  3597. ENV ee5 \$ee11
  3598. RUN [ "$ee1,$ee2,$ee3,$ee4,$ee5" = 'bar,bar,,$ee1,$ee11' ]
  3599. ENV eee1="foo"
  3600. ENV eee2='foo'
  3601. ENV eee3 "foo"
  3602. ENV eee4 'foo'
  3603. RUN [ "$eee1,$eee2,$eee3,$eee4" = 'foo,foo,foo,foo' ]
  3604. `
  3605. ctx, err := fakeContext(dockerfile, map[string]string{
  3606. "hello/docker/world": "hello",
  3607. })
  3608. if err != nil {
  3609. t.Fatal(err)
  3610. }
  3611. defer ctx.Close()
  3612. _, err = buildImageFromContext(name, ctx, true)
  3613. if err != nil {
  3614. t.Fatal(err)
  3615. }
  3616. logDone("build - environment variables usage2")
  3617. }
  3618. func TestBuildAddScript(t *testing.T) {
  3619. name := "testbuildaddscript"
  3620. defer deleteImages(name)
  3621. dockerfile := `
  3622. FROM busybox
  3623. ADD test /test
  3624. RUN ["chmod","+x","/test"]
  3625. RUN ["/test"]
  3626. RUN [ "$(cat /testfile)" = 'test!' ]`
  3627. ctx, err := fakeContext(dockerfile, map[string]string{
  3628. "test": "#!/bin/sh\necho 'test!' > /testfile",
  3629. })
  3630. if err != nil {
  3631. t.Fatal(err)
  3632. }
  3633. defer ctx.Close()
  3634. _, err = buildImageFromContext(name, ctx, true)
  3635. if err != nil {
  3636. t.Fatal(err)
  3637. }
  3638. logDone("build - add and run script")
  3639. }
  3640. func TestBuildAddTar(t *testing.T) {
  3641. name := "testbuildaddtar"
  3642. defer deleteImages(name)
  3643. ctx := func() *FakeContext {
  3644. dockerfile := `
  3645. FROM busybox
  3646. ADD test.tar /
  3647. RUN cat /test/foo | grep Hi
  3648. ADD test.tar /test.tar
  3649. RUN cat /test.tar/test/foo | grep Hi
  3650. ADD test.tar /unlikely-to-exist
  3651. RUN cat /unlikely-to-exist/test/foo | grep Hi
  3652. ADD test.tar /unlikely-to-exist-trailing-slash/
  3653. RUN cat /unlikely-to-exist-trailing-slash/test/foo | grep Hi
  3654. RUN mkdir /existing-directory
  3655. ADD test.tar /existing-directory
  3656. RUN cat /existing-directory/test/foo | grep Hi
  3657. ADD test.tar /existing-directory-trailing-slash/
  3658. RUN cat /existing-directory-trailing-slash/test/foo | grep Hi`
  3659. tmpDir, err := ioutil.TempDir("", "fake-context")
  3660. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3661. if err != nil {
  3662. t.Fatalf("failed to create test.tar archive: %v", err)
  3663. }
  3664. defer testTar.Close()
  3665. tw := tar.NewWriter(testTar)
  3666. if err := tw.WriteHeader(&tar.Header{
  3667. Name: "test/foo",
  3668. Size: 2,
  3669. }); err != nil {
  3670. t.Fatalf("failed to write tar file header: %v", err)
  3671. }
  3672. if _, err := tw.Write([]byte("Hi")); err != nil {
  3673. t.Fatalf("failed to write tar file content: %v", err)
  3674. }
  3675. if err := tw.Close(); err != nil {
  3676. t.Fatalf("failed to close tar archive: %v", err)
  3677. }
  3678. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3679. t.Fatalf("failed to open destination dockerfile: %v", err)
  3680. }
  3681. return fakeContextFromDir(tmpDir)
  3682. }()
  3683. defer ctx.Close()
  3684. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3685. t.Fatalf("build failed to complete for TestBuildAddTar: %v", err)
  3686. }
  3687. logDone("build - ADD tar")
  3688. }
  3689. func TestBuildAddTarXz(t *testing.T) {
  3690. name := "testbuildaddtarxz"
  3691. defer deleteImages(name)
  3692. ctx := func() *FakeContext {
  3693. dockerfile := `
  3694. FROM busybox
  3695. ADD test.tar.xz /
  3696. RUN cat /test/foo | grep Hi`
  3697. tmpDir, err := ioutil.TempDir("", "fake-context")
  3698. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3699. if err != nil {
  3700. t.Fatalf("failed to create test.tar archive: %v", err)
  3701. }
  3702. defer testTar.Close()
  3703. tw := tar.NewWriter(testTar)
  3704. if err := tw.WriteHeader(&tar.Header{
  3705. Name: "test/foo",
  3706. Size: 2,
  3707. }); err != nil {
  3708. t.Fatalf("failed to write tar file header: %v", err)
  3709. }
  3710. if _, err := tw.Write([]byte("Hi")); err != nil {
  3711. t.Fatalf("failed to write tar file content: %v", err)
  3712. }
  3713. if err := tw.Close(); err != nil {
  3714. t.Fatalf("failed to close tar archive: %v", err)
  3715. }
  3716. xzCompressCmd := exec.Command("xz", "-k", "test.tar")
  3717. xzCompressCmd.Dir = tmpDir
  3718. out, _, err := runCommandWithOutput(xzCompressCmd)
  3719. if err != nil {
  3720. t.Fatal(err, out)
  3721. }
  3722. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3723. t.Fatalf("failed to open destination dockerfile: %v", err)
  3724. }
  3725. return fakeContextFromDir(tmpDir)
  3726. }()
  3727. defer ctx.Close()
  3728. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3729. t.Fatalf("build failed to complete for TestBuildAddTarXz: %v", err)
  3730. }
  3731. logDone("build - ADD tar.xz")
  3732. }
  3733. func TestBuildAddTarXzGz(t *testing.T) {
  3734. name := "testbuildaddtarxzgz"
  3735. defer deleteImages(name)
  3736. ctx := func() *FakeContext {
  3737. dockerfile := `
  3738. FROM busybox
  3739. ADD test.tar.xz.gz /
  3740. RUN ls /test.tar.xz.gz`
  3741. tmpDir, err := ioutil.TempDir("", "fake-context")
  3742. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3743. if err != nil {
  3744. t.Fatalf("failed to create test.tar archive: %v", err)
  3745. }
  3746. defer testTar.Close()
  3747. tw := tar.NewWriter(testTar)
  3748. if err := tw.WriteHeader(&tar.Header{
  3749. Name: "test/foo",
  3750. Size: 2,
  3751. }); err != nil {
  3752. t.Fatalf("failed to write tar file header: %v", err)
  3753. }
  3754. if _, err := tw.Write([]byte("Hi")); err != nil {
  3755. t.Fatalf("failed to write tar file content: %v", err)
  3756. }
  3757. if err := tw.Close(); err != nil {
  3758. t.Fatalf("failed to close tar archive: %v", err)
  3759. }
  3760. xzCompressCmd := exec.Command("xz", "-k", "test.tar")
  3761. xzCompressCmd.Dir = tmpDir
  3762. out, _, err := runCommandWithOutput(xzCompressCmd)
  3763. if err != nil {
  3764. t.Fatal(err, out)
  3765. }
  3766. gzipCompressCmd := exec.Command("gzip", "test.tar.xz")
  3767. gzipCompressCmd.Dir = tmpDir
  3768. out, _, err = runCommandWithOutput(gzipCompressCmd)
  3769. if err != nil {
  3770. t.Fatal(err, out)
  3771. }
  3772. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3773. t.Fatalf("failed to open destination dockerfile: %v", err)
  3774. }
  3775. return fakeContextFromDir(tmpDir)
  3776. }()
  3777. defer ctx.Close()
  3778. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3779. t.Fatalf("build failed to complete for TestBuildAddTarXz: %v", err)
  3780. }
  3781. logDone("build - ADD tar.xz.gz")
  3782. }
  3783. func TestBuildFromGIT(t *testing.T) {
  3784. name := "testbuildfromgit"
  3785. defer deleteImages(name)
  3786. git, err := fakeGIT("repo", map[string]string{
  3787. "Dockerfile": `FROM busybox
  3788. ADD first /first
  3789. RUN [ -f /first ]
  3790. MAINTAINER docker`,
  3791. "first": "test git data",
  3792. }, true)
  3793. if err != nil {
  3794. t.Fatal(err)
  3795. }
  3796. defer git.Close()
  3797. _, err = buildImageFromPath(name, git.RepoURL, true)
  3798. if err != nil {
  3799. t.Fatal(err)
  3800. }
  3801. res, err := inspectField(name, "Author")
  3802. if err != nil {
  3803. t.Fatal(err)
  3804. }
  3805. if res != "docker" {
  3806. t.Fatalf("Maintainer should be docker, got %s", res)
  3807. }
  3808. logDone("build - build from GIT")
  3809. }
  3810. func TestBuildCleanupCmdOnEntrypoint(t *testing.T) {
  3811. name := "testbuildcmdcleanuponentrypoint"
  3812. defer deleteImages(name)
  3813. if _, err := buildImage(name,
  3814. `FROM scratch
  3815. CMD ["test"]
  3816. ENTRYPOINT ["echo"]`,
  3817. true); err != nil {
  3818. t.Fatal(err)
  3819. }
  3820. if _, err := buildImage(name,
  3821. fmt.Sprintf(`FROM %s
  3822. ENTRYPOINT ["cat"]`, name),
  3823. true); err != nil {
  3824. t.Fatal(err)
  3825. }
  3826. res, err := inspectField(name, "Config.Cmd")
  3827. if err != nil {
  3828. t.Fatal(err)
  3829. }
  3830. if expected := "<no value>"; res != expected {
  3831. t.Fatalf("Cmd %s, expected %s", res, expected)
  3832. }
  3833. res, err = inspectField(name, "Config.Entrypoint")
  3834. if err != nil {
  3835. t.Fatal(err)
  3836. }
  3837. if expected := "[cat]"; res != expected {
  3838. t.Fatalf("Entrypoint %s, expected %s", res, expected)
  3839. }
  3840. logDone("build - cleanup cmd on ENTRYPOINT")
  3841. }
  3842. func TestBuildClearCmd(t *testing.T) {
  3843. name := "testbuildclearcmd"
  3844. defer deleteImages(name)
  3845. _, err := buildImage(name,
  3846. `From scratch
  3847. ENTRYPOINT ["/bin/bash"]
  3848. CMD []`,
  3849. true)
  3850. if err != nil {
  3851. t.Fatal(err)
  3852. }
  3853. res, err := inspectFieldJSON(name, "Config.Cmd")
  3854. if err != nil {
  3855. t.Fatal(err)
  3856. }
  3857. if res != "[]" {
  3858. t.Fatalf("Cmd %s, expected %s", res, "[]")
  3859. }
  3860. logDone("build - clearcmd")
  3861. }
  3862. func TestBuildEmptyCmd(t *testing.T) {
  3863. name := "testbuildemptycmd"
  3864. defer deleteImages(name)
  3865. if _, err := buildImage(name, "FROM scratch\nMAINTAINER quux\n", true); err != nil {
  3866. t.Fatal(err)
  3867. }
  3868. res, err := inspectFieldJSON(name, "Config.Cmd")
  3869. if err != nil {
  3870. t.Fatal(err)
  3871. }
  3872. if res != "null" {
  3873. t.Fatalf("Cmd %s, expected %s", res, "null")
  3874. }
  3875. logDone("build - empty cmd")
  3876. }
  3877. func TestBuildOnBuildOutput(t *testing.T) {
  3878. name := "testbuildonbuildparent"
  3879. defer deleteImages(name)
  3880. if _, err := buildImage(name, "FROM busybox\nONBUILD RUN echo foo\n", true); err != nil {
  3881. t.Fatal(err)
  3882. }
  3883. childname := "testbuildonbuildchild"
  3884. defer deleteImages(childname)
  3885. _, out, err := buildImageWithOut(name, "FROM "+name+"\nMAINTAINER quux\n", true)
  3886. if err != nil {
  3887. t.Fatal(err)
  3888. }
  3889. if !strings.Contains(out, "Trigger 0, RUN echo foo") {
  3890. t.Fatal("failed to find the ONBUILD output", out)
  3891. }
  3892. logDone("build - onbuild output")
  3893. }
  3894. func TestBuildInvalidTag(t *testing.T) {
  3895. name := "abcd:" + stringutils.GenerateRandomAlphaOnlyString(200)
  3896. defer deleteImages(name)
  3897. _, out, err := buildImageWithOut(name, "FROM scratch\nMAINTAINER quux\n", true)
  3898. // if the error doesnt check for illegal tag name, or the image is built
  3899. // then this should fail
  3900. if !strings.Contains(out, "Illegal tag name") || strings.Contains(out, "Sending build context to Docker daemon") {
  3901. t.Fatalf("failed to stop before building. Error: %s, Output: %s", err, out)
  3902. }
  3903. logDone("build - invalid tag")
  3904. }
  3905. func TestBuildCmdShDashC(t *testing.T) {
  3906. name := "testbuildcmdshc"
  3907. defer deleteImages(name)
  3908. if _, err := buildImage(name, "FROM busybox\nCMD echo cmd\n", true); err != nil {
  3909. t.Fatal(err)
  3910. }
  3911. res, err := inspectFieldJSON(name, "Config.Cmd")
  3912. if err != nil {
  3913. t.Fatal(err, res)
  3914. }
  3915. expected := `["/bin/sh","-c","echo cmd"]`
  3916. if res != expected {
  3917. t.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  3918. }
  3919. logDone("build - cmd should have sh -c for non-json")
  3920. }
  3921. func TestBuildCmdSpaces(t *testing.T) {
  3922. // Test to make sure that when we strcat arrays we take into account
  3923. // the arg separator to make sure ["echo","hi"] and ["echo hi"] don't
  3924. // look the same
  3925. name := "testbuildcmdspaces"
  3926. defer deleteImages(name)
  3927. var id1 string
  3928. var id2 string
  3929. var err error
  3930. if id1, err = buildImage(name, "FROM busybox\nCMD [\"echo hi\"]\n", true); err != nil {
  3931. t.Fatal(err)
  3932. }
  3933. if id2, err = buildImage(name, "FROM busybox\nCMD [\"echo\", \"hi\"]\n", true); err != nil {
  3934. t.Fatal(err)
  3935. }
  3936. if id1 == id2 {
  3937. t.Fatal("Should not have resulted in the same CMD")
  3938. }
  3939. // Now do the same with ENTRYPOINT
  3940. if id1, err = buildImage(name, "FROM busybox\nENTRYPOINT [\"echo hi\"]\n", true); err != nil {
  3941. t.Fatal(err)
  3942. }
  3943. if id2, err = buildImage(name, "FROM busybox\nENTRYPOINT [\"echo\", \"hi\"]\n", true); err != nil {
  3944. t.Fatal(err)
  3945. }
  3946. if id1 == id2 {
  3947. t.Fatal("Should not have resulted in the same ENTRYPOINT")
  3948. }
  3949. logDone("build - cmd with spaces")
  3950. }
  3951. func TestBuildCmdJSONNoShDashC(t *testing.T) {
  3952. name := "testbuildcmdjson"
  3953. defer deleteImages(name)
  3954. if _, err := buildImage(name, "FROM busybox\nCMD [\"echo\", \"cmd\"]", true); err != nil {
  3955. t.Fatal(err)
  3956. }
  3957. res, err := inspectFieldJSON(name, "Config.Cmd")
  3958. if err != nil {
  3959. t.Fatal(err, res)
  3960. }
  3961. expected := `["echo","cmd"]`
  3962. if res != expected {
  3963. t.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  3964. }
  3965. logDone("build - cmd should not have /bin/sh -c for json")
  3966. }
  3967. func TestBuildErrorInvalidInstruction(t *testing.T) {
  3968. name := "testbuildignoreinvalidinstruction"
  3969. defer deleteImages(name)
  3970. out, _, err := buildImageWithOut(name, "FROM busybox\nfoo bar", true)
  3971. if err == nil {
  3972. t.Fatalf("Should have failed: %s", out)
  3973. }
  3974. logDone("build - error invalid Dockerfile instruction")
  3975. }
  3976. func TestBuildEntrypointInheritance(t *testing.T) {
  3977. defer deleteImages("parent", "child")
  3978. defer deleteAllContainers()
  3979. if _, err := buildImage("parent", `
  3980. FROM busybox
  3981. ENTRYPOINT exit 130
  3982. `, true); err != nil {
  3983. t.Fatal(err)
  3984. }
  3985. status, _ := runCommand(exec.Command(dockerBinary, "run", "parent"))
  3986. if status != 130 {
  3987. t.Fatalf("expected exit code 130 but received %d", status)
  3988. }
  3989. if _, err := buildImage("child", `
  3990. FROM parent
  3991. ENTRYPOINT exit 5
  3992. `, true); err != nil {
  3993. t.Fatal(err)
  3994. }
  3995. status, _ = runCommand(exec.Command(dockerBinary, "run", "child"))
  3996. if status != 5 {
  3997. t.Fatalf("expected exit code 5 but received %d", status)
  3998. }
  3999. logDone("build - clear entrypoint")
  4000. }
  4001. func TestBuildEntrypointInheritanceInspect(t *testing.T) {
  4002. var (
  4003. name = "testbuildepinherit"
  4004. name2 = "testbuildepinherit2"
  4005. expected = `["/bin/sh","-c","echo quux"]`
  4006. )
  4007. defer deleteImages(name, name2)
  4008. defer deleteAllContainers()
  4009. if _, err := buildImage(name, "FROM busybox\nENTRYPOINT /foo/bar", true); err != nil {
  4010. t.Fatal(err)
  4011. }
  4012. if _, err := buildImage(name2, fmt.Sprintf("FROM %s\nENTRYPOINT echo quux", name), true); err != nil {
  4013. t.Fatal(err)
  4014. }
  4015. res, err := inspectFieldJSON(name2, "Config.Entrypoint")
  4016. if err != nil {
  4017. t.Fatal(err, res)
  4018. }
  4019. if res != expected {
  4020. t.Fatalf("Expected value %s not in Config.Entrypoint: %s", expected, res)
  4021. }
  4022. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-t", name2))
  4023. if err != nil {
  4024. t.Fatal(err, out)
  4025. }
  4026. expected = "quux"
  4027. if strings.TrimSpace(out) != expected {
  4028. t.Fatalf("Expected output is %s, got %s", expected, out)
  4029. }
  4030. logDone("build - entrypoint override inheritance properly")
  4031. }
  4032. func TestBuildRunShEntrypoint(t *testing.T) {
  4033. name := "testbuildentrypoint"
  4034. defer deleteImages(name)
  4035. _, err := buildImage(name,
  4036. `FROM busybox
  4037. ENTRYPOINT /bin/echo`,
  4038. true)
  4039. if err != nil {
  4040. t.Fatal(err)
  4041. }
  4042. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--rm", name))
  4043. if err != nil {
  4044. t.Fatal(err, out)
  4045. }
  4046. logDone("build - entrypoint with /bin/echo running successfully")
  4047. }
  4048. func TestBuildExoticShellInterpolation(t *testing.T) {
  4049. name := "testbuildexoticshellinterpolation"
  4050. defer deleteImages(name)
  4051. _, err := buildImage(name, `
  4052. FROM busybox
  4053. ENV SOME_VAR a.b.c
  4054. RUN [ "$SOME_VAR" = 'a.b.c' ]
  4055. RUN [ "${SOME_VAR}" = 'a.b.c' ]
  4056. RUN [ "${SOME_VAR%.*}" = 'a.b' ]
  4057. RUN [ "${SOME_VAR%%.*}" = 'a' ]
  4058. RUN [ "${SOME_VAR#*.}" = 'b.c' ]
  4059. RUN [ "${SOME_VAR##*.}" = 'c' ]
  4060. RUN [ "${SOME_VAR/c/d}" = 'a.b.d' ]
  4061. RUN [ "${#SOME_VAR}" = '5' ]
  4062. RUN [ "${SOME_UNSET_VAR:-$SOME_VAR}" = 'a.b.c' ]
  4063. RUN [ "${SOME_VAR:+Version: ${SOME_VAR}}" = 'Version: a.b.c' ]
  4064. RUN [ "${SOME_UNSET_VAR:+${SOME_VAR}}" = '' ]
  4065. RUN [ "${SOME_UNSET_VAR:-${SOME_VAR:-d.e.f}}" = 'a.b.c' ]
  4066. `, false)
  4067. if err != nil {
  4068. t.Fatal(err)
  4069. }
  4070. logDone("build - exotic shell interpolation")
  4071. }
  4072. func TestBuildVerifySingleQuoteFails(t *testing.T) {
  4073. // This testcase is supposed to generate an error because the
  4074. // JSON array we're passing in on the CMD uses single quotes instead
  4075. // of double quotes (per the JSON spec). This means we interpret it
  4076. // as a "string" insead of "JSON array" and pass it on to "sh -c" and
  4077. // it should barf on it.
  4078. name := "testbuildsinglequotefails"
  4079. defer deleteImages(name)
  4080. defer deleteAllContainers()
  4081. _, err := buildImage(name,
  4082. `FROM busybox
  4083. CMD [ '/bin/sh', '-c', 'echo hi' ]`,
  4084. true)
  4085. _, _, err = runCommandWithOutput(exec.Command(dockerBinary, "run", "--rm", name))
  4086. if err == nil {
  4087. t.Fatal("The image was not supposed to be able to run")
  4088. }
  4089. logDone("build - verify single quotes break the build")
  4090. }
  4091. func TestBuildVerboseOut(t *testing.T) {
  4092. name := "testbuildverboseout"
  4093. defer deleteImages(name)
  4094. _, out, err := buildImageWithOut(name,
  4095. `FROM busybox
  4096. RUN echo 123`,
  4097. false)
  4098. if err != nil {
  4099. t.Fatal(err)
  4100. }
  4101. if !strings.Contains(out, "\n123\n") {
  4102. t.Fatalf("Output should contain %q: %q", "123", out)
  4103. }
  4104. logDone("build - verbose output from commands")
  4105. }
  4106. func TestBuildWithTabs(t *testing.T) {
  4107. name := "testbuildwithtabs"
  4108. defer deleteImages(name)
  4109. _, err := buildImage(name,
  4110. "FROM busybox\nRUN echo\tone\t\ttwo", true)
  4111. if err != nil {
  4112. t.Fatal(err)
  4113. }
  4114. res, err := inspectFieldJSON(name, "ContainerConfig.Cmd")
  4115. if err != nil {
  4116. t.Fatal(err)
  4117. }
  4118. expected1 := `["/bin/sh","-c","echo\tone\t\ttwo"]`
  4119. expected2 := `["/bin/sh","-c","echo\u0009one\u0009\u0009two"]` // syntactically equivalent, and what Go 1.3 generates
  4120. if res != expected1 && res != expected2 {
  4121. t.Fatalf("Missing tabs.\nGot: %s\nExp: %s or %s", res, expected1, expected2)
  4122. }
  4123. logDone("build - with tabs")
  4124. }
  4125. func TestBuildLabels(t *testing.T) {
  4126. name := "testbuildlabel"
  4127. expected := `{"License":"GPL","Vendor":"Acme"}`
  4128. defer deleteImages(name)
  4129. _, err := buildImage(name,
  4130. `FROM busybox
  4131. LABEL Vendor=Acme
  4132. LABEL License GPL`,
  4133. true)
  4134. if err != nil {
  4135. t.Fatal(err)
  4136. }
  4137. res, err := inspectFieldJSON(name, "Config.Labels")
  4138. if err != nil {
  4139. t.Fatal(err)
  4140. }
  4141. if res != expected {
  4142. t.Fatalf("Labels %s, expected %s", res, expected)
  4143. }
  4144. logDone("build - label")
  4145. }
  4146. func TestBuildLabelsCache(t *testing.T) {
  4147. name := "testbuildlabelcache"
  4148. defer deleteImages(name)
  4149. id1, err := buildImage(name,
  4150. `FROM busybox
  4151. LABEL Vendor=Acme`, false)
  4152. if err != nil {
  4153. t.Fatalf("Build 1 should have worked: %v", err)
  4154. }
  4155. id2, err := buildImage(name,
  4156. `FROM busybox
  4157. LABEL Vendor=Acme`, true)
  4158. if err != nil || id1 != id2 {
  4159. t.Fatalf("Build 2 should have worked & used cache(%s,%s): %v", id1, id2, err)
  4160. }
  4161. id2, err = buildImage(name,
  4162. `FROM busybox
  4163. LABEL Vendor=Acme1`, true)
  4164. if err != nil || id1 == id2 {
  4165. t.Fatalf("Build 3 should have worked & NOT used cache(%s,%s): %v", id1, id2, err)
  4166. }
  4167. id2, err = buildImage(name,
  4168. `FROM busybox
  4169. LABEL Vendor Acme`, true) // Note: " " and "=" should be same
  4170. if err != nil || id1 != id2 {
  4171. t.Fatalf("Build 4 should have worked & used cache(%s,%s): %v", id1, id2, err)
  4172. }
  4173. // Now make sure the cache isn't used by mistake
  4174. id1, err = buildImage(name,
  4175. `FROM busybox
  4176. LABEL f1=b1 f2=b2`, false)
  4177. if err != nil {
  4178. t.Fatalf("Build 5 should have worked: %q", err)
  4179. }
  4180. id2, err = buildImage(name,
  4181. `FROM busybox
  4182. LABEL f1="b1 f2=b2"`, true)
  4183. if err != nil || id1 == id2 {
  4184. t.Fatalf("Build 6 should have worked & NOT used the cache(%s,%s): %q", id1, id2, err)
  4185. }
  4186. logDone("build - label cache")
  4187. }
  4188. func TestBuildStderr(t *testing.T) {
  4189. // This test just makes sure that no non-error output goes
  4190. // to stderr
  4191. name := "testbuildstderr"
  4192. defer deleteImages(name)
  4193. _, _, stderr, err := buildImageWithStdoutStderr(name,
  4194. "FROM busybox\nRUN echo one", true)
  4195. if err != nil {
  4196. t.Fatal(err)
  4197. }
  4198. if runtime.GOOS == "windows" {
  4199. // stderr might contain a security warning on windows
  4200. lines := strings.Split(stderr, "\n")
  4201. for _, v := range lines {
  4202. if v != "" && !strings.Contains(v, "SECURITY WARNING:") {
  4203. t.Fatalf("Stderr contains unexpected output line: %q", v)
  4204. }
  4205. }
  4206. } else {
  4207. if stderr != "" {
  4208. t.Fatalf("Stderr should have been empty, instead its: %q", stderr)
  4209. }
  4210. }
  4211. logDone("build - testing stderr")
  4212. }
  4213. func TestBuildChownSingleFile(t *testing.T) {
  4214. testRequires(t, UnixCli) // test uses chown: not available on windows
  4215. name := "testbuildchownsinglefile"
  4216. defer deleteImages(name)
  4217. ctx, err := fakeContext(`
  4218. FROM busybox
  4219. COPY test /
  4220. RUN ls -l /test
  4221. RUN [ $(ls -l /test | awk '{print $3":"$4}') = 'root:root' ]
  4222. `, map[string]string{
  4223. "test": "test",
  4224. })
  4225. if err != nil {
  4226. t.Fatal(err)
  4227. }
  4228. defer ctx.Close()
  4229. if err := os.Chown(filepath.Join(ctx.Dir, "test"), 4242, 4242); err != nil {
  4230. t.Fatal(err)
  4231. }
  4232. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  4233. t.Fatal(err)
  4234. }
  4235. logDone("build - change permission on single file")
  4236. }
  4237. func TestBuildSymlinkBreakout(t *testing.T) {
  4238. name := "testbuildsymlinkbreakout"
  4239. tmpdir, err := ioutil.TempDir("", name)
  4240. if err != nil {
  4241. t.Fatal(err)
  4242. }
  4243. defer os.RemoveAll(tmpdir)
  4244. ctx := filepath.Join(tmpdir, "context")
  4245. if err := os.MkdirAll(ctx, 0755); err != nil {
  4246. t.Fatal(err)
  4247. }
  4248. if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte(`
  4249. from busybox
  4250. add symlink.tar /
  4251. add inject /symlink/
  4252. `), 0644); err != nil {
  4253. t.Fatal(err)
  4254. }
  4255. inject := filepath.Join(ctx, "inject")
  4256. if err := ioutil.WriteFile(inject, nil, 0644); err != nil {
  4257. t.Fatal(err)
  4258. }
  4259. f, err := os.Create(filepath.Join(ctx, "symlink.tar"))
  4260. if err != nil {
  4261. t.Fatal(err)
  4262. }
  4263. w := tar.NewWriter(f)
  4264. w.WriteHeader(&tar.Header{
  4265. Name: "symlink2",
  4266. Typeflag: tar.TypeSymlink,
  4267. Linkname: "/../../../../../../../../../../../../../../",
  4268. Uid: os.Getuid(),
  4269. Gid: os.Getgid(),
  4270. })
  4271. w.WriteHeader(&tar.Header{
  4272. Name: "symlink",
  4273. Typeflag: tar.TypeSymlink,
  4274. Linkname: filepath.Join("symlink2", tmpdir),
  4275. Uid: os.Getuid(),
  4276. Gid: os.Getgid(),
  4277. })
  4278. w.Close()
  4279. f.Close()
  4280. if _, err := buildImageFromContext(name, fakeContextFromDir(ctx), false); err != nil {
  4281. t.Fatal(err)
  4282. }
  4283. if _, err := os.Lstat(filepath.Join(tmpdir, "inject")); err == nil {
  4284. t.Fatal("symlink breakout - inject")
  4285. } else if !os.IsNotExist(err) {
  4286. t.Fatalf("unexpected error: %v", err)
  4287. }
  4288. logDone("build - symlink breakout")
  4289. }
  4290. func TestBuildXZHost(t *testing.T) {
  4291. name := "testbuildxzhost"
  4292. defer deleteImages(name)
  4293. ctx, err := fakeContext(`
  4294. FROM busybox
  4295. ADD xz /usr/local/sbin/
  4296. RUN chmod 755 /usr/local/sbin/xz
  4297. ADD test.xz /
  4298. RUN [ ! -e /injected ]`,
  4299. map[string]string{
  4300. "test.xz": "\xfd\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00" +
  4301. "\x21\x01\x16\x00\x00\x00\x74\x2f\xe5\xa3\x01\x00\x3f\xfd" +
  4302. "\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00\x21",
  4303. "xz": "#!/bin/sh\ntouch /injected",
  4304. })
  4305. if err != nil {
  4306. t.Fatal(err)
  4307. }
  4308. defer ctx.Close()
  4309. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  4310. t.Fatal(err)
  4311. }
  4312. logDone("build - xz host is being used")
  4313. }
  4314. func TestBuildVolumesRetainContents(t *testing.T) {
  4315. var (
  4316. name = "testbuildvolumescontent"
  4317. expected = "some text"
  4318. )
  4319. defer deleteImages(name)
  4320. ctx, err := fakeContext(`
  4321. FROM busybox
  4322. COPY content /foo/file
  4323. VOLUME /foo
  4324. CMD cat /foo/file`,
  4325. map[string]string{
  4326. "content": expected,
  4327. })
  4328. if err != nil {
  4329. t.Fatal(err)
  4330. }
  4331. defer ctx.Close()
  4332. if _, err := buildImageFromContext(name, ctx, false); err != nil {
  4333. t.Fatal(err)
  4334. }
  4335. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--rm", name))
  4336. if err != nil {
  4337. t.Fatal(err)
  4338. }
  4339. if out != expected {
  4340. t.Fatalf("expected file contents for /foo/file to be %q but received %q", expected, out)
  4341. }
  4342. logDone("build - volumes retain contents in build")
  4343. }
  4344. func TestBuildRenamedDockerfile(t *testing.T) {
  4345. defer deleteAllContainers()
  4346. ctx, err := fakeContext(`FROM busybox
  4347. RUN echo from Dockerfile`,
  4348. map[string]string{
  4349. "Dockerfile": "FROM busybox\nRUN echo from Dockerfile",
  4350. "files/Dockerfile": "FROM busybox\nRUN echo from files/Dockerfile",
  4351. "files/dFile": "FROM busybox\nRUN echo from files/dFile",
  4352. "dFile": "FROM busybox\nRUN echo from dFile",
  4353. "files/dFile2": "FROM busybox\nRUN echo from files/dFile2",
  4354. })
  4355. defer ctx.Close()
  4356. if err != nil {
  4357. t.Fatal(err)
  4358. }
  4359. out, _, err := dockerCmdInDir(t, ctx.Dir, "build", "-t", "test1", ".")
  4360. if err != nil {
  4361. t.Fatalf("Failed to build: %s\n%s", out, err)
  4362. }
  4363. if !strings.Contains(out, "from Dockerfile") {
  4364. t.Fatalf("test1 should have used Dockerfile, output:%s", out)
  4365. }
  4366. out, _, err = dockerCmdInDir(t, ctx.Dir, "build", "-f", filepath.Join("files", "Dockerfile"), "-t", "test2", ".")
  4367. if err != nil {
  4368. t.Fatal(err)
  4369. }
  4370. if !strings.Contains(out, "from files/Dockerfile") {
  4371. t.Fatalf("test2 should have used files/Dockerfile, output:%s", out)
  4372. }
  4373. out, _, err = dockerCmdInDir(t, ctx.Dir, "build", fmt.Sprintf("--file=%s", filepath.Join("files", "dFile")), "-t", "test3", ".")
  4374. if err != nil {
  4375. t.Fatal(err)
  4376. }
  4377. if !strings.Contains(out, "from files/dFile") {
  4378. t.Fatalf("test3 should have used files/dFile, output:%s", out)
  4379. }
  4380. out, _, err = dockerCmdInDir(t, ctx.Dir, "build", "--file=dFile", "-t", "test4", ".")
  4381. if err != nil {
  4382. t.Fatal(err)
  4383. }
  4384. if !strings.Contains(out, "from dFile") {
  4385. t.Fatalf("test4 should have used dFile, output:%s", out)
  4386. }
  4387. dirWithNoDockerfile, _ := ioutil.TempDir(os.TempDir(), "test5")
  4388. nonDockerfileFile := filepath.Join(dirWithNoDockerfile, "notDockerfile")
  4389. if _, err = os.Create(nonDockerfileFile); err != nil {
  4390. t.Fatal(err)
  4391. }
  4392. out, _, err = dockerCmdInDir(t, ctx.Dir, "build", fmt.Sprintf("--file=%s", nonDockerfileFile), "-t", "test5", ".")
  4393. if err == nil {
  4394. t.Fatalf("test5 was supposed to fail to find passwd")
  4395. }
  4396. if expected := fmt.Sprintf("The Dockerfile (%s) must be within the build context (.)", strings.Replace(nonDockerfileFile, `\`, `\\`, -1)); !strings.Contains(out, expected) {
  4397. t.Fatalf("wrong error messsage:%v\nexpected to contain=%v", out, expected)
  4398. }
  4399. out, _, err = dockerCmdInDir(t, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join("..", "Dockerfile"), "-t", "test6", "..")
  4400. if err != nil {
  4401. t.Fatalf("test6 failed: %s", err)
  4402. }
  4403. if !strings.Contains(out, "from Dockerfile") {
  4404. t.Fatalf("test6 should have used root Dockerfile, output:%s", out)
  4405. }
  4406. out, _, err = dockerCmdInDir(t, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join(ctx.Dir, "files", "Dockerfile"), "-t", "test7", "..")
  4407. if err != nil {
  4408. t.Fatalf("test7 failed: %s", err)
  4409. }
  4410. if !strings.Contains(out, "from files/Dockerfile") {
  4411. t.Fatalf("test7 should have used files Dockerfile, output:%s", out)
  4412. }
  4413. out, _, err = dockerCmdInDir(t, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join("..", "Dockerfile"), "-t", "test8", ".")
  4414. if err == nil || !strings.Contains(out, "must be within the build context") {
  4415. t.Fatalf("test8 should have failed with Dockerfile out of context: %s", err)
  4416. }
  4417. tmpDir := os.TempDir()
  4418. out, _, err = dockerCmdInDir(t, tmpDir, "build", "-t", "test9", ctx.Dir)
  4419. if err != nil {
  4420. t.Fatalf("test9 - failed: %s", err)
  4421. }
  4422. if !strings.Contains(out, "from Dockerfile") {
  4423. t.Fatalf("test9 should have used root Dockerfile, output:%s", out)
  4424. }
  4425. out, _, err = dockerCmdInDir(t, filepath.Join(ctx.Dir, "files"), "build", "-f", "dFile2", "-t", "test10", ".")
  4426. if err != nil {
  4427. t.Fatalf("test10 should have worked: %s", err)
  4428. }
  4429. if !strings.Contains(out, "from files/dFile2") {
  4430. t.Fatalf("test10 should have used files/dFile2, output:%s", out)
  4431. }
  4432. logDone("build - rename dockerfile")
  4433. }
  4434. func TestBuildFromMixedcaseDockerfile(t *testing.T) {
  4435. testRequires(t, UnixCli) // Dockerfile overwrites dockerfile on windows
  4436. defer deleteImages("test1")
  4437. ctx, err := fakeContext(`FROM busybox
  4438. RUN echo from dockerfile`,
  4439. map[string]string{
  4440. "dockerfile": "FROM busybox\nRUN echo from dockerfile",
  4441. })
  4442. defer ctx.Close()
  4443. if err != nil {
  4444. t.Fatal(err)
  4445. }
  4446. out, _, err := dockerCmdInDir(t, ctx.Dir, "build", "-t", "test1", ".")
  4447. if err != nil {
  4448. t.Fatalf("Failed to build: %s\n%s", out, err)
  4449. }
  4450. if !strings.Contains(out, "from dockerfile") {
  4451. t.Fatalf("Missing proper output: %s", out)
  4452. }
  4453. logDone("build - mixedcase Dockerfile")
  4454. }
  4455. func TestBuildWithTwoDockerfiles(t *testing.T) {
  4456. testRequires(t, UnixCli) // Dockerfile overwrites dockerfile on windows
  4457. defer deleteImages("test1")
  4458. ctx, err := fakeContext(`FROM busybox
  4459. RUN echo from Dockerfile`,
  4460. map[string]string{
  4461. "dockerfile": "FROM busybox\nRUN echo from dockerfile",
  4462. })
  4463. defer ctx.Close()
  4464. if err != nil {
  4465. t.Fatal(err)
  4466. }
  4467. out, _, err := dockerCmdInDir(t, ctx.Dir, "build", "-t", "test1", ".")
  4468. if err != nil {
  4469. t.Fatalf("Failed to build: %s\n%s", out, err)
  4470. }
  4471. if !strings.Contains(out, "from Dockerfile") {
  4472. t.Fatalf("Missing proper output: %s", out)
  4473. }
  4474. logDone("build - two Dockerfiles")
  4475. }
  4476. func TestBuildFromURLWithF(t *testing.T) {
  4477. defer deleteImages("test1")
  4478. server, err := fakeStorage(map[string]string{"baz": `FROM busybox
  4479. RUN echo from baz
  4480. COPY * /tmp/
  4481. RUN find /tmp/`})
  4482. if err != nil {
  4483. t.Fatal(err)
  4484. }
  4485. defer server.Close()
  4486. ctx, err := fakeContext(`FROM busybox
  4487. RUN echo from Dockerfile`,
  4488. map[string]string{})
  4489. defer ctx.Close()
  4490. if err != nil {
  4491. t.Fatal(err)
  4492. }
  4493. // Make sure that -f is ignored and that we don't use the Dockerfile
  4494. // that's in the current dir
  4495. out, _, err := dockerCmdInDir(t, ctx.Dir, "build", "-f", "baz", "-t", "test1", server.URL()+"/baz")
  4496. if err != nil {
  4497. t.Fatalf("Failed to build: %s\n%s", out, err)
  4498. }
  4499. if !strings.Contains(out, "from baz") ||
  4500. strings.Contains(out, "/tmp/baz") ||
  4501. !strings.Contains(out, "/tmp/Dockerfile") {
  4502. t.Fatalf("Missing proper output: %s", out)
  4503. }
  4504. logDone("build - from URL with -f")
  4505. }
  4506. func TestBuildFromStdinWithF(t *testing.T) {
  4507. defer deleteImages("test1")
  4508. ctx, err := fakeContext(`FROM busybox
  4509. RUN echo from Dockerfile`,
  4510. map[string]string{})
  4511. defer ctx.Close()
  4512. if err != nil {
  4513. t.Fatal(err)
  4514. }
  4515. // Make sure that -f is ignored and that we don't use the Dockerfile
  4516. // that's in the current dir
  4517. dockerCommand := exec.Command(dockerBinary, "build", "-f", "baz", "-t", "test1", "-")
  4518. dockerCommand.Dir = ctx.Dir
  4519. dockerCommand.Stdin = strings.NewReader(`FROM busybox
  4520. RUN echo from baz
  4521. COPY * /tmp/
  4522. RUN find /tmp/`)
  4523. out, status, err := runCommandWithOutput(dockerCommand)
  4524. if err != nil || status != 0 {
  4525. t.Fatalf("Error building: %s", err)
  4526. }
  4527. if !strings.Contains(out, "from baz") ||
  4528. strings.Contains(out, "/tmp/baz") ||
  4529. !strings.Contains(out, "/tmp/Dockerfile") {
  4530. t.Fatalf("Missing proper output: %s", out)
  4531. }
  4532. logDone("build - from stdin with -f")
  4533. }
  4534. func TestBuildFromOfficialNames(t *testing.T) {
  4535. name := "testbuildfromofficial"
  4536. fromNames := []string{
  4537. "busybox",
  4538. "docker.io/busybox",
  4539. "index.docker.io/busybox",
  4540. "library/busybox",
  4541. "docker.io/library/busybox",
  4542. "index.docker.io/library/busybox",
  4543. }
  4544. for idx, fromName := range fromNames {
  4545. imgName := fmt.Sprintf("%s%d", name, idx)
  4546. _, err := buildImage(imgName, "FROM "+fromName, true)
  4547. if err != nil {
  4548. t.Errorf("Build failed using FROM %s: %s", fromName, err)
  4549. }
  4550. deleteImages(imgName)
  4551. }
  4552. logDone("build - from official names")
  4553. }
  4554. func TestBuildDockerfileOutsideContext(t *testing.T) {
  4555. testRequires(t, UnixCli) // uses os.Symlink: not implemented in windows at the time of writing (go-1.4.2)
  4556. name := "testbuilddockerfileoutsidecontext"
  4557. tmpdir, err := ioutil.TempDir("", name)
  4558. if err != nil {
  4559. t.Fatal(err)
  4560. }
  4561. defer os.RemoveAll(tmpdir)
  4562. ctx := filepath.Join(tmpdir, "context")
  4563. if err := os.MkdirAll(ctx, 0755); err != nil {
  4564. t.Fatal(err)
  4565. }
  4566. if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte("FROM scratch\nENV X Y"), 0644); err != nil {
  4567. t.Fatal(err)
  4568. }
  4569. wd, err := os.Getwd()
  4570. if err != nil {
  4571. t.Fatal(err)
  4572. }
  4573. defer os.Chdir(wd)
  4574. if err := os.Chdir(ctx); err != nil {
  4575. t.Fatal(err)
  4576. }
  4577. if err := ioutil.WriteFile(filepath.Join(tmpdir, "outsideDockerfile"), []byte("FROM scratch\nENV x y"), 0644); err != nil {
  4578. t.Fatal(err)
  4579. }
  4580. if err := os.Symlink(filepath.Join("..", "outsideDockerfile"), filepath.Join(ctx, "dockerfile1")); err != nil {
  4581. t.Fatal(err)
  4582. }
  4583. if err := os.Symlink(filepath.Join(tmpdir, "outsideDockerfile"), filepath.Join(ctx, "dockerfile2")); err != nil {
  4584. t.Fatal(err)
  4585. }
  4586. for _, dockerfilePath := range []string{
  4587. filepath.Join("..", "outsideDockerfile"),
  4588. filepath.Join(ctx, "dockerfile1"),
  4589. filepath.Join(ctx, "dockerfile2"),
  4590. } {
  4591. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "build", "-t", name, "--no-cache", "-f", dockerfilePath, "."))
  4592. if err == nil {
  4593. t.Fatalf("Expected error with %s. Out: %s", dockerfilePath, out)
  4594. }
  4595. if !strings.Contains(out, "must be within the build context") && !strings.Contains(out, "Cannot locate Dockerfile") {
  4596. t.Fatalf("Unexpected error with %s. Out: %s", dockerfilePath, out)
  4597. }
  4598. deleteImages(name)
  4599. }
  4600. os.Chdir(tmpdir)
  4601. // Path to Dockerfile should be resolved relative to working directory, not relative to context.
  4602. // There is a Dockerfile in the context, but since there is no Dockerfile in the current directory, the following should fail
  4603. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "build", "-t", name, "--no-cache", "-f", "Dockerfile", ctx))
  4604. if err == nil {
  4605. t.Fatalf("Expected error. Out: %s", out)
  4606. }
  4607. deleteImages(name)
  4608. logDone("build - Dockerfile outside context")
  4609. }
  4610. func TestBuildSpaces(t *testing.T) {
  4611. // Test to make sure that leading/trailing spaces on a command
  4612. // doesn't change the error msg we get
  4613. var (
  4614. err1 error
  4615. err2 error
  4616. )
  4617. name := "testspaces"
  4618. defer deleteImages(name)
  4619. ctx, err := fakeContext("FROM busybox\nCOPY\n",
  4620. map[string]string{
  4621. "Dockerfile": "FROM busybox\nCOPY\n",
  4622. })
  4623. if err != nil {
  4624. t.Fatal(err)
  4625. }
  4626. defer ctx.Close()
  4627. if _, err1 = buildImageFromContext(name, ctx, false); err1 == nil {
  4628. t.Fatal("Build 1 was supposed to fail, but didn't")
  4629. }
  4630. ctx.Add("Dockerfile", "FROM busybox\nCOPY ")
  4631. if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil {
  4632. t.Fatal("Build 2 was supposed to fail, but didn't")
  4633. }
  4634. removeLogTimestamps := func(s string) string {
  4635. return regexp.MustCompile(`time="(.*?)"`).ReplaceAllString(s, `time=[TIMESTAMP]`)
  4636. }
  4637. // Skip over the times
  4638. e1 := removeLogTimestamps(err1.Error())
  4639. e2 := removeLogTimestamps(err2.Error())
  4640. // Ignore whitespace since that's what were verifying doesn't change stuff
  4641. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  4642. t.Fatalf("Build 2's error wasn't the same as build 1's\n1:%s\n2:%s", err1, err2)
  4643. }
  4644. ctx.Add("Dockerfile", "FROM busybox\n COPY")
  4645. if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil {
  4646. t.Fatal("Build 3 was supposed to fail, but didn't")
  4647. }
  4648. // Skip over the times
  4649. e1 = removeLogTimestamps(err1.Error())
  4650. e2 = removeLogTimestamps(err2.Error())
  4651. // Ignore whitespace since that's what were verifying doesn't change stuff
  4652. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  4653. t.Fatalf("Build 3's error wasn't the same as build 1's\n1:%s\n3:%s", err1, err2)
  4654. }
  4655. ctx.Add("Dockerfile", "FROM busybox\n COPY ")
  4656. if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil {
  4657. t.Fatal("Build 4 was supposed to fail, but didn't")
  4658. }
  4659. // Skip over the times
  4660. e1 = removeLogTimestamps(err1.Error())
  4661. e2 = removeLogTimestamps(err2.Error())
  4662. // Ignore whitespace since that's what were verifying doesn't change stuff
  4663. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  4664. t.Fatalf("Build 4's error wasn't the same as build 1's\n1:%s\n4:%s", err1, err2)
  4665. }
  4666. logDone("build - test spaces")
  4667. }
  4668. func TestBuildSpacesWithQuotes(t *testing.T) {
  4669. // Test to make sure that spaces in quotes aren't lost
  4670. name := "testspacesquotes"
  4671. defer deleteImages(name)
  4672. dockerfile := `FROM busybox
  4673. RUN echo " \
  4674. foo "`
  4675. _, out, err := buildImageWithOut(name, dockerfile, false)
  4676. if err != nil {
  4677. t.Fatal("Build failed:", err)
  4678. }
  4679. expecting := "\n foo \n"
  4680. if !strings.Contains(out, expecting) {
  4681. t.Fatalf("Bad output: %q expecting to contian %q", out, expecting)
  4682. }
  4683. logDone("build - test spaces with quotes")
  4684. }
  4685. // #4393
  4686. func TestBuildVolumeFileExistsinContainer(t *testing.T) {
  4687. buildCmd := exec.Command(dockerBinary, "build", "-t", "docker-test-errcreatevolumewithfile", "-")
  4688. buildCmd.Stdin = strings.NewReader(`
  4689. FROM busybox
  4690. RUN touch /foo
  4691. VOLUME /foo
  4692. `)
  4693. out, _, err := runCommandWithOutput(buildCmd)
  4694. if err == nil || !strings.Contains(out, "file exists") {
  4695. t.Fatalf("expected build to fail when file exists in container at requested volume path")
  4696. }
  4697. logDone("build - errors when volume is specified where a file exists")
  4698. }
  4699. func TestBuildMissingArgs(t *testing.T) {
  4700. // Test to make sure that all Dockerfile commands (except the ones listed
  4701. // in skipCmds) will generate an error if no args are provided.
  4702. // Note: INSERT is deprecated so we exclude it because of that.
  4703. skipCmds := map[string]struct{}{
  4704. "CMD": {},
  4705. "RUN": {},
  4706. "ENTRYPOINT": {},
  4707. "INSERT": {},
  4708. }
  4709. defer deleteAllContainers()
  4710. for cmd := range command.Commands {
  4711. cmd = strings.ToUpper(cmd)
  4712. if _, ok := skipCmds[cmd]; ok {
  4713. continue
  4714. }
  4715. var dockerfile string
  4716. if cmd == "FROM" {
  4717. dockerfile = cmd
  4718. } else {
  4719. // Add FROM to make sure we don't complain about it missing
  4720. dockerfile = "FROM busybox\n" + cmd
  4721. }
  4722. ctx, err := fakeContext(dockerfile, map[string]string{})
  4723. if err != nil {
  4724. t.Fatal(err)
  4725. }
  4726. defer ctx.Close()
  4727. var out string
  4728. if out, err = buildImageFromContext("args", ctx, true); err == nil {
  4729. t.Fatalf("%s was supposed to fail. Out:%s", cmd, out)
  4730. }
  4731. if !strings.Contains(err.Error(), cmd+" requires") {
  4732. t.Fatalf("%s returned the wrong type of error:%s", cmd, err)
  4733. }
  4734. }
  4735. logDone("build - verify missing args")
  4736. }
  4737. func TestBuildEmptyScratch(t *testing.T) {
  4738. defer deleteImages("sc")
  4739. _, out, err := buildImageWithOut("sc", "FROM scratch", true)
  4740. if err == nil {
  4741. t.Fatalf("Build was supposed to fail")
  4742. }
  4743. if !strings.Contains(out, "No image was generated") {
  4744. t.Fatalf("Wrong error message: %v", out)
  4745. }
  4746. logDone("build - empty scratch Dockerfile")
  4747. }
  4748. func TestBuildDotDotFile(t *testing.T) {
  4749. defer deleteImages("sc")
  4750. ctx, err := fakeContext("FROM busybox\n",
  4751. map[string]string{
  4752. "..gitme": "",
  4753. })
  4754. if err != nil {
  4755. t.Fatal(err)
  4756. }
  4757. defer ctx.Close()
  4758. if _, err = buildImageFromContext("sc", ctx, false); err != nil {
  4759. t.Fatalf("Build was supposed to work: %s", err)
  4760. }
  4761. logDone("build - ..file")
  4762. }
  4763. func TestBuildNotVerbose(t *testing.T) {
  4764. defer deleteAllContainers()
  4765. defer deleteImages("verbose")
  4766. ctx, err := fakeContext("FROM busybox\nENV abc=hi\nRUN echo $abc there", map[string]string{})
  4767. if err != nil {
  4768. t.Fatal(err)
  4769. }
  4770. defer ctx.Close()
  4771. // First do it w/verbose - baseline
  4772. buildCmd := exec.Command(dockerBinary, "build", "--no-cache", "-t", "verbose", ".")
  4773. buildCmd.Dir = ctx.Dir
  4774. out, _, err := runCommandWithOutput(buildCmd)
  4775. if err != nil {
  4776. t.Fatalf("failed to build the image w/o -q: %s, %v", out, err)
  4777. }
  4778. if !strings.Contains(out, "hi there") {
  4779. t.Fatalf("missing output:%s\n", out)
  4780. }
  4781. // Now do it w/o verbose
  4782. buildCmd = exec.Command(dockerBinary, "build", "--no-cache", "-q", "-t", "verbose", ".")
  4783. buildCmd.Dir = ctx.Dir
  4784. out, _, err = runCommandWithOutput(buildCmd)
  4785. if err != nil {
  4786. t.Fatalf("failed to build the image w/ -q: %s, %v", out, err)
  4787. }
  4788. if strings.Contains(out, "hi there") {
  4789. t.Fatalf("Bad output, should not contain 'hi there':%s", out)
  4790. }
  4791. logDone("build - not verbose")
  4792. }
  4793. func TestBuildRUNoneJSON(t *testing.T) {
  4794. name := "testbuildrunonejson"
  4795. defer deleteAllContainers()
  4796. defer deleteImages(name, "hello-world")
  4797. ctx, err := fakeContext(`FROM hello-world:frozen
  4798. RUN [ "/hello" ]`, map[string]string{})
  4799. if err != nil {
  4800. t.Fatal(err)
  4801. }
  4802. defer ctx.Close()
  4803. buildCmd := exec.Command(dockerBinary, "build", "--no-cache", "-t", name, ".")
  4804. buildCmd.Dir = ctx.Dir
  4805. out, _, err := runCommandWithOutput(buildCmd)
  4806. if err != nil {
  4807. t.Fatalf("failed to build the image: %s, %v", out, err)
  4808. }
  4809. if !strings.Contains(out, "Hello from Docker") {
  4810. t.Fatalf("bad output: %s", out)
  4811. }
  4812. logDone("build - RUN with one JSON arg")
  4813. }
  4814. func TestBuildResourceConstraintsAreUsed(t *testing.T) {
  4815. name := "testbuildresourceconstraints"
  4816. defer deleteAllContainers()
  4817. defer deleteImages(name, "hello-world")
  4818. ctx, err := fakeContext(`
  4819. FROM hello-world:frozen
  4820. RUN ["/hello"]
  4821. `, map[string]string{})
  4822. if err != nil {
  4823. t.Fatal(err)
  4824. }
  4825. cmd := exec.Command(dockerBinary, "build", "--rm=false", "--memory=64m", "--memory-swap=-1", "--cpuset-cpus=1", "--cpu-shares=100", "-t", name, ".")
  4826. cmd.Dir = ctx.Dir
  4827. out, _, err := runCommandWithOutput(cmd)
  4828. if err != nil {
  4829. t.Fatal(err, out)
  4830. }
  4831. out, _, err = dockerCmd(t, "ps", "-lq")
  4832. if err != nil {
  4833. t.Fatal(err, out)
  4834. }
  4835. cID := stripTrailingCharacters(out)
  4836. type hostConfig struct {
  4837. Memory float64 // Use float64 here since the json decoder sees it that way
  4838. MemorySwap int
  4839. CpusetCpus string
  4840. CpuShares int
  4841. }
  4842. cfg, err := inspectFieldJSON(cID, "HostConfig")
  4843. if err != nil {
  4844. t.Fatal(err)
  4845. }
  4846. var c1 hostConfig
  4847. if err := json.Unmarshal([]byte(cfg), &c1); err != nil {
  4848. t.Fatal(err, cfg)
  4849. }
  4850. mem := int64(c1.Memory)
  4851. if mem != 67108864 || c1.MemorySwap != -1 || c1.CpusetCpus != "1" || c1.CpuShares != 100 {
  4852. t.Fatalf("resource constraints not set properly:\nMemory: %d, MemSwap: %d, CpusetCpus: %s, CpuShares: %d",
  4853. mem, c1.MemorySwap, c1.CpusetCpus, c1.CpuShares)
  4854. }
  4855. // Make sure constraints aren't saved to image
  4856. _, _, err = dockerCmd(t, "run", "--name=test", name)
  4857. if err != nil {
  4858. t.Fatal(err)
  4859. }
  4860. cfg, err = inspectFieldJSON("test", "HostConfig")
  4861. if err != nil {
  4862. t.Fatal(err)
  4863. }
  4864. var c2 hostConfig
  4865. if err := json.Unmarshal([]byte(cfg), &c2); err != nil {
  4866. t.Fatal(err, cfg)
  4867. }
  4868. mem = int64(c2.Memory)
  4869. if mem == 67108864 || c2.MemorySwap == -1 || c2.CpusetCpus == "1" || c2.CpuShares == 100 {
  4870. t.Fatalf("resource constraints leaked from build:\nMemory: %d, MemSwap: %d, CpusetCpus: %s, CpuShares: %d",
  4871. mem, c2.MemorySwap, c2.CpusetCpus, c2.CpuShares)
  4872. }
  4873. logDone("build - resource constraints applied")
  4874. }
  4875. func TestBuildEmptyStringVolume(t *testing.T) {
  4876. name := "testbuildemptystringvolume"
  4877. defer deleteImages(name)
  4878. _, err := buildImage(name, `
  4879. FROM busybox
  4880. ENV foo=""
  4881. VOLUME $foo
  4882. `, false)
  4883. if err == nil {
  4884. t.Fatal("Should have failed to build")
  4885. }
  4886. logDone("build - empty string volume")
  4887. }