docker_cli_build_test.go 143 KB

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