xds_end2end_test.cc 244 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767
  1. /*
  2. *
  3. * Copyright 2017 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. #include <deque>
  19. #include <memory>
  20. #include <mutex>
  21. #include <numeric>
  22. #include <set>
  23. #include <sstream>
  24. #include <string>
  25. #include <thread>
  26. #include <vector>
  27. #include <gmock/gmock.h>
  28. #include <gtest/gtest.h>
  29. #include "absl/strings/str_cat.h"
  30. #include "absl/types/optional.h"
  31. #include <grpc/grpc.h>
  32. #include <grpc/support/alloc.h>
  33. #include <grpc/support/log.h>
  34. #include <grpc/support/time.h>
  35. #include <grpcpp/channel.h>
  36. #include <grpcpp/client_context.h>
  37. #include <grpcpp/create_channel.h>
  38. #include <grpcpp/server.h>
  39. #include <grpcpp/server_builder.h>
  40. #include "src/core/ext/filters/client_channel/backup_poller.h"
  41. #include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
  42. #include "src/core/ext/filters/client_channel/server_address.h"
  43. #include "src/core/ext/xds/xds_api.h"
  44. #include "src/core/ext/xds/xds_channel_args.h"
  45. #include "src/core/ext/xds/xds_client.h"
  46. #include "src/core/lib/channel/channel_args.h"
  47. #include "src/core/lib/gpr/env.h"
  48. #include "src/core/lib/gpr/tmpfile.h"
  49. #include "src/core/lib/gprpp/map.h"
  50. #include "src/core/lib/gprpp/ref_counted_ptr.h"
  51. #include "src/core/lib/gprpp/sync.h"
  52. #include "src/core/lib/iomgr/parse_address.h"
  53. #include "src/core/lib/iomgr/sockaddr.h"
  54. #include "src/core/lib/security/credentials/fake/fake_credentials.h"
  55. #include "src/cpp/client/secure_credentials.h"
  56. #include "src/cpp/server/secure_server_credentials.h"
  57. #include "test/core/util/port.h"
  58. #include "test/core/util/test_config.h"
  59. #include "test/cpp/end2end/test_service_impl.h"
  60. #include "src/proto/grpc/testing/echo.grpc.pb.h"
  61. #include "src/proto/grpc/testing/xds/ads_for_test.grpc.pb.h"
  62. #include "src/proto/grpc/testing/xds/cds_for_test.grpc.pb.h"
  63. #include "src/proto/grpc/testing/xds/eds_for_test.grpc.pb.h"
  64. #include "src/proto/grpc/testing/xds/lds_rds_for_test.grpc.pb.h"
  65. #include "src/proto/grpc/testing/xds/lrs_for_test.grpc.pb.h"
  66. #include "src/proto/grpc/testing/xds/v3/ads.grpc.pb.h"
  67. #include "src/proto/grpc/testing/xds/v3/cluster.grpc.pb.h"
  68. #include "src/proto/grpc/testing/xds/v3/discovery.grpc.pb.h"
  69. #include "src/proto/grpc/testing/xds/v3/endpoint.grpc.pb.h"
  70. #include "src/proto/grpc/testing/xds/v3/http_connection_manager.grpc.pb.h"
  71. #include "src/proto/grpc/testing/xds/v3/listener.grpc.pb.h"
  72. #include "src/proto/grpc/testing/xds/v3/lrs.grpc.pb.h"
  73. #include "src/proto/grpc/testing/xds/v3/route.grpc.pb.h"
  74. namespace grpc {
  75. namespace testing {
  76. namespace {
  77. using std::chrono::system_clock;
  78. using ::envoy::config::cluster::v3::CircuitBreakers;
  79. using ::envoy::config::cluster::v3::Cluster;
  80. using ::envoy::config::cluster::v3::RoutingPriority;
  81. using ::envoy::config::endpoint::v3::ClusterLoadAssignment;
  82. using ::envoy::config::endpoint::v3::HealthStatus;
  83. using ::envoy::config::listener::v3::Listener;
  84. using ::envoy::config::route::v3::RouteConfiguration;
  85. using ::envoy::extensions::filters::network::http_connection_manager::v3::
  86. HttpConnectionManager;
  87. using ::envoy::type::v3::FractionalPercent;
  88. constexpr char kLdsTypeUrl[] =
  89. "type.googleapis.com/envoy.config.listener.v3.Listener";
  90. constexpr char kRdsTypeUrl[] =
  91. "type.googleapis.com/envoy.config.route.v3.RouteConfiguration";
  92. constexpr char kCdsTypeUrl[] =
  93. "type.googleapis.com/envoy.config.cluster.v3.Cluster";
  94. constexpr char kEdsTypeUrl[] =
  95. "type.googleapis.com/envoy.config.endpoint.v3.ClusterLoadAssignment";
  96. constexpr char kLdsV2TypeUrl[] = "type.googleapis.com/envoy.api.v2.Listener";
  97. constexpr char kRdsV2TypeUrl[] =
  98. "type.googleapis.com/envoy.api.v2.RouteConfiguration";
  99. constexpr char kCdsV2TypeUrl[] = "type.googleapis.com/envoy.api.v2.Cluster";
  100. constexpr char kEdsV2TypeUrl[] =
  101. "type.googleapis.com/envoy.api.v2.ClusterLoadAssignment";
  102. constexpr char kDefaultLocalityRegion[] = "xds_default_locality_region";
  103. constexpr char kDefaultLocalityZone[] = "xds_default_locality_zone";
  104. constexpr char kLbDropType[] = "lb";
  105. constexpr char kThrottleDropType[] = "throttle";
  106. constexpr char kServerName[] = "server.example.com";
  107. constexpr char kDefaultRouteConfigurationName[] = "route_config_name";
  108. constexpr char kDefaultClusterName[] = "cluster_name";
  109. constexpr char kDefaultEdsServiceName[] = "eds_service_name";
  110. constexpr int kDefaultLocalityWeight = 3;
  111. constexpr int kDefaultLocalityPriority = 0;
  112. constexpr char kRequestMessage[] = "Live long and prosper.";
  113. constexpr char kDefaultServiceConfig[] =
  114. "{\n"
  115. " \"loadBalancingConfig\":[\n"
  116. " { \"does_not_exist\":{} },\n"
  117. " { \"eds_experimental\":{\n"
  118. " \"clusterName\": \"application_target_name\",\n"
  119. " \"lrsLoadReportingServerName\": \"\"\n"
  120. " } }\n"
  121. " ]\n"
  122. "}";
  123. constexpr char kDefaultServiceConfigWithoutLoadReporting[] =
  124. "{\n"
  125. " \"loadBalancingConfig\":[\n"
  126. " { \"does_not_exist\":{} },\n"
  127. " { \"eds_experimental\":{\n"
  128. " \"clusterName\": \"application_target_name\"\n"
  129. " } }\n"
  130. " ]\n"
  131. "}";
  132. constexpr char kBootstrapFileV3[] =
  133. "{\n"
  134. " \"xds_servers\": [\n"
  135. " {\n"
  136. " \"server_uri\": \"fake:///xds_server\",\n"
  137. " \"channel_creds\": [\n"
  138. " {\n"
  139. " \"type\": \"fake\"\n"
  140. " }\n"
  141. " ],\n"
  142. " \"server_features\": [\"xds_v3\"]\n"
  143. " }\n"
  144. " ],\n"
  145. " \"node\": {\n"
  146. " \"id\": \"xds_end2end_test\",\n"
  147. " \"cluster\": \"test\",\n"
  148. " \"metadata\": {\n"
  149. " \"foo\": \"bar\"\n"
  150. " },\n"
  151. " \"locality\": {\n"
  152. " \"region\": \"corp\",\n"
  153. " \"zone\": \"svl\",\n"
  154. " \"subzone\": \"mp3\"\n"
  155. " }\n"
  156. " }\n"
  157. "}\n";
  158. constexpr char kBootstrapFileV2[] =
  159. "{\n"
  160. " \"xds_servers\": [\n"
  161. " {\n"
  162. " \"server_uri\": \"fake:///xds_server\",\n"
  163. " \"channel_creds\": [\n"
  164. " {\n"
  165. " \"type\": \"fake\"\n"
  166. " }\n"
  167. " ]\n"
  168. " }\n"
  169. " ],\n"
  170. " \"node\": {\n"
  171. " \"id\": \"xds_end2end_test\",\n"
  172. " \"cluster\": \"test\",\n"
  173. " \"metadata\": {\n"
  174. " \"foo\": \"bar\"\n"
  175. " },\n"
  176. " \"locality\": {\n"
  177. " \"region\": \"corp\",\n"
  178. " \"zone\": \"svl\",\n"
  179. " \"subzone\": \"mp3\"\n"
  180. " }\n"
  181. " }\n"
  182. "}\n";
  183. char* g_bootstrap_file_v3;
  184. char* g_bootstrap_file_v2;
  185. void WriteBootstrapFiles() {
  186. char* bootstrap_file;
  187. FILE* out = gpr_tmpfile("xds_bootstrap_v3", &bootstrap_file);
  188. fputs(kBootstrapFileV3, out);
  189. fclose(out);
  190. g_bootstrap_file_v3 = bootstrap_file;
  191. out = gpr_tmpfile("xds_bootstrap_v2", &bootstrap_file);
  192. fputs(kBootstrapFileV2, out);
  193. fclose(out);
  194. g_bootstrap_file_v2 = bootstrap_file;
  195. }
  196. // Helper class to minimize the number of unique ports we use for this test.
  197. class PortSaver {
  198. public:
  199. int GetPort() {
  200. if (idx_ >= ports_.size()) {
  201. ports_.push_back(grpc_pick_unused_port_or_die());
  202. }
  203. return ports_[idx_++];
  204. }
  205. void Reset() { idx_ = 0; }
  206. private:
  207. std::vector<int> ports_;
  208. size_t idx_ = 0;
  209. };
  210. PortSaver* g_port_saver = nullptr;
  211. template <typename ServiceType>
  212. class CountedService : public ServiceType {
  213. public:
  214. size_t request_count() {
  215. grpc_core::MutexLock lock(&mu_);
  216. return request_count_;
  217. }
  218. size_t response_count() {
  219. grpc_core::MutexLock lock(&mu_);
  220. return response_count_;
  221. }
  222. void IncreaseResponseCount() {
  223. grpc_core::MutexLock lock(&mu_);
  224. ++response_count_;
  225. }
  226. void IncreaseRequestCount() {
  227. grpc_core::MutexLock lock(&mu_);
  228. ++request_count_;
  229. }
  230. void ResetCounters() {
  231. grpc_core::MutexLock lock(&mu_);
  232. request_count_ = 0;
  233. response_count_ = 0;
  234. }
  235. private:
  236. grpc_core::Mutex mu_;
  237. size_t request_count_ = 0;
  238. size_t response_count_ = 0;
  239. };
  240. const char g_kCallCredsMdKey[] = "Balancer should not ...";
  241. const char g_kCallCredsMdValue[] = "... receive me";
  242. template <typename RpcService>
  243. class BackendServiceImpl
  244. : public CountedService<TestMultipleServiceImpl<RpcService>> {
  245. public:
  246. BackendServiceImpl() {}
  247. Status Echo(ServerContext* context, const EchoRequest* request,
  248. EchoResponse* response) override {
  249. // Backend should receive the call credentials metadata.
  250. auto call_credentials_entry =
  251. context->client_metadata().find(g_kCallCredsMdKey);
  252. EXPECT_NE(call_credentials_entry, context->client_metadata().end());
  253. if (call_credentials_entry != context->client_metadata().end()) {
  254. EXPECT_EQ(call_credentials_entry->second, g_kCallCredsMdValue);
  255. }
  256. CountedService<TestMultipleServiceImpl<RpcService>>::IncreaseRequestCount();
  257. const auto status =
  258. TestMultipleServiceImpl<RpcService>::Echo(context, request, response);
  259. CountedService<
  260. TestMultipleServiceImpl<RpcService>>::IncreaseResponseCount();
  261. AddClient(context->peer());
  262. return status;
  263. }
  264. Status Echo1(ServerContext* context, const EchoRequest* request,
  265. EchoResponse* response) override {
  266. return Echo(context, request, response);
  267. }
  268. Status Echo2(ServerContext* context, const EchoRequest* request,
  269. EchoResponse* response) override {
  270. return Echo(context, request, response);
  271. }
  272. void Start() {}
  273. void Shutdown() {}
  274. std::set<std::string> clients() {
  275. grpc_core::MutexLock lock(&clients_mu_);
  276. return clients_;
  277. }
  278. private:
  279. void AddClient(const std::string& client) {
  280. grpc_core::MutexLock lock(&clients_mu_);
  281. clients_.insert(client);
  282. }
  283. grpc_core::Mutex clients_mu_;
  284. std::set<std::string> clients_;
  285. };
  286. class ClientStats {
  287. public:
  288. struct LocalityStats {
  289. LocalityStats() {}
  290. // Converts from proto message class.
  291. template <class UpstreamLocalityStats>
  292. LocalityStats(const UpstreamLocalityStats& upstream_locality_stats)
  293. : total_successful_requests(
  294. upstream_locality_stats.total_successful_requests()),
  295. total_requests_in_progress(
  296. upstream_locality_stats.total_requests_in_progress()),
  297. total_error_requests(upstream_locality_stats.total_error_requests()),
  298. total_issued_requests(
  299. upstream_locality_stats.total_issued_requests()) {}
  300. LocalityStats& operator+=(const LocalityStats& other) {
  301. total_successful_requests += other.total_successful_requests;
  302. total_requests_in_progress += other.total_requests_in_progress;
  303. total_error_requests += other.total_error_requests;
  304. total_issued_requests += other.total_issued_requests;
  305. return *this;
  306. }
  307. uint64_t total_successful_requests = 0;
  308. uint64_t total_requests_in_progress = 0;
  309. uint64_t total_error_requests = 0;
  310. uint64_t total_issued_requests = 0;
  311. };
  312. ClientStats() {}
  313. // Converts from proto message class.
  314. template <class ClusterStats>
  315. explicit ClientStats(const ClusterStats& cluster_stats)
  316. : cluster_name_(cluster_stats.cluster_name()),
  317. total_dropped_requests_(cluster_stats.total_dropped_requests()) {
  318. for (const auto& input_locality_stats :
  319. cluster_stats.upstream_locality_stats()) {
  320. locality_stats_.emplace(input_locality_stats.locality().sub_zone(),
  321. LocalityStats(input_locality_stats));
  322. }
  323. for (const auto& input_dropped_requests :
  324. cluster_stats.dropped_requests()) {
  325. dropped_requests_.emplace(input_dropped_requests.category(),
  326. input_dropped_requests.dropped_count());
  327. }
  328. }
  329. const std::string& cluster_name() const { return cluster_name_; }
  330. const std::map<std::string, LocalityStats>& locality_stats() const {
  331. return locality_stats_;
  332. }
  333. uint64_t total_successful_requests() const {
  334. uint64_t sum = 0;
  335. for (auto& p : locality_stats_) {
  336. sum += p.second.total_successful_requests;
  337. }
  338. return sum;
  339. }
  340. uint64_t total_requests_in_progress() const {
  341. uint64_t sum = 0;
  342. for (auto& p : locality_stats_) {
  343. sum += p.second.total_requests_in_progress;
  344. }
  345. return sum;
  346. }
  347. uint64_t total_error_requests() const {
  348. uint64_t sum = 0;
  349. for (auto& p : locality_stats_) {
  350. sum += p.second.total_error_requests;
  351. }
  352. return sum;
  353. }
  354. uint64_t total_issued_requests() const {
  355. uint64_t sum = 0;
  356. for (auto& p : locality_stats_) {
  357. sum += p.second.total_issued_requests;
  358. }
  359. return sum;
  360. }
  361. uint64_t total_dropped_requests() const { return total_dropped_requests_; }
  362. uint64_t dropped_requests(const std::string& category) const {
  363. auto iter = dropped_requests_.find(category);
  364. GPR_ASSERT(iter != dropped_requests_.end());
  365. return iter->second;
  366. }
  367. ClientStats& operator+=(const ClientStats& other) {
  368. for (const auto& p : other.locality_stats_) {
  369. locality_stats_[p.first] += p.second;
  370. }
  371. total_dropped_requests_ += other.total_dropped_requests_;
  372. for (const auto& p : other.dropped_requests_) {
  373. dropped_requests_[p.first] += p.second;
  374. }
  375. return *this;
  376. }
  377. private:
  378. std::string cluster_name_;
  379. std::map<std::string, LocalityStats> locality_stats_;
  380. uint64_t total_dropped_requests_ = 0;
  381. std::map<std::string, uint64_t> dropped_requests_;
  382. };
  383. class AdsServiceImpl : public std::enable_shared_from_this<AdsServiceImpl> {
  384. public:
  385. struct ResponseState {
  386. enum State { NOT_SENT, SENT, ACKED, NACKED };
  387. State state = NOT_SENT;
  388. std::string error_message;
  389. };
  390. struct EdsResourceArgs {
  391. struct Locality {
  392. Locality(const std::string& sub_zone, std::vector<int> ports,
  393. int lb_weight = kDefaultLocalityWeight,
  394. int priority = kDefaultLocalityPriority,
  395. std::vector<HealthStatus> health_statuses = {})
  396. : sub_zone(std::move(sub_zone)),
  397. ports(std::move(ports)),
  398. lb_weight(lb_weight),
  399. priority(priority),
  400. health_statuses(std::move(health_statuses)) {}
  401. const std::string sub_zone;
  402. std::vector<int> ports;
  403. int lb_weight;
  404. int priority;
  405. std::vector<HealthStatus> health_statuses;
  406. };
  407. EdsResourceArgs() = default;
  408. explicit EdsResourceArgs(std::vector<Locality> locality_list)
  409. : locality_list(std::move(locality_list)) {}
  410. std::vector<Locality> locality_list;
  411. std::map<std::string, uint32_t> drop_categories;
  412. FractionalPercent::DenominatorType drop_denominator =
  413. FractionalPercent::MILLION;
  414. };
  415. explicit AdsServiceImpl(bool enable_load_reporting)
  416. : v2_rpc_service_(this, /*is_v2=*/true),
  417. v3_rpc_service_(this, /*is_v2=*/false) {
  418. // Construct RDS response data.
  419. default_route_config_.set_name(kDefaultRouteConfigurationName);
  420. auto* virtual_host = default_route_config_.add_virtual_hosts();
  421. virtual_host->add_domains("*");
  422. auto* route = virtual_host->add_routes();
  423. route->mutable_match()->set_prefix("");
  424. route->mutable_route()->set_cluster(kDefaultClusterName);
  425. SetRdsResource(default_route_config_);
  426. // Construct LDS response data (with inlined RDS result).
  427. default_listener_ = BuildListener(default_route_config_);
  428. SetLdsResource(default_listener_);
  429. // Construct CDS response data.
  430. default_cluster_.set_name(kDefaultClusterName);
  431. default_cluster_.set_type(Cluster::EDS);
  432. auto* eds_config = default_cluster_.mutable_eds_cluster_config();
  433. eds_config->mutable_eds_config()->mutable_ads();
  434. eds_config->set_service_name(kDefaultEdsServiceName);
  435. default_cluster_.set_lb_policy(Cluster::ROUND_ROBIN);
  436. if (enable_load_reporting) {
  437. default_cluster_.mutable_lrs_server()->mutable_self();
  438. }
  439. SetCdsResource(default_cluster_);
  440. }
  441. bool seen_v2_client() const { return seen_v2_client_; }
  442. bool seen_v3_client() const { return seen_v3_client_; }
  443. ::envoy::service::discovery::v2::AggregatedDiscoveryService::Service*
  444. v2_rpc_service() {
  445. return &v2_rpc_service_;
  446. }
  447. ::envoy::service::discovery::v3::AggregatedDiscoveryService::Service*
  448. v3_rpc_service() {
  449. return &v3_rpc_service_;
  450. }
  451. Listener default_listener() const { return default_listener_; }
  452. RouteConfiguration default_route_config() const {
  453. return default_route_config_;
  454. }
  455. Cluster default_cluster() const { return default_cluster_; }
  456. ResponseState lds_response_state() {
  457. grpc_core::MutexLock lock(&ads_mu_);
  458. return resource_type_response_state_[kLdsTypeUrl];
  459. }
  460. ResponseState rds_response_state() {
  461. grpc_core::MutexLock lock(&ads_mu_);
  462. return resource_type_response_state_[kRdsTypeUrl];
  463. }
  464. ResponseState cds_response_state() {
  465. grpc_core::MutexLock lock(&ads_mu_);
  466. return resource_type_response_state_[kCdsTypeUrl];
  467. }
  468. ResponseState eds_response_state() {
  469. grpc_core::MutexLock lock(&ads_mu_);
  470. return resource_type_response_state_[kEdsTypeUrl];
  471. }
  472. void SetResourceIgnore(const std::string& type_url) {
  473. grpc_core::MutexLock lock(&ads_mu_);
  474. resource_types_to_ignore_.emplace(type_url);
  475. }
  476. void UnsetResource(const std::string& type_url, const std::string& name) {
  477. grpc_core::MutexLock lock(&ads_mu_);
  478. ResourceState& state = resource_map_[type_url][name];
  479. ++state.version;
  480. state.resource.reset();
  481. gpr_log(GPR_INFO, "ADS[%p]: Unsetting %s resource %s to version %u", this,
  482. type_url.c_str(), name.c_str(), state.version);
  483. for (SubscriptionState* subscription : state.subscriptions) {
  484. subscription->update_queue->emplace_back(type_url, name);
  485. }
  486. }
  487. void SetResource(google::protobuf::Any resource, const std::string& type_url,
  488. const std::string& name) {
  489. grpc_core::MutexLock lock(&ads_mu_);
  490. ResourceState& state = resource_map_[type_url][name];
  491. ++state.version;
  492. state.resource = std::move(resource);
  493. gpr_log(GPR_INFO, "ADS[%p]: Updating %s resource %s to version %u", this,
  494. type_url.c_str(), name.c_str(), state.version);
  495. for (SubscriptionState* subscription : state.subscriptions) {
  496. subscription->update_queue->emplace_back(type_url, name);
  497. }
  498. }
  499. void SetLdsResource(const Listener& listener) {
  500. google::protobuf::Any resource;
  501. resource.PackFrom(listener);
  502. SetResource(std::move(resource), kLdsTypeUrl, listener.name());
  503. }
  504. void SetRdsResource(const RouteConfiguration& route) {
  505. google::protobuf::Any resource;
  506. resource.PackFrom(route);
  507. SetResource(std::move(resource), kRdsTypeUrl, route.name());
  508. }
  509. void SetCdsResource(const Cluster& cluster) {
  510. google::protobuf::Any resource;
  511. resource.PackFrom(cluster);
  512. SetResource(std::move(resource), kCdsTypeUrl, cluster.name());
  513. }
  514. void SetEdsResource(const ClusterLoadAssignment& assignment) {
  515. google::protobuf::Any resource;
  516. resource.PackFrom(assignment);
  517. SetResource(std::move(resource), kEdsTypeUrl, assignment.cluster_name());
  518. }
  519. void SetLdsToUseDynamicRds() {
  520. auto listener = default_listener_;
  521. HttpConnectionManager http_connection_manager;
  522. auto* rds = http_connection_manager.mutable_rds();
  523. rds->set_route_config_name(kDefaultRouteConfigurationName);
  524. rds->mutable_config_source()->mutable_ads();
  525. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  526. http_connection_manager);
  527. SetLdsResource(listener);
  528. }
  529. static Listener BuildListener(const RouteConfiguration& route_config) {
  530. HttpConnectionManager http_connection_manager;
  531. *(http_connection_manager.mutable_route_config()) = route_config;
  532. Listener listener;
  533. listener.set_name(kServerName);
  534. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  535. http_connection_manager);
  536. return listener;
  537. }
  538. static ClusterLoadAssignment BuildEdsResource(
  539. const EdsResourceArgs& args,
  540. const char* eds_service_name = kDefaultEdsServiceName) {
  541. ClusterLoadAssignment assignment;
  542. assignment.set_cluster_name(eds_service_name);
  543. for (const auto& locality : args.locality_list) {
  544. auto* endpoints = assignment.add_endpoints();
  545. endpoints->mutable_load_balancing_weight()->set_value(locality.lb_weight);
  546. endpoints->set_priority(locality.priority);
  547. endpoints->mutable_locality()->set_region(kDefaultLocalityRegion);
  548. endpoints->mutable_locality()->set_zone(kDefaultLocalityZone);
  549. endpoints->mutable_locality()->set_sub_zone(locality.sub_zone);
  550. for (size_t i = 0; i < locality.ports.size(); ++i) {
  551. const int& port = locality.ports[i];
  552. auto* lb_endpoints = endpoints->add_lb_endpoints();
  553. if (locality.health_statuses.size() > i &&
  554. locality.health_statuses[i] != HealthStatus::UNKNOWN) {
  555. lb_endpoints->set_health_status(locality.health_statuses[i]);
  556. }
  557. auto* endpoint = lb_endpoints->mutable_endpoint();
  558. auto* address = endpoint->mutable_address();
  559. auto* socket_address = address->mutable_socket_address();
  560. socket_address->set_address("127.0.0.1");
  561. socket_address->set_port_value(port);
  562. }
  563. }
  564. if (!args.drop_categories.empty()) {
  565. auto* policy = assignment.mutable_policy();
  566. for (const auto& p : args.drop_categories) {
  567. const std::string& name = p.first;
  568. const uint32_t parts_per_million = p.second;
  569. auto* drop_overload = policy->add_drop_overloads();
  570. drop_overload->set_category(name);
  571. auto* drop_percentage = drop_overload->mutable_drop_percentage();
  572. drop_percentage->set_numerator(parts_per_million);
  573. drop_percentage->set_denominator(args.drop_denominator);
  574. }
  575. }
  576. return assignment;
  577. }
  578. void Start() {
  579. grpc_core::MutexLock lock(&ads_mu_);
  580. ads_done_ = false;
  581. }
  582. void Shutdown() {
  583. {
  584. grpc_core::MutexLock lock(&ads_mu_);
  585. NotifyDoneWithAdsCallLocked();
  586. resource_type_response_state_.clear();
  587. }
  588. gpr_log(GPR_INFO, "ADS[%p]: shut down", this);
  589. }
  590. void NotifyDoneWithAdsCall() {
  591. grpc_core::MutexLock lock(&ads_mu_);
  592. NotifyDoneWithAdsCallLocked();
  593. }
  594. void NotifyDoneWithAdsCallLocked() {
  595. if (!ads_done_) {
  596. ads_done_ = true;
  597. ads_cond_.Broadcast();
  598. }
  599. }
  600. std::set<std::string> clients() {
  601. grpc_core::MutexLock lock(&clients_mu_);
  602. return clients_;
  603. }
  604. private:
  605. // A queue of resource type/name pairs that have changed since the client
  606. // subscribed to them.
  607. using UpdateQueue = std::deque<
  608. std::pair<std::string /* type url */, std::string /* resource name */>>;
  609. // A struct representing a client's subscription to a particular resource.
  610. struct SubscriptionState {
  611. // Version that the client currently knows about.
  612. int current_version = 0;
  613. // The queue upon which to place updates when the resource is updated.
  614. UpdateQueue* update_queue;
  615. };
  616. // A struct representing the a client's subscription to all the resources.
  617. using SubscriptionNameMap =
  618. std::map<std::string /* resource_name */, SubscriptionState>;
  619. using SubscriptionMap =
  620. std::map<std::string /* type_url */, SubscriptionNameMap>;
  621. // A struct representing the current state for a resource:
  622. // - the version of the resource that is set by the SetResource() methods.
  623. // - a list of subscriptions interested in this resource.
  624. struct ResourceState {
  625. int version = 0;
  626. absl::optional<google::protobuf::Any> resource;
  627. std::set<SubscriptionState*> subscriptions;
  628. };
  629. // A struct representing the current state for all resources:
  630. // LDS, CDS, EDS, and RDS for the class as a whole.
  631. using ResourceNameMap =
  632. std::map<std::string /* resource_name */, ResourceState>;
  633. using ResourceMap = std::map<std::string /* type_url */, ResourceNameMap>;
  634. template <class RpcApi, class DiscoveryRequest, class DiscoveryResponse>
  635. class RpcService : public RpcApi::Service {
  636. public:
  637. using Stream = ServerReaderWriter<DiscoveryResponse, DiscoveryRequest>;
  638. RpcService(AdsServiceImpl* parent, bool is_v2)
  639. : parent_(parent), is_v2_(is_v2) {}
  640. Status StreamAggregatedResources(ServerContext* context,
  641. Stream* stream) override {
  642. gpr_log(GPR_INFO, "ADS[%p]: StreamAggregatedResources starts", this);
  643. parent_->AddClient(context->peer());
  644. if (is_v2_) {
  645. parent_->seen_v2_client_ = true;
  646. } else {
  647. parent_->seen_v3_client_ = true;
  648. }
  649. // Resources (type/name pairs) that have changed since the client
  650. // subscribed to them.
  651. UpdateQueue update_queue;
  652. // Resources that the client will be subscribed to keyed by resource type
  653. // url.
  654. SubscriptionMap subscription_map;
  655. [&]() {
  656. {
  657. grpc_core::MutexLock lock(&parent_->ads_mu_);
  658. if (parent_->ads_done_) return;
  659. }
  660. // Balancer shouldn't receive the call credentials metadata.
  661. EXPECT_EQ(context->client_metadata().find(g_kCallCredsMdKey),
  662. context->client_metadata().end());
  663. // Current Version map keyed by resource type url.
  664. std::map<std::string, int> resource_type_version;
  665. // Creating blocking thread to read from stream.
  666. std::deque<DiscoveryRequest> requests;
  667. bool stream_closed = false;
  668. // Take a reference of the AdsServiceImpl object, reference will go
  669. // out of scope after the reader thread is joined.
  670. std::shared_ptr<AdsServiceImpl> ads_service_impl =
  671. parent_->shared_from_this();
  672. std::thread reader(std::bind(&RpcService::BlockingRead, this, stream,
  673. &requests, &stream_closed));
  674. // Main loop to look for requests and updates.
  675. while (true) {
  676. // Look for new requests and and decide what to handle.
  677. absl::optional<DiscoveryResponse> response;
  678. // Boolean to keep track if the loop received any work to do: a
  679. // request or an update; regardless whether a response was actually
  680. // sent out.
  681. bool did_work = false;
  682. {
  683. grpc_core::MutexLock lock(&parent_->ads_mu_);
  684. if (stream_closed) break;
  685. if (!requests.empty()) {
  686. DiscoveryRequest request = std::move(requests.front());
  687. requests.pop_front();
  688. did_work = true;
  689. gpr_log(GPR_INFO,
  690. "ADS[%p]: Received request for type %s with content %s",
  691. this, request.type_url().c_str(),
  692. request.DebugString().c_str());
  693. const std::string v3_resource_type =
  694. TypeUrlToV3(request.type_url());
  695. // As long as we are not in shutdown, identify ACK and NACK by
  696. // looking for version information and comparing it to nonce (this
  697. // server ensures they are always set to the same in a response.)
  698. auto it =
  699. parent_->resource_type_response_state_.find(v3_resource_type);
  700. if (it != parent_->resource_type_response_state_.end()) {
  701. if (!request.response_nonce().empty()) {
  702. it->second.state =
  703. (!request.version_info().empty() &&
  704. request.version_info() == request.response_nonce())
  705. ? ResponseState::ACKED
  706. : ResponseState::NACKED;
  707. }
  708. if (request.has_error_detail()) {
  709. it->second.error_message = request.error_detail().message();
  710. }
  711. }
  712. // As long as the test did not tell us to ignore this type of
  713. // request, look at all the resource names.
  714. if (parent_->resource_types_to_ignore_.find(v3_resource_type) ==
  715. parent_->resource_types_to_ignore_.end()) {
  716. auto& subscription_name_map =
  717. subscription_map[v3_resource_type];
  718. auto& resource_name_map =
  719. parent_->resource_map_[v3_resource_type];
  720. std::set<std::string> resources_in_current_request;
  721. std::set<std::string> resources_added_to_response;
  722. for (const std::string& resource_name :
  723. request.resource_names()) {
  724. resources_in_current_request.emplace(resource_name);
  725. auto& subscription_state =
  726. subscription_name_map[resource_name];
  727. auto& resource_state = resource_name_map[resource_name];
  728. // Subscribe if needed.
  729. parent_->MaybeSubscribe(v3_resource_type, resource_name,
  730. &subscription_state, &resource_state,
  731. &update_queue);
  732. // Send update if needed.
  733. if (ClientNeedsResourceUpdate(resource_state,
  734. &subscription_state)) {
  735. gpr_log(GPR_INFO,
  736. "ADS[%p]: Sending update for type=%s name=%s "
  737. "version=%d",
  738. this, request.type_url().c_str(),
  739. resource_name.c_str(), resource_state.version);
  740. resources_added_to_response.emplace(resource_name);
  741. if (!response.has_value()) response.emplace();
  742. if (resource_state.resource.has_value()) {
  743. auto* resource = response->add_resources();
  744. resource->CopyFrom(resource_state.resource.value());
  745. if (is_v2_) {
  746. resource->set_type_url(request.type_url());
  747. }
  748. }
  749. } else {
  750. gpr_log(GPR_INFO,
  751. "ADS[%p]: client does not need update for "
  752. "type=%s name=%s version=%d",
  753. this, request.type_url().c_str(),
  754. resource_name.c_str(), resource_state.version);
  755. }
  756. }
  757. // Process unsubscriptions for any resource no longer
  758. // present in the request's resource list.
  759. parent_->ProcessUnsubscriptions(
  760. v3_resource_type, resources_in_current_request,
  761. &subscription_name_map, &resource_name_map);
  762. // Send response if needed.
  763. if (!resources_added_to_response.empty()) {
  764. CompleteBuildingDiscoveryResponse(
  765. v3_resource_type, request.type_url(),
  766. ++resource_type_version[v3_resource_type],
  767. subscription_name_map, resources_added_to_response,
  768. &response.value());
  769. }
  770. }
  771. }
  772. }
  773. if (response.has_value()) {
  774. gpr_log(GPR_INFO, "ADS[%p]: Sending response: %s", this,
  775. response->DebugString().c_str());
  776. stream->Write(response.value());
  777. }
  778. response.reset();
  779. // Look for updates and decide what to handle.
  780. {
  781. grpc_core::MutexLock lock(&parent_->ads_mu_);
  782. if (!update_queue.empty()) {
  783. const std::string resource_type =
  784. std::move(update_queue.front().first);
  785. const std::string resource_name =
  786. std::move(update_queue.front().second);
  787. update_queue.pop_front();
  788. const std::string v2_resource_type = TypeUrlToV2(resource_type);
  789. did_work = true;
  790. gpr_log(GPR_INFO, "ADS[%p]: Received update for type=%s name=%s",
  791. this, resource_type.c_str(), resource_name.c_str());
  792. auto& subscription_name_map = subscription_map[resource_type];
  793. auto& resource_name_map = parent_->resource_map_[resource_type];
  794. auto it = subscription_name_map.find(resource_name);
  795. if (it != subscription_name_map.end()) {
  796. SubscriptionState& subscription_state = it->second;
  797. ResourceState& resource_state =
  798. resource_name_map[resource_name];
  799. if (ClientNeedsResourceUpdate(resource_state,
  800. &subscription_state)) {
  801. gpr_log(
  802. GPR_INFO,
  803. "ADS[%p]: Sending update for type=%s name=%s version=%d",
  804. this, resource_type.c_str(), resource_name.c_str(),
  805. resource_state.version);
  806. response.emplace();
  807. if (resource_state.resource.has_value()) {
  808. auto* resource = response->add_resources();
  809. resource->CopyFrom(resource_state.resource.value());
  810. if (is_v2_) {
  811. resource->set_type_url(v2_resource_type);
  812. }
  813. }
  814. CompleteBuildingDiscoveryResponse(
  815. resource_type, v2_resource_type,
  816. ++resource_type_version[resource_type],
  817. subscription_name_map, {resource_name},
  818. &response.value());
  819. }
  820. }
  821. }
  822. }
  823. if (response.has_value()) {
  824. gpr_log(GPR_INFO, "ADS[%p]: Sending update response: %s", this,
  825. response->DebugString().c_str());
  826. stream->Write(response.value());
  827. }
  828. // If we didn't find anything to do, delay before the next loop
  829. // iteration; otherwise, check whether we should exit and then
  830. // immediately continue.
  831. gpr_timespec deadline =
  832. grpc_timeout_milliseconds_to_deadline(did_work ? 0 : 10);
  833. {
  834. grpc_core::MutexLock lock(&parent_->ads_mu_);
  835. if (!parent_->ads_cond_.WaitUntil(
  836. &parent_->ads_mu_, [this] { return parent_->ads_done_; },
  837. deadline)) {
  838. break;
  839. }
  840. }
  841. }
  842. reader.join();
  843. }();
  844. // Clean up any subscriptions that were still active when the call
  845. // finished.
  846. {
  847. grpc_core::MutexLock lock(&parent_->ads_mu_);
  848. for (auto& p : subscription_map) {
  849. const std::string& type_url = p.first;
  850. SubscriptionNameMap& subscription_name_map = p.second;
  851. for (auto& q : subscription_name_map) {
  852. const std::string& resource_name = q.first;
  853. SubscriptionState& subscription_state = q.second;
  854. ResourceState& resource_state =
  855. parent_->resource_map_[type_url][resource_name];
  856. resource_state.subscriptions.erase(&subscription_state);
  857. }
  858. }
  859. }
  860. gpr_log(GPR_INFO, "ADS[%p]: StreamAggregatedResources done", this);
  861. parent_->RemoveClient(context->peer());
  862. return Status::OK;
  863. }
  864. private:
  865. static std::string TypeUrlToV2(const std::string& resource_type) {
  866. if (resource_type == kLdsTypeUrl) return kLdsV2TypeUrl;
  867. if (resource_type == kRdsTypeUrl) return kRdsV2TypeUrl;
  868. if (resource_type == kCdsTypeUrl) return kCdsV2TypeUrl;
  869. if (resource_type == kEdsTypeUrl) return kEdsV2TypeUrl;
  870. return resource_type;
  871. }
  872. static std::string TypeUrlToV3(const std::string& resource_type) {
  873. if (resource_type == kLdsV2TypeUrl) return kLdsTypeUrl;
  874. if (resource_type == kRdsV2TypeUrl) return kRdsTypeUrl;
  875. if (resource_type == kCdsV2TypeUrl) return kCdsTypeUrl;
  876. if (resource_type == kEdsV2TypeUrl) return kEdsTypeUrl;
  877. return resource_type;
  878. }
  879. // Starting a thread to do blocking read on the stream until cancel.
  880. void BlockingRead(Stream* stream, std::deque<DiscoveryRequest>* requests,
  881. bool* stream_closed) {
  882. DiscoveryRequest request;
  883. bool seen_first_request = false;
  884. while (stream->Read(&request)) {
  885. if (!seen_first_request) {
  886. EXPECT_TRUE(request.has_node());
  887. ASSERT_FALSE(request.node().client_features().empty());
  888. EXPECT_EQ(request.node().client_features(0),
  889. "envoy.lb.does_not_support_overprovisioning");
  890. CheckBuildVersion(request);
  891. seen_first_request = true;
  892. }
  893. {
  894. grpc_core::MutexLock lock(&parent_->ads_mu_);
  895. requests->emplace_back(std::move(request));
  896. }
  897. }
  898. gpr_log(GPR_INFO, "ADS[%p]: Null read, stream closed", this);
  899. grpc_core::MutexLock lock(&parent_->ads_mu_);
  900. *stream_closed = true;
  901. }
  902. static void CheckBuildVersion(
  903. const ::envoy::api::v2::DiscoveryRequest& request) {
  904. EXPECT_FALSE(request.node().build_version().empty());
  905. }
  906. static void CheckBuildVersion(
  907. const ::envoy::service::discovery::v3::DiscoveryRequest& request) {}
  908. // Completing the building a DiscoveryResponse by adding common information
  909. // for all resources and by adding all subscribed resources for LDS and CDS.
  910. void CompleteBuildingDiscoveryResponse(
  911. const std::string& resource_type, const std::string& v2_resource_type,
  912. const int version, const SubscriptionNameMap& subscription_name_map,
  913. const std::set<std::string>& resources_added_to_response,
  914. DiscoveryResponse* response) {
  915. auto& response_state =
  916. parent_->resource_type_response_state_[resource_type];
  917. if (response_state.state == ResponseState::NOT_SENT) {
  918. response_state.state = ResponseState::SENT;
  919. }
  920. response->set_type_url(is_v2_ ? v2_resource_type : resource_type);
  921. response->set_version_info(absl::StrCat(version));
  922. response->set_nonce(absl::StrCat(version));
  923. if (resource_type == kLdsTypeUrl || resource_type == kCdsTypeUrl) {
  924. // For LDS and CDS we must send back all subscribed resources
  925. // (even the unchanged ones)
  926. for (const auto& p : subscription_name_map) {
  927. const std::string& resource_name = p.first;
  928. if (resources_added_to_response.find(resource_name) ==
  929. resources_added_to_response.end()) {
  930. const ResourceState& resource_state =
  931. parent_->resource_map_[resource_type][resource_name];
  932. if (resource_state.resource.has_value()) {
  933. auto* resource = response->add_resources();
  934. resource->CopyFrom(resource_state.resource.value());
  935. if (is_v2_) {
  936. resource->set_type_url(v2_resource_type);
  937. }
  938. }
  939. }
  940. }
  941. }
  942. }
  943. AdsServiceImpl* parent_;
  944. const bool is_v2_;
  945. };
  946. // Checks whether the client needs to receive a newer version of
  947. // the resource. If so, updates subscription_state->current_version and
  948. // returns true.
  949. static bool ClientNeedsResourceUpdate(const ResourceState& resource_state,
  950. SubscriptionState* subscription_state) {
  951. if (subscription_state->current_version < resource_state.version) {
  952. subscription_state->current_version = resource_state.version;
  953. return true;
  954. }
  955. return false;
  956. }
  957. // Subscribes to a resource if not already subscribed:
  958. // 1. Sets the update_queue field in subscription_state.
  959. // 2. Adds subscription_state to resource_state->subscriptions.
  960. void MaybeSubscribe(const std::string& resource_type,
  961. const std::string& resource_name,
  962. SubscriptionState* subscription_state,
  963. ResourceState* resource_state,
  964. UpdateQueue* update_queue) {
  965. // The update_queue will be null if we were not previously subscribed.
  966. if (subscription_state->update_queue != nullptr) return;
  967. subscription_state->update_queue = update_queue;
  968. resource_state->subscriptions.emplace(subscription_state);
  969. gpr_log(GPR_INFO, "ADS[%p]: subscribe to resource type %s name %s state %p",
  970. this, resource_type.c_str(), resource_name.c_str(),
  971. &subscription_state);
  972. }
  973. // Removes subscriptions for resources no longer present in the
  974. // current request.
  975. void ProcessUnsubscriptions(
  976. const std::string& resource_type,
  977. const std::set<std::string>& resources_in_current_request,
  978. SubscriptionNameMap* subscription_name_map,
  979. ResourceNameMap* resource_name_map) {
  980. for (auto it = subscription_name_map->begin();
  981. it != subscription_name_map->end();) {
  982. const std::string& resource_name = it->first;
  983. SubscriptionState& subscription_state = it->second;
  984. if (resources_in_current_request.find(resource_name) !=
  985. resources_in_current_request.end()) {
  986. ++it;
  987. continue;
  988. }
  989. gpr_log(GPR_INFO, "ADS[%p]: Unsubscribe to type=%s name=%s state=%p",
  990. this, resource_type.c_str(), resource_name.c_str(),
  991. &subscription_state);
  992. auto resource_it = resource_name_map->find(resource_name);
  993. GPR_ASSERT(resource_it != resource_name_map->end());
  994. auto& resource_state = resource_it->second;
  995. resource_state.subscriptions.erase(&subscription_state);
  996. if (resource_state.subscriptions.empty() &&
  997. !resource_state.resource.has_value()) {
  998. resource_name_map->erase(resource_it);
  999. }
  1000. it = subscription_name_map->erase(it);
  1001. }
  1002. }
  1003. void AddClient(const std::string& client) {
  1004. grpc_core::MutexLock lock(&clients_mu_);
  1005. clients_.insert(client);
  1006. }
  1007. void RemoveClient(const std::string& client) {
  1008. grpc_core::MutexLock lock(&clients_mu_);
  1009. clients_.erase(client);
  1010. }
  1011. RpcService<::envoy::service::discovery::v2::AggregatedDiscoveryService,
  1012. ::envoy::api::v2::DiscoveryRequest,
  1013. ::envoy::api::v2::DiscoveryResponse>
  1014. v2_rpc_service_;
  1015. RpcService<::envoy::service::discovery::v3::AggregatedDiscoveryService,
  1016. ::envoy::service::discovery::v3::DiscoveryRequest,
  1017. ::envoy::service::discovery::v3::DiscoveryResponse>
  1018. v3_rpc_service_;
  1019. std::atomic_bool seen_v2_client_{false};
  1020. std::atomic_bool seen_v3_client_{false};
  1021. grpc_core::CondVar ads_cond_;
  1022. // Protect the members below.
  1023. grpc_core::Mutex ads_mu_;
  1024. bool ads_done_ = false;
  1025. Listener default_listener_;
  1026. RouteConfiguration default_route_config_;
  1027. Cluster default_cluster_;
  1028. std::map<std::string /* type_url */, ResponseState>
  1029. resource_type_response_state_;
  1030. std::set<std::string /*resource_type*/> resource_types_to_ignore_;
  1031. // An instance data member containing the current state of all resources.
  1032. // Note that an entry will exist whenever either of the following is true:
  1033. // - The resource exists (i.e., has been created by SetResource() and has not
  1034. // yet been destroyed by UnsetResource()).
  1035. // - There is at least one subscription for the resource.
  1036. ResourceMap resource_map_;
  1037. grpc_core::Mutex clients_mu_;
  1038. std::set<std::string> clients_;
  1039. };
  1040. class LrsServiceImpl : public std::enable_shared_from_this<LrsServiceImpl> {
  1041. public:
  1042. explicit LrsServiceImpl(int client_load_reporting_interval_seconds)
  1043. : v2_rpc_service_(this),
  1044. v3_rpc_service_(this),
  1045. client_load_reporting_interval_seconds_(
  1046. client_load_reporting_interval_seconds),
  1047. cluster_names_({kDefaultClusterName}) {}
  1048. ::envoy::service::load_stats::v2::LoadReportingService::Service*
  1049. v2_rpc_service() {
  1050. return &v2_rpc_service_;
  1051. }
  1052. ::envoy::service::load_stats::v3::LoadReportingService::Service*
  1053. v3_rpc_service() {
  1054. return &v3_rpc_service_;
  1055. }
  1056. size_t request_count() {
  1057. return v2_rpc_service_.request_count() + v3_rpc_service_.request_count();
  1058. }
  1059. size_t response_count() {
  1060. return v2_rpc_service_.response_count() + v3_rpc_service_.response_count();
  1061. }
  1062. // Must be called before the LRS call is started.
  1063. void set_send_all_clusters(bool send_all_clusters) {
  1064. send_all_clusters_ = send_all_clusters;
  1065. }
  1066. void set_cluster_names(const std::set<std::string>& cluster_names) {
  1067. cluster_names_ = cluster_names;
  1068. }
  1069. void Start() {
  1070. lrs_done_ = false;
  1071. result_queue_.clear();
  1072. }
  1073. void Shutdown() {
  1074. {
  1075. grpc_core::MutexLock lock(&lrs_mu_);
  1076. NotifyDoneWithLrsCallLocked();
  1077. }
  1078. gpr_log(GPR_INFO, "LRS[%p]: shut down", this);
  1079. }
  1080. std::vector<ClientStats> WaitForLoadReport() {
  1081. grpc_core::MutexLock lock(&load_report_mu_);
  1082. grpc_core::CondVar cv;
  1083. if (result_queue_.empty()) {
  1084. load_report_cond_ = &cv;
  1085. load_report_cond_->WaitUntil(&load_report_mu_,
  1086. [this] { return !result_queue_.empty(); });
  1087. load_report_cond_ = nullptr;
  1088. }
  1089. std::vector<ClientStats> result = std::move(result_queue_.front());
  1090. result_queue_.pop_front();
  1091. return result;
  1092. }
  1093. void NotifyDoneWithLrsCall() {
  1094. grpc_core::MutexLock lock(&lrs_mu_);
  1095. NotifyDoneWithLrsCallLocked();
  1096. }
  1097. private:
  1098. template <class RpcApi, class LoadStatsRequest, class LoadStatsResponse>
  1099. class RpcService : public CountedService<typename RpcApi::Service> {
  1100. public:
  1101. using Stream = ServerReaderWriter<LoadStatsResponse, LoadStatsRequest>;
  1102. explicit RpcService(LrsServiceImpl* parent) : parent_(parent) {}
  1103. Status StreamLoadStats(ServerContext* /*context*/,
  1104. Stream* stream) override {
  1105. gpr_log(GPR_INFO, "LRS[%p]: StreamLoadStats starts", this);
  1106. EXPECT_GT(parent_->client_load_reporting_interval_seconds_, 0);
  1107. // Take a reference of the LrsServiceImpl object, reference will go
  1108. // out of scope after this method exits.
  1109. std::shared_ptr<LrsServiceImpl> lrs_service_impl =
  1110. parent_->shared_from_this();
  1111. // Read initial request.
  1112. LoadStatsRequest request;
  1113. if (stream->Read(&request)) {
  1114. CountedService<typename RpcApi::Service>::IncreaseRequestCount();
  1115. // Verify client features.
  1116. EXPECT_THAT(
  1117. request.node().client_features(),
  1118. ::testing::Contains("envoy.lrs.supports_send_all_clusters"));
  1119. // Send initial response.
  1120. LoadStatsResponse response;
  1121. if (parent_->send_all_clusters_) {
  1122. response.set_send_all_clusters(true);
  1123. } else {
  1124. for (const std::string& cluster_name : parent_->cluster_names_) {
  1125. response.add_clusters(cluster_name);
  1126. }
  1127. }
  1128. response.mutable_load_reporting_interval()->set_seconds(
  1129. parent_->client_load_reporting_interval_seconds_);
  1130. stream->Write(response);
  1131. CountedService<typename RpcApi::Service>::IncreaseResponseCount();
  1132. // Wait for report.
  1133. request.Clear();
  1134. while (stream->Read(&request)) {
  1135. gpr_log(GPR_INFO, "LRS[%p]: received client load report message: %s",
  1136. this, request.DebugString().c_str());
  1137. std::vector<ClientStats> stats;
  1138. for (const auto& cluster_stats : request.cluster_stats()) {
  1139. stats.emplace_back(cluster_stats);
  1140. }
  1141. grpc_core::MutexLock lock(&parent_->load_report_mu_);
  1142. parent_->result_queue_.emplace_back(std::move(stats));
  1143. if (parent_->load_report_cond_ != nullptr) {
  1144. parent_->load_report_cond_->Signal();
  1145. }
  1146. }
  1147. // Wait until notified done.
  1148. grpc_core::MutexLock lock(&parent_->lrs_mu_);
  1149. parent_->lrs_cv_.WaitUntil(&parent_->lrs_mu_,
  1150. [this] { return parent_->lrs_done_; });
  1151. }
  1152. gpr_log(GPR_INFO, "LRS[%p]: StreamLoadStats done", this);
  1153. return Status::OK;
  1154. }
  1155. private:
  1156. LrsServiceImpl* parent_;
  1157. };
  1158. void NotifyDoneWithLrsCallLocked() {
  1159. if (!lrs_done_) {
  1160. lrs_done_ = true;
  1161. lrs_cv_.Broadcast();
  1162. }
  1163. }
  1164. RpcService<::envoy::service::load_stats::v2::LoadReportingService,
  1165. ::envoy::service::load_stats::v2::LoadStatsRequest,
  1166. ::envoy::service::load_stats::v2::LoadStatsResponse>
  1167. v2_rpc_service_;
  1168. RpcService<::envoy::service::load_stats::v3::LoadReportingService,
  1169. ::envoy::service::load_stats::v3::LoadStatsRequest,
  1170. ::envoy::service::load_stats::v3::LoadStatsResponse>
  1171. v3_rpc_service_;
  1172. const int client_load_reporting_interval_seconds_;
  1173. bool send_all_clusters_ = false;
  1174. std::set<std::string> cluster_names_;
  1175. grpc_core::CondVar lrs_cv_;
  1176. grpc_core::Mutex lrs_mu_; // Protects lrs_done_.
  1177. bool lrs_done_ = false;
  1178. grpc_core::Mutex load_report_mu_; // Protects the members below.
  1179. grpc_core::CondVar* load_report_cond_ = nullptr;
  1180. std::deque<std::vector<ClientStats>> result_queue_;
  1181. };
  1182. class TestType {
  1183. public:
  1184. TestType(bool use_xds_resolver, bool enable_load_reporting,
  1185. bool enable_rds_testing = false, bool use_v2 = false)
  1186. : use_xds_resolver_(use_xds_resolver),
  1187. enable_load_reporting_(enable_load_reporting),
  1188. enable_rds_testing_(enable_rds_testing),
  1189. use_v2_(use_v2) {}
  1190. bool use_xds_resolver() const { return use_xds_resolver_; }
  1191. bool enable_load_reporting() const { return enable_load_reporting_; }
  1192. bool enable_rds_testing() const { return enable_rds_testing_; }
  1193. bool use_v2() const { return use_v2_; }
  1194. std::string AsString() const {
  1195. std::string retval = (use_xds_resolver_ ? "XdsResolver" : "FakeResolver");
  1196. retval += (use_v2_ ? "V2" : "V3");
  1197. if (enable_load_reporting_) retval += "WithLoadReporting";
  1198. if (enable_rds_testing_) retval += "Rds";
  1199. return retval;
  1200. }
  1201. private:
  1202. const bool use_xds_resolver_;
  1203. const bool enable_load_reporting_;
  1204. const bool enable_rds_testing_;
  1205. const bool use_v2_;
  1206. };
  1207. class XdsEnd2endTest : public ::testing::TestWithParam<TestType> {
  1208. protected:
  1209. XdsEnd2endTest(size_t num_backends, size_t num_balancers,
  1210. int client_load_reporting_interval_seconds = 100)
  1211. : num_backends_(num_backends),
  1212. num_balancers_(num_balancers),
  1213. client_load_reporting_interval_seconds_(
  1214. client_load_reporting_interval_seconds) {}
  1215. static void SetUpTestCase() {
  1216. // Make the backup poller poll very frequently in order to pick up
  1217. // updates from all the subchannels's FDs.
  1218. GPR_GLOBAL_CONFIG_SET(grpc_client_channel_backup_poll_interval_ms, 1);
  1219. #if TARGET_OS_IPHONE
  1220. // Workaround Apple CFStream bug
  1221. gpr_setenv("grpc_cfstream", "0");
  1222. #endif
  1223. grpc_init();
  1224. }
  1225. static void TearDownTestCase() { grpc_shutdown(); }
  1226. void SetUp() override {
  1227. gpr_setenv("GRPC_XDS_EXPERIMENTAL_V3_SUPPORT", "true");
  1228. gpr_setenv("GRPC_XDS_BOOTSTRAP",
  1229. GetParam().use_v2() ? g_bootstrap_file_v2 : g_bootstrap_file_v3);
  1230. g_port_saver->Reset();
  1231. response_generator_ =
  1232. grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
  1233. // Inject xDS channel response generator.
  1234. lb_channel_response_generator_ =
  1235. grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
  1236. xds_channel_args_to_add_.emplace_back(
  1237. grpc_core::FakeResolverResponseGenerator::MakeChannelArg(
  1238. lb_channel_response_generator_.get()));
  1239. if (xds_resource_does_not_exist_timeout_ms_ > 0) {
  1240. xds_channel_args_to_add_.emplace_back(grpc_channel_arg_integer_create(
  1241. const_cast<char*>(GRPC_ARG_XDS_RESOURCE_DOES_NOT_EXIST_TIMEOUT_MS),
  1242. xds_resource_does_not_exist_timeout_ms_));
  1243. }
  1244. xds_channel_args_.num_args = xds_channel_args_to_add_.size();
  1245. xds_channel_args_.args = xds_channel_args_to_add_.data();
  1246. grpc_core::internal::SetXdsChannelArgsForTest(&xds_channel_args_);
  1247. // Make sure each test creates a new XdsClient instance rather than
  1248. // reusing the one from the previous test. This avoids spurious failures
  1249. // caused when a load reporting test runs after a non-load reporting test
  1250. // and the XdsClient is still talking to the old LRS server, which fails
  1251. // because it's not expecting the client to connect. It also
  1252. // ensures that each test can independently set the global channel
  1253. // args for the xDS channel.
  1254. grpc_core::internal::UnsetGlobalXdsClientForTest();
  1255. // Start the backends.
  1256. for (size_t i = 0; i < num_backends_; ++i) {
  1257. backends_.emplace_back(new BackendServerThread);
  1258. backends_.back()->Start();
  1259. }
  1260. // Start the load balancers.
  1261. for (size_t i = 0; i < num_balancers_; ++i) {
  1262. balancers_.emplace_back(
  1263. new BalancerServerThread(GetParam().enable_load_reporting()
  1264. ? client_load_reporting_interval_seconds_
  1265. : 0));
  1266. balancers_.back()->Start();
  1267. if (GetParam().enable_rds_testing()) {
  1268. balancers_[i]->ads_service()->SetLdsToUseDynamicRds();
  1269. }
  1270. }
  1271. ResetStub();
  1272. }
  1273. const char* DefaultEdsServiceName() const {
  1274. return GetParam().use_xds_resolver() ? kDefaultEdsServiceName : kServerName;
  1275. }
  1276. void TearDown() override {
  1277. ShutdownAllBackends();
  1278. for (auto& balancer : balancers_) balancer->Shutdown();
  1279. // Clear global xDS channel args, since they will go out of scope
  1280. // when this test object is destroyed.
  1281. grpc_core::internal::SetXdsChannelArgsForTest(nullptr);
  1282. }
  1283. void StartAllBackends() {
  1284. for (auto& backend : backends_) backend->Start();
  1285. }
  1286. void StartBackend(size_t index) { backends_[index]->Start(); }
  1287. void ShutdownAllBackends() {
  1288. for (auto& backend : backends_) backend->Shutdown();
  1289. }
  1290. void ShutdownBackend(size_t index) { backends_[index]->Shutdown(); }
  1291. void ResetStub(int failover_timeout = 0) {
  1292. channel_ = CreateChannel(failover_timeout);
  1293. stub_ = grpc::testing::EchoTestService::NewStub(channel_);
  1294. stub1_ = grpc::testing::EchoTest1Service::NewStub(channel_);
  1295. stub2_ = grpc::testing::EchoTest2Service::NewStub(channel_);
  1296. }
  1297. std::shared_ptr<Channel> CreateChannel(
  1298. int failover_timeout = 0, const char* server_name = kServerName) {
  1299. ChannelArguments args;
  1300. if (failover_timeout > 0) {
  1301. args.SetInt(GRPC_ARG_PRIORITY_FAILOVER_TIMEOUT_MS, failover_timeout);
  1302. }
  1303. // If the parent channel is using the fake resolver, we inject the
  1304. // response generator here.
  1305. if (!GetParam().use_xds_resolver()) {
  1306. args.SetPointer(GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR,
  1307. response_generator_.get());
  1308. }
  1309. std::string uri = absl::StrCat(
  1310. GetParam().use_xds_resolver() ? "xds" : "fake", ":///", server_name);
  1311. // TODO(dgq): templatize tests to run everything using both secure and
  1312. // insecure channel credentials.
  1313. grpc_channel_credentials* channel_creds =
  1314. grpc_fake_transport_security_credentials_create();
  1315. grpc_call_credentials* call_creds = grpc_md_only_test_credentials_create(
  1316. g_kCallCredsMdKey, g_kCallCredsMdValue, false);
  1317. std::shared_ptr<ChannelCredentials> creds(
  1318. new SecureChannelCredentials(grpc_composite_channel_credentials_create(
  1319. channel_creds, call_creds, nullptr)));
  1320. call_creds->Unref();
  1321. channel_creds->Unref();
  1322. return ::grpc::CreateCustomChannel(uri, creds, args);
  1323. }
  1324. enum RpcService {
  1325. SERVICE_ECHO,
  1326. SERVICE_ECHO1,
  1327. SERVICE_ECHO2,
  1328. };
  1329. enum RpcMethod {
  1330. METHOD_ECHO,
  1331. METHOD_ECHO1,
  1332. METHOD_ECHO2,
  1333. };
  1334. struct RpcOptions {
  1335. RpcService service = SERVICE_ECHO;
  1336. RpcMethod method = METHOD_ECHO;
  1337. int timeout_ms = 1000;
  1338. bool wait_for_ready = false;
  1339. bool server_fail = false;
  1340. std::vector<std::pair<std::string, std::string>> metadata;
  1341. RpcOptions() {}
  1342. RpcOptions& set_rpc_service(RpcService rpc_service) {
  1343. service = rpc_service;
  1344. return *this;
  1345. }
  1346. RpcOptions& set_rpc_method(RpcMethod rpc_method) {
  1347. method = rpc_method;
  1348. return *this;
  1349. }
  1350. RpcOptions& set_timeout_ms(int rpc_timeout_ms) {
  1351. timeout_ms = rpc_timeout_ms;
  1352. return *this;
  1353. }
  1354. RpcOptions& set_wait_for_ready(bool rpc_wait_for_ready) {
  1355. wait_for_ready = rpc_wait_for_ready;
  1356. return *this;
  1357. }
  1358. RpcOptions& set_server_fail(bool rpc_server_fail) {
  1359. server_fail = rpc_server_fail;
  1360. return *this;
  1361. }
  1362. RpcOptions& set_metadata(
  1363. std::vector<std::pair<std::string, std::string>> rpc_metadata) {
  1364. metadata = rpc_metadata;
  1365. return *this;
  1366. }
  1367. };
  1368. template <typename Stub>
  1369. Status SendRpcMethod(Stub* stub, const RpcOptions& rpc_options,
  1370. ClientContext* context, EchoRequest& request,
  1371. EchoResponse* response) {
  1372. switch (rpc_options.method) {
  1373. case METHOD_ECHO:
  1374. return (*stub)->Echo(context, request, response);
  1375. case METHOD_ECHO1:
  1376. return (*stub)->Echo1(context, request, response);
  1377. case METHOD_ECHO2:
  1378. return (*stub)->Echo2(context, request, response);
  1379. }
  1380. }
  1381. void ResetBackendCounters(size_t start_index = 0, size_t stop_index = 0) {
  1382. if (stop_index == 0) stop_index = backends_.size();
  1383. for (size_t i = start_index; i < stop_index; ++i) {
  1384. backends_[i]->backend_service()->ResetCounters();
  1385. backends_[i]->backend_service1()->ResetCounters();
  1386. backends_[i]->backend_service2()->ResetCounters();
  1387. }
  1388. }
  1389. bool SeenAllBackends(size_t start_index = 0, size_t stop_index = 0,
  1390. const RpcOptions& rpc_options = RpcOptions()) {
  1391. if (stop_index == 0) stop_index = backends_.size();
  1392. for (size_t i = start_index; i < stop_index; ++i) {
  1393. switch (rpc_options.service) {
  1394. case SERVICE_ECHO:
  1395. if (backends_[i]->backend_service()->request_count() == 0)
  1396. return false;
  1397. break;
  1398. case SERVICE_ECHO1:
  1399. if (backends_[i]->backend_service1()->request_count() == 0)
  1400. return false;
  1401. break;
  1402. case SERVICE_ECHO2:
  1403. if (backends_[i]->backend_service2()->request_count() == 0)
  1404. return false;
  1405. break;
  1406. }
  1407. }
  1408. return true;
  1409. }
  1410. void SendRpcAndCount(int* num_total, int* num_ok, int* num_failure,
  1411. int* num_drops,
  1412. const RpcOptions& rpc_options = RpcOptions()) {
  1413. const Status status = SendRpc(rpc_options);
  1414. if (status.ok()) {
  1415. ++*num_ok;
  1416. } else {
  1417. if (status.error_message() == "Call dropped by load balancing policy") {
  1418. ++*num_drops;
  1419. } else {
  1420. ++*num_failure;
  1421. }
  1422. }
  1423. ++*num_total;
  1424. }
  1425. std::tuple<int, int, int> WaitForAllBackends(
  1426. size_t start_index = 0, size_t stop_index = 0, bool reset_counters = true,
  1427. const RpcOptions& rpc_options = RpcOptions(),
  1428. bool allow_failures = false) {
  1429. int num_ok = 0;
  1430. int num_failure = 0;
  1431. int num_drops = 0;
  1432. int num_total = 0;
  1433. while (!SeenAllBackends(start_index, stop_index, rpc_options)) {
  1434. SendRpcAndCount(&num_total, &num_ok, &num_failure, &num_drops,
  1435. rpc_options);
  1436. }
  1437. if (reset_counters) ResetBackendCounters();
  1438. gpr_log(GPR_INFO,
  1439. "Performed %d warm up requests against the backends. "
  1440. "%d succeeded, %d failed, %d dropped.",
  1441. num_total, num_ok, num_failure, num_drops);
  1442. if (!allow_failures) EXPECT_EQ(num_failure, 0);
  1443. return std::make_tuple(num_ok, num_failure, num_drops);
  1444. }
  1445. void WaitForBackend(size_t backend_idx, bool reset_counters = true,
  1446. bool require_success = false) {
  1447. gpr_log(GPR_INFO, "========= WAITING FOR BACKEND %lu ==========",
  1448. static_cast<unsigned long>(backend_idx));
  1449. do {
  1450. Status status = SendRpc();
  1451. if (require_success) {
  1452. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  1453. << " message=" << status.error_message();
  1454. }
  1455. } while (backends_[backend_idx]->backend_service()->request_count() == 0);
  1456. if (reset_counters) ResetBackendCounters();
  1457. gpr_log(GPR_INFO, "========= BACKEND %lu READY ==========",
  1458. static_cast<unsigned long>(backend_idx));
  1459. }
  1460. grpc_core::ServerAddressList CreateAddressListFromPortList(
  1461. const std::vector<int>& ports) {
  1462. grpc_core::ServerAddressList addresses;
  1463. for (int port : ports) {
  1464. std::string lb_uri_str = absl::StrCat("ipv4:127.0.0.1:", port);
  1465. grpc_uri* lb_uri = grpc_uri_parse(lb_uri_str.c_str(), true);
  1466. GPR_ASSERT(lb_uri != nullptr);
  1467. grpc_resolved_address address;
  1468. GPR_ASSERT(grpc_parse_uri(lb_uri, &address));
  1469. addresses.emplace_back(address.addr, address.len, nullptr);
  1470. grpc_uri_destroy(lb_uri);
  1471. }
  1472. return addresses;
  1473. }
  1474. void SetNextResolution(const std::vector<int>& ports) {
  1475. if (GetParam().use_xds_resolver()) return; // Not used with xds resolver.
  1476. grpc_core::ExecCtx exec_ctx;
  1477. grpc_core::Resolver::Result result;
  1478. result.addresses = CreateAddressListFromPortList(ports);
  1479. grpc_error* error = GRPC_ERROR_NONE;
  1480. const char* service_config_json =
  1481. GetParam().enable_load_reporting()
  1482. ? kDefaultServiceConfig
  1483. : kDefaultServiceConfigWithoutLoadReporting;
  1484. result.service_config =
  1485. grpc_core::ServiceConfig::Create(nullptr, service_config_json, &error);
  1486. ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_string(error);
  1487. ASSERT_NE(result.service_config.get(), nullptr);
  1488. response_generator_->SetResponse(std::move(result));
  1489. }
  1490. void SetNextResolutionForLbChannelAllBalancers(
  1491. const char* service_config_json = nullptr,
  1492. const char* expected_targets = nullptr) {
  1493. std::vector<int> ports;
  1494. for (size_t i = 0; i < balancers_.size(); ++i) {
  1495. ports.emplace_back(balancers_[i]->port());
  1496. }
  1497. SetNextResolutionForLbChannel(ports, service_config_json, expected_targets);
  1498. }
  1499. void SetNextResolutionForLbChannel(const std::vector<int>& ports,
  1500. const char* service_config_json = nullptr,
  1501. const char* expected_targets = nullptr) {
  1502. grpc_core::ExecCtx exec_ctx;
  1503. grpc_core::Resolver::Result result;
  1504. result.addresses = CreateAddressListFromPortList(ports);
  1505. if (service_config_json != nullptr) {
  1506. grpc_error* error = GRPC_ERROR_NONE;
  1507. result.service_config = grpc_core::ServiceConfig::Create(
  1508. nullptr, service_config_json, &error);
  1509. ASSERT_NE(result.service_config.get(), nullptr);
  1510. ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_string(error);
  1511. }
  1512. if (expected_targets != nullptr) {
  1513. grpc_arg expected_targets_arg = grpc_channel_arg_string_create(
  1514. const_cast<char*>(GRPC_ARG_FAKE_SECURITY_EXPECTED_TARGETS),
  1515. const_cast<char*>(expected_targets));
  1516. result.args =
  1517. grpc_channel_args_copy_and_add(nullptr, &expected_targets_arg, 1);
  1518. }
  1519. lb_channel_response_generator_->SetResponse(std::move(result));
  1520. }
  1521. void SetNextReresolutionResponse(const std::vector<int>& ports) {
  1522. grpc_core::ExecCtx exec_ctx;
  1523. grpc_core::Resolver::Result result;
  1524. result.addresses = CreateAddressListFromPortList(ports);
  1525. response_generator_->SetReresolutionResponse(std::move(result));
  1526. }
  1527. const std::vector<int> GetBackendPorts(size_t start_index = 0,
  1528. size_t stop_index = 0) const {
  1529. if (stop_index == 0) stop_index = backends_.size();
  1530. std::vector<int> backend_ports;
  1531. for (size_t i = start_index; i < stop_index; ++i) {
  1532. backend_ports.push_back(backends_[i]->port());
  1533. }
  1534. return backend_ports;
  1535. }
  1536. Status SendRpc(const RpcOptions& rpc_options = RpcOptions(),
  1537. EchoResponse* response = nullptr) {
  1538. const bool local_response = (response == nullptr);
  1539. if (local_response) response = new EchoResponse;
  1540. EchoRequest request;
  1541. ClientContext context;
  1542. for (const auto& metadata : rpc_options.metadata) {
  1543. context.AddMetadata(metadata.first, metadata.second);
  1544. }
  1545. if (rpc_options.timeout_ms != 0) {
  1546. context.set_deadline(
  1547. grpc_timeout_milliseconds_to_deadline(rpc_options.timeout_ms));
  1548. }
  1549. if (rpc_options.wait_for_ready) context.set_wait_for_ready(true);
  1550. request.set_message(kRequestMessage);
  1551. if (rpc_options.server_fail) {
  1552. request.mutable_param()->mutable_expected_error()->set_code(
  1553. GRPC_STATUS_FAILED_PRECONDITION);
  1554. }
  1555. Status status;
  1556. switch (rpc_options.service) {
  1557. case SERVICE_ECHO:
  1558. status =
  1559. SendRpcMethod(&stub_, rpc_options, &context, request, response);
  1560. break;
  1561. case SERVICE_ECHO1:
  1562. status =
  1563. SendRpcMethod(&stub1_, rpc_options, &context, request, response);
  1564. break;
  1565. case SERVICE_ECHO2:
  1566. status =
  1567. SendRpcMethod(&stub2_, rpc_options, &context, request, response);
  1568. break;
  1569. }
  1570. if (local_response) delete response;
  1571. return status;
  1572. }
  1573. void CheckRpcSendOk(const size_t times = 1,
  1574. const RpcOptions& rpc_options = RpcOptions()) {
  1575. for (size_t i = 0; i < times; ++i) {
  1576. EchoResponse response;
  1577. const Status status = SendRpc(rpc_options, &response);
  1578. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  1579. << " message=" << status.error_message();
  1580. EXPECT_EQ(response.message(), kRequestMessage);
  1581. }
  1582. }
  1583. void CheckRpcSendFailure(const size_t times = 1,
  1584. const RpcOptions& rpc_options = RpcOptions()) {
  1585. for (size_t i = 0; i < times; ++i) {
  1586. const Status status = SendRpc(rpc_options);
  1587. EXPECT_FALSE(status.ok());
  1588. }
  1589. }
  1590. void SetRouteConfiguration(int idx, const RouteConfiguration& route_config) {
  1591. if (GetParam().enable_rds_testing()) {
  1592. balancers_[idx]->ads_service()->SetRdsResource(route_config);
  1593. } else {
  1594. balancers_[idx]->ads_service()->SetLdsResource(
  1595. AdsServiceImpl::BuildListener(route_config));
  1596. }
  1597. }
  1598. AdsServiceImpl::ResponseState RouteConfigurationResponseState(int idx) const {
  1599. AdsServiceImpl* ads_service = balancers_[idx]->ads_service();
  1600. if (GetParam().enable_rds_testing()) {
  1601. return ads_service->rds_response_state();
  1602. }
  1603. return ads_service->lds_response_state();
  1604. }
  1605. public:
  1606. // This method could benefit test subclasses; to make it accessible
  1607. // via bind with a qualified name, it needs to be public.
  1608. void SetEdsResourceWithDelay(size_t i,
  1609. const ClusterLoadAssignment& assignment,
  1610. int delay_ms) {
  1611. GPR_ASSERT(delay_ms > 0);
  1612. gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(delay_ms));
  1613. balancers_[i]->ads_service()->SetEdsResource(assignment);
  1614. }
  1615. protected:
  1616. class ServerThread {
  1617. public:
  1618. ServerThread() : port_(g_port_saver->GetPort()) {}
  1619. virtual ~ServerThread(){};
  1620. void Start() {
  1621. gpr_log(GPR_INFO, "starting %s server on port %d", Type(), port_);
  1622. GPR_ASSERT(!running_);
  1623. running_ = true;
  1624. StartAllServices();
  1625. grpc_core::Mutex mu;
  1626. // We need to acquire the lock here in order to prevent the notify_one
  1627. // by ServerThread::Serve from firing before the wait below is hit.
  1628. grpc_core::MutexLock lock(&mu);
  1629. grpc_core::CondVar cond;
  1630. thread_.reset(
  1631. new std::thread(std::bind(&ServerThread::Serve, this, &mu, &cond)));
  1632. cond.Wait(&mu);
  1633. gpr_log(GPR_INFO, "%s server startup complete", Type());
  1634. }
  1635. void Serve(grpc_core::Mutex* mu, grpc_core::CondVar* cond) {
  1636. // We need to acquire the lock here in order to prevent the notify_one
  1637. // below from firing before its corresponding wait is executed.
  1638. grpc_core::MutexLock lock(mu);
  1639. std::ostringstream server_address;
  1640. server_address << "localhost:" << port_;
  1641. ServerBuilder builder;
  1642. std::shared_ptr<ServerCredentials> creds(new SecureServerCredentials(
  1643. grpc_fake_transport_security_server_credentials_create()));
  1644. builder.AddListeningPort(server_address.str(), creds);
  1645. RegisterAllServices(&builder);
  1646. server_ = builder.BuildAndStart();
  1647. cond->Signal();
  1648. }
  1649. void Shutdown() {
  1650. if (!running_) return;
  1651. gpr_log(GPR_INFO, "%s about to shutdown", Type());
  1652. ShutdownAllServices();
  1653. server_->Shutdown(grpc_timeout_milliseconds_to_deadline(0));
  1654. thread_->join();
  1655. gpr_log(GPR_INFO, "%s shutdown completed", Type());
  1656. running_ = false;
  1657. }
  1658. int port() const { return port_; }
  1659. private:
  1660. virtual void RegisterAllServices(ServerBuilder* builder) = 0;
  1661. virtual void StartAllServices() = 0;
  1662. virtual void ShutdownAllServices() = 0;
  1663. virtual const char* Type() = 0;
  1664. const int port_;
  1665. std::unique_ptr<Server> server_;
  1666. std::unique_ptr<std::thread> thread_;
  1667. bool running_ = false;
  1668. };
  1669. class BackendServerThread : public ServerThread {
  1670. public:
  1671. BackendServiceImpl<::grpc::testing::EchoTestService::Service>*
  1672. backend_service() {
  1673. return &backend_service_;
  1674. }
  1675. BackendServiceImpl<::grpc::testing::EchoTest1Service::Service>*
  1676. backend_service1() {
  1677. return &backend_service1_;
  1678. }
  1679. BackendServiceImpl<::grpc::testing::EchoTest2Service::Service>*
  1680. backend_service2() {
  1681. return &backend_service2_;
  1682. }
  1683. private:
  1684. void RegisterAllServices(ServerBuilder* builder) override {
  1685. builder->RegisterService(&backend_service_);
  1686. builder->RegisterService(&backend_service1_);
  1687. builder->RegisterService(&backend_service2_);
  1688. }
  1689. void StartAllServices() override {
  1690. backend_service_.Start();
  1691. backend_service1_.Start();
  1692. backend_service2_.Start();
  1693. }
  1694. void ShutdownAllServices() override {
  1695. backend_service_.Shutdown();
  1696. backend_service1_.Shutdown();
  1697. backend_service2_.Shutdown();
  1698. }
  1699. const char* Type() override { return "Backend"; }
  1700. BackendServiceImpl<::grpc::testing::EchoTestService::Service>
  1701. backend_service_;
  1702. BackendServiceImpl<::grpc::testing::EchoTest1Service::Service>
  1703. backend_service1_;
  1704. BackendServiceImpl<::grpc::testing::EchoTest2Service::Service>
  1705. backend_service2_;
  1706. };
  1707. class BalancerServerThread : public ServerThread {
  1708. public:
  1709. explicit BalancerServerThread(int client_load_reporting_interval = 0)
  1710. : ads_service_(new AdsServiceImpl(client_load_reporting_interval > 0)),
  1711. lrs_service_(new LrsServiceImpl(client_load_reporting_interval)) {}
  1712. AdsServiceImpl* ads_service() { return ads_service_.get(); }
  1713. LrsServiceImpl* lrs_service() { return lrs_service_.get(); }
  1714. private:
  1715. void RegisterAllServices(ServerBuilder* builder) override {
  1716. builder->RegisterService(ads_service_->v2_rpc_service());
  1717. builder->RegisterService(ads_service_->v3_rpc_service());
  1718. builder->RegisterService(lrs_service_->v2_rpc_service());
  1719. builder->RegisterService(lrs_service_->v3_rpc_service());
  1720. }
  1721. void StartAllServices() override {
  1722. ads_service_->Start();
  1723. lrs_service_->Start();
  1724. }
  1725. void ShutdownAllServices() override {
  1726. ads_service_->Shutdown();
  1727. lrs_service_->Shutdown();
  1728. }
  1729. const char* Type() override { return "Balancer"; }
  1730. std::shared_ptr<AdsServiceImpl> ads_service_;
  1731. std::shared_ptr<LrsServiceImpl> lrs_service_;
  1732. };
  1733. const size_t num_backends_;
  1734. const size_t num_balancers_;
  1735. const int client_load_reporting_interval_seconds_;
  1736. std::shared_ptr<Channel> channel_;
  1737. std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
  1738. std::unique_ptr<grpc::testing::EchoTest1Service::Stub> stub1_;
  1739. std::unique_ptr<grpc::testing::EchoTest2Service::Stub> stub2_;
  1740. std::vector<std::unique_ptr<BackendServerThread>> backends_;
  1741. std::vector<std::unique_ptr<BalancerServerThread>> balancers_;
  1742. grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
  1743. response_generator_;
  1744. grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
  1745. lb_channel_response_generator_;
  1746. int xds_resource_does_not_exist_timeout_ms_ = 0;
  1747. absl::InlinedVector<grpc_arg, 2> xds_channel_args_to_add_;
  1748. grpc_channel_args xds_channel_args_;
  1749. };
  1750. class BasicTest : public XdsEnd2endTest {
  1751. public:
  1752. BasicTest() : XdsEnd2endTest(4, 1) {}
  1753. };
  1754. // Tests that the balancer sends the correct response to the client, and the
  1755. // client sends RPCs to the backends using the default child policy.
  1756. TEST_P(BasicTest, Vanilla) {
  1757. SetNextResolution({});
  1758. SetNextResolutionForLbChannelAllBalancers();
  1759. const size_t kNumRpcsPerAddress = 100;
  1760. AdsServiceImpl::EdsResourceArgs args({
  1761. {"locality0", GetBackendPorts()},
  1762. });
  1763. balancers_[0]->ads_service()->SetEdsResource(
  1764. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  1765. // Make sure that trying to connect works without a call.
  1766. channel_->GetState(true /* try_to_connect */);
  1767. // We need to wait for all backends to come online.
  1768. WaitForAllBackends();
  1769. // Send kNumRpcsPerAddress RPCs per server.
  1770. CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
  1771. // Each backend should have gotten 100 requests.
  1772. for (size_t i = 0; i < backends_.size(); ++i) {
  1773. EXPECT_EQ(kNumRpcsPerAddress,
  1774. backends_[i]->backend_service()->request_count());
  1775. }
  1776. // Check LB policy name for the channel.
  1777. EXPECT_EQ((GetParam().use_xds_resolver() ? "xds_cluster_manager_experimental"
  1778. : "eds_experimental"),
  1779. channel_->GetLoadBalancingPolicyName());
  1780. }
  1781. TEST_P(BasicTest, IgnoresUnhealthyEndpoints) {
  1782. SetNextResolution({});
  1783. SetNextResolutionForLbChannelAllBalancers();
  1784. const size_t kNumRpcsPerAddress = 100;
  1785. AdsServiceImpl::EdsResourceArgs args({
  1786. {"locality0",
  1787. GetBackendPorts(),
  1788. kDefaultLocalityWeight,
  1789. kDefaultLocalityPriority,
  1790. {HealthStatus::DRAINING}},
  1791. });
  1792. balancers_[0]->ads_service()->SetEdsResource(
  1793. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  1794. // Make sure that trying to connect works without a call.
  1795. channel_->GetState(true /* try_to_connect */);
  1796. // We need to wait for all backends to come online.
  1797. WaitForAllBackends(/*start_index=*/1);
  1798. // Send kNumRpcsPerAddress RPCs per server.
  1799. CheckRpcSendOk(kNumRpcsPerAddress * (num_backends_ - 1));
  1800. // Each backend should have gotten 100 requests.
  1801. for (size_t i = 1; i < backends_.size(); ++i) {
  1802. EXPECT_EQ(kNumRpcsPerAddress,
  1803. backends_[i]->backend_service()->request_count());
  1804. }
  1805. }
  1806. // Tests that subchannel sharing works when the same backend is listed multiple
  1807. // times.
  1808. TEST_P(BasicTest, SameBackendListedMultipleTimes) {
  1809. SetNextResolution({});
  1810. SetNextResolutionForLbChannelAllBalancers();
  1811. // Same backend listed twice.
  1812. std::vector<int> ports(2, backends_[0]->port());
  1813. AdsServiceImpl::EdsResourceArgs args({
  1814. {"locality0", ports},
  1815. });
  1816. const size_t kNumRpcsPerAddress = 10;
  1817. balancers_[0]->ads_service()->SetEdsResource(
  1818. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  1819. // We need to wait for the backend to come online.
  1820. WaitForBackend(0);
  1821. // Send kNumRpcsPerAddress RPCs per server.
  1822. CheckRpcSendOk(kNumRpcsPerAddress * ports.size());
  1823. // Backend should have gotten 20 requests.
  1824. EXPECT_EQ(kNumRpcsPerAddress * ports.size(),
  1825. backends_[0]->backend_service()->request_count());
  1826. // And they should have come from a single client port, because of
  1827. // subchannel sharing.
  1828. EXPECT_EQ(1UL, backends_[0]->backend_service()->clients().size());
  1829. }
  1830. // Tests that RPCs will be blocked until a non-empty serverlist is received.
  1831. TEST_P(BasicTest, InitiallyEmptyServerlist) {
  1832. SetNextResolution({});
  1833. SetNextResolutionForLbChannelAllBalancers();
  1834. const int kServerlistDelayMs = 500 * grpc_test_slowdown_factor();
  1835. const int kCallDeadlineMs = kServerlistDelayMs * 2;
  1836. // First response is an empty serverlist, sent right away.
  1837. AdsServiceImpl::EdsResourceArgs::Locality empty_locality("locality0", {});
  1838. AdsServiceImpl::EdsResourceArgs args({
  1839. empty_locality,
  1840. });
  1841. balancers_[0]->ads_service()->SetEdsResource(
  1842. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  1843. // Send non-empty serverlist only after kServerlistDelayMs.
  1844. args = AdsServiceImpl::EdsResourceArgs({
  1845. {"locality0", GetBackendPorts()},
  1846. });
  1847. std::thread delayed_resource_setter(
  1848. std::bind(&BasicTest::SetEdsResourceWithDelay, this, 0,
  1849. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()),
  1850. kServerlistDelayMs));
  1851. const auto t0 = system_clock::now();
  1852. // Client will block: LB will initially send empty serverlist.
  1853. CheckRpcSendOk(
  1854. 1, RpcOptions().set_timeout_ms(kCallDeadlineMs).set_wait_for_ready(true));
  1855. const auto ellapsed_ms =
  1856. std::chrono::duration_cast<std::chrono::milliseconds>(
  1857. system_clock::now() - t0);
  1858. // but eventually, the LB sends a serverlist update that allows the call to
  1859. // proceed. The call delay must be larger than the delay in sending the
  1860. // populated serverlist but under the call's deadline (which is enforced by
  1861. // the call's deadline).
  1862. EXPECT_GT(ellapsed_ms.count(), kServerlistDelayMs);
  1863. delayed_resource_setter.join();
  1864. }
  1865. // Tests that RPCs will fail with UNAVAILABLE instead of DEADLINE_EXCEEDED if
  1866. // all the servers are unreachable.
  1867. TEST_P(BasicTest, AllServersUnreachableFailFast) {
  1868. SetNextResolution({});
  1869. SetNextResolutionForLbChannelAllBalancers();
  1870. const size_t kNumUnreachableServers = 5;
  1871. std::vector<int> ports;
  1872. for (size_t i = 0; i < kNumUnreachableServers; ++i) {
  1873. ports.push_back(g_port_saver->GetPort());
  1874. }
  1875. AdsServiceImpl::EdsResourceArgs args({
  1876. {"locality0", ports},
  1877. });
  1878. balancers_[0]->ads_service()->SetEdsResource(
  1879. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  1880. const Status status = SendRpc();
  1881. // The error shouldn't be DEADLINE_EXCEEDED.
  1882. EXPECT_EQ(StatusCode::UNAVAILABLE, status.error_code());
  1883. }
  1884. // Tests that RPCs fail when the backends are down, and will succeed again after
  1885. // the backends are restarted.
  1886. TEST_P(BasicTest, BackendsRestart) {
  1887. SetNextResolution({});
  1888. SetNextResolutionForLbChannelAllBalancers();
  1889. AdsServiceImpl::EdsResourceArgs args({
  1890. {"locality0", GetBackendPorts()},
  1891. });
  1892. balancers_[0]->ads_service()->SetEdsResource(
  1893. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  1894. WaitForAllBackends();
  1895. // Stop backends. RPCs should fail.
  1896. ShutdownAllBackends();
  1897. // Sending multiple failed requests instead of just one to ensure that the
  1898. // client notices that all backends are down before we restart them. If we
  1899. // didn't do this, then a single RPC could fail here due to the race condition
  1900. // between the LB pick and the GOAWAY from the chosen backend being shut down,
  1901. // which would not actually prove that the client noticed that all of the
  1902. // backends are down. Then, when we send another request below (which we
  1903. // expect to succeed), if the callbacks happen in the wrong order, the same
  1904. // race condition could happen again due to the client not yet having noticed
  1905. // that the backends were all down.
  1906. CheckRpcSendFailure(num_backends_);
  1907. // Restart all backends. RPCs should start succeeding again.
  1908. StartAllBackends();
  1909. CheckRpcSendOk(1, RpcOptions().set_timeout_ms(2000).set_wait_for_ready(true));
  1910. }
  1911. TEST_P(BasicTest, IgnoresDuplicateUpdates) {
  1912. const size_t kNumRpcsPerAddress = 100;
  1913. SetNextResolution({});
  1914. SetNextResolutionForLbChannelAllBalancers();
  1915. AdsServiceImpl::EdsResourceArgs args({
  1916. {"locality0", GetBackendPorts()},
  1917. });
  1918. balancers_[0]->ads_service()->SetEdsResource(
  1919. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  1920. // Wait for all backends to come online.
  1921. WaitForAllBackends();
  1922. // Send kNumRpcsPerAddress RPCs per server, but send an EDS update in
  1923. // between. If the update is not ignored, this will cause the
  1924. // round_robin policy to see an update, which will randomly reset its
  1925. // position in the address list.
  1926. for (size_t i = 0; i < kNumRpcsPerAddress; ++i) {
  1927. CheckRpcSendOk(2);
  1928. balancers_[0]->ads_service()->SetEdsResource(
  1929. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  1930. CheckRpcSendOk(2);
  1931. }
  1932. // Each backend should have gotten the right number of requests.
  1933. for (size_t i = 1; i < backends_.size(); ++i) {
  1934. EXPECT_EQ(kNumRpcsPerAddress,
  1935. backends_[i]->backend_service()->request_count());
  1936. }
  1937. }
  1938. using XdsResolverOnlyTest = BasicTest;
  1939. // Tests switching over from one cluster to another.
  1940. TEST_P(XdsResolverOnlyTest, ChangeClusters) {
  1941. const char* kNewClusterName = "new_cluster_name";
  1942. const char* kNewEdsServiceName = "new_eds_service_name";
  1943. SetNextResolution({});
  1944. SetNextResolutionForLbChannelAllBalancers();
  1945. AdsServiceImpl::EdsResourceArgs args({
  1946. {"locality0", GetBackendPorts(0, 2)},
  1947. });
  1948. balancers_[0]->ads_service()->SetEdsResource(
  1949. AdsServiceImpl::BuildEdsResource(args));
  1950. // We need to wait for all backends to come online.
  1951. WaitForAllBackends(0, 2);
  1952. // Populate new EDS resource.
  1953. AdsServiceImpl::EdsResourceArgs args2({
  1954. {"locality0", GetBackendPorts(2, 4)},
  1955. });
  1956. balancers_[0]->ads_service()->SetEdsResource(
  1957. AdsServiceImpl::BuildEdsResource(args2, kNewEdsServiceName));
  1958. // Populate new CDS resource.
  1959. Cluster new_cluster = balancers_[0]->ads_service()->default_cluster();
  1960. new_cluster.set_name(kNewClusterName);
  1961. new_cluster.mutable_eds_cluster_config()->set_service_name(
  1962. kNewEdsServiceName);
  1963. balancers_[0]->ads_service()->SetCdsResource(new_cluster);
  1964. // Change RDS resource to point to new cluster.
  1965. RouteConfiguration new_route_config =
  1966. balancers_[0]->ads_service()->default_route_config();
  1967. new_route_config.mutable_virtual_hosts(0)
  1968. ->mutable_routes(0)
  1969. ->mutable_route()
  1970. ->set_cluster(kNewClusterName);
  1971. Listener listener =
  1972. balancers_[0]->ads_service()->BuildListener(new_route_config);
  1973. balancers_[0]->ads_service()->SetLdsResource(listener);
  1974. // Wait for all new backends to be used.
  1975. std::tuple<int, int, int> counts = WaitForAllBackends(2, 4);
  1976. // Make sure no RPCs failed in the transition.
  1977. EXPECT_EQ(0, std::get<1>(counts));
  1978. }
  1979. // Tests that we go into TRANSIENT_FAILURE if the Cluster disappears.
  1980. TEST_P(XdsResolverOnlyTest, ClusterRemoved) {
  1981. SetNextResolution({});
  1982. SetNextResolutionForLbChannelAllBalancers();
  1983. AdsServiceImpl::EdsResourceArgs args({
  1984. {"locality0", GetBackendPorts()},
  1985. });
  1986. balancers_[0]->ads_service()->SetEdsResource(
  1987. AdsServiceImpl::BuildEdsResource(args));
  1988. // We need to wait for all backends to come online.
  1989. WaitForAllBackends();
  1990. // Unset CDS resource.
  1991. balancers_[0]->ads_service()->UnsetResource(kCdsTypeUrl, kDefaultClusterName);
  1992. // Wait for RPCs to start failing.
  1993. do {
  1994. } while (SendRpc(RpcOptions(), nullptr).ok());
  1995. // Make sure RPCs are still failing.
  1996. CheckRpcSendFailure(1000);
  1997. // Make sure we ACK'ed the update.
  1998. EXPECT_EQ(balancers_[0]->ads_service()->cds_response_state().state,
  1999. AdsServiceImpl::ResponseState::ACKED);
  2000. }
  2001. // Tests that we restart all xDS requests when we reestablish the ADS call.
  2002. TEST_P(XdsResolverOnlyTest, RestartsRequestsUponReconnection) {
  2003. balancers_[0]->ads_service()->SetLdsToUseDynamicRds();
  2004. const char* kNewClusterName = "new_cluster_name";
  2005. const char* kNewEdsServiceName = "new_eds_service_name";
  2006. SetNextResolution({});
  2007. SetNextResolutionForLbChannelAllBalancers();
  2008. AdsServiceImpl::EdsResourceArgs args({
  2009. {"locality0", GetBackendPorts(0, 2)},
  2010. });
  2011. balancers_[0]->ads_service()->SetEdsResource(
  2012. AdsServiceImpl::BuildEdsResource(args));
  2013. // We need to wait for all backends to come online.
  2014. WaitForAllBackends(0, 2);
  2015. // Now shut down and restart the balancer. When the client
  2016. // reconnects, it should automatically restart the requests for all
  2017. // resource types.
  2018. balancers_[0]->Shutdown();
  2019. balancers_[0]->Start();
  2020. // Make sure things are still working.
  2021. CheckRpcSendOk(100);
  2022. // Populate new EDS resource.
  2023. AdsServiceImpl::EdsResourceArgs args2({
  2024. {"locality0", GetBackendPorts(2, 4)},
  2025. });
  2026. balancers_[0]->ads_service()->SetEdsResource(
  2027. AdsServiceImpl::BuildEdsResource(args2, kNewEdsServiceName));
  2028. // Populate new CDS resource.
  2029. Cluster new_cluster = balancers_[0]->ads_service()->default_cluster();
  2030. new_cluster.set_name(kNewClusterName);
  2031. new_cluster.mutable_eds_cluster_config()->set_service_name(
  2032. kNewEdsServiceName);
  2033. balancers_[0]->ads_service()->SetCdsResource(new_cluster);
  2034. // Change RDS resource to point to new cluster.
  2035. RouteConfiguration new_route_config =
  2036. balancers_[0]->ads_service()->default_route_config();
  2037. new_route_config.mutable_virtual_hosts(0)
  2038. ->mutable_routes(0)
  2039. ->mutable_route()
  2040. ->set_cluster(kNewClusterName);
  2041. balancers_[0]->ads_service()->SetRdsResource(new_route_config);
  2042. // Wait for all new backends to be used.
  2043. std::tuple<int, int, int> counts = WaitForAllBackends(2, 4);
  2044. // Make sure no RPCs failed in the transition.
  2045. EXPECT_EQ(0, std::get<1>(counts));
  2046. }
  2047. TEST_P(XdsResolverOnlyTest, DefaultRouteSpecifiesSlashPrefix) {
  2048. RouteConfiguration route_config =
  2049. balancers_[0]->ads_service()->default_route_config();
  2050. route_config.mutable_virtual_hosts(0)
  2051. ->mutable_routes(0)
  2052. ->mutable_match()
  2053. ->set_prefix("/");
  2054. balancers_[0]->ads_service()->SetLdsResource(
  2055. AdsServiceImpl::BuildListener(route_config));
  2056. SetNextResolution({});
  2057. SetNextResolutionForLbChannelAllBalancers();
  2058. AdsServiceImpl::EdsResourceArgs args({
  2059. {"locality0", GetBackendPorts()},
  2060. });
  2061. balancers_[0]->ads_service()->SetEdsResource(
  2062. AdsServiceImpl::BuildEdsResource(args));
  2063. // We need to wait for all backends to come online.
  2064. WaitForAllBackends();
  2065. }
  2066. TEST_P(XdsResolverOnlyTest, CircuitBreaking) {
  2067. class TestRpc {
  2068. public:
  2069. TestRpc() {}
  2070. void StartRpc(grpc::testing::EchoTestService::Stub* stub) {
  2071. sender_thread_ = std::thread([this, stub]() {
  2072. EchoResponse response;
  2073. EchoRequest request;
  2074. request.mutable_param()->set_client_cancel_after_us(1 * 1000 * 1000);
  2075. request.set_message(kRequestMessage);
  2076. status_ = stub->Echo(&context_, request, &response);
  2077. });
  2078. }
  2079. void CancelRpc() {
  2080. context_.TryCancel();
  2081. sender_thread_.join();
  2082. }
  2083. private:
  2084. std::thread sender_thread_;
  2085. ClientContext context_;
  2086. Status status_;
  2087. };
  2088. const char* kNewClusterName = "new_cluster";
  2089. constexpr size_t kMaxConcurrentRequests = 10;
  2090. SetNextResolution({});
  2091. SetNextResolutionForLbChannelAllBalancers();
  2092. // Populate new EDS resources.
  2093. AdsServiceImpl::EdsResourceArgs args({
  2094. {"locality0", GetBackendPorts(0, 1)},
  2095. });
  2096. balancers_[0]->ads_service()->SetEdsResource(
  2097. AdsServiceImpl::BuildEdsResource(args));
  2098. // Update CDS resource to set max concurrent request.
  2099. CircuitBreakers circuit_breaks;
  2100. Cluster cluster = balancers_[0]->ads_service()->default_cluster();
  2101. auto* threshold = cluster.mutable_circuit_breakers()->add_thresholds();
  2102. threshold->set_priority(RoutingPriority::DEFAULT);
  2103. threshold->mutable_max_requests()->set_value(kMaxConcurrentRequests);
  2104. balancers_[0]->ads_service()->SetCdsResource(cluster);
  2105. // Send exactly max_concurrent_requests long RPCs.
  2106. TestRpc rpcs[kMaxConcurrentRequests];
  2107. for (size_t i = 0; i < kMaxConcurrentRequests; ++i) {
  2108. rpcs[i].StartRpc(stub_.get());
  2109. }
  2110. // Wait for all RPCs to be in flight.
  2111. while (backends_[0]->backend_service()->RpcsWaitingForClientCancel() <
  2112. kMaxConcurrentRequests) {
  2113. gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
  2114. gpr_time_from_micros(1 * 1000, GPR_TIMESPAN)));
  2115. }
  2116. // Sending a RPC now should fail, the error message should tell us
  2117. // we hit the max concurrent requests limit and got dropped.
  2118. Status status = SendRpc();
  2119. EXPECT_FALSE(status.ok());
  2120. EXPECT_EQ(status.error_message(), "Call dropped by load balancing policy");
  2121. // Cancel one RPC to allow another one through
  2122. rpcs[0].CancelRpc();
  2123. status = SendRpc();
  2124. EXPECT_TRUE(status.ok());
  2125. for (size_t i = 1; i < kMaxConcurrentRequests; ++i) {
  2126. rpcs[i].CancelRpc();
  2127. }
  2128. // Make sure RPCs go to the correct backend:
  2129. EXPECT_EQ(kMaxConcurrentRequests + 1,
  2130. backends_[0]->backend_service()->request_count());
  2131. }
  2132. TEST_P(XdsResolverOnlyTest, MultipleChannelsShareXdsClient) {
  2133. const char* kNewServerName = "new-server.example.com";
  2134. Listener listener = balancers_[0]->ads_service()->default_listener();
  2135. listener.set_name(kNewServerName);
  2136. balancers_[0]->ads_service()->SetLdsResource(listener);
  2137. SetNextResolution({});
  2138. SetNextResolutionForLbChannelAllBalancers();
  2139. AdsServiceImpl::EdsResourceArgs args({
  2140. {"locality0", GetBackendPorts()},
  2141. });
  2142. balancers_[0]->ads_service()->SetEdsResource(
  2143. AdsServiceImpl::BuildEdsResource(args));
  2144. WaitForAllBackends();
  2145. // Create second channel and tell it to connect to kNewServerName.
  2146. auto channel2 = CreateChannel(/*failover_timeout=*/0, kNewServerName);
  2147. channel2->GetState(/*try_to_connect=*/true);
  2148. ASSERT_TRUE(
  2149. channel2->WaitForConnected(grpc_timeout_milliseconds_to_deadline(100)));
  2150. // Make sure there's only one client connected.
  2151. EXPECT_EQ(1UL, balancers_[0]->ads_service()->clients().size());
  2152. }
  2153. class XdsResolverLoadReportingOnlyTest : public XdsEnd2endTest {
  2154. public:
  2155. XdsResolverLoadReportingOnlyTest() : XdsEnd2endTest(4, 1, 3) {}
  2156. };
  2157. // Tests load reporting when switching over from one cluster to another.
  2158. TEST_P(XdsResolverLoadReportingOnlyTest, ChangeClusters) {
  2159. const char* kNewClusterName = "new_cluster_name";
  2160. const char* kNewEdsServiceName = "new_eds_service_name";
  2161. balancers_[0]->lrs_service()->set_cluster_names(
  2162. {kDefaultClusterName, kNewClusterName});
  2163. SetNextResolution({});
  2164. SetNextResolutionForLbChannelAllBalancers();
  2165. // cluster kDefaultClusterName -> locality0 -> backends 0 and 1
  2166. AdsServiceImpl::EdsResourceArgs args({
  2167. {"locality0", GetBackendPorts(0, 2)},
  2168. });
  2169. balancers_[0]->ads_service()->SetEdsResource(
  2170. AdsServiceImpl::BuildEdsResource(args));
  2171. // cluster kNewClusterName -> locality1 -> backends 2 and 3
  2172. AdsServiceImpl::EdsResourceArgs args2({
  2173. {"locality1", GetBackendPorts(2, 4)},
  2174. });
  2175. balancers_[0]->ads_service()->SetEdsResource(
  2176. AdsServiceImpl::BuildEdsResource(args2, kNewEdsServiceName));
  2177. // CDS resource for kNewClusterName.
  2178. Cluster new_cluster = balancers_[0]->ads_service()->default_cluster();
  2179. new_cluster.set_name(kNewClusterName);
  2180. new_cluster.mutable_eds_cluster_config()->set_service_name(
  2181. kNewEdsServiceName);
  2182. balancers_[0]->ads_service()->SetCdsResource(new_cluster);
  2183. // Wait for all backends to come online.
  2184. int num_ok = 0;
  2185. int num_failure = 0;
  2186. int num_drops = 0;
  2187. std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends(0, 2);
  2188. // The load report received at the balancer should be correct.
  2189. std::vector<ClientStats> load_report =
  2190. balancers_[0]->lrs_service()->WaitForLoadReport();
  2191. EXPECT_THAT(
  2192. load_report,
  2193. ::testing::ElementsAre(::testing::AllOf(
  2194. ::testing::Property(&ClientStats::cluster_name, kDefaultClusterName),
  2195. ::testing::Property(
  2196. &ClientStats::locality_stats,
  2197. ::testing::ElementsAre(::testing::Pair(
  2198. "locality0",
  2199. ::testing::AllOf(
  2200. ::testing::Field(&ClientStats::LocalityStats::
  2201. total_successful_requests,
  2202. num_ok),
  2203. ::testing::Field(&ClientStats::LocalityStats::
  2204. total_requests_in_progress,
  2205. 0UL),
  2206. ::testing::Field(
  2207. &ClientStats::LocalityStats::total_error_requests,
  2208. num_failure),
  2209. ::testing::Field(
  2210. &ClientStats::LocalityStats::total_issued_requests,
  2211. num_failure + num_ok))))),
  2212. ::testing::Property(&ClientStats::total_dropped_requests,
  2213. num_drops))));
  2214. // Change RDS resource to point to new cluster.
  2215. RouteConfiguration new_route_config =
  2216. balancers_[0]->ads_service()->default_route_config();
  2217. new_route_config.mutable_virtual_hosts(0)
  2218. ->mutable_routes(0)
  2219. ->mutable_route()
  2220. ->set_cluster(kNewClusterName);
  2221. Listener listener =
  2222. balancers_[0]->ads_service()->BuildListener(new_route_config);
  2223. balancers_[0]->ads_service()->SetLdsResource(listener);
  2224. // Wait for all new backends to be used.
  2225. std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends(2, 4);
  2226. // The load report received at the balancer should be correct.
  2227. load_report = balancers_[0]->lrs_service()->WaitForLoadReport();
  2228. EXPECT_THAT(
  2229. load_report,
  2230. ::testing::ElementsAre(
  2231. ::testing::AllOf(
  2232. ::testing::Property(&ClientStats::cluster_name,
  2233. kDefaultClusterName),
  2234. ::testing::Property(
  2235. &ClientStats::locality_stats,
  2236. ::testing::ElementsAre(::testing::Pair(
  2237. "locality0",
  2238. ::testing::AllOf(
  2239. ::testing::Field(&ClientStats::LocalityStats::
  2240. total_successful_requests,
  2241. ::testing::Lt(num_ok)),
  2242. ::testing::Field(&ClientStats::LocalityStats::
  2243. total_requests_in_progress,
  2244. 0UL),
  2245. ::testing::Field(
  2246. &ClientStats::LocalityStats::total_error_requests,
  2247. ::testing::Le(num_failure)),
  2248. ::testing::Field(
  2249. &ClientStats::LocalityStats::
  2250. total_issued_requests,
  2251. ::testing::Le(num_failure + num_ok)))))),
  2252. ::testing::Property(&ClientStats::total_dropped_requests,
  2253. num_drops)),
  2254. ::testing::AllOf(
  2255. ::testing::Property(&ClientStats::cluster_name, kNewClusterName),
  2256. ::testing::Property(
  2257. &ClientStats::locality_stats,
  2258. ::testing::ElementsAre(::testing::Pair(
  2259. "locality1",
  2260. ::testing::AllOf(
  2261. ::testing::Field(&ClientStats::LocalityStats::
  2262. total_successful_requests,
  2263. ::testing::Le(num_ok)),
  2264. ::testing::Field(&ClientStats::LocalityStats::
  2265. total_requests_in_progress,
  2266. 0UL),
  2267. ::testing::Field(
  2268. &ClientStats::LocalityStats::total_error_requests,
  2269. ::testing::Le(num_failure)),
  2270. ::testing::Field(
  2271. &ClientStats::LocalityStats::
  2272. total_issued_requests,
  2273. ::testing::Le(num_failure + num_ok)))))),
  2274. ::testing::Property(&ClientStats::total_dropped_requests,
  2275. num_drops))));
  2276. int total_ok = 0;
  2277. int total_failure = 0;
  2278. for (const ClientStats& client_stats : load_report) {
  2279. total_ok += client_stats.total_successful_requests();
  2280. total_failure += client_stats.total_error_requests();
  2281. }
  2282. EXPECT_EQ(total_ok, num_ok);
  2283. EXPECT_EQ(total_failure, num_failure);
  2284. // The LRS service got a single request, and sent a single response.
  2285. EXPECT_EQ(1U, balancers_[0]->lrs_service()->request_count());
  2286. EXPECT_EQ(1U, balancers_[0]->lrs_service()->response_count());
  2287. }
  2288. using SecureNamingTest = BasicTest;
  2289. // Tests that secure naming check passes if target name is expected.
  2290. TEST_P(SecureNamingTest, TargetNameIsExpected) {
  2291. SetNextResolution({});
  2292. SetNextResolutionForLbChannel({balancers_[0]->port()}, nullptr, "xds_server");
  2293. AdsServiceImpl::EdsResourceArgs args({
  2294. {"locality0", GetBackendPorts()},
  2295. });
  2296. balancers_[0]->ads_service()->SetEdsResource(
  2297. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  2298. CheckRpcSendOk();
  2299. }
  2300. // Tests that secure naming check fails if target name is unexpected.
  2301. TEST_P(SecureNamingTest, TargetNameIsUnexpected) {
  2302. ::testing::FLAGS_gtest_death_test_style = "threadsafe";
  2303. SetNextResolution({});
  2304. SetNextResolutionForLbChannel({balancers_[0]->port()}, nullptr,
  2305. "incorrect_server_name");
  2306. AdsServiceImpl::EdsResourceArgs args({
  2307. {"locality0", GetBackendPorts()},
  2308. });
  2309. balancers_[0]->ads_service()->SetEdsResource(
  2310. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  2311. // Make sure that we blow up (via abort() from the security connector) when
  2312. // the name from the balancer doesn't match expectations.
  2313. ASSERT_DEATH_IF_SUPPORTED({ CheckRpcSendOk(); }, "");
  2314. }
  2315. using LdsTest = BasicTest;
  2316. // Tests that LDS client should send a NACK if there is no API listener in the
  2317. // Listener in the LDS response.
  2318. TEST_P(LdsTest, NoApiListener) {
  2319. auto listener = balancers_[0]->ads_service()->default_listener();
  2320. listener.clear_api_listener();
  2321. balancers_[0]->ads_service()->SetLdsResource(listener);
  2322. SetNextResolution({});
  2323. SetNextResolutionForLbChannelAllBalancers();
  2324. CheckRpcSendFailure();
  2325. const auto& response_state =
  2326. balancers_[0]->ads_service()->lds_response_state();
  2327. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2328. EXPECT_EQ(response_state.error_message, "Listener has no ApiListener.");
  2329. }
  2330. // Tests that LDS client should send a NACK if the route_specifier in the
  2331. // http_connection_manager is neither inlined route_config nor RDS.
  2332. TEST_P(LdsTest, WrongRouteSpecifier) {
  2333. auto listener = balancers_[0]->ads_service()->default_listener();
  2334. HttpConnectionManager http_connection_manager;
  2335. http_connection_manager.mutable_scoped_routes();
  2336. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  2337. http_connection_manager);
  2338. balancers_[0]->ads_service()->SetLdsResource(listener);
  2339. SetNextResolution({});
  2340. SetNextResolutionForLbChannelAllBalancers();
  2341. CheckRpcSendFailure();
  2342. const auto& response_state =
  2343. balancers_[0]->ads_service()->lds_response_state();
  2344. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2345. EXPECT_EQ(response_state.error_message,
  2346. "HttpConnectionManager neither has inlined route_config nor RDS.");
  2347. }
  2348. // Tests that LDS client should send a NACK if the rds message in the
  2349. // http_connection_manager is missing the config_source field.
  2350. TEST_P(LdsTest, RdsMissingConfigSource) {
  2351. auto listener = balancers_[0]->ads_service()->default_listener();
  2352. HttpConnectionManager http_connection_manager;
  2353. http_connection_manager.mutable_rds()->set_route_config_name(
  2354. kDefaultRouteConfigurationName);
  2355. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  2356. http_connection_manager);
  2357. balancers_[0]->ads_service()->SetLdsResource(listener);
  2358. SetNextResolution({});
  2359. SetNextResolutionForLbChannelAllBalancers();
  2360. CheckRpcSendFailure();
  2361. const auto& response_state =
  2362. balancers_[0]->ads_service()->lds_response_state();
  2363. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2364. EXPECT_EQ(response_state.error_message,
  2365. "HttpConnectionManager missing config_source for RDS.");
  2366. }
  2367. // Tests that LDS client should send a NACK if the rds message in the
  2368. // http_connection_manager has a config_source field that does not specify ADS.
  2369. TEST_P(LdsTest, RdsConfigSourceDoesNotSpecifyAds) {
  2370. auto listener = balancers_[0]->ads_service()->default_listener();
  2371. HttpConnectionManager http_connection_manager;
  2372. auto* rds = http_connection_manager.mutable_rds();
  2373. rds->set_route_config_name(kDefaultRouteConfigurationName);
  2374. rds->mutable_config_source()->mutable_self();
  2375. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  2376. http_connection_manager);
  2377. balancers_[0]->ads_service()->SetLdsResource(listener);
  2378. SetNextResolution({});
  2379. SetNextResolutionForLbChannelAllBalancers();
  2380. CheckRpcSendFailure();
  2381. const auto& response_state =
  2382. balancers_[0]->ads_service()->lds_response_state();
  2383. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2384. EXPECT_EQ(response_state.error_message,
  2385. "HttpConnectionManager ConfigSource for RDS does not specify ADS.");
  2386. }
  2387. using LdsRdsTest = BasicTest;
  2388. // Tests that LDS client should send an ACK upon correct LDS response (with
  2389. // inlined RDS result).
  2390. TEST_P(LdsRdsTest, Vanilla) {
  2391. SetNextResolution({});
  2392. SetNextResolutionForLbChannelAllBalancers();
  2393. (void)SendRpc();
  2394. EXPECT_EQ(RouteConfigurationResponseState(0).state,
  2395. AdsServiceImpl::ResponseState::ACKED);
  2396. // Make sure we actually used the RPC service for the right version of xDS.
  2397. EXPECT_EQ(balancers_[0]->ads_service()->seen_v2_client(),
  2398. GetParam().use_v2());
  2399. EXPECT_NE(balancers_[0]->ads_service()->seen_v3_client(),
  2400. GetParam().use_v2());
  2401. }
  2402. // Tests that we go into TRANSIENT_FAILURE if the Listener is removed.
  2403. TEST_P(LdsRdsTest, ListenerRemoved) {
  2404. SetNextResolution({});
  2405. SetNextResolutionForLbChannelAllBalancers();
  2406. AdsServiceImpl::EdsResourceArgs args({
  2407. {"locality0", GetBackendPorts()},
  2408. });
  2409. balancers_[0]->ads_service()->SetEdsResource(
  2410. AdsServiceImpl::BuildEdsResource(args));
  2411. // We need to wait for all backends to come online.
  2412. WaitForAllBackends();
  2413. // Unset LDS resource.
  2414. balancers_[0]->ads_service()->UnsetResource(kLdsTypeUrl, kServerName);
  2415. // Wait for RPCs to start failing.
  2416. do {
  2417. } while (SendRpc(RpcOptions(), nullptr).ok());
  2418. // Make sure RPCs are still failing.
  2419. CheckRpcSendFailure(1000);
  2420. // Make sure we ACK'ed the update.
  2421. EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state().state,
  2422. AdsServiceImpl::ResponseState::ACKED);
  2423. }
  2424. // Tests that LDS client ACKs but fails if matching domain can't be found in
  2425. // the LDS response.
  2426. TEST_P(LdsRdsTest, NoMatchedDomain) {
  2427. RouteConfiguration route_config =
  2428. balancers_[0]->ads_service()->default_route_config();
  2429. route_config.mutable_virtual_hosts(0)->clear_domains();
  2430. route_config.mutable_virtual_hosts(0)->add_domains("unmatched_domain");
  2431. SetRouteConfiguration(0, route_config);
  2432. SetNextResolution({});
  2433. SetNextResolutionForLbChannelAllBalancers();
  2434. CheckRpcSendFailure();
  2435. // Do a bit of polling, to allow the ACK to get to the ADS server.
  2436. channel_->WaitForConnected(grpc_timeout_milliseconds_to_deadline(100));
  2437. const auto& response_state = RouteConfigurationResponseState(0);
  2438. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
  2439. }
  2440. // Tests that LDS client should choose the virtual host with matching domain if
  2441. // multiple virtual hosts exist in the LDS response.
  2442. TEST_P(LdsRdsTest, ChooseMatchedDomain) {
  2443. RouteConfiguration route_config =
  2444. balancers_[0]->ads_service()->default_route_config();
  2445. *(route_config.add_virtual_hosts()) = route_config.virtual_hosts(0);
  2446. route_config.mutable_virtual_hosts(0)->clear_domains();
  2447. route_config.mutable_virtual_hosts(0)->add_domains("unmatched_domain");
  2448. SetRouteConfiguration(0, route_config);
  2449. SetNextResolution({});
  2450. SetNextResolutionForLbChannelAllBalancers();
  2451. (void)SendRpc();
  2452. EXPECT_EQ(RouteConfigurationResponseState(0).state,
  2453. AdsServiceImpl::ResponseState::ACKED);
  2454. }
  2455. // Tests that LDS client should choose the last route in the virtual host if
  2456. // multiple routes exist in the LDS response.
  2457. TEST_P(LdsRdsTest, ChooseLastRoute) {
  2458. RouteConfiguration route_config =
  2459. balancers_[0]->ads_service()->default_route_config();
  2460. *(route_config.mutable_virtual_hosts(0)->add_routes()) =
  2461. route_config.virtual_hosts(0).routes(0);
  2462. route_config.mutable_virtual_hosts(0)
  2463. ->mutable_routes(0)
  2464. ->mutable_route()
  2465. ->mutable_cluster_header();
  2466. SetRouteConfiguration(0, route_config);
  2467. SetNextResolution({});
  2468. SetNextResolutionForLbChannelAllBalancers();
  2469. (void)SendRpc();
  2470. EXPECT_EQ(RouteConfigurationResponseState(0).state,
  2471. AdsServiceImpl::ResponseState::ACKED);
  2472. }
  2473. // Tests that LDS client should send a NACK if route match has a case_sensitive
  2474. // set to false.
  2475. TEST_P(LdsRdsTest, RouteMatchHasCaseSensitiveFalse) {
  2476. RouteConfiguration route_config =
  2477. balancers_[0]->ads_service()->default_route_config();
  2478. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2479. route1->mutable_match()->mutable_case_sensitive()->set_value(false);
  2480. SetRouteConfiguration(0, route_config);
  2481. SetNextResolution({});
  2482. SetNextResolutionForLbChannelAllBalancers();
  2483. CheckRpcSendFailure();
  2484. const auto& response_state = RouteConfigurationResponseState(0);
  2485. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2486. EXPECT_EQ(response_state.error_message,
  2487. "case_sensitive if set must be set to true.");
  2488. }
  2489. // Tests that LDS client should ignore route which has query_parameters.
  2490. TEST_P(LdsRdsTest, RouteMatchHasQueryParameters) {
  2491. RouteConfiguration route_config =
  2492. balancers_[0]->ads_service()->default_route_config();
  2493. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2494. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  2495. route1->mutable_match()->add_query_parameters();
  2496. SetRouteConfiguration(0, route_config);
  2497. SetNextResolution({});
  2498. SetNextResolutionForLbChannelAllBalancers();
  2499. CheckRpcSendFailure();
  2500. const auto& response_state = RouteConfigurationResponseState(0);
  2501. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2502. EXPECT_EQ(response_state.error_message, "No valid routes specified.");
  2503. }
  2504. // Tests that LDS client should send a ACK if route match has a prefix
  2505. // that is either empty or a single slash
  2506. TEST_P(LdsRdsTest, RouteMatchHasValidPrefixEmptyOrSingleSlash) {
  2507. RouteConfiguration route_config =
  2508. balancers_[0]->ads_service()->default_route_config();
  2509. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2510. route1->mutable_match()->set_prefix("");
  2511. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  2512. default_route->mutable_match()->set_prefix("/");
  2513. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  2514. SetRouteConfiguration(0, route_config);
  2515. SetNextResolution({});
  2516. SetNextResolutionForLbChannelAllBalancers();
  2517. (void)SendRpc();
  2518. const auto& response_state = RouteConfigurationResponseState(0);
  2519. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
  2520. }
  2521. // Tests that LDS client should ignore route which has a path
  2522. // prefix string does not start with "/".
  2523. TEST_P(LdsRdsTest, RouteMatchHasInvalidPrefixNoLeadingSlash) {
  2524. RouteConfiguration route_config =
  2525. balancers_[0]->ads_service()->default_route_config();
  2526. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2527. route1->mutable_match()->set_prefix("grpc.testing.EchoTest1Service/");
  2528. SetRouteConfiguration(0, route_config);
  2529. SetNextResolution({});
  2530. SetNextResolutionForLbChannelAllBalancers();
  2531. CheckRpcSendFailure();
  2532. const auto& response_state = RouteConfigurationResponseState(0);
  2533. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2534. EXPECT_EQ(response_state.error_message, "No valid routes specified.");
  2535. }
  2536. // Tests that LDS client should ignore route which has a prefix
  2537. // string with more than 2 slashes.
  2538. TEST_P(LdsRdsTest, RouteMatchHasInvalidPrefixExtraContent) {
  2539. RouteConfiguration route_config =
  2540. balancers_[0]->ads_service()->default_route_config();
  2541. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2542. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/Echo1/");
  2543. SetRouteConfiguration(0, route_config);
  2544. SetNextResolution({});
  2545. SetNextResolutionForLbChannelAllBalancers();
  2546. CheckRpcSendFailure();
  2547. const auto& response_state = RouteConfigurationResponseState(0);
  2548. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2549. EXPECT_EQ(response_state.error_message, "No valid routes specified.");
  2550. }
  2551. // Tests that LDS client should ignore route which has a prefix
  2552. // string "//".
  2553. TEST_P(LdsRdsTest, RouteMatchHasInvalidPrefixDoubleSlash) {
  2554. RouteConfiguration route_config =
  2555. balancers_[0]->ads_service()->default_route_config();
  2556. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2557. route1->mutable_match()->set_prefix("//");
  2558. SetRouteConfiguration(0, route_config);
  2559. SetNextResolution({});
  2560. SetNextResolutionForLbChannelAllBalancers();
  2561. CheckRpcSendFailure();
  2562. const auto& response_state = RouteConfigurationResponseState(0);
  2563. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2564. EXPECT_EQ(response_state.error_message, "No valid routes specified.");
  2565. }
  2566. // Tests that LDS client should ignore route which has path
  2567. // but it's empty.
  2568. TEST_P(LdsRdsTest, RouteMatchHasInvalidPathEmptyPath) {
  2569. RouteConfiguration route_config =
  2570. balancers_[0]->ads_service()->default_route_config();
  2571. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2572. route1->mutable_match()->set_path("");
  2573. SetRouteConfiguration(0, route_config);
  2574. SetNextResolution({});
  2575. SetNextResolutionForLbChannelAllBalancers();
  2576. CheckRpcSendFailure();
  2577. const auto& response_state = RouteConfigurationResponseState(0);
  2578. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2579. EXPECT_EQ(response_state.error_message, "No valid routes specified.");
  2580. }
  2581. // Tests that LDS client should ignore route which has path
  2582. // string does not start with "/".
  2583. TEST_P(LdsRdsTest, RouteMatchHasInvalidPathNoLeadingSlash) {
  2584. RouteConfiguration route_config =
  2585. balancers_[0]->ads_service()->default_route_config();
  2586. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2587. route1->mutable_match()->set_path("grpc.testing.EchoTest1Service/Echo1");
  2588. SetRouteConfiguration(0, route_config);
  2589. SetNextResolution({});
  2590. SetNextResolutionForLbChannelAllBalancers();
  2591. CheckRpcSendFailure();
  2592. const auto& response_state = RouteConfigurationResponseState(0);
  2593. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2594. EXPECT_EQ(response_state.error_message, "No valid routes specified.");
  2595. }
  2596. // Tests that LDS client should ignore route which has path
  2597. // string that has too many slashes; for example, ends with "/".
  2598. TEST_P(LdsRdsTest, RouteMatchHasInvalidPathTooManySlashes) {
  2599. RouteConfiguration route_config =
  2600. balancers_[0]->ads_service()->default_route_config();
  2601. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2602. route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service/Echo1/");
  2603. SetRouteConfiguration(0, route_config);
  2604. SetNextResolution({});
  2605. SetNextResolutionForLbChannelAllBalancers();
  2606. CheckRpcSendFailure();
  2607. const auto& response_state = RouteConfigurationResponseState(0);
  2608. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2609. EXPECT_EQ(response_state.error_message, "No valid routes specified.");
  2610. }
  2611. // Tests that LDS client should ignore route which has path
  2612. // string that has only 1 slash: missing "/" between service and method.
  2613. TEST_P(LdsRdsTest, RouteMatchHasInvalidPathOnlyOneSlash) {
  2614. RouteConfiguration route_config =
  2615. balancers_[0]->ads_service()->default_route_config();
  2616. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2617. route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service.Echo1");
  2618. SetRouteConfiguration(0, route_config);
  2619. SetNextResolution({});
  2620. SetNextResolutionForLbChannelAllBalancers();
  2621. CheckRpcSendFailure();
  2622. const auto& response_state = RouteConfigurationResponseState(0);
  2623. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2624. EXPECT_EQ(response_state.error_message, "No valid routes specified.");
  2625. }
  2626. // Tests that LDS client should ignore route which has path
  2627. // string that is missing service.
  2628. TEST_P(LdsRdsTest, RouteMatchHasInvalidPathMissingService) {
  2629. RouteConfiguration route_config =
  2630. balancers_[0]->ads_service()->default_route_config();
  2631. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2632. route1->mutable_match()->set_path("//Echo1");
  2633. SetRouteConfiguration(0, route_config);
  2634. SetNextResolution({});
  2635. SetNextResolutionForLbChannelAllBalancers();
  2636. CheckRpcSendFailure();
  2637. const auto& response_state = RouteConfigurationResponseState(0);
  2638. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2639. EXPECT_EQ(response_state.error_message, "No valid routes specified.");
  2640. }
  2641. // Tests that LDS client should ignore route which has path
  2642. // string that is missing method.
  2643. TEST_P(LdsRdsTest, RouteMatchHasInvalidPathMissingMethod) {
  2644. RouteConfiguration route_config =
  2645. balancers_[0]->ads_service()->default_route_config();
  2646. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2647. route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service/");
  2648. SetRouteConfiguration(0, route_config);
  2649. SetNextResolution({});
  2650. SetNextResolutionForLbChannelAllBalancers();
  2651. CheckRpcSendFailure();
  2652. const auto& response_state = RouteConfigurationResponseState(0);
  2653. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2654. EXPECT_EQ(response_state.error_message, "No valid routes specified.");
  2655. }
  2656. // Test that LDS client should reject route which has invalid path regex.
  2657. TEST_P(LdsRdsTest, RouteMatchHasInvalidPathRegex) {
  2658. const char* kNewCluster1Name = "new_cluster_1";
  2659. RouteConfiguration route_config =
  2660. balancers_[0]->ads_service()->default_route_config();
  2661. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2662. route1->mutable_match()->mutable_safe_regex()->set_regex("a[z-a]");
  2663. route1->mutable_route()->set_cluster(kNewCluster1Name);
  2664. SetRouteConfiguration(0, route_config);
  2665. SetNextResolution({});
  2666. SetNextResolutionForLbChannelAllBalancers();
  2667. CheckRpcSendFailure();
  2668. const auto& response_state = RouteConfigurationResponseState(0);
  2669. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2670. EXPECT_EQ(response_state.error_message,
  2671. "Invalid regex string specified in path matcher.");
  2672. }
  2673. // Tests that LDS client should send a NACK if route has an action other than
  2674. // RouteAction in the LDS response.
  2675. TEST_P(LdsRdsTest, RouteHasNoRouteAction) {
  2676. RouteConfiguration route_config =
  2677. balancers_[0]->ads_service()->default_route_config();
  2678. route_config.mutable_virtual_hosts(0)->mutable_routes(0)->mutable_redirect();
  2679. SetRouteConfiguration(0, route_config);
  2680. SetNextResolution({});
  2681. SetNextResolutionForLbChannelAllBalancers();
  2682. CheckRpcSendFailure();
  2683. const auto& response_state = RouteConfigurationResponseState(0);
  2684. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2685. EXPECT_EQ(response_state.error_message, "No RouteAction found in route.");
  2686. }
  2687. TEST_P(LdsRdsTest, RouteActionClusterHasEmptyClusterName) {
  2688. RouteConfiguration route_config =
  2689. balancers_[0]->ads_service()->default_route_config();
  2690. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2691. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  2692. route1->mutable_route()->set_cluster("");
  2693. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  2694. default_route->mutable_match()->set_prefix("");
  2695. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  2696. SetRouteConfiguration(0, route_config);
  2697. SetNextResolution({});
  2698. SetNextResolutionForLbChannelAllBalancers();
  2699. CheckRpcSendFailure();
  2700. const auto& response_state = RouteConfigurationResponseState(0);
  2701. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2702. EXPECT_EQ(response_state.error_message,
  2703. "RouteAction cluster contains empty cluster name.");
  2704. }
  2705. TEST_P(LdsRdsTest, RouteActionWeightedTargetHasIncorrectTotalWeightSet) {
  2706. const size_t kWeight75 = 75;
  2707. const char* kNewCluster1Name = "new_cluster_1";
  2708. RouteConfiguration route_config =
  2709. balancers_[0]->ads_service()->default_route_config();
  2710. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2711. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  2712. auto* weighted_cluster1 =
  2713. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  2714. weighted_cluster1->set_name(kNewCluster1Name);
  2715. weighted_cluster1->mutable_weight()->set_value(kWeight75);
  2716. route1->mutable_route()
  2717. ->mutable_weighted_clusters()
  2718. ->mutable_total_weight()
  2719. ->set_value(kWeight75 + 1);
  2720. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  2721. default_route->mutable_match()->set_prefix("");
  2722. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  2723. SetRouteConfiguration(0, route_config);
  2724. SetNextResolution({});
  2725. SetNextResolutionForLbChannelAllBalancers();
  2726. CheckRpcSendFailure();
  2727. const auto& response_state = RouteConfigurationResponseState(0);
  2728. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2729. EXPECT_EQ(response_state.error_message,
  2730. "RouteAction weighted_cluster has incorrect total weight");
  2731. }
  2732. TEST_P(LdsRdsTest, RouteActionWeightedTargetClusterHasEmptyClusterName) {
  2733. const size_t kWeight75 = 75;
  2734. RouteConfiguration route_config =
  2735. balancers_[0]->ads_service()->default_route_config();
  2736. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2737. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  2738. auto* weighted_cluster1 =
  2739. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  2740. weighted_cluster1->set_name("");
  2741. weighted_cluster1->mutable_weight()->set_value(kWeight75);
  2742. route1->mutable_route()
  2743. ->mutable_weighted_clusters()
  2744. ->mutable_total_weight()
  2745. ->set_value(kWeight75);
  2746. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  2747. default_route->mutable_match()->set_prefix("");
  2748. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  2749. SetRouteConfiguration(0, route_config);
  2750. SetNextResolution({});
  2751. SetNextResolutionForLbChannelAllBalancers();
  2752. CheckRpcSendFailure();
  2753. const auto& response_state = RouteConfigurationResponseState(0);
  2754. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2755. EXPECT_EQ(
  2756. response_state.error_message,
  2757. "RouteAction weighted_cluster cluster contains empty cluster name.");
  2758. }
  2759. TEST_P(LdsRdsTest, RouteActionWeightedTargetClusterHasNoWeight) {
  2760. const size_t kWeight75 = 75;
  2761. const char* kNewCluster1Name = "new_cluster_1";
  2762. RouteConfiguration route_config =
  2763. balancers_[0]->ads_service()->default_route_config();
  2764. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2765. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  2766. auto* weighted_cluster1 =
  2767. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  2768. weighted_cluster1->set_name(kNewCluster1Name);
  2769. route1->mutable_route()
  2770. ->mutable_weighted_clusters()
  2771. ->mutable_total_weight()
  2772. ->set_value(kWeight75);
  2773. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  2774. default_route->mutable_match()->set_prefix("");
  2775. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  2776. SetRouteConfiguration(0, route_config);
  2777. SetNextResolution({});
  2778. SetNextResolutionForLbChannelAllBalancers();
  2779. CheckRpcSendFailure();
  2780. const auto& response_state = RouteConfigurationResponseState(0);
  2781. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2782. EXPECT_EQ(response_state.error_message,
  2783. "RouteAction weighted_cluster cluster missing weight");
  2784. }
  2785. TEST_P(LdsRdsTest, RouteHeaderMatchInvalidRegex) {
  2786. const char* kNewCluster1Name = "new_cluster_1";
  2787. RouteConfiguration route_config =
  2788. balancers_[0]->ads_service()->default_route_config();
  2789. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2790. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  2791. auto* header_matcher1 = route1->mutable_match()->add_headers();
  2792. header_matcher1->set_name("header1");
  2793. header_matcher1->mutable_safe_regex_match()->set_regex("a[z-a]");
  2794. route1->mutable_route()->set_cluster(kNewCluster1Name);
  2795. SetRouteConfiguration(0, route_config);
  2796. SetNextResolution({});
  2797. SetNextResolutionForLbChannelAllBalancers();
  2798. CheckRpcSendFailure();
  2799. const auto& response_state = RouteConfigurationResponseState(0);
  2800. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2801. EXPECT_EQ(response_state.error_message,
  2802. "Invalid regex string specified in header matcher.");
  2803. }
  2804. TEST_P(LdsRdsTest, RouteHeaderMatchInvalidRange) {
  2805. const char* kNewCluster1Name = "new_cluster_1";
  2806. RouteConfiguration route_config =
  2807. balancers_[0]->ads_service()->default_route_config();
  2808. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2809. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  2810. auto* header_matcher1 = route1->mutable_match()->add_headers();
  2811. header_matcher1->set_name("header1");
  2812. header_matcher1->mutable_range_match()->set_start(1001);
  2813. header_matcher1->mutable_range_match()->set_end(1000);
  2814. route1->mutable_route()->set_cluster(kNewCluster1Name);
  2815. SetRouteConfiguration(0, route_config);
  2816. SetNextResolution({});
  2817. SetNextResolutionForLbChannelAllBalancers();
  2818. CheckRpcSendFailure();
  2819. const auto& response_state = RouteConfigurationResponseState(0);
  2820. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2821. EXPECT_EQ(response_state.error_message,
  2822. "Invalid range header matcher specifier specified: end "
  2823. "cannot be smaller than start.");
  2824. }
  2825. // Tests that LDS client should choose the default route (with no matching
  2826. // specified) after unable to find a match with previous routes.
  2827. TEST_P(LdsRdsTest, XdsRoutingPathMatching) {
  2828. const char* kNewCluster1Name = "new_cluster_1";
  2829. const char* kNewEdsService1Name = "new_eds_service_name_1";
  2830. const char* kNewCluster2Name = "new_cluster_2";
  2831. const char* kNewEdsService2Name = "new_eds_service_name_2";
  2832. const size_t kNumEcho1Rpcs = 10;
  2833. const size_t kNumEcho2Rpcs = 20;
  2834. const size_t kNumEchoRpcs = 30;
  2835. SetNextResolution({});
  2836. SetNextResolutionForLbChannelAllBalancers();
  2837. // Populate new EDS resources.
  2838. AdsServiceImpl::EdsResourceArgs args({
  2839. {"locality0", GetBackendPorts(0, 2)},
  2840. });
  2841. AdsServiceImpl::EdsResourceArgs args1({
  2842. {"locality0", GetBackendPorts(2, 3)},
  2843. });
  2844. AdsServiceImpl::EdsResourceArgs args2({
  2845. {"locality0", GetBackendPorts(3, 4)},
  2846. });
  2847. balancers_[0]->ads_service()->SetEdsResource(
  2848. AdsServiceImpl::BuildEdsResource(args));
  2849. balancers_[0]->ads_service()->SetEdsResource(
  2850. AdsServiceImpl::BuildEdsResource(args1, kNewEdsService1Name));
  2851. balancers_[0]->ads_service()->SetEdsResource(
  2852. AdsServiceImpl::BuildEdsResource(args2, kNewEdsService2Name));
  2853. // Populate new CDS resources.
  2854. Cluster new_cluster1 = balancers_[0]->ads_service()->default_cluster();
  2855. new_cluster1.set_name(kNewCluster1Name);
  2856. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  2857. kNewEdsService1Name);
  2858. balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
  2859. Cluster new_cluster2 = balancers_[0]->ads_service()->default_cluster();
  2860. new_cluster2.set_name(kNewCluster2Name);
  2861. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  2862. kNewEdsService2Name);
  2863. balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
  2864. // Populating Route Configurations for LDS.
  2865. RouteConfiguration new_route_config =
  2866. balancers_[0]->ads_service()->default_route_config();
  2867. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2868. route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service/Echo1");
  2869. route1->mutable_route()->set_cluster(kNewCluster1Name);
  2870. auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
  2871. route2->mutable_match()->set_path("/grpc.testing.EchoTest2Service/Echo2");
  2872. route2->mutable_route()->set_cluster(kNewCluster2Name);
  2873. auto* route3 = new_route_config.mutable_virtual_hosts(0)->add_routes();
  2874. route3->mutable_match()->set_path("/grpc.testing.EchoTest3Service/Echo3");
  2875. route3->mutable_route()->set_cluster(kDefaultClusterName);
  2876. auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
  2877. default_route->mutable_match()->set_prefix("");
  2878. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  2879. SetRouteConfiguration(0, new_route_config);
  2880. WaitForAllBackends(0, 2);
  2881. CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
  2882. CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions()
  2883. .set_rpc_service(SERVICE_ECHO1)
  2884. .set_rpc_method(METHOD_ECHO1)
  2885. .set_wait_for_ready(true));
  2886. CheckRpcSendOk(kNumEcho2Rpcs, RpcOptions()
  2887. .set_rpc_service(SERVICE_ECHO2)
  2888. .set_rpc_method(METHOD_ECHO2)
  2889. .set_wait_for_ready(true));
  2890. // Make sure RPCs all go to the correct backend.
  2891. for (size_t i = 0; i < 2; ++i) {
  2892. EXPECT_EQ(kNumEchoRpcs / 2,
  2893. backends_[i]->backend_service()->request_count());
  2894. EXPECT_EQ(0, backends_[i]->backend_service1()->request_count());
  2895. EXPECT_EQ(0, backends_[i]->backend_service2()->request_count());
  2896. }
  2897. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  2898. EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
  2899. EXPECT_EQ(0, backends_[2]->backend_service2()->request_count());
  2900. EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
  2901. EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
  2902. EXPECT_EQ(kNumEcho2Rpcs, backends_[3]->backend_service2()->request_count());
  2903. }
  2904. TEST_P(LdsRdsTest, XdsRoutingPrefixMatching) {
  2905. const char* kNewCluster1Name = "new_cluster_1";
  2906. const char* kNewEdsService1Name = "new_eds_service_name_1";
  2907. const char* kNewCluster2Name = "new_cluster_2";
  2908. const char* kNewEdsService2Name = "new_eds_service_name_2";
  2909. const size_t kNumEcho1Rpcs = 10;
  2910. const size_t kNumEcho2Rpcs = 20;
  2911. const size_t kNumEchoRpcs = 30;
  2912. SetNextResolution({});
  2913. SetNextResolutionForLbChannelAllBalancers();
  2914. // Populate new EDS resources.
  2915. AdsServiceImpl::EdsResourceArgs args({
  2916. {"locality0", GetBackendPorts(0, 2)},
  2917. });
  2918. AdsServiceImpl::EdsResourceArgs args1({
  2919. {"locality0", GetBackendPorts(2, 3)},
  2920. });
  2921. AdsServiceImpl::EdsResourceArgs args2({
  2922. {"locality0", GetBackendPorts(3, 4)},
  2923. });
  2924. balancers_[0]->ads_service()->SetEdsResource(
  2925. AdsServiceImpl::BuildEdsResource(args));
  2926. balancers_[0]->ads_service()->SetEdsResource(
  2927. AdsServiceImpl::BuildEdsResource(args1, kNewEdsService1Name));
  2928. balancers_[0]->ads_service()->SetEdsResource(
  2929. AdsServiceImpl::BuildEdsResource(args2, kNewEdsService2Name));
  2930. // Populate new CDS resources.
  2931. Cluster new_cluster1 = balancers_[0]->ads_service()->default_cluster();
  2932. new_cluster1.set_name(kNewCluster1Name);
  2933. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  2934. kNewEdsService1Name);
  2935. balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
  2936. Cluster new_cluster2 = balancers_[0]->ads_service()->default_cluster();
  2937. new_cluster2.set_name(kNewCluster2Name);
  2938. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  2939. kNewEdsService2Name);
  2940. balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
  2941. // Populating Route Configurations for LDS.
  2942. RouteConfiguration new_route_config =
  2943. balancers_[0]->ads_service()->default_route_config();
  2944. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2945. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  2946. route1->mutable_route()->set_cluster(kNewCluster1Name);
  2947. auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
  2948. route2->mutable_match()->set_prefix("/grpc.testing.EchoTest2Service/");
  2949. route2->mutable_route()->set_cluster(kNewCluster2Name);
  2950. auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
  2951. default_route->mutable_match()->set_prefix("");
  2952. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  2953. SetRouteConfiguration(0, new_route_config);
  2954. WaitForAllBackends(0, 2);
  2955. CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
  2956. CheckRpcSendOk(
  2957. kNumEcho1Rpcs,
  2958. RpcOptions().set_rpc_service(SERVICE_ECHO1).set_wait_for_ready(true));
  2959. CheckRpcSendOk(
  2960. kNumEcho2Rpcs,
  2961. RpcOptions().set_rpc_service(SERVICE_ECHO2).set_wait_for_ready(true));
  2962. // Make sure RPCs all go to the correct backend.
  2963. for (size_t i = 0; i < 2; ++i) {
  2964. EXPECT_EQ(kNumEchoRpcs / 2,
  2965. backends_[i]->backend_service()->request_count());
  2966. EXPECT_EQ(0, backends_[i]->backend_service1()->request_count());
  2967. EXPECT_EQ(0, backends_[i]->backend_service2()->request_count());
  2968. }
  2969. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  2970. EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
  2971. EXPECT_EQ(0, backends_[2]->backend_service2()->request_count());
  2972. EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
  2973. EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
  2974. EXPECT_EQ(kNumEcho2Rpcs, backends_[3]->backend_service2()->request_count());
  2975. }
  2976. TEST_P(LdsRdsTest, XdsRoutingPathRegexMatching) {
  2977. const char* kNewCluster1Name = "new_cluster_1";
  2978. const char* kNewEdsService1Name = "new_eds_service_name_1";
  2979. const char* kNewCluster2Name = "new_cluster_2";
  2980. const char* kNewEdsService2Name = "new_eds_service_name_2";
  2981. const size_t kNumEcho1Rpcs = 10;
  2982. const size_t kNumEcho2Rpcs = 20;
  2983. const size_t kNumEchoRpcs = 30;
  2984. SetNextResolution({});
  2985. SetNextResolutionForLbChannelAllBalancers();
  2986. // Populate new EDS resources.
  2987. AdsServiceImpl::EdsResourceArgs args({
  2988. {"locality0", GetBackendPorts(0, 2)},
  2989. });
  2990. AdsServiceImpl::EdsResourceArgs args1({
  2991. {"locality0", GetBackendPorts(2, 3)},
  2992. });
  2993. AdsServiceImpl::EdsResourceArgs args2({
  2994. {"locality0", GetBackendPorts(3, 4)},
  2995. });
  2996. balancers_[0]->ads_service()->SetEdsResource(
  2997. AdsServiceImpl::BuildEdsResource(args));
  2998. balancers_[0]->ads_service()->SetEdsResource(
  2999. AdsServiceImpl::BuildEdsResource(args1, kNewEdsService1Name));
  3000. balancers_[0]->ads_service()->SetEdsResource(
  3001. AdsServiceImpl::BuildEdsResource(args2, kNewEdsService2Name));
  3002. // Populate new CDS resources.
  3003. Cluster new_cluster1 = balancers_[0]->ads_service()->default_cluster();
  3004. new_cluster1.set_name(kNewCluster1Name);
  3005. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  3006. kNewEdsService1Name);
  3007. balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
  3008. Cluster new_cluster2 = balancers_[0]->ads_service()->default_cluster();
  3009. new_cluster2.set_name(kNewCluster2Name);
  3010. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  3011. kNewEdsService2Name);
  3012. balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
  3013. // Populating Route Configurations for LDS.
  3014. RouteConfiguration new_route_config =
  3015. balancers_[0]->ads_service()->default_route_config();
  3016. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3017. // Will match "/grpc.testing.EchoTest1Service/"
  3018. route1->mutable_match()->mutable_safe_regex()->set_regex(".*1.*");
  3019. route1->mutable_route()->set_cluster(kNewCluster1Name);
  3020. auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3021. // Will match "/grpc.testing.EchoTest2Service/"
  3022. route2->mutable_match()->mutable_safe_regex()->set_regex(".*2.*");
  3023. route2->mutable_route()->set_cluster(kNewCluster2Name);
  3024. auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3025. default_route->mutable_match()->set_prefix("");
  3026. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3027. SetRouteConfiguration(0, new_route_config);
  3028. WaitForAllBackends(0, 2);
  3029. CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
  3030. CheckRpcSendOk(
  3031. kNumEcho1Rpcs,
  3032. RpcOptions().set_rpc_service(SERVICE_ECHO1).set_wait_for_ready(true));
  3033. CheckRpcSendOk(
  3034. kNumEcho2Rpcs,
  3035. RpcOptions().set_rpc_service(SERVICE_ECHO2).set_wait_for_ready(true));
  3036. // Make sure RPCs all go to the correct backend.
  3037. for (size_t i = 0; i < 2; ++i) {
  3038. EXPECT_EQ(kNumEchoRpcs / 2,
  3039. backends_[i]->backend_service()->request_count());
  3040. EXPECT_EQ(0, backends_[i]->backend_service1()->request_count());
  3041. EXPECT_EQ(0, backends_[i]->backend_service2()->request_count());
  3042. }
  3043. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  3044. EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
  3045. EXPECT_EQ(0, backends_[2]->backend_service2()->request_count());
  3046. EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
  3047. EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
  3048. EXPECT_EQ(kNumEcho2Rpcs, backends_[3]->backend_service2()->request_count());
  3049. }
  3050. TEST_P(LdsRdsTest, XdsRoutingWeightedCluster) {
  3051. const char* kNewCluster1Name = "new_cluster_1";
  3052. const char* kNewEdsService1Name = "new_eds_service_name_1";
  3053. const char* kNewCluster2Name = "new_cluster_2";
  3054. const char* kNewEdsService2Name = "new_eds_service_name_2";
  3055. const size_t kNumEcho1Rpcs = 1000;
  3056. const size_t kNumEchoRpcs = 10;
  3057. const size_t kWeight75 = 75;
  3058. const size_t kWeight25 = 25;
  3059. SetNextResolution({});
  3060. SetNextResolutionForLbChannelAllBalancers();
  3061. // Populate new EDS resources.
  3062. AdsServiceImpl::EdsResourceArgs args({
  3063. {"locality0", GetBackendPorts(0, 1)},
  3064. });
  3065. AdsServiceImpl::EdsResourceArgs args1({
  3066. {"locality0", GetBackendPorts(1, 2)},
  3067. });
  3068. AdsServiceImpl::EdsResourceArgs args2({
  3069. {"locality0", GetBackendPorts(2, 3)},
  3070. });
  3071. balancers_[0]->ads_service()->SetEdsResource(
  3072. AdsServiceImpl::BuildEdsResource(args));
  3073. balancers_[0]->ads_service()->SetEdsResource(
  3074. AdsServiceImpl::BuildEdsResource(args1, kNewEdsService1Name));
  3075. balancers_[0]->ads_service()->SetEdsResource(
  3076. AdsServiceImpl::BuildEdsResource(args2, kNewEdsService2Name));
  3077. // Populate new CDS resources.
  3078. Cluster new_cluster1 = balancers_[0]->ads_service()->default_cluster();
  3079. new_cluster1.set_name(kNewCluster1Name);
  3080. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  3081. kNewEdsService1Name);
  3082. balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
  3083. Cluster new_cluster2 = balancers_[0]->ads_service()->default_cluster();
  3084. new_cluster2.set_name(kNewCluster2Name);
  3085. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  3086. kNewEdsService2Name);
  3087. balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
  3088. // Populating Route Configurations for LDS.
  3089. RouteConfiguration new_route_config =
  3090. balancers_[0]->ads_service()->default_route_config();
  3091. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3092. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3093. auto* weighted_cluster1 =
  3094. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3095. weighted_cluster1->set_name(kNewCluster1Name);
  3096. weighted_cluster1->mutable_weight()->set_value(kWeight75);
  3097. auto* weighted_cluster2 =
  3098. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3099. weighted_cluster2->set_name(kNewCluster2Name);
  3100. weighted_cluster2->mutable_weight()->set_value(kWeight25);
  3101. route1->mutable_route()
  3102. ->mutable_weighted_clusters()
  3103. ->mutable_total_weight()
  3104. ->set_value(kWeight75 + kWeight25);
  3105. auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3106. default_route->mutable_match()->set_prefix("");
  3107. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3108. SetRouteConfiguration(0, new_route_config);
  3109. WaitForAllBackends(0, 1);
  3110. WaitForAllBackends(1, 3, true, RpcOptions().set_rpc_service(SERVICE_ECHO1));
  3111. CheckRpcSendOk(kNumEchoRpcs);
  3112. CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
  3113. // Make sure RPCs all go to the correct backend.
  3114. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  3115. EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
  3116. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  3117. const int weight_75_request_count =
  3118. backends_[1]->backend_service1()->request_count();
  3119. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  3120. const int weight_25_request_count =
  3121. backends_[2]->backend_service1()->request_count();
  3122. const double kErrorTolerance = 0.2;
  3123. EXPECT_THAT(weight_75_request_count,
  3124. ::testing::AllOf(::testing::Ge(kNumEcho1Rpcs * kWeight75 / 100 *
  3125. (1 - kErrorTolerance)),
  3126. ::testing::Le(kNumEcho1Rpcs * kWeight75 / 100 *
  3127. (1 + kErrorTolerance))));
  3128. // TODO: (@donnadionne) Reduce tolerance: increased the tolerance to keep the
  3129. // test from flaking while debugging potential root cause.
  3130. const double kErrorToleranceSmallLoad = 0.3;
  3131. gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
  3132. weight_75_request_count, weight_25_request_count);
  3133. EXPECT_THAT(weight_25_request_count,
  3134. ::testing::AllOf(::testing::Ge(kNumEcho1Rpcs * kWeight25 / 100 *
  3135. (1 - kErrorToleranceSmallLoad)),
  3136. ::testing::Le(kNumEcho1Rpcs * kWeight25 / 100 *
  3137. (1 + kErrorToleranceSmallLoad))));
  3138. }
  3139. TEST_P(LdsRdsTest, RouteActionWeightedTargetDefaultRoute) {
  3140. const char* kNewCluster1Name = "new_cluster_1";
  3141. const char* kNewEdsService1Name = "new_eds_service_name_1";
  3142. const char* kNewCluster2Name = "new_cluster_2";
  3143. const char* kNewEdsService2Name = "new_eds_service_name_2";
  3144. const size_t kNumEchoRpcs = 1000;
  3145. const size_t kWeight75 = 75;
  3146. const size_t kWeight25 = 25;
  3147. SetNextResolution({});
  3148. SetNextResolutionForLbChannelAllBalancers();
  3149. // Populate new EDS resources.
  3150. AdsServiceImpl::EdsResourceArgs args({
  3151. {"locality0", GetBackendPorts(0, 1)},
  3152. });
  3153. AdsServiceImpl::EdsResourceArgs args1({
  3154. {"locality0", GetBackendPorts(1, 2)},
  3155. });
  3156. AdsServiceImpl::EdsResourceArgs args2({
  3157. {"locality0", GetBackendPorts(2, 3)},
  3158. });
  3159. balancers_[0]->ads_service()->SetEdsResource(
  3160. AdsServiceImpl::BuildEdsResource(args));
  3161. balancers_[0]->ads_service()->SetEdsResource(
  3162. AdsServiceImpl::BuildEdsResource(args1, kNewEdsService1Name));
  3163. balancers_[0]->ads_service()->SetEdsResource(
  3164. AdsServiceImpl::BuildEdsResource(args2, kNewEdsService2Name));
  3165. // Populate new CDS resources.
  3166. Cluster new_cluster1 = balancers_[0]->ads_service()->default_cluster();
  3167. new_cluster1.set_name(kNewCluster1Name);
  3168. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  3169. kNewEdsService1Name);
  3170. balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
  3171. Cluster new_cluster2 = balancers_[0]->ads_service()->default_cluster();
  3172. new_cluster2.set_name(kNewCluster2Name);
  3173. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  3174. kNewEdsService2Name);
  3175. balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
  3176. // Populating Route Configurations for LDS.
  3177. RouteConfiguration new_route_config =
  3178. balancers_[0]->ads_service()->default_route_config();
  3179. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3180. route1->mutable_match()->set_prefix("");
  3181. auto* weighted_cluster1 =
  3182. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3183. weighted_cluster1->set_name(kNewCluster1Name);
  3184. weighted_cluster1->mutable_weight()->set_value(kWeight75);
  3185. auto* weighted_cluster2 =
  3186. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3187. weighted_cluster2->set_name(kNewCluster2Name);
  3188. weighted_cluster2->mutable_weight()->set_value(kWeight25);
  3189. route1->mutable_route()
  3190. ->mutable_weighted_clusters()
  3191. ->mutable_total_weight()
  3192. ->set_value(kWeight75 + kWeight25);
  3193. SetRouteConfiguration(0, new_route_config);
  3194. WaitForAllBackends(1, 3);
  3195. CheckRpcSendOk(kNumEchoRpcs);
  3196. // Make sure RPCs all go to the correct backend.
  3197. EXPECT_EQ(0, backends_[0]->backend_service()->request_count());
  3198. const int weight_75_request_count =
  3199. backends_[1]->backend_service()->request_count();
  3200. const int weight_25_request_count =
  3201. backends_[2]->backend_service()->request_count();
  3202. const double kErrorTolerance = 0.2;
  3203. EXPECT_THAT(weight_75_request_count,
  3204. ::testing::AllOf(::testing::Ge(kNumEchoRpcs * kWeight75 / 100 *
  3205. (1 - kErrorTolerance)),
  3206. ::testing::Le(kNumEchoRpcs * kWeight75 / 100 *
  3207. (1 + kErrorTolerance))));
  3208. // TODO: (@donnadionne) Reduce tolerance: increased the tolerance to keep the
  3209. // test from flaking while debugging potential root cause.
  3210. const double kErrorToleranceSmallLoad = 0.3;
  3211. gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
  3212. weight_75_request_count, weight_25_request_count);
  3213. EXPECT_THAT(weight_25_request_count,
  3214. ::testing::AllOf(::testing::Ge(kNumEchoRpcs * kWeight25 / 100 *
  3215. (1 - kErrorToleranceSmallLoad)),
  3216. ::testing::Le(kNumEchoRpcs * kWeight25 / 100 *
  3217. (1 + kErrorToleranceSmallLoad))));
  3218. }
  3219. TEST_P(LdsRdsTest, XdsRoutingWeightedClusterUpdateWeights) {
  3220. const char* kNewCluster1Name = "new_cluster_1";
  3221. const char* kNewEdsService1Name = "new_eds_service_name_1";
  3222. const char* kNewCluster2Name = "new_cluster_2";
  3223. const char* kNewEdsService2Name = "new_eds_service_name_2";
  3224. const char* kNewCluster3Name = "new_cluster_3";
  3225. const char* kNewEdsService3Name = "new_eds_service_name_3";
  3226. const size_t kNumEcho1Rpcs = 1000;
  3227. const size_t kNumEchoRpcs = 10;
  3228. const size_t kWeight75 = 75;
  3229. const size_t kWeight25 = 25;
  3230. const size_t kWeight50 = 50;
  3231. SetNextResolution({});
  3232. SetNextResolutionForLbChannelAllBalancers();
  3233. // Populate new EDS resources.
  3234. AdsServiceImpl::EdsResourceArgs args({
  3235. {"locality0", GetBackendPorts(0, 1)},
  3236. });
  3237. AdsServiceImpl::EdsResourceArgs args1({
  3238. {"locality0", GetBackendPorts(1, 2)},
  3239. });
  3240. AdsServiceImpl::EdsResourceArgs args2({
  3241. {"locality0", GetBackendPorts(2, 3)},
  3242. });
  3243. AdsServiceImpl::EdsResourceArgs args3({
  3244. {"locality0", GetBackendPorts(3, 4)},
  3245. });
  3246. balancers_[0]->ads_service()->SetEdsResource(
  3247. AdsServiceImpl::BuildEdsResource(args));
  3248. balancers_[0]->ads_service()->SetEdsResource(
  3249. AdsServiceImpl::BuildEdsResource(args1, kNewEdsService1Name));
  3250. balancers_[0]->ads_service()->SetEdsResource(
  3251. AdsServiceImpl::BuildEdsResource(args2, kNewEdsService2Name));
  3252. balancers_[0]->ads_service()->SetEdsResource(
  3253. AdsServiceImpl::BuildEdsResource(args3, kNewEdsService3Name));
  3254. // Populate new CDS resources.
  3255. Cluster new_cluster1 = balancers_[0]->ads_service()->default_cluster();
  3256. new_cluster1.set_name(kNewCluster1Name);
  3257. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  3258. kNewEdsService1Name);
  3259. balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
  3260. Cluster new_cluster2 = balancers_[0]->ads_service()->default_cluster();
  3261. new_cluster2.set_name(kNewCluster2Name);
  3262. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  3263. kNewEdsService2Name);
  3264. balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
  3265. Cluster new_cluster3 = balancers_[0]->ads_service()->default_cluster();
  3266. new_cluster3.set_name(kNewCluster3Name);
  3267. new_cluster3.mutable_eds_cluster_config()->set_service_name(
  3268. kNewEdsService3Name);
  3269. balancers_[0]->ads_service()->SetCdsResource(new_cluster3);
  3270. // Populating Route Configurations.
  3271. RouteConfiguration new_route_config =
  3272. balancers_[0]->ads_service()->default_route_config();
  3273. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3274. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3275. auto* weighted_cluster1 =
  3276. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3277. weighted_cluster1->set_name(kNewCluster1Name);
  3278. weighted_cluster1->mutable_weight()->set_value(kWeight75);
  3279. auto* weighted_cluster2 =
  3280. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3281. weighted_cluster2->set_name(kNewCluster2Name);
  3282. weighted_cluster2->mutable_weight()->set_value(kWeight25);
  3283. route1->mutable_route()
  3284. ->mutable_weighted_clusters()
  3285. ->mutable_total_weight()
  3286. ->set_value(kWeight75 + kWeight25);
  3287. auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3288. default_route->mutable_match()->set_prefix("");
  3289. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3290. SetRouteConfiguration(0, new_route_config);
  3291. WaitForAllBackends(0, 1);
  3292. WaitForAllBackends(1, 3, true, RpcOptions().set_rpc_service(SERVICE_ECHO1));
  3293. CheckRpcSendOk(kNumEchoRpcs);
  3294. CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
  3295. // Make sure RPCs all go to the correct backend.
  3296. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  3297. EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
  3298. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  3299. const int weight_75_request_count =
  3300. backends_[1]->backend_service1()->request_count();
  3301. EXPECT_EQ(0, backends_[1]->backend_service2()->request_count());
  3302. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  3303. const int weight_25_request_count =
  3304. backends_[2]->backend_service1()->request_count();
  3305. EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
  3306. EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
  3307. const double kErrorTolerance = 0.2;
  3308. EXPECT_THAT(weight_75_request_count,
  3309. ::testing::AllOf(::testing::Ge(kNumEcho1Rpcs * kWeight75 / 100 *
  3310. (1 - kErrorTolerance)),
  3311. ::testing::Le(kNumEcho1Rpcs * kWeight75 / 100 *
  3312. (1 + kErrorTolerance))));
  3313. // TODO: (@donnadionne) Reduce tolerance: increased the tolerance to keep the
  3314. // test from flaking while debugging potential root cause.
  3315. const double kErrorToleranceSmallLoad = 0.3;
  3316. gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
  3317. weight_75_request_count, weight_25_request_count);
  3318. EXPECT_THAT(weight_25_request_count,
  3319. ::testing::AllOf(::testing::Ge(kNumEcho1Rpcs * kWeight25 / 100 *
  3320. (1 - kErrorToleranceSmallLoad)),
  3321. ::testing::Le(kNumEcho1Rpcs * kWeight25 / 100 *
  3322. (1 + kErrorToleranceSmallLoad))));
  3323. // Change Route Configurations: same clusters different weights.
  3324. weighted_cluster1->mutable_weight()->set_value(kWeight50);
  3325. weighted_cluster2->mutable_weight()->set_value(kWeight50);
  3326. // Change default route to a new cluster to help to identify when new polices
  3327. // are seen by the client.
  3328. default_route->mutable_route()->set_cluster(kNewCluster3Name);
  3329. SetRouteConfiguration(0, new_route_config);
  3330. ResetBackendCounters();
  3331. WaitForAllBackends(3, 4);
  3332. CheckRpcSendOk(kNumEchoRpcs);
  3333. CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
  3334. // Make sure RPCs all go to the correct backend.
  3335. EXPECT_EQ(0, backends_[0]->backend_service()->request_count());
  3336. EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
  3337. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  3338. const int weight_50_request_count_1 =
  3339. backends_[1]->backend_service1()->request_count();
  3340. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  3341. const int weight_50_request_count_2 =
  3342. backends_[2]->backend_service1()->request_count();
  3343. EXPECT_EQ(kNumEchoRpcs, backends_[3]->backend_service()->request_count());
  3344. EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
  3345. EXPECT_THAT(weight_50_request_count_1,
  3346. ::testing::AllOf(::testing::Ge(kNumEcho1Rpcs * kWeight50 / 100 *
  3347. (1 - kErrorTolerance)),
  3348. ::testing::Le(kNumEcho1Rpcs * kWeight50 / 100 *
  3349. (1 + kErrorTolerance))));
  3350. EXPECT_THAT(weight_50_request_count_2,
  3351. ::testing::AllOf(::testing::Ge(kNumEcho1Rpcs * kWeight50 / 100 *
  3352. (1 - kErrorTolerance)),
  3353. ::testing::Le(kNumEcho1Rpcs * kWeight50 / 100 *
  3354. (1 + kErrorTolerance))));
  3355. }
  3356. TEST_P(LdsRdsTest, XdsRoutingWeightedClusterUpdateClusters) {
  3357. const char* kNewCluster1Name = "new_cluster_1";
  3358. const char* kNewEdsService1Name = "new_eds_service_name_1";
  3359. const char* kNewCluster2Name = "new_cluster_2";
  3360. const char* kNewEdsService2Name = "new_eds_service_name_2";
  3361. const char* kNewCluster3Name = "new_cluster_3";
  3362. const char* kNewEdsService3Name = "new_eds_service_name_3";
  3363. const size_t kNumEcho1Rpcs = 1000;
  3364. const size_t kNumEchoRpcs = 10;
  3365. const size_t kWeight75 = 75;
  3366. const size_t kWeight25 = 25;
  3367. const size_t kWeight50 = 50;
  3368. SetNextResolution({});
  3369. SetNextResolutionForLbChannelAllBalancers();
  3370. // Populate new EDS resources.
  3371. AdsServiceImpl::EdsResourceArgs args({
  3372. {"locality0", GetBackendPorts(0, 1)},
  3373. });
  3374. AdsServiceImpl::EdsResourceArgs args1({
  3375. {"locality0", GetBackendPorts(1, 2)},
  3376. });
  3377. AdsServiceImpl::EdsResourceArgs args2({
  3378. {"locality0", GetBackendPorts(2, 3)},
  3379. });
  3380. AdsServiceImpl::EdsResourceArgs args3({
  3381. {"locality0", GetBackendPorts(3, 4)},
  3382. });
  3383. balancers_[0]->ads_service()->SetEdsResource(
  3384. AdsServiceImpl::BuildEdsResource(args));
  3385. balancers_[0]->ads_service()->SetEdsResource(
  3386. AdsServiceImpl::BuildEdsResource(args1, kNewEdsService1Name));
  3387. balancers_[0]->ads_service()->SetEdsResource(
  3388. AdsServiceImpl::BuildEdsResource(args2, kNewEdsService2Name));
  3389. balancers_[0]->ads_service()->SetEdsResource(
  3390. AdsServiceImpl::BuildEdsResource(args3, kNewEdsService3Name));
  3391. // Populate new CDS resources.
  3392. Cluster new_cluster1 = balancers_[0]->ads_service()->default_cluster();
  3393. new_cluster1.set_name(kNewCluster1Name);
  3394. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  3395. kNewEdsService1Name);
  3396. balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
  3397. Cluster new_cluster2 = balancers_[0]->ads_service()->default_cluster();
  3398. new_cluster2.set_name(kNewCluster2Name);
  3399. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  3400. kNewEdsService2Name);
  3401. balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
  3402. Cluster new_cluster3 = balancers_[0]->ads_service()->default_cluster();
  3403. new_cluster3.set_name(kNewCluster3Name);
  3404. new_cluster3.mutable_eds_cluster_config()->set_service_name(
  3405. kNewEdsService3Name);
  3406. balancers_[0]->ads_service()->SetCdsResource(new_cluster3);
  3407. // Populating Route Configurations.
  3408. RouteConfiguration new_route_config =
  3409. balancers_[0]->ads_service()->default_route_config();
  3410. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3411. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3412. auto* weighted_cluster1 =
  3413. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3414. weighted_cluster1->set_name(kNewCluster1Name);
  3415. weighted_cluster1->mutable_weight()->set_value(kWeight75);
  3416. auto* weighted_cluster2 =
  3417. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3418. weighted_cluster2->set_name(kDefaultClusterName);
  3419. weighted_cluster2->mutable_weight()->set_value(kWeight25);
  3420. route1->mutable_route()
  3421. ->mutable_weighted_clusters()
  3422. ->mutable_total_weight()
  3423. ->set_value(kWeight75 + kWeight25);
  3424. auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3425. default_route->mutable_match()->set_prefix("");
  3426. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3427. SetRouteConfiguration(0, new_route_config);
  3428. WaitForAllBackends(0, 1);
  3429. WaitForAllBackends(1, 2, true, RpcOptions().set_rpc_service(SERVICE_ECHO1));
  3430. CheckRpcSendOk(kNumEchoRpcs);
  3431. CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
  3432. // Make sure RPCs all go to the correct backend.
  3433. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  3434. int weight_25_request_count =
  3435. backends_[0]->backend_service1()->request_count();
  3436. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  3437. int weight_75_request_count =
  3438. backends_[1]->backend_service1()->request_count();
  3439. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  3440. EXPECT_EQ(0, backends_[2]->backend_service1()->request_count());
  3441. EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
  3442. EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
  3443. const double kErrorTolerance = 0.2;
  3444. EXPECT_THAT(weight_75_request_count,
  3445. ::testing::AllOf(::testing::Ge(kNumEcho1Rpcs * kWeight75 / 100 *
  3446. (1 - kErrorTolerance)),
  3447. ::testing::Le(kNumEcho1Rpcs * kWeight75 / 100 *
  3448. (1 + kErrorTolerance))));
  3449. // TODO: (@donnadionne) Reduce tolerance: increased the tolerance to keep the
  3450. // test from flaking while debugging potential root cause.
  3451. const double kErrorToleranceSmallLoad = 0.3;
  3452. gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
  3453. weight_75_request_count, weight_25_request_count);
  3454. EXPECT_THAT(weight_25_request_count,
  3455. ::testing::AllOf(::testing::Ge(kNumEcho1Rpcs * kWeight25 / 100 *
  3456. (1 - kErrorToleranceSmallLoad)),
  3457. ::testing::Le(kNumEcho1Rpcs * kWeight25 / 100 *
  3458. (1 + kErrorToleranceSmallLoad))));
  3459. // Change Route Configurations: new set of clusters with different weights.
  3460. weighted_cluster1->mutable_weight()->set_value(kWeight50);
  3461. weighted_cluster2->set_name(kNewCluster2Name);
  3462. weighted_cluster2->mutable_weight()->set_value(kWeight50);
  3463. SetRouteConfiguration(0, new_route_config);
  3464. ResetBackendCounters();
  3465. WaitForAllBackends(2, 3, true, RpcOptions().set_rpc_service(SERVICE_ECHO1));
  3466. CheckRpcSendOk(kNumEchoRpcs);
  3467. CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
  3468. // Make sure RPCs all go to the correct backend.
  3469. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  3470. EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
  3471. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  3472. const int weight_50_request_count_1 =
  3473. backends_[1]->backend_service1()->request_count();
  3474. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  3475. const int weight_50_request_count_2 =
  3476. backends_[2]->backend_service1()->request_count();
  3477. EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
  3478. EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
  3479. EXPECT_THAT(weight_50_request_count_1,
  3480. ::testing::AllOf(::testing::Ge(kNumEcho1Rpcs * kWeight50 / 100 *
  3481. (1 - kErrorTolerance)),
  3482. ::testing::Le(kNumEcho1Rpcs * kWeight50 / 100 *
  3483. (1 + kErrorTolerance))));
  3484. EXPECT_THAT(weight_50_request_count_2,
  3485. ::testing::AllOf(::testing::Ge(kNumEcho1Rpcs * kWeight50 / 100 *
  3486. (1 - kErrorTolerance)),
  3487. ::testing::Le(kNumEcho1Rpcs * kWeight50 / 100 *
  3488. (1 + kErrorTolerance))));
  3489. // Change Route Configurations.
  3490. weighted_cluster1->mutable_weight()->set_value(kWeight75);
  3491. weighted_cluster2->set_name(kNewCluster3Name);
  3492. weighted_cluster2->mutable_weight()->set_value(kWeight25);
  3493. SetRouteConfiguration(0, new_route_config);
  3494. ResetBackendCounters();
  3495. WaitForAllBackends(3, 4, true, RpcOptions().set_rpc_service(SERVICE_ECHO1));
  3496. CheckRpcSendOk(kNumEchoRpcs);
  3497. CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
  3498. // Make sure RPCs all go to the correct backend.
  3499. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  3500. EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
  3501. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  3502. weight_75_request_count = backends_[1]->backend_service1()->request_count();
  3503. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  3504. EXPECT_EQ(0, backends_[2]->backend_service1()->request_count());
  3505. EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
  3506. weight_25_request_count = backends_[3]->backend_service1()->request_count();
  3507. EXPECT_THAT(weight_75_request_count,
  3508. ::testing::AllOf(::testing::Ge(kNumEcho1Rpcs * kWeight75 / 100 *
  3509. (1 - kErrorTolerance)),
  3510. ::testing::Le(kNumEcho1Rpcs * kWeight75 / 100 *
  3511. (1 + kErrorTolerance))));
  3512. // TODO: (@donnadionne) Reduce tolerance: increased the tolerance to keep the
  3513. // test from flaking while debugging potential root cause.
  3514. gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
  3515. weight_75_request_count, weight_25_request_count);
  3516. EXPECT_THAT(weight_25_request_count,
  3517. ::testing::AllOf(::testing::Ge(kNumEcho1Rpcs * kWeight25 / 100 *
  3518. (1 - kErrorToleranceSmallLoad)),
  3519. ::testing::Le(kNumEcho1Rpcs * kWeight25 / 100 *
  3520. (1 + kErrorToleranceSmallLoad))));
  3521. }
  3522. TEST_P(LdsRdsTest, XdsRoutingClusterUpdateClusters) {
  3523. const char* kNewClusterName = "new_cluster";
  3524. const char* kNewEdsServiceName = "new_eds_service_name";
  3525. const size_t kNumEchoRpcs = 5;
  3526. SetNextResolution({});
  3527. SetNextResolutionForLbChannelAllBalancers();
  3528. // Populate new EDS resources.
  3529. AdsServiceImpl::EdsResourceArgs args({
  3530. {"locality0", GetBackendPorts(0, 1)},
  3531. });
  3532. AdsServiceImpl::EdsResourceArgs args1({
  3533. {"locality0", GetBackendPorts(1, 2)},
  3534. });
  3535. balancers_[0]->ads_service()->SetEdsResource(
  3536. AdsServiceImpl::BuildEdsResource(args));
  3537. balancers_[0]->ads_service()->SetEdsResource(
  3538. AdsServiceImpl::BuildEdsResource(args1, kNewEdsServiceName));
  3539. // Populate new CDS resources.
  3540. Cluster new_cluster = balancers_[0]->ads_service()->default_cluster();
  3541. new_cluster.set_name(kNewClusterName);
  3542. new_cluster.mutable_eds_cluster_config()->set_service_name(
  3543. kNewEdsServiceName);
  3544. balancers_[0]->ads_service()->SetCdsResource(new_cluster);
  3545. // Send Route Configuration.
  3546. RouteConfiguration new_route_config =
  3547. balancers_[0]->ads_service()->default_route_config();
  3548. SetRouteConfiguration(0, new_route_config);
  3549. WaitForAllBackends(0, 1);
  3550. CheckRpcSendOk(kNumEchoRpcs);
  3551. // Make sure RPCs all go to the correct backend.
  3552. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  3553. // Change Route Configurations: new default cluster.
  3554. auto* default_route =
  3555. new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3556. default_route->mutable_route()->set_cluster(kNewClusterName);
  3557. SetRouteConfiguration(0, new_route_config);
  3558. WaitForAllBackends(1, 2);
  3559. CheckRpcSendOk(kNumEchoRpcs);
  3560. // Make sure RPCs all go to the correct backend.
  3561. EXPECT_EQ(kNumEchoRpcs, backends_[1]->backend_service()->request_count());
  3562. }
  3563. TEST_P(LdsRdsTest, XdsRoutingClusterUpdateClustersWithPickingDelays) {
  3564. const char* kNewClusterName = "new_cluster";
  3565. const char* kNewEdsServiceName = "new_eds_service_name";
  3566. SetNextResolution({});
  3567. SetNextResolutionForLbChannelAllBalancers();
  3568. // Populate new EDS resources.
  3569. AdsServiceImpl::EdsResourceArgs args({
  3570. {"locality0", GetBackendPorts(0, 1)},
  3571. });
  3572. AdsServiceImpl::EdsResourceArgs args1({
  3573. {"locality0", GetBackendPorts(1, 2)},
  3574. });
  3575. balancers_[0]->ads_service()->SetEdsResource(
  3576. AdsServiceImpl::BuildEdsResource(args));
  3577. balancers_[0]->ads_service()->SetEdsResource(
  3578. AdsServiceImpl::BuildEdsResource(args1, kNewEdsServiceName));
  3579. // Populate new CDS resources.
  3580. Cluster new_cluster = balancers_[0]->ads_service()->default_cluster();
  3581. new_cluster.set_name(kNewClusterName);
  3582. new_cluster.mutable_eds_cluster_config()->set_service_name(
  3583. kNewEdsServiceName);
  3584. balancers_[0]->ads_service()->SetCdsResource(new_cluster);
  3585. // Bring down the current backend: 0, this will delay route picking time,
  3586. // resulting in un-committed RPCs.
  3587. ShutdownBackend(0);
  3588. // Send a RouteConfiguration with a default route that points to
  3589. // backend 0.
  3590. RouteConfiguration new_route_config =
  3591. balancers_[0]->ads_service()->default_route_config();
  3592. SetRouteConfiguration(0, new_route_config);
  3593. // Send exactly one RPC with no deadline and with wait_for_ready=true.
  3594. // This RPC will not complete until after backend 0 is started.
  3595. std::thread sending_rpc([this]() {
  3596. CheckRpcSendOk(1, RpcOptions().set_wait_for_ready(true).set_timeout_ms(0));
  3597. });
  3598. // Send a non-wait_for_ready RPC which should fail, this will tell us
  3599. // that the client has received the update and attempted to connect.
  3600. const Status status = SendRpc(RpcOptions().set_timeout_ms(0));
  3601. EXPECT_FALSE(status.ok());
  3602. // Send a update RouteConfiguration to use backend 1.
  3603. auto* default_route =
  3604. new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3605. default_route->mutable_route()->set_cluster(kNewClusterName);
  3606. SetRouteConfiguration(0, new_route_config);
  3607. // Wait for RPCs to go to the new backend: 1, this ensures that the client has
  3608. // processed the update.
  3609. WaitForAllBackends(1, 2, false, RpcOptions(), true);
  3610. // Bring up the previous backend: 0, this will allow the delayed RPC to
  3611. // finally call on_call_committed upon completion.
  3612. StartBackend(0);
  3613. sending_rpc.join();
  3614. // Make sure RPCs go to the correct backend:
  3615. EXPECT_EQ(1, backends_[0]->backend_service()->request_count());
  3616. EXPECT_EQ(1, backends_[1]->backend_service()->request_count());
  3617. }
  3618. TEST_P(LdsRdsTest, XdsRoutingHeadersMatching) {
  3619. const char* kNewClusterName = "new_cluster";
  3620. const char* kNewEdsServiceName = "new_eds_service_name";
  3621. const size_t kNumEcho1Rpcs = 100;
  3622. const size_t kNumEchoRpcs = 5;
  3623. SetNextResolution({});
  3624. SetNextResolutionForLbChannelAllBalancers();
  3625. // Populate new EDS resources.
  3626. AdsServiceImpl::EdsResourceArgs args({
  3627. {"locality0", GetBackendPorts(0, 1)},
  3628. });
  3629. AdsServiceImpl::EdsResourceArgs args1({
  3630. {"locality0", GetBackendPorts(1, 2)},
  3631. });
  3632. balancers_[0]->ads_service()->SetEdsResource(
  3633. AdsServiceImpl::BuildEdsResource(args));
  3634. balancers_[0]->ads_service()->SetEdsResource(
  3635. AdsServiceImpl::BuildEdsResource(args1, kNewEdsServiceName));
  3636. // Populate new CDS resources.
  3637. Cluster new_cluster = balancers_[0]->ads_service()->default_cluster();
  3638. new_cluster.set_name(kNewClusterName);
  3639. new_cluster.mutable_eds_cluster_config()->set_service_name(
  3640. kNewEdsServiceName);
  3641. balancers_[0]->ads_service()->SetCdsResource(new_cluster);
  3642. // Populating Route Configurations for LDS.
  3643. RouteConfiguration route_config =
  3644. balancers_[0]->ads_service()->default_route_config();
  3645. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3646. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3647. auto* header_matcher1 = route1->mutable_match()->add_headers();
  3648. header_matcher1->set_name("header1");
  3649. header_matcher1->set_exact_match("POST,PUT,GET");
  3650. auto* header_matcher2 = route1->mutable_match()->add_headers();
  3651. header_matcher2->set_name("header2");
  3652. header_matcher2->mutable_safe_regex_match()->set_regex("[a-z]*");
  3653. auto* header_matcher3 = route1->mutable_match()->add_headers();
  3654. header_matcher3->set_name("header3");
  3655. header_matcher3->mutable_range_match()->set_start(1);
  3656. header_matcher3->mutable_range_match()->set_end(1000);
  3657. auto* header_matcher4 = route1->mutable_match()->add_headers();
  3658. header_matcher4->set_name("header4");
  3659. header_matcher4->set_present_match(false);
  3660. auto* header_matcher5 = route1->mutable_match()->add_headers();
  3661. header_matcher5->set_name("header5");
  3662. header_matcher5->set_prefix_match("/grpc");
  3663. auto* header_matcher6 = route1->mutable_match()->add_headers();
  3664. header_matcher6->set_name("header6");
  3665. header_matcher6->set_suffix_match(".cc");
  3666. header_matcher6->set_invert_match(true);
  3667. route1->mutable_route()->set_cluster(kNewClusterName);
  3668. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  3669. default_route->mutable_match()->set_prefix("");
  3670. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3671. SetRouteConfiguration(0, route_config);
  3672. std::vector<std::pair<std::string, std::string>> metadata = {
  3673. {"header1", "POST"}, {"header2", "blah"},
  3674. {"header3", "1"}, {"header5", "/grpc.testing.EchoTest1Service/"},
  3675. {"header1", "PUT"}, {"header6", "grpc.java"},
  3676. {"header1", "GET"},
  3677. };
  3678. const auto header_match_rpc_options = RpcOptions()
  3679. .set_rpc_service(SERVICE_ECHO1)
  3680. .set_rpc_method(METHOD_ECHO1)
  3681. .set_metadata(std::move(metadata));
  3682. // Make sure all backends are up.
  3683. WaitForAllBackends(0, 1);
  3684. WaitForAllBackends(1, 2, true, header_match_rpc_options);
  3685. // Send RPCs.
  3686. CheckRpcSendOk(kNumEchoRpcs);
  3687. CheckRpcSendOk(kNumEcho1Rpcs, header_match_rpc_options);
  3688. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  3689. EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
  3690. EXPECT_EQ(0, backends_[0]->backend_service2()->request_count());
  3691. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  3692. EXPECT_EQ(kNumEcho1Rpcs, backends_[1]->backend_service1()->request_count());
  3693. EXPECT_EQ(0, backends_[1]->backend_service2()->request_count());
  3694. const auto& response_state = RouteConfigurationResponseState(0);
  3695. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
  3696. }
  3697. TEST_P(LdsRdsTest, XdsRoutingHeadersMatchingSpecialHeaderContentType) {
  3698. const char* kNewClusterName = "new_cluster";
  3699. const char* kNewEdsServiceName = "new_eds_service_name";
  3700. const size_t kNumEchoRpcs = 100;
  3701. SetNextResolution({});
  3702. SetNextResolutionForLbChannelAllBalancers();
  3703. // Populate new EDS resources.
  3704. AdsServiceImpl::EdsResourceArgs args({
  3705. {"locality0", GetBackendPorts(0, 1)},
  3706. });
  3707. AdsServiceImpl::EdsResourceArgs args1({
  3708. {"locality0", GetBackendPorts(1, 2)},
  3709. });
  3710. balancers_[0]->ads_service()->SetEdsResource(
  3711. AdsServiceImpl::BuildEdsResource(args));
  3712. balancers_[0]->ads_service()->SetEdsResource(
  3713. AdsServiceImpl::BuildEdsResource(args1, kNewEdsServiceName));
  3714. // Populate new CDS resources.
  3715. Cluster new_cluster = balancers_[0]->ads_service()->default_cluster();
  3716. new_cluster.set_name(kNewClusterName);
  3717. new_cluster.mutable_eds_cluster_config()->set_service_name(
  3718. kNewEdsServiceName);
  3719. balancers_[0]->ads_service()->SetCdsResource(new_cluster);
  3720. // Populating Route Configurations for LDS.
  3721. RouteConfiguration route_config =
  3722. balancers_[0]->ads_service()->default_route_config();
  3723. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3724. route1->mutable_match()->set_prefix("");
  3725. auto* header_matcher1 = route1->mutable_match()->add_headers();
  3726. header_matcher1->set_name("content-type");
  3727. header_matcher1->set_exact_match("notapplication/grpc");
  3728. route1->mutable_route()->set_cluster(kNewClusterName);
  3729. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  3730. default_route->mutable_match()->set_prefix("");
  3731. auto* header_matcher2 = default_route->mutable_match()->add_headers();
  3732. header_matcher2->set_name("content-type");
  3733. header_matcher2->set_exact_match("application/grpc");
  3734. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3735. SetRouteConfiguration(0, route_config);
  3736. // Make sure the backend is up.
  3737. WaitForAllBackends(0, 1);
  3738. // Send RPCs.
  3739. CheckRpcSendOk(kNumEchoRpcs);
  3740. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  3741. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  3742. const auto& response_state = RouteConfigurationResponseState(0);
  3743. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
  3744. }
  3745. TEST_P(LdsRdsTest, XdsRoutingHeadersMatchingSpecialCasesToIgnore) {
  3746. const char* kNewCluster1Name = "new_cluster_1";
  3747. const char* kNewEdsService1Name = "new_eds_service_name_1";
  3748. const char* kNewCluster2Name = "new_cluster_2";
  3749. const char* kNewEdsService2Name = "new_eds_service_name_2";
  3750. const size_t kNumEchoRpcs = 100;
  3751. SetNextResolution({});
  3752. SetNextResolutionForLbChannelAllBalancers();
  3753. // Populate new EDS resources.
  3754. AdsServiceImpl::EdsResourceArgs args({
  3755. {"locality0", GetBackendPorts(0, 1)},
  3756. });
  3757. AdsServiceImpl::EdsResourceArgs args1({
  3758. {"locality0", GetBackendPorts(1, 2)},
  3759. });
  3760. AdsServiceImpl::EdsResourceArgs args2({
  3761. {"locality0", GetBackendPorts(2, 3)},
  3762. });
  3763. balancers_[0]->ads_service()->SetEdsResource(
  3764. AdsServiceImpl::BuildEdsResource(args));
  3765. balancers_[0]->ads_service()->SetEdsResource(
  3766. AdsServiceImpl::BuildEdsResource(args1, kNewEdsService1Name));
  3767. balancers_[0]->ads_service()->SetEdsResource(
  3768. AdsServiceImpl::BuildEdsResource(args2, kNewEdsService2Name));
  3769. // Populate new CDS resources.
  3770. Cluster new_cluster1 = balancers_[0]->ads_service()->default_cluster();
  3771. new_cluster1.set_name(kNewCluster1Name);
  3772. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  3773. kNewEdsService1Name);
  3774. balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
  3775. Cluster new_cluster2 = balancers_[0]->ads_service()->default_cluster();
  3776. new_cluster2.set_name(kNewCluster2Name);
  3777. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  3778. kNewEdsService2Name);
  3779. balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
  3780. // Populating Route Configurations for LDS.
  3781. RouteConfiguration route_config =
  3782. balancers_[0]->ads_service()->default_route_config();
  3783. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3784. route1->mutable_match()->set_prefix("");
  3785. auto* header_matcher1 = route1->mutable_match()->add_headers();
  3786. header_matcher1->set_name("grpc-foo-bin");
  3787. header_matcher1->set_present_match(true);
  3788. route1->mutable_route()->set_cluster(kNewCluster1Name);
  3789. auto route2 = route_config.mutable_virtual_hosts(0)->add_routes();
  3790. route2->mutable_match()->set_prefix("");
  3791. auto* header_matcher2 = route2->mutable_match()->add_headers();
  3792. header_matcher2->set_name("grpc-previous-rpc-attempts");
  3793. header_matcher2->set_present_match(true);
  3794. route2->mutable_route()->set_cluster(kNewCluster2Name);
  3795. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  3796. default_route->mutable_match()->set_prefix("");
  3797. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3798. SetRouteConfiguration(0, route_config);
  3799. // Send headers which will mismatch each route
  3800. std::vector<std::pair<std::string, std::string>> metadata = {
  3801. {"grpc-foo-bin", "grpc-foo-bin"},
  3802. {"grpc-previous-rpc-attempts", "grpc-previous-rpc-attempts"},
  3803. };
  3804. WaitForAllBackends(0, 1);
  3805. CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_metadata(metadata));
  3806. // Verify that only the default backend got RPCs since all previous routes
  3807. // were mismatched.
  3808. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  3809. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  3810. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  3811. const auto& response_state = RouteConfigurationResponseState(0);
  3812. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
  3813. }
  3814. TEST_P(LdsRdsTest, XdsRoutingRuntimeFractionMatching) {
  3815. const char* kNewClusterName = "new_cluster";
  3816. const char* kNewEdsServiceName = "new_eds_service_name";
  3817. const size_t kNumRpcs = 1000;
  3818. SetNextResolution({});
  3819. SetNextResolutionForLbChannelAllBalancers();
  3820. // Populate new EDS resources.
  3821. AdsServiceImpl::EdsResourceArgs args({
  3822. {"locality0", GetBackendPorts(0, 1)},
  3823. });
  3824. AdsServiceImpl::EdsResourceArgs args1({
  3825. {"locality0", GetBackendPorts(1, 2)},
  3826. });
  3827. balancers_[0]->ads_service()->SetEdsResource(
  3828. AdsServiceImpl::BuildEdsResource(args));
  3829. balancers_[0]->ads_service()->SetEdsResource(
  3830. AdsServiceImpl::BuildEdsResource(args1, kNewEdsServiceName));
  3831. // Populate new CDS resources.
  3832. Cluster new_cluster = balancers_[0]->ads_service()->default_cluster();
  3833. new_cluster.set_name(kNewClusterName);
  3834. new_cluster.mutable_eds_cluster_config()->set_service_name(
  3835. kNewEdsServiceName);
  3836. balancers_[0]->ads_service()->SetCdsResource(new_cluster);
  3837. // Populating Route Configurations for LDS.
  3838. RouteConfiguration route_config =
  3839. balancers_[0]->ads_service()->default_route_config();
  3840. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3841. route1->mutable_match()
  3842. ->mutable_runtime_fraction()
  3843. ->mutable_default_value()
  3844. ->set_numerator(25);
  3845. route1->mutable_route()->set_cluster(kNewClusterName);
  3846. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  3847. default_route->mutable_match()->set_prefix("");
  3848. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3849. SetRouteConfiguration(0, route_config);
  3850. WaitForAllBackends(0, 2);
  3851. CheckRpcSendOk(kNumRpcs);
  3852. const int default_backend_count =
  3853. backends_[0]->backend_service()->request_count();
  3854. const int matched_backend_count =
  3855. backends_[1]->backend_service()->request_count();
  3856. const double kErrorTolerance = 0.2;
  3857. EXPECT_THAT(default_backend_count,
  3858. ::testing::AllOf(
  3859. ::testing::Ge(kNumRpcs * 75 / 100 * (1 - kErrorTolerance)),
  3860. ::testing::Le(kNumRpcs * 75 / 100 * (1 + kErrorTolerance))));
  3861. EXPECT_THAT(matched_backend_count,
  3862. ::testing::AllOf(
  3863. ::testing::Ge(kNumRpcs * 25 / 100 * (1 - kErrorTolerance)),
  3864. ::testing::Le(kNumRpcs * 25 / 100 * (1 + kErrorTolerance))));
  3865. const auto& response_state = RouteConfigurationResponseState(0);
  3866. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
  3867. }
  3868. TEST_P(LdsRdsTest, XdsRoutingHeadersMatchingUnmatchCases) {
  3869. const char* kNewCluster1Name = "new_cluster_1";
  3870. const char* kNewEdsService1Name = "new_eds_service_name_1";
  3871. const char* kNewCluster2Name = "new_cluster_2";
  3872. const char* kNewEdsService2Name = "new_eds_service_name_2";
  3873. const char* kNewCluster3Name = "new_cluster_3";
  3874. const char* kNewEdsService3Name = "new_eds_service_name_3";
  3875. const size_t kNumEcho1Rpcs = 100;
  3876. const size_t kNumEchoRpcs = 5;
  3877. SetNextResolution({});
  3878. SetNextResolutionForLbChannelAllBalancers();
  3879. // Populate new EDS resources.
  3880. AdsServiceImpl::EdsResourceArgs args({
  3881. {"locality0", GetBackendPorts(0, 1)},
  3882. });
  3883. AdsServiceImpl::EdsResourceArgs args1({
  3884. {"locality0", GetBackendPorts(1, 2)},
  3885. });
  3886. AdsServiceImpl::EdsResourceArgs args2({
  3887. {"locality0", GetBackendPorts(2, 3)},
  3888. });
  3889. AdsServiceImpl::EdsResourceArgs args3({
  3890. {"locality0", GetBackendPorts(3, 4)},
  3891. });
  3892. balancers_[0]->ads_service()->SetEdsResource(
  3893. AdsServiceImpl::BuildEdsResource(args));
  3894. balancers_[0]->ads_service()->SetEdsResource(
  3895. AdsServiceImpl::BuildEdsResource(args1, kNewEdsService1Name));
  3896. balancers_[0]->ads_service()->SetEdsResource(
  3897. AdsServiceImpl::BuildEdsResource(args2, kNewEdsService2Name));
  3898. balancers_[0]->ads_service()->SetEdsResource(
  3899. AdsServiceImpl::BuildEdsResource(args3, kNewEdsService3Name));
  3900. // Populate new CDS resources.
  3901. Cluster new_cluster1 = balancers_[0]->ads_service()->default_cluster();
  3902. new_cluster1.set_name(kNewCluster1Name);
  3903. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  3904. kNewEdsService1Name);
  3905. balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
  3906. Cluster new_cluster2 = balancers_[0]->ads_service()->default_cluster();
  3907. new_cluster2.set_name(kNewCluster2Name);
  3908. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  3909. kNewEdsService2Name);
  3910. balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
  3911. Cluster new_cluster3 = balancers_[0]->ads_service()->default_cluster();
  3912. new_cluster3.set_name(kNewCluster3Name);
  3913. new_cluster3.mutable_eds_cluster_config()->set_service_name(
  3914. kNewEdsService3Name);
  3915. balancers_[0]->ads_service()->SetCdsResource(new_cluster3);
  3916. // Populating Route Configurations for LDS.
  3917. RouteConfiguration route_config =
  3918. balancers_[0]->ads_service()->default_route_config();
  3919. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3920. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3921. auto* header_matcher1 = route1->mutable_match()->add_headers();
  3922. header_matcher1->set_name("header1");
  3923. header_matcher1->set_exact_match("POST");
  3924. route1->mutable_route()->set_cluster(kNewCluster1Name);
  3925. auto route2 = route_config.mutable_virtual_hosts(0)->add_routes();
  3926. route2->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3927. auto* header_matcher2 = route2->mutable_match()->add_headers();
  3928. header_matcher2->set_name("header2");
  3929. header_matcher2->mutable_range_match()->set_start(1);
  3930. header_matcher2->mutable_range_match()->set_end(1000);
  3931. route2->mutable_route()->set_cluster(kNewCluster2Name);
  3932. auto route3 = route_config.mutable_virtual_hosts(0)->add_routes();
  3933. route3->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3934. auto* header_matcher3 = route3->mutable_match()->add_headers();
  3935. header_matcher3->set_name("header3");
  3936. header_matcher3->mutable_safe_regex_match()->set_regex("[a-z]*");
  3937. route3->mutable_route()->set_cluster(kNewCluster3Name);
  3938. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  3939. default_route->mutable_match()->set_prefix("");
  3940. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3941. SetRouteConfiguration(0, route_config);
  3942. // Send headers which will mismatch each route
  3943. std::vector<std::pair<std::string, std::string>> metadata = {
  3944. {"header1", "POST"},
  3945. {"header2", "1000"},
  3946. {"header3", "123"},
  3947. {"header1", "GET"},
  3948. };
  3949. WaitForAllBackends(0, 1);
  3950. CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_metadata(metadata));
  3951. CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions()
  3952. .set_rpc_service(SERVICE_ECHO1)
  3953. .set_rpc_method(METHOD_ECHO1)
  3954. .set_metadata(metadata));
  3955. // Verify that only the default backend got RPCs since all previous routes
  3956. // were mismatched.
  3957. for (size_t i = 1; i < 4; ++i) {
  3958. EXPECT_EQ(0, backends_[i]->backend_service()->request_count());
  3959. EXPECT_EQ(0, backends_[i]->backend_service1()->request_count());
  3960. EXPECT_EQ(0, backends_[i]->backend_service2()->request_count());
  3961. }
  3962. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  3963. EXPECT_EQ(kNumEcho1Rpcs, backends_[0]->backend_service1()->request_count());
  3964. EXPECT_EQ(0, backends_[0]->backend_service2()->request_count());
  3965. const auto& response_state = RouteConfigurationResponseState(0);
  3966. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
  3967. }
  3968. TEST_P(LdsRdsTest, XdsRoutingChangeRoutesWithoutChangingClusters) {
  3969. const char* kNewClusterName = "new_cluster";
  3970. const char* kNewEdsServiceName = "new_eds_service_name";
  3971. SetNextResolution({});
  3972. SetNextResolutionForLbChannelAllBalancers();
  3973. // Populate new EDS resources.
  3974. AdsServiceImpl::EdsResourceArgs args({
  3975. {"locality0", GetBackendPorts(0, 1)},
  3976. });
  3977. AdsServiceImpl::EdsResourceArgs args1({
  3978. {"locality0", GetBackendPorts(1, 2)},
  3979. });
  3980. balancers_[0]->ads_service()->SetEdsResource(
  3981. AdsServiceImpl::BuildEdsResource(args));
  3982. balancers_[0]->ads_service()->SetEdsResource(
  3983. AdsServiceImpl::BuildEdsResource(args1, kNewEdsServiceName));
  3984. // Populate new CDS resources.
  3985. Cluster new_cluster = balancers_[0]->ads_service()->default_cluster();
  3986. new_cluster.set_name(kNewClusterName);
  3987. new_cluster.mutable_eds_cluster_config()->set_service_name(
  3988. kNewEdsServiceName);
  3989. balancers_[0]->ads_service()->SetCdsResource(new_cluster);
  3990. // Populating Route Configurations for LDS.
  3991. RouteConfiguration route_config =
  3992. balancers_[0]->ads_service()->default_route_config();
  3993. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3994. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3995. route1->mutable_route()->set_cluster(kNewClusterName);
  3996. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  3997. default_route->mutable_match()->set_prefix("");
  3998. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3999. SetRouteConfiguration(0, route_config);
  4000. // Make sure all backends are up and that requests for each RPC
  4001. // service go to the right backends.
  4002. WaitForAllBackends(0, 1, false);
  4003. WaitForAllBackends(1, 2, false, RpcOptions().set_rpc_service(SERVICE_ECHO1));
  4004. WaitForAllBackends(0, 1, false, RpcOptions().set_rpc_service(SERVICE_ECHO2));
  4005. // Requests for services Echo and Echo2 should have gone to backend 0.
  4006. EXPECT_EQ(1, backends_[0]->backend_service()->request_count());
  4007. EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
  4008. EXPECT_EQ(1, backends_[0]->backend_service2()->request_count());
  4009. // Requests for service Echo1 should have gone to backend 1.
  4010. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  4011. EXPECT_EQ(1, backends_[1]->backend_service1()->request_count());
  4012. EXPECT_EQ(0, backends_[1]->backend_service2()->request_count());
  4013. // Now send an update that changes the first route to match a
  4014. // different RPC service, and wait for the client to make the change.
  4015. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest2Service/");
  4016. SetRouteConfiguration(0, route_config);
  4017. WaitForAllBackends(1, 2, true, RpcOptions().set_rpc_service(SERVICE_ECHO2));
  4018. // Now repeat the earlier test, making sure all traffic goes to the
  4019. // right place.
  4020. WaitForAllBackends(0, 1, false);
  4021. WaitForAllBackends(0, 1, false, RpcOptions().set_rpc_service(SERVICE_ECHO1));
  4022. WaitForAllBackends(1, 2, false, RpcOptions().set_rpc_service(SERVICE_ECHO2));
  4023. // Requests for services Echo and Echo1 should have gone to backend 0.
  4024. EXPECT_EQ(1, backends_[0]->backend_service()->request_count());
  4025. EXPECT_EQ(1, backends_[0]->backend_service1()->request_count());
  4026. EXPECT_EQ(0, backends_[0]->backend_service2()->request_count());
  4027. // Requests for service Echo2 should have gone to backend 1.
  4028. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  4029. EXPECT_EQ(0, backends_[1]->backend_service1()->request_count());
  4030. EXPECT_EQ(1, backends_[1]->backend_service2()->request_count());
  4031. }
  4032. using CdsTest = BasicTest;
  4033. // Tests that CDS client should send an ACK upon correct CDS response.
  4034. TEST_P(CdsTest, Vanilla) {
  4035. SetNextResolution({});
  4036. SetNextResolutionForLbChannelAllBalancers();
  4037. (void)SendRpc();
  4038. EXPECT_EQ(balancers_[0]->ads_service()->cds_response_state().state,
  4039. AdsServiceImpl::ResponseState::ACKED);
  4040. }
  4041. // Tests that CDS client should send a NACK if the cluster type in CDS response
  4042. // is other than EDS.
  4043. TEST_P(CdsTest, WrongClusterType) {
  4044. auto cluster = balancers_[0]->ads_service()->default_cluster();
  4045. cluster.set_type(Cluster::STATIC);
  4046. balancers_[0]->ads_service()->SetCdsResource(cluster);
  4047. SetNextResolution({});
  4048. SetNextResolutionForLbChannelAllBalancers();
  4049. CheckRpcSendFailure();
  4050. const auto& response_state =
  4051. balancers_[0]->ads_service()->cds_response_state();
  4052. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  4053. EXPECT_EQ(response_state.error_message, "DiscoveryType is not EDS.");
  4054. }
  4055. // Tests that CDS client should send a NACK if the eds_config in CDS response is
  4056. // other than ADS.
  4057. TEST_P(CdsTest, WrongEdsConfig) {
  4058. auto cluster = balancers_[0]->ads_service()->default_cluster();
  4059. cluster.mutable_eds_cluster_config()->mutable_eds_config()->mutable_self();
  4060. balancers_[0]->ads_service()->SetCdsResource(cluster);
  4061. SetNextResolution({});
  4062. SetNextResolutionForLbChannelAllBalancers();
  4063. CheckRpcSendFailure();
  4064. const auto& response_state =
  4065. balancers_[0]->ads_service()->cds_response_state();
  4066. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  4067. EXPECT_EQ(response_state.error_message, "EDS ConfigSource is not ADS.");
  4068. }
  4069. // Tests that CDS client should send a NACK if the lb_policy in CDS response is
  4070. // other than ROUND_ROBIN.
  4071. TEST_P(CdsTest, WrongLbPolicy) {
  4072. auto cluster = balancers_[0]->ads_service()->default_cluster();
  4073. cluster.set_lb_policy(Cluster::LEAST_REQUEST);
  4074. balancers_[0]->ads_service()->SetCdsResource(cluster);
  4075. SetNextResolution({});
  4076. SetNextResolutionForLbChannelAllBalancers();
  4077. CheckRpcSendFailure();
  4078. const auto& response_state =
  4079. balancers_[0]->ads_service()->cds_response_state();
  4080. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  4081. EXPECT_EQ(response_state.error_message, "LB policy is not ROUND_ROBIN.");
  4082. }
  4083. // Tests that CDS client should send a NACK if the lrs_server in CDS response is
  4084. // other than SELF.
  4085. TEST_P(CdsTest, WrongLrsServer) {
  4086. auto cluster = balancers_[0]->ads_service()->default_cluster();
  4087. cluster.mutable_lrs_server()->mutable_ads();
  4088. balancers_[0]->ads_service()->SetCdsResource(cluster);
  4089. SetNextResolution({});
  4090. SetNextResolutionForLbChannelAllBalancers();
  4091. CheckRpcSendFailure();
  4092. const auto& response_state =
  4093. balancers_[0]->ads_service()->cds_response_state();
  4094. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  4095. EXPECT_EQ(response_state.error_message, "LRS ConfigSource is not self.");
  4096. }
  4097. using EdsTest = BasicTest;
  4098. // Tests that EDS client should send a NACK if the EDS update contains
  4099. // sparse priorities.
  4100. TEST_P(EdsTest, NacksSparsePriorityList) {
  4101. SetNextResolution({});
  4102. SetNextResolutionForLbChannelAllBalancers();
  4103. AdsServiceImpl::EdsResourceArgs args({
  4104. {"locality0", GetBackendPorts(), kDefaultLocalityWeight, 1},
  4105. });
  4106. balancers_[0]->ads_service()->SetEdsResource(
  4107. AdsServiceImpl::BuildEdsResource(args));
  4108. CheckRpcSendFailure();
  4109. const auto& response_state =
  4110. balancers_[0]->ads_service()->eds_response_state();
  4111. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  4112. EXPECT_EQ(response_state.error_message,
  4113. "EDS update includes sparse priority list");
  4114. }
  4115. // In most of our tests, we use different names for different resource
  4116. // types, to make sure that there are no cut-and-paste errors in the code
  4117. // that cause us to look at data for the wrong resource type. So we add
  4118. // this test to make sure that the EDS resource name defaults to the
  4119. // cluster name if not specified in the CDS resource.
  4120. TEST_P(EdsTest, EdsServiceNameDefaultsToClusterName) {
  4121. AdsServiceImpl::EdsResourceArgs args({
  4122. {"locality0", GetBackendPorts()},
  4123. });
  4124. balancers_[0]->ads_service()->SetEdsResource(
  4125. AdsServiceImpl::BuildEdsResource(args, kDefaultClusterName));
  4126. Cluster cluster = balancers_[0]->ads_service()->default_cluster();
  4127. cluster.mutable_eds_cluster_config()->clear_service_name();
  4128. balancers_[0]->ads_service()->SetCdsResource(cluster);
  4129. SetNextResolution({});
  4130. SetNextResolutionForLbChannelAllBalancers();
  4131. CheckRpcSendOk();
  4132. }
  4133. class TimeoutTest : public BasicTest {
  4134. protected:
  4135. void SetUp() override {
  4136. xds_resource_does_not_exist_timeout_ms_ = 500;
  4137. BasicTest::SetUp();
  4138. }
  4139. };
  4140. // Tests that LDS client times out when no response received.
  4141. TEST_P(TimeoutTest, Lds) {
  4142. balancers_[0]->ads_service()->SetResourceIgnore(kLdsTypeUrl);
  4143. SetNextResolution({});
  4144. SetNextResolutionForLbChannelAllBalancers();
  4145. CheckRpcSendFailure();
  4146. }
  4147. TEST_P(TimeoutTest, Rds) {
  4148. balancers_[0]->ads_service()->SetResourceIgnore(kRdsTypeUrl);
  4149. SetNextResolution({});
  4150. SetNextResolutionForLbChannelAllBalancers();
  4151. CheckRpcSendFailure();
  4152. }
  4153. // Tests that CDS client times out when no response received.
  4154. TEST_P(TimeoutTest, Cds) {
  4155. balancers_[0]->ads_service()->SetResourceIgnore(kCdsTypeUrl);
  4156. SetNextResolution({});
  4157. SetNextResolutionForLbChannelAllBalancers();
  4158. CheckRpcSendFailure();
  4159. }
  4160. TEST_P(TimeoutTest, Eds) {
  4161. balancers_[0]->ads_service()->SetResourceIgnore(kEdsTypeUrl);
  4162. SetNextResolution({});
  4163. SetNextResolutionForLbChannelAllBalancers();
  4164. CheckRpcSendFailure();
  4165. }
  4166. using LocalityMapTest = BasicTest;
  4167. // Tests that the localities in a locality map are picked according to their
  4168. // weights.
  4169. TEST_P(LocalityMapTest, WeightedRoundRobin) {
  4170. SetNextResolution({});
  4171. SetNextResolutionForLbChannelAllBalancers();
  4172. const size_t kNumRpcs = 5000;
  4173. const int kLocalityWeight0 = 2;
  4174. const int kLocalityWeight1 = 8;
  4175. const int kTotalLocalityWeight = kLocalityWeight0 + kLocalityWeight1;
  4176. const double kLocalityWeightRate0 =
  4177. static_cast<double>(kLocalityWeight0) / kTotalLocalityWeight;
  4178. const double kLocalityWeightRate1 =
  4179. static_cast<double>(kLocalityWeight1) / kTotalLocalityWeight;
  4180. // ADS response contains 2 localities, each of which contains 1 backend.
  4181. AdsServiceImpl::EdsResourceArgs args({
  4182. {"locality0", GetBackendPorts(0, 1), kLocalityWeight0},
  4183. {"locality1", GetBackendPorts(1, 2), kLocalityWeight1},
  4184. });
  4185. balancers_[0]->ads_service()->SetEdsResource(
  4186. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  4187. // Wait for both backends to be ready.
  4188. WaitForAllBackends(0, 2);
  4189. // Send kNumRpcs RPCs.
  4190. CheckRpcSendOk(kNumRpcs);
  4191. // The locality picking rates should be roughly equal to the expectation.
  4192. const double locality_picked_rate_0 =
  4193. static_cast<double>(backends_[0]->backend_service()->request_count()) /
  4194. kNumRpcs;
  4195. const double locality_picked_rate_1 =
  4196. static_cast<double>(backends_[1]->backend_service()->request_count()) /
  4197. kNumRpcs;
  4198. const double kErrorTolerance = 0.2;
  4199. EXPECT_THAT(locality_picked_rate_0,
  4200. ::testing::AllOf(
  4201. ::testing::Ge(kLocalityWeightRate0 * (1 - kErrorTolerance)),
  4202. ::testing::Le(kLocalityWeightRate0 * (1 + kErrorTolerance))));
  4203. EXPECT_THAT(locality_picked_rate_1,
  4204. ::testing::AllOf(
  4205. ::testing::Ge(kLocalityWeightRate1 * (1 - kErrorTolerance)),
  4206. ::testing::Le(kLocalityWeightRate1 * (1 + kErrorTolerance))));
  4207. }
  4208. // Tests that we correctly handle a locality containing no endpoints.
  4209. TEST_P(LocalityMapTest, LocalityContainingNoEndpoints) {
  4210. SetNextResolution({});
  4211. SetNextResolutionForLbChannelAllBalancers();
  4212. const size_t kNumRpcs = 5000;
  4213. // EDS response contains 2 localities, one with no endpoints.
  4214. AdsServiceImpl::EdsResourceArgs args({
  4215. {"locality0", GetBackendPorts()},
  4216. {"locality1", {}},
  4217. });
  4218. balancers_[0]->ads_service()->SetEdsResource(
  4219. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  4220. // Wait for both backends to be ready.
  4221. WaitForAllBackends();
  4222. // Send kNumRpcs RPCs.
  4223. CheckRpcSendOk(kNumRpcs);
  4224. // All traffic should go to the reachable locality.
  4225. EXPECT_EQ(backends_[0]->backend_service()->request_count(),
  4226. kNumRpcs / backends_.size());
  4227. EXPECT_EQ(backends_[1]->backend_service()->request_count(),
  4228. kNumRpcs / backends_.size());
  4229. EXPECT_EQ(backends_[2]->backend_service()->request_count(),
  4230. kNumRpcs / backends_.size());
  4231. EXPECT_EQ(backends_[3]->backend_service()->request_count(),
  4232. kNumRpcs / backends_.size());
  4233. }
  4234. // EDS update with no localities.
  4235. TEST_P(LocalityMapTest, NoLocalities) {
  4236. SetNextResolution({});
  4237. SetNextResolutionForLbChannelAllBalancers();
  4238. balancers_[0]->ads_service()->SetEdsResource(
  4239. AdsServiceImpl::BuildEdsResource({}, DefaultEdsServiceName()));
  4240. Status status = SendRpc();
  4241. EXPECT_FALSE(status.ok());
  4242. EXPECT_EQ(status.error_code(), StatusCode::UNAVAILABLE);
  4243. }
  4244. // Tests that the locality map can work properly even when it contains a large
  4245. // number of localities.
  4246. TEST_P(LocalityMapTest, StressTest) {
  4247. SetNextResolution({});
  4248. SetNextResolutionForLbChannelAllBalancers();
  4249. const size_t kNumLocalities = 100;
  4250. // The first ADS response contains kNumLocalities localities, each of which
  4251. // contains backend 0.
  4252. AdsServiceImpl::EdsResourceArgs args;
  4253. for (size_t i = 0; i < kNumLocalities; ++i) {
  4254. std::string name = absl::StrCat("locality", i);
  4255. AdsServiceImpl::EdsResourceArgs::Locality locality(name,
  4256. {backends_[0]->port()});
  4257. args.locality_list.emplace_back(std::move(locality));
  4258. }
  4259. balancers_[0]->ads_service()->SetEdsResource(
  4260. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  4261. // The second ADS response contains 1 locality, which contains backend 1.
  4262. args = AdsServiceImpl::EdsResourceArgs({
  4263. {"locality0", GetBackendPorts(1, 2)},
  4264. });
  4265. std::thread delayed_resource_setter(
  4266. std::bind(&BasicTest::SetEdsResourceWithDelay, this, 0,
  4267. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()),
  4268. 60 * 1000));
  4269. // Wait until backend 0 is ready, before which kNumLocalities localities are
  4270. // received and handled by the xds policy.
  4271. WaitForBackend(0, /*reset_counters=*/false);
  4272. EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
  4273. // Wait until backend 1 is ready, before which kNumLocalities localities are
  4274. // removed by the xds policy.
  4275. WaitForBackend(1);
  4276. delayed_resource_setter.join();
  4277. }
  4278. // Tests that the localities in a locality map are picked correctly after update
  4279. // (addition, modification, deletion).
  4280. TEST_P(LocalityMapTest, UpdateMap) {
  4281. SetNextResolution({});
  4282. SetNextResolutionForLbChannelAllBalancers();
  4283. const size_t kNumRpcs = 3000;
  4284. // The locality weight for the first 3 localities.
  4285. const std::vector<int> kLocalityWeights0 = {2, 3, 4};
  4286. const double kTotalLocalityWeight0 =
  4287. std::accumulate(kLocalityWeights0.begin(), kLocalityWeights0.end(), 0);
  4288. std::vector<double> locality_weight_rate_0;
  4289. for (int weight : kLocalityWeights0) {
  4290. locality_weight_rate_0.push_back(weight / kTotalLocalityWeight0);
  4291. }
  4292. // Delete the first locality, keep the second locality, change the third
  4293. // locality's weight from 4 to 2, and add a new locality with weight 6.
  4294. const std::vector<int> kLocalityWeights1 = {3, 2, 6};
  4295. const double kTotalLocalityWeight1 =
  4296. std::accumulate(kLocalityWeights1.begin(), kLocalityWeights1.end(), 0);
  4297. std::vector<double> locality_weight_rate_1 = {
  4298. 0 /* placeholder for locality 0 */};
  4299. for (int weight : kLocalityWeights1) {
  4300. locality_weight_rate_1.push_back(weight / kTotalLocalityWeight1);
  4301. }
  4302. AdsServiceImpl::EdsResourceArgs args({
  4303. {"locality0", GetBackendPorts(0, 1), 2},
  4304. {"locality1", GetBackendPorts(1, 2), 3},
  4305. {"locality2", GetBackendPorts(2, 3), 4},
  4306. });
  4307. balancers_[0]->ads_service()->SetEdsResource(
  4308. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  4309. // Wait for the first 3 backends to be ready.
  4310. WaitForAllBackends(0, 3);
  4311. gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
  4312. // Send kNumRpcs RPCs.
  4313. CheckRpcSendOk(kNumRpcs);
  4314. gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
  4315. // The picking rates of the first 3 backends should be roughly equal to the
  4316. // expectation.
  4317. std::vector<double> locality_picked_rates;
  4318. for (size_t i = 0; i < 3; ++i) {
  4319. locality_picked_rates.push_back(
  4320. static_cast<double>(backends_[i]->backend_service()->request_count()) /
  4321. kNumRpcs);
  4322. }
  4323. const double kErrorTolerance = 0.2;
  4324. for (size_t i = 0; i < 3; ++i) {
  4325. gpr_log(GPR_INFO, "Locality %" PRIuPTR " rate %f", i,
  4326. locality_picked_rates[i]);
  4327. EXPECT_THAT(
  4328. locality_picked_rates[i],
  4329. ::testing::AllOf(
  4330. ::testing::Ge(locality_weight_rate_0[i] * (1 - kErrorTolerance)),
  4331. ::testing::Le(locality_weight_rate_0[i] * (1 + kErrorTolerance))));
  4332. }
  4333. args = AdsServiceImpl::EdsResourceArgs({
  4334. {"locality1", GetBackendPorts(1, 2), 3},
  4335. {"locality2", GetBackendPorts(2, 3), 2},
  4336. {"locality3", GetBackendPorts(3, 4), 6},
  4337. });
  4338. balancers_[0]->ads_service()->SetEdsResource(
  4339. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  4340. // Backend 3 hasn't received any request.
  4341. EXPECT_EQ(0U, backends_[3]->backend_service()->request_count());
  4342. // Wait until the locality update has been processed, as signaled by backend 3
  4343. // receiving a request.
  4344. WaitForAllBackends(3, 4);
  4345. gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
  4346. // Send kNumRpcs RPCs.
  4347. CheckRpcSendOk(kNumRpcs);
  4348. gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
  4349. // Backend 0 no longer receives any request.
  4350. EXPECT_EQ(0U, backends_[0]->backend_service()->request_count());
  4351. // The picking rates of the last 3 backends should be roughly equal to the
  4352. // expectation.
  4353. locality_picked_rates = {0 /* placeholder for backend 0 */};
  4354. for (size_t i = 1; i < 4; ++i) {
  4355. locality_picked_rates.push_back(
  4356. static_cast<double>(backends_[i]->backend_service()->request_count()) /
  4357. kNumRpcs);
  4358. }
  4359. for (size_t i = 1; i < 4; ++i) {
  4360. gpr_log(GPR_INFO, "Locality %" PRIuPTR " rate %f", i,
  4361. locality_picked_rates[i]);
  4362. EXPECT_THAT(
  4363. locality_picked_rates[i],
  4364. ::testing::AllOf(
  4365. ::testing::Ge(locality_weight_rate_1[i] * (1 - kErrorTolerance)),
  4366. ::testing::Le(locality_weight_rate_1[i] * (1 + kErrorTolerance))));
  4367. }
  4368. }
  4369. // Tests that we don't fail RPCs when replacing all of the localities in
  4370. // a given priority.
  4371. TEST_P(LocalityMapTest, ReplaceAllLocalitiesInPriority) {
  4372. SetNextResolution({});
  4373. SetNextResolutionForLbChannelAllBalancers();
  4374. AdsServiceImpl::EdsResourceArgs args({
  4375. {"locality0", GetBackendPorts(0, 1)},
  4376. });
  4377. balancers_[0]->ads_service()->SetEdsResource(
  4378. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  4379. args = AdsServiceImpl::EdsResourceArgs({
  4380. {"locality1", GetBackendPorts(1, 2)},
  4381. });
  4382. std::thread delayed_resource_setter(std::bind(
  4383. &BasicTest::SetEdsResourceWithDelay, this, 0,
  4384. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()), 5000));
  4385. // Wait for the first backend to be ready.
  4386. WaitForBackend(0);
  4387. // Keep sending RPCs until we switch over to backend 1, which tells us
  4388. // that we received the update. No RPCs should fail during this
  4389. // transition.
  4390. WaitForBackend(1, /*reset_counters=*/true, /*require_success=*/true);
  4391. delayed_resource_setter.join();
  4392. }
  4393. class FailoverTest : public BasicTest {
  4394. public:
  4395. void SetUp() override {
  4396. BasicTest::SetUp();
  4397. ResetStub(500);
  4398. }
  4399. };
  4400. // Localities with the highest priority are used when multiple priority exist.
  4401. TEST_P(FailoverTest, ChooseHighestPriority) {
  4402. SetNextResolution({});
  4403. SetNextResolutionForLbChannelAllBalancers();
  4404. AdsServiceImpl::EdsResourceArgs args({
  4405. {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
  4406. {"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
  4407. {"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
  4408. {"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
  4409. });
  4410. balancers_[0]->ads_service()->SetEdsResource(
  4411. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  4412. WaitForBackend(3, false);
  4413. for (size_t i = 0; i < 3; ++i) {
  4414. EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
  4415. }
  4416. }
  4417. // Does not choose priority with no endpoints.
  4418. TEST_P(FailoverTest, DoesNotUsePriorityWithNoEndpoints) {
  4419. SetNextResolution({});
  4420. SetNextResolutionForLbChannelAllBalancers();
  4421. AdsServiceImpl::EdsResourceArgs args({
  4422. {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
  4423. {"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
  4424. {"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
  4425. {"locality3", {}, kDefaultLocalityWeight, 0},
  4426. });
  4427. balancers_[0]->ads_service()->SetEdsResource(
  4428. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  4429. WaitForBackend(0, false);
  4430. for (size_t i = 1; i < 3; ++i) {
  4431. EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
  4432. }
  4433. }
  4434. // Does not choose locality with no endpoints.
  4435. TEST_P(FailoverTest, DoesNotUseLocalityWithNoEndpoints) {
  4436. SetNextResolution({});
  4437. SetNextResolutionForLbChannelAllBalancers();
  4438. AdsServiceImpl::EdsResourceArgs args({
  4439. {"locality0", {}, kDefaultLocalityWeight, 0},
  4440. {"locality1", GetBackendPorts(), kDefaultLocalityWeight, 0},
  4441. });
  4442. balancers_[0]->ads_service()->SetEdsResource(
  4443. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  4444. // Wait for all backends to be used.
  4445. std::tuple<int, int, int> counts = WaitForAllBackends();
  4446. // Make sure no RPCs failed in the transition.
  4447. EXPECT_EQ(0, std::get<1>(counts));
  4448. }
  4449. // If the higher priority localities are not reachable, failover to the highest
  4450. // priority among the rest.
  4451. TEST_P(FailoverTest, Failover) {
  4452. SetNextResolution({});
  4453. SetNextResolutionForLbChannelAllBalancers();
  4454. AdsServiceImpl::EdsResourceArgs args({
  4455. {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
  4456. {"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
  4457. {"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
  4458. {"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
  4459. });
  4460. ShutdownBackend(3);
  4461. ShutdownBackend(0);
  4462. balancers_[0]->ads_service()->SetEdsResource(
  4463. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  4464. WaitForBackend(1, false);
  4465. for (size_t i = 0; i < 4; ++i) {
  4466. if (i == 1) continue;
  4467. EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
  4468. }
  4469. }
  4470. // If a locality with higher priority than the current one becomes ready,
  4471. // switch to it.
  4472. TEST_P(FailoverTest, SwitchBackToHigherPriority) {
  4473. SetNextResolution({});
  4474. SetNextResolutionForLbChannelAllBalancers();
  4475. const size_t kNumRpcs = 100;
  4476. AdsServiceImpl::EdsResourceArgs args({
  4477. {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
  4478. {"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
  4479. {"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
  4480. {"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
  4481. });
  4482. ShutdownBackend(3);
  4483. ShutdownBackend(0);
  4484. balancers_[0]->ads_service()->SetEdsResource(
  4485. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  4486. WaitForBackend(1, false);
  4487. for (size_t i = 0; i < 4; ++i) {
  4488. if (i == 1) continue;
  4489. EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
  4490. }
  4491. StartBackend(0);
  4492. WaitForBackend(0);
  4493. CheckRpcSendOk(kNumRpcs);
  4494. EXPECT_EQ(kNumRpcs, backends_[0]->backend_service()->request_count());
  4495. }
  4496. // The first update only contains unavailable priorities. The second update
  4497. // contains available priorities.
  4498. TEST_P(FailoverTest, UpdateInitialUnavailable) {
  4499. SetNextResolution({});
  4500. SetNextResolutionForLbChannelAllBalancers();
  4501. AdsServiceImpl::EdsResourceArgs args({
  4502. {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 0},
  4503. {"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 1},
  4504. });
  4505. balancers_[0]->ads_service()->SetEdsResource(
  4506. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  4507. args = AdsServiceImpl::EdsResourceArgs({
  4508. {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 0},
  4509. {"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 1},
  4510. {"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 2},
  4511. {"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 3},
  4512. });
  4513. ShutdownBackend(0);
  4514. ShutdownBackend(1);
  4515. std::thread delayed_resource_setter(std::bind(
  4516. &BasicTest::SetEdsResourceWithDelay, this, 0,
  4517. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()), 1000));
  4518. gpr_timespec deadline = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
  4519. gpr_time_from_millis(500, GPR_TIMESPAN));
  4520. // Send 0.5 second worth of RPCs.
  4521. do {
  4522. CheckRpcSendFailure();
  4523. } while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
  4524. WaitForBackend(2, false);
  4525. for (size_t i = 0; i < 4; ++i) {
  4526. if (i == 2) continue;
  4527. EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
  4528. }
  4529. delayed_resource_setter.join();
  4530. }
  4531. // Tests that after the localities' priorities are updated, we still choose the
  4532. // highest READY priority with the updated localities.
  4533. TEST_P(FailoverTest, UpdatePriority) {
  4534. SetNextResolution({});
  4535. SetNextResolutionForLbChannelAllBalancers();
  4536. const size_t kNumRpcs = 100;
  4537. AdsServiceImpl::EdsResourceArgs args({
  4538. {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
  4539. {"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
  4540. {"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
  4541. {"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
  4542. });
  4543. balancers_[0]->ads_service()->SetEdsResource(
  4544. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  4545. args = AdsServiceImpl::EdsResourceArgs({
  4546. {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 2},
  4547. {"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 0},
  4548. {"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 1},
  4549. {"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 3},
  4550. });
  4551. std::thread delayed_resource_setter(std::bind(
  4552. &BasicTest::SetEdsResourceWithDelay, this, 0,
  4553. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()), 1000));
  4554. WaitForBackend(3, false);
  4555. for (size_t i = 0; i < 3; ++i) {
  4556. EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
  4557. }
  4558. WaitForBackend(1);
  4559. CheckRpcSendOk(kNumRpcs);
  4560. EXPECT_EQ(kNumRpcs, backends_[1]->backend_service()->request_count());
  4561. delayed_resource_setter.join();
  4562. }
  4563. // Moves all localities in the current priority to a higher priority.
  4564. TEST_P(FailoverTest, MoveAllLocalitiesInCurrentPriorityToHigherPriority) {
  4565. SetNextResolution({});
  4566. SetNextResolutionForLbChannelAllBalancers();
  4567. // First update:
  4568. // - Priority 0 is locality 0, containing backend 0, which is down.
  4569. // - Priority 1 is locality 1, containing backends 1 and 2, which are up.
  4570. ShutdownBackend(0);
  4571. AdsServiceImpl::EdsResourceArgs args({
  4572. {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 0},
  4573. {"locality1", GetBackendPorts(1, 3), kDefaultLocalityWeight, 1},
  4574. });
  4575. balancers_[0]->ads_service()->SetEdsResource(
  4576. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  4577. // Second update:
  4578. // - Priority 0 contains both localities 0 and 1.
  4579. // - Priority 1 is not present.
  4580. // - We add backend 3 to locality 1, just so we have a way to know
  4581. // when the update has been seen by the client.
  4582. args = AdsServiceImpl::EdsResourceArgs({
  4583. {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 0},
  4584. {"locality1", GetBackendPorts(1, 4), kDefaultLocalityWeight, 0},
  4585. });
  4586. std::thread delayed_resource_setter(std::bind(
  4587. &BasicTest::SetEdsResourceWithDelay, this, 0,
  4588. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()), 1000));
  4589. // When we get the first update, all backends in priority 0 are down,
  4590. // so we will create priority 1. Backends 1 and 2 should have traffic,
  4591. // but backend 3 should not.
  4592. WaitForAllBackends(1, 3, false);
  4593. EXPECT_EQ(0UL, backends_[3]->backend_service()->request_count());
  4594. // When backend 3 gets traffic, we know the second update has been seen.
  4595. WaitForBackend(3);
  4596. // The ADS service of balancer 0 got at least 1 response.
  4597. EXPECT_GT(balancers_[0]->ads_service()->eds_response_state().state,
  4598. AdsServiceImpl::ResponseState::NOT_SENT);
  4599. delayed_resource_setter.join();
  4600. }
  4601. using DropTest = BasicTest;
  4602. // Tests that RPCs are dropped according to the drop config.
  4603. TEST_P(DropTest, Vanilla) {
  4604. SetNextResolution({});
  4605. SetNextResolutionForLbChannelAllBalancers();
  4606. const size_t kNumRpcs = 5000;
  4607. const uint32_t kDropPerMillionForLb = 100000;
  4608. const uint32_t kDropPerMillionForThrottle = 200000;
  4609. const double kDropRateForLb = kDropPerMillionForLb / 1000000.0;
  4610. const double kDropRateForThrottle = kDropPerMillionForThrottle / 1000000.0;
  4611. const double KDropRateForLbAndThrottle =
  4612. kDropRateForLb + (1 - kDropRateForLb) * kDropRateForThrottle;
  4613. // The ADS response contains two drop categories.
  4614. AdsServiceImpl::EdsResourceArgs args({
  4615. {"locality0", GetBackendPorts()},
  4616. });
  4617. args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
  4618. {kThrottleDropType, kDropPerMillionForThrottle}};
  4619. balancers_[0]->ads_service()->SetEdsResource(
  4620. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  4621. WaitForAllBackends();
  4622. // Send kNumRpcs RPCs and count the drops.
  4623. size_t num_drops = 0;
  4624. for (size_t i = 0; i < kNumRpcs; ++i) {
  4625. EchoResponse response;
  4626. const Status status = SendRpc(RpcOptions(), &response);
  4627. if (!status.ok() &&
  4628. status.error_message() == "Call dropped by load balancing policy") {
  4629. ++num_drops;
  4630. } else {
  4631. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  4632. << " message=" << status.error_message();
  4633. EXPECT_EQ(response.message(), kRequestMessage);
  4634. }
  4635. }
  4636. // The drop rate should be roughly equal to the expectation.
  4637. const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
  4638. const double kErrorTolerance = 0.2;
  4639. EXPECT_THAT(
  4640. seen_drop_rate,
  4641. ::testing::AllOf(
  4642. ::testing::Ge(KDropRateForLbAndThrottle * (1 - kErrorTolerance)),
  4643. ::testing::Le(KDropRateForLbAndThrottle * (1 + kErrorTolerance))));
  4644. }
  4645. // Tests that drop config is converted correctly from per hundred.
  4646. TEST_P(DropTest, DropPerHundred) {
  4647. SetNextResolution({});
  4648. SetNextResolutionForLbChannelAllBalancers();
  4649. const size_t kNumRpcs = 5000;
  4650. const uint32_t kDropPerHundredForLb = 10;
  4651. const double kDropRateForLb = kDropPerHundredForLb / 100.0;
  4652. // The ADS response contains one drop category.
  4653. AdsServiceImpl::EdsResourceArgs args({
  4654. {"locality0", GetBackendPorts()},
  4655. });
  4656. args.drop_categories = {{kLbDropType, kDropPerHundredForLb}};
  4657. args.drop_denominator = FractionalPercent::HUNDRED;
  4658. balancers_[0]->ads_service()->SetEdsResource(
  4659. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  4660. WaitForAllBackends();
  4661. // Send kNumRpcs RPCs and count the drops.
  4662. size_t num_drops = 0;
  4663. for (size_t i = 0; i < kNumRpcs; ++i) {
  4664. EchoResponse response;
  4665. const Status status = SendRpc(RpcOptions(), &response);
  4666. if (!status.ok() &&
  4667. status.error_message() == "Call dropped by load balancing policy") {
  4668. ++num_drops;
  4669. } else {
  4670. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  4671. << " message=" << status.error_message();
  4672. EXPECT_EQ(response.message(), kRequestMessage);
  4673. }
  4674. }
  4675. // The drop rate should be roughly equal to the expectation.
  4676. const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
  4677. const double kErrorTolerance = 0.2;
  4678. EXPECT_THAT(
  4679. seen_drop_rate,
  4680. ::testing::AllOf(::testing::Ge(kDropRateForLb * (1 - kErrorTolerance)),
  4681. ::testing::Le(kDropRateForLb * (1 + kErrorTolerance))));
  4682. }
  4683. // Tests that drop config is converted correctly from per ten thousand.
  4684. TEST_P(DropTest, DropPerTenThousand) {
  4685. SetNextResolution({});
  4686. SetNextResolutionForLbChannelAllBalancers();
  4687. const size_t kNumRpcs = 5000;
  4688. const uint32_t kDropPerTenThousandForLb = 1000;
  4689. const double kDropRateForLb = kDropPerTenThousandForLb / 10000.0;
  4690. // The ADS response contains one drop category.
  4691. AdsServiceImpl::EdsResourceArgs args({
  4692. {"locality0", GetBackendPorts()},
  4693. });
  4694. args.drop_categories = {{kLbDropType, kDropPerTenThousandForLb}};
  4695. args.drop_denominator = FractionalPercent::TEN_THOUSAND;
  4696. balancers_[0]->ads_service()->SetEdsResource(
  4697. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  4698. WaitForAllBackends();
  4699. // Send kNumRpcs RPCs and count the drops.
  4700. size_t num_drops = 0;
  4701. for (size_t i = 0; i < kNumRpcs; ++i) {
  4702. EchoResponse response;
  4703. const Status status = SendRpc(RpcOptions(), &response);
  4704. if (!status.ok() &&
  4705. status.error_message() == "Call dropped by load balancing policy") {
  4706. ++num_drops;
  4707. } else {
  4708. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  4709. << " message=" << status.error_message();
  4710. EXPECT_EQ(response.message(), kRequestMessage);
  4711. }
  4712. }
  4713. // The drop rate should be roughly equal to the expectation.
  4714. const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
  4715. const double kErrorTolerance = 0.2;
  4716. EXPECT_THAT(
  4717. seen_drop_rate,
  4718. ::testing::AllOf(::testing::Ge(kDropRateForLb * (1 - kErrorTolerance)),
  4719. ::testing::Le(kDropRateForLb * (1 + kErrorTolerance))));
  4720. }
  4721. // Tests that drop is working correctly after update.
  4722. TEST_P(DropTest, Update) {
  4723. SetNextResolution({});
  4724. SetNextResolutionForLbChannelAllBalancers();
  4725. const size_t kNumRpcs = 3000;
  4726. const uint32_t kDropPerMillionForLb = 100000;
  4727. const uint32_t kDropPerMillionForThrottle = 200000;
  4728. const double kDropRateForLb = kDropPerMillionForLb / 1000000.0;
  4729. const double kDropRateForThrottle = kDropPerMillionForThrottle / 1000000.0;
  4730. const double KDropRateForLbAndThrottle =
  4731. kDropRateForLb + (1 - kDropRateForLb) * kDropRateForThrottle;
  4732. // The first ADS response contains one drop category.
  4733. AdsServiceImpl::EdsResourceArgs args({
  4734. {"locality0", GetBackendPorts()},
  4735. });
  4736. args.drop_categories = {{kLbDropType, kDropPerMillionForLb}};
  4737. balancers_[0]->ads_service()->SetEdsResource(
  4738. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  4739. WaitForAllBackends();
  4740. // Send kNumRpcs RPCs and count the drops.
  4741. size_t num_drops = 0;
  4742. gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
  4743. for (size_t i = 0; i < kNumRpcs; ++i) {
  4744. EchoResponse response;
  4745. const Status status = SendRpc(RpcOptions(), &response);
  4746. if (!status.ok() &&
  4747. status.error_message() == "Call dropped by load balancing policy") {
  4748. ++num_drops;
  4749. } else {
  4750. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  4751. << " message=" << status.error_message();
  4752. EXPECT_EQ(response.message(), kRequestMessage);
  4753. }
  4754. }
  4755. gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
  4756. // The drop rate should be roughly equal to the expectation.
  4757. double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
  4758. gpr_log(GPR_INFO, "First batch drop rate %f", seen_drop_rate);
  4759. const double kErrorTolerance = 0.3;
  4760. EXPECT_THAT(
  4761. seen_drop_rate,
  4762. ::testing::AllOf(::testing::Ge(kDropRateForLb * (1 - kErrorTolerance)),
  4763. ::testing::Le(kDropRateForLb * (1 + kErrorTolerance))));
  4764. // The second ADS response contains two drop categories, send an update EDS
  4765. // response.
  4766. args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
  4767. {kThrottleDropType, kDropPerMillionForThrottle}};
  4768. balancers_[0]->ads_service()->SetEdsResource(
  4769. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  4770. // Wait until the drop rate increases to the middle of the two configs, which
  4771. // implies that the update has been in effect.
  4772. const double kDropRateThreshold =
  4773. (kDropRateForLb + KDropRateForLbAndThrottle) / 2;
  4774. size_t num_rpcs = kNumRpcs;
  4775. while (seen_drop_rate < kDropRateThreshold) {
  4776. EchoResponse response;
  4777. const Status status = SendRpc(RpcOptions(), &response);
  4778. ++num_rpcs;
  4779. if (!status.ok() &&
  4780. status.error_message() == "Call dropped by load balancing policy") {
  4781. ++num_drops;
  4782. } else {
  4783. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  4784. << " message=" << status.error_message();
  4785. EXPECT_EQ(response.message(), kRequestMessage);
  4786. }
  4787. seen_drop_rate = static_cast<double>(num_drops) / num_rpcs;
  4788. }
  4789. // Send kNumRpcs RPCs and count the drops.
  4790. num_drops = 0;
  4791. gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
  4792. for (size_t i = 0; i < kNumRpcs; ++i) {
  4793. EchoResponse response;
  4794. const Status status = SendRpc(RpcOptions(), &response);
  4795. if (!status.ok() &&
  4796. status.error_message() == "Call dropped by load balancing policy") {
  4797. ++num_drops;
  4798. } else {
  4799. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  4800. << " message=" << status.error_message();
  4801. EXPECT_EQ(response.message(), kRequestMessage);
  4802. }
  4803. }
  4804. gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
  4805. // The new drop rate should be roughly equal to the expectation.
  4806. seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
  4807. gpr_log(GPR_INFO, "Second batch drop rate %f", seen_drop_rate);
  4808. EXPECT_THAT(
  4809. seen_drop_rate,
  4810. ::testing::AllOf(
  4811. ::testing::Ge(KDropRateForLbAndThrottle * (1 - kErrorTolerance)),
  4812. ::testing::Le(KDropRateForLbAndThrottle * (1 + kErrorTolerance))));
  4813. }
  4814. // Tests that all the RPCs are dropped if any drop category drops 100%.
  4815. TEST_P(DropTest, DropAll) {
  4816. SetNextResolution({});
  4817. SetNextResolutionForLbChannelAllBalancers();
  4818. const size_t kNumRpcs = 1000;
  4819. const uint32_t kDropPerMillionForLb = 100000;
  4820. const uint32_t kDropPerMillionForThrottle = 1000000;
  4821. // The ADS response contains two drop categories.
  4822. AdsServiceImpl::EdsResourceArgs args;
  4823. args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
  4824. {kThrottleDropType, kDropPerMillionForThrottle}};
  4825. balancers_[0]->ads_service()->SetEdsResource(
  4826. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  4827. // Send kNumRpcs RPCs and all of them are dropped.
  4828. for (size_t i = 0; i < kNumRpcs; ++i) {
  4829. EchoResponse response;
  4830. const Status status = SendRpc(RpcOptions(), &response);
  4831. EXPECT_EQ(status.error_code(), StatusCode::UNAVAILABLE);
  4832. EXPECT_EQ(status.error_message(), "Call dropped by load balancing policy");
  4833. }
  4834. }
  4835. class BalancerUpdateTest : public XdsEnd2endTest {
  4836. public:
  4837. BalancerUpdateTest() : XdsEnd2endTest(4, 3) {}
  4838. };
  4839. // Tests that the old LB call is still used after the balancer address update as
  4840. // long as that call is still alive.
  4841. TEST_P(BalancerUpdateTest, UpdateBalancersButKeepUsingOriginalBalancer) {
  4842. SetNextResolution({});
  4843. SetNextResolutionForLbChannelAllBalancers();
  4844. AdsServiceImpl::EdsResourceArgs args({
  4845. {"locality0", {backends_[0]->port()}},
  4846. });
  4847. balancers_[0]->ads_service()->SetEdsResource(
  4848. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  4849. args = AdsServiceImpl::EdsResourceArgs({
  4850. {"locality0", {backends_[1]->port()}},
  4851. });
  4852. balancers_[1]->ads_service()->SetEdsResource(
  4853. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  4854. // Wait until the first backend is ready.
  4855. WaitForBackend(0);
  4856. // Send 10 requests.
  4857. gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
  4858. CheckRpcSendOk(10);
  4859. gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
  4860. // All 10 requests should have gone to the first backend.
  4861. EXPECT_EQ(10U, backends_[0]->backend_service()->request_count());
  4862. // The ADS service of balancer 0 sent at least 1 response.
  4863. EXPECT_GT(balancers_[0]->ads_service()->eds_response_state().state,
  4864. AdsServiceImpl::ResponseState::NOT_SENT);
  4865. EXPECT_EQ(balancers_[1]->ads_service()->eds_response_state().state,
  4866. AdsServiceImpl::ResponseState::NOT_SENT)
  4867. << "Error Message:"
  4868. << balancers_[1]->ads_service()->eds_response_state().error_message;
  4869. EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
  4870. AdsServiceImpl::ResponseState::NOT_SENT)
  4871. << "Error Message:"
  4872. << balancers_[2]->ads_service()->eds_response_state().error_message;
  4873. gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
  4874. SetNextResolutionForLbChannel({balancers_[1]->port()});
  4875. gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
  4876. EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
  4877. gpr_timespec deadline = gpr_time_add(
  4878. gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_millis(10000, GPR_TIMESPAN));
  4879. // Send 10 seconds worth of RPCs
  4880. do {
  4881. CheckRpcSendOk();
  4882. } while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
  4883. // The current LB call is still working, so xds continued using it to the
  4884. // first balancer, which doesn't assign the second backend.
  4885. EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
  4886. // The ADS service of balancer 0 sent at least 1 response.
  4887. EXPECT_GT(balancers_[0]->ads_service()->eds_response_state().state,
  4888. AdsServiceImpl::ResponseState::NOT_SENT);
  4889. EXPECT_EQ(balancers_[1]->ads_service()->eds_response_state().state,
  4890. AdsServiceImpl::ResponseState::NOT_SENT)
  4891. << "Error Message:"
  4892. << balancers_[1]->ads_service()->eds_response_state().error_message;
  4893. EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
  4894. AdsServiceImpl::ResponseState::NOT_SENT)
  4895. << "Error Message:"
  4896. << balancers_[2]->ads_service()->eds_response_state().error_message;
  4897. }
  4898. // Tests that the old LB call is still used after multiple balancer address
  4899. // updates as long as that call is still alive. Send an update with the same set
  4900. // of LBs as the one in SetUp() in order to verify that the LB channel inside
  4901. // xds keeps the initial connection (which by definition is also present in the
  4902. // update).
  4903. TEST_P(BalancerUpdateTest, Repeated) {
  4904. SetNextResolution({});
  4905. SetNextResolutionForLbChannelAllBalancers();
  4906. AdsServiceImpl::EdsResourceArgs args({
  4907. {"locality0", {backends_[0]->port()}},
  4908. });
  4909. balancers_[0]->ads_service()->SetEdsResource(
  4910. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  4911. args = AdsServiceImpl::EdsResourceArgs({
  4912. {"locality0", {backends_[1]->port()}},
  4913. });
  4914. balancers_[1]->ads_service()->SetEdsResource(
  4915. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  4916. // Wait until the first backend is ready.
  4917. WaitForBackend(0);
  4918. // Send 10 requests.
  4919. gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
  4920. CheckRpcSendOk(10);
  4921. gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
  4922. // All 10 requests should have gone to the first backend.
  4923. EXPECT_EQ(10U, backends_[0]->backend_service()->request_count());
  4924. // The ADS service of balancer 0 sent at least 1 response.
  4925. EXPECT_GT(balancers_[0]->ads_service()->eds_response_state().state,
  4926. AdsServiceImpl::ResponseState::NOT_SENT);
  4927. EXPECT_EQ(balancers_[1]->ads_service()->eds_response_state().state,
  4928. AdsServiceImpl::ResponseState::NOT_SENT)
  4929. << "Error Message:"
  4930. << balancers_[1]->ads_service()->eds_response_state().error_message;
  4931. EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
  4932. AdsServiceImpl::ResponseState::NOT_SENT)
  4933. << "Error Message:"
  4934. << balancers_[2]->ads_service()->eds_response_state().error_message;
  4935. std::vector<int> ports;
  4936. ports.emplace_back(balancers_[0]->port());
  4937. ports.emplace_back(balancers_[1]->port());
  4938. ports.emplace_back(balancers_[2]->port());
  4939. gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
  4940. SetNextResolutionForLbChannel(ports);
  4941. gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
  4942. EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
  4943. gpr_timespec deadline = gpr_time_add(
  4944. gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_millis(10000, GPR_TIMESPAN));
  4945. // Send 10 seconds worth of RPCs
  4946. do {
  4947. CheckRpcSendOk();
  4948. } while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
  4949. // xds continued using the original LB call to the first balancer, which
  4950. // doesn't assign the second backend.
  4951. EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
  4952. ports.clear();
  4953. ports.emplace_back(balancers_[0]->port());
  4954. ports.emplace_back(balancers_[1]->port());
  4955. gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 2 ==========");
  4956. SetNextResolutionForLbChannel(ports);
  4957. gpr_log(GPR_INFO, "========= UPDATE 2 DONE ==========");
  4958. EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
  4959. deadline = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
  4960. gpr_time_from_millis(10000, GPR_TIMESPAN));
  4961. // Send 10 seconds worth of RPCs
  4962. do {
  4963. CheckRpcSendOk();
  4964. } while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
  4965. // xds continued using the original LB call to the first balancer, which
  4966. // doesn't assign the second backend.
  4967. EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
  4968. }
  4969. // Tests that if the balancer is down, the RPCs will still be sent to the
  4970. // backends according to the last balancer response, until a new balancer is
  4971. // reachable.
  4972. TEST_P(BalancerUpdateTest, DeadUpdate) {
  4973. SetNextResolution({});
  4974. SetNextResolutionForLbChannel({balancers_[0]->port()});
  4975. AdsServiceImpl::EdsResourceArgs args({
  4976. {"locality0", {backends_[0]->port()}},
  4977. });
  4978. balancers_[0]->ads_service()->SetEdsResource(
  4979. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  4980. args = AdsServiceImpl::EdsResourceArgs({
  4981. {"locality0", {backends_[1]->port()}},
  4982. });
  4983. balancers_[1]->ads_service()->SetEdsResource(
  4984. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  4985. // Start servers and send 10 RPCs per server.
  4986. gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
  4987. CheckRpcSendOk(10);
  4988. gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
  4989. // All 10 requests should have gone to the first backend.
  4990. EXPECT_EQ(10U, backends_[0]->backend_service()->request_count());
  4991. // The ADS service of balancer 0 sent at least 1 response.
  4992. EXPECT_GT(balancers_[0]->ads_service()->eds_response_state().state,
  4993. AdsServiceImpl::ResponseState::NOT_SENT);
  4994. EXPECT_EQ(balancers_[1]->ads_service()->eds_response_state().state,
  4995. AdsServiceImpl::ResponseState::NOT_SENT)
  4996. << "Error Message:"
  4997. << balancers_[1]->ads_service()->eds_response_state().error_message;
  4998. EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
  4999. AdsServiceImpl::ResponseState::NOT_SENT)
  5000. << "Error Message:"
  5001. << balancers_[2]->ads_service()->eds_response_state().error_message;
  5002. // Kill balancer 0
  5003. gpr_log(GPR_INFO, "********** ABOUT TO KILL BALANCER 0 *************");
  5004. balancers_[0]->Shutdown();
  5005. gpr_log(GPR_INFO, "********** KILLED BALANCER 0 *************");
  5006. // This is serviced by the existing child policy.
  5007. gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
  5008. CheckRpcSendOk(10);
  5009. gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
  5010. // All 10 requests should again have gone to the first backend.
  5011. EXPECT_EQ(20U, backends_[0]->backend_service()->request_count());
  5012. EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
  5013. // The ADS service of no balancers sent anything
  5014. EXPECT_EQ(balancers_[0]->ads_service()->eds_response_state().state,
  5015. AdsServiceImpl::ResponseState::NOT_SENT)
  5016. << "Error Message:"
  5017. << balancers_[0]->ads_service()->eds_response_state().error_message;
  5018. EXPECT_EQ(balancers_[1]->ads_service()->eds_response_state().state,
  5019. AdsServiceImpl::ResponseState::NOT_SENT)
  5020. << "Error Message:"
  5021. << balancers_[1]->ads_service()->eds_response_state().error_message;
  5022. EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
  5023. AdsServiceImpl::ResponseState::NOT_SENT)
  5024. << "Error Message:"
  5025. << balancers_[2]->ads_service()->eds_response_state().error_message;
  5026. gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
  5027. SetNextResolutionForLbChannel({balancers_[1]->port()});
  5028. gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
  5029. // Wait until update has been processed, as signaled by the second backend
  5030. // receiving a request. In the meantime, the client continues to be serviced
  5031. // (by the first backend) without interruption.
  5032. EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
  5033. WaitForBackend(1);
  5034. // This is serviced by the updated RR policy
  5035. backends_[1]->backend_service()->ResetCounters();
  5036. gpr_log(GPR_INFO, "========= BEFORE THIRD BATCH ==========");
  5037. CheckRpcSendOk(10);
  5038. gpr_log(GPR_INFO, "========= DONE WITH THIRD BATCH ==========");
  5039. // All 10 requests should have gone to the second backend.
  5040. EXPECT_EQ(10U, backends_[1]->backend_service()->request_count());
  5041. // The ADS service of balancer 1 sent at least 1 response.
  5042. EXPECT_EQ(balancers_[0]->ads_service()->eds_response_state().state,
  5043. AdsServiceImpl::ResponseState::NOT_SENT)
  5044. << "Error Message:"
  5045. << balancers_[0]->ads_service()->eds_response_state().error_message;
  5046. EXPECT_GT(balancers_[1]->ads_service()->eds_response_state().state,
  5047. AdsServiceImpl::ResponseState::NOT_SENT);
  5048. EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
  5049. AdsServiceImpl::ResponseState::NOT_SENT)
  5050. << "Error Message:"
  5051. << balancers_[2]->ads_service()->eds_response_state().error_message;
  5052. }
  5053. // The re-resolution tests are deferred because they rely on the fallback mode,
  5054. // which hasn't been supported.
  5055. // TODO(juanlishen): Add TEST_P(BalancerUpdateTest, ReresolveDeadBackend).
  5056. // TODO(juanlishen): Add TEST_P(UpdatesWithClientLoadReportingTest,
  5057. // ReresolveDeadBalancer)
  5058. class ClientLoadReportingTest : public XdsEnd2endTest {
  5059. public:
  5060. ClientLoadReportingTest() : XdsEnd2endTest(4, 1, 3) {}
  5061. };
  5062. // Tests that the load report received at the balancer is correct.
  5063. TEST_P(ClientLoadReportingTest, Vanilla) {
  5064. if (!GetParam().use_xds_resolver()) {
  5065. balancers_[0]->lrs_service()->set_cluster_names({kServerName});
  5066. }
  5067. SetNextResolution({});
  5068. SetNextResolutionForLbChannel({balancers_[0]->port()});
  5069. const size_t kNumRpcsPerAddress = 10;
  5070. const size_t kNumFailuresPerAddress = 3;
  5071. // TODO(juanlishen): Partition the backends after multiple localities is
  5072. // tested.
  5073. AdsServiceImpl::EdsResourceArgs args({
  5074. {"locality0", GetBackendPorts()},
  5075. });
  5076. balancers_[0]->ads_service()->SetEdsResource(
  5077. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  5078. // Wait until all backends are ready.
  5079. int num_ok = 0;
  5080. int num_failure = 0;
  5081. int num_drops = 0;
  5082. std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
  5083. // Send kNumRpcsPerAddress RPCs per server.
  5084. CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
  5085. CheckRpcSendFailure(kNumFailuresPerAddress * num_backends_,
  5086. RpcOptions().set_server_fail(true));
  5087. // Check that each backend got the right number of requests.
  5088. for (size_t i = 0; i < backends_.size(); ++i) {
  5089. EXPECT_EQ(kNumRpcsPerAddress + kNumFailuresPerAddress,
  5090. backends_[i]->backend_service()->request_count());
  5091. }
  5092. // The load report received at the balancer should be correct.
  5093. std::vector<ClientStats> load_report =
  5094. balancers_[0]->lrs_service()->WaitForLoadReport();
  5095. ASSERT_EQ(load_report.size(), 1UL);
  5096. ClientStats& client_stats = load_report.front();
  5097. EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + num_ok,
  5098. client_stats.total_successful_requests());
  5099. EXPECT_EQ(0U, client_stats.total_requests_in_progress());
  5100. EXPECT_EQ((kNumRpcsPerAddress + kNumFailuresPerAddress) * num_backends_ +
  5101. num_ok + num_failure,
  5102. client_stats.total_issued_requests());
  5103. EXPECT_EQ(kNumFailuresPerAddress * num_backends_ + num_failure,
  5104. client_stats.total_error_requests());
  5105. EXPECT_EQ(0U, client_stats.total_dropped_requests());
  5106. // The LRS service got a single request, and sent a single response.
  5107. EXPECT_EQ(1U, balancers_[0]->lrs_service()->request_count());
  5108. EXPECT_EQ(1U, balancers_[0]->lrs_service()->response_count());
  5109. }
  5110. // Tests send_all_clusters.
  5111. TEST_P(ClientLoadReportingTest, SendAllClusters) {
  5112. balancers_[0]->lrs_service()->set_send_all_clusters(true);
  5113. SetNextResolution({});
  5114. SetNextResolutionForLbChannel({balancers_[0]->port()});
  5115. const size_t kNumRpcsPerAddress = 10;
  5116. const size_t kNumFailuresPerAddress = 3;
  5117. // TODO(juanlishen): Partition the backends after multiple localities is
  5118. // tested.
  5119. AdsServiceImpl::EdsResourceArgs args({
  5120. {"locality0", GetBackendPorts()},
  5121. });
  5122. balancers_[0]->ads_service()->SetEdsResource(
  5123. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  5124. // Wait until all backends are ready.
  5125. int num_ok = 0;
  5126. int num_failure = 0;
  5127. int num_drops = 0;
  5128. std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
  5129. // Send kNumRpcsPerAddress RPCs per server.
  5130. CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
  5131. CheckRpcSendFailure(kNumFailuresPerAddress * num_backends_,
  5132. RpcOptions().set_server_fail(true));
  5133. // Check that each backend got the right number of requests.
  5134. for (size_t i = 0; i < backends_.size(); ++i) {
  5135. EXPECT_EQ(kNumRpcsPerAddress + kNumFailuresPerAddress,
  5136. backends_[i]->backend_service()->request_count());
  5137. }
  5138. // The load report received at the balancer should be correct.
  5139. std::vector<ClientStats> load_report =
  5140. balancers_[0]->lrs_service()->WaitForLoadReport();
  5141. ASSERT_EQ(load_report.size(), 1UL);
  5142. ClientStats& client_stats = load_report.front();
  5143. EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + num_ok,
  5144. client_stats.total_successful_requests());
  5145. EXPECT_EQ(0U, client_stats.total_requests_in_progress());
  5146. EXPECT_EQ((kNumRpcsPerAddress + kNumFailuresPerAddress) * num_backends_ +
  5147. num_ok + num_failure,
  5148. client_stats.total_issued_requests());
  5149. EXPECT_EQ(kNumFailuresPerAddress * num_backends_ + num_failure,
  5150. client_stats.total_error_requests());
  5151. EXPECT_EQ(0U, client_stats.total_dropped_requests());
  5152. // The LRS service got a single request, and sent a single response.
  5153. EXPECT_EQ(1U, balancers_[0]->lrs_service()->request_count());
  5154. EXPECT_EQ(1U, balancers_[0]->lrs_service()->response_count());
  5155. }
  5156. // Tests that we don't include stats for clusters that are not requested
  5157. // by the LRS server.
  5158. TEST_P(ClientLoadReportingTest, HonorsClustersRequestedByLrsServer) {
  5159. balancers_[0]->lrs_service()->set_cluster_names({"bogus"});
  5160. SetNextResolution({});
  5161. SetNextResolutionForLbChannel({balancers_[0]->port()});
  5162. const size_t kNumRpcsPerAddress = 100;
  5163. AdsServiceImpl::EdsResourceArgs args({
  5164. {"locality0", GetBackendPorts()},
  5165. });
  5166. balancers_[0]->ads_service()->SetEdsResource(
  5167. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  5168. // Wait until all backends are ready.
  5169. int num_ok = 0;
  5170. int num_failure = 0;
  5171. int num_drops = 0;
  5172. std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
  5173. // Send kNumRpcsPerAddress RPCs per server.
  5174. CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
  5175. // Each backend should have gotten 100 requests.
  5176. for (size_t i = 0; i < backends_.size(); ++i) {
  5177. EXPECT_EQ(kNumRpcsPerAddress,
  5178. backends_[i]->backend_service()->request_count());
  5179. }
  5180. // The LRS service got a single request, and sent a single response.
  5181. EXPECT_EQ(1U, balancers_[0]->lrs_service()->request_count());
  5182. EXPECT_EQ(1U, balancers_[0]->lrs_service()->response_count());
  5183. // The load report received at the balancer should be correct.
  5184. std::vector<ClientStats> load_report =
  5185. balancers_[0]->lrs_service()->WaitForLoadReport();
  5186. ASSERT_EQ(load_report.size(), 0UL);
  5187. }
  5188. // Tests that if the balancer restarts, the client load report contains the
  5189. // stats before and after the restart correctly.
  5190. TEST_P(ClientLoadReportingTest, BalancerRestart) {
  5191. if (!GetParam().use_xds_resolver()) {
  5192. balancers_[0]->lrs_service()->set_cluster_names({kServerName});
  5193. }
  5194. SetNextResolution({});
  5195. SetNextResolutionForLbChannel({balancers_[0]->port()});
  5196. const size_t kNumBackendsFirstPass = backends_.size() / 2;
  5197. const size_t kNumBackendsSecondPass =
  5198. backends_.size() - kNumBackendsFirstPass;
  5199. AdsServiceImpl::EdsResourceArgs args({
  5200. {"locality0", GetBackendPorts(0, kNumBackendsFirstPass)},
  5201. });
  5202. balancers_[0]->ads_service()->SetEdsResource(
  5203. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  5204. // Wait until all backends returned by the balancer are ready.
  5205. int num_ok = 0;
  5206. int num_failure = 0;
  5207. int num_drops = 0;
  5208. std::tie(num_ok, num_failure, num_drops) =
  5209. WaitForAllBackends(/* start_index */ 0,
  5210. /* stop_index */ kNumBackendsFirstPass);
  5211. std::vector<ClientStats> load_report =
  5212. balancers_[0]->lrs_service()->WaitForLoadReport();
  5213. ASSERT_EQ(load_report.size(), 1UL);
  5214. ClientStats client_stats = std::move(load_report.front());
  5215. EXPECT_EQ(static_cast<size_t>(num_ok),
  5216. client_stats.total_successful_requests());
  5217. EXPECT_EQ(0U, client_stats.total_requests_in_progress());
  5218. EXPECT_EQ(0U, client_stats.total_error_requests());
  5219. EXPECT_EQ(0U, client_stats.total_dropped_requests());
  5220. // Shut down the balancer.
  5221. balancers_[0]->Shutdown();
  5222. // We should continue using the last EDS response we received from the
  5223. // balancer before it was shut down.
  5224. // Note: We need to use WaitForAllBackends() here instead of just
  5225. // CheckRpcSendOk(kNumBackendsFirstPass), because when the balancer
  5226. // shuts down, the XdsClient will generate an error to the
  5227. // ServiceConfigWatcher, which will cause the xds resolver to send a
  5228. // no-op update to the LB policy. When this update gets down to the
  5229. // round_robin child policy for the locality, it will generate a new
  5230. // subchannel list, which resets the start index randomly. So we need
  5231. // to be a little more permissive here to avoid spurious failures.
  5232. ResetBackendCounters();
  5233. int num_started = std::get<0>(WaitForAllBackends(
  5234. /* start_index */ 0, /* stop_index */ kNumBackendsFirstPass));
  5235. // Now restart the balancer, this time pointing to the new backends.
  5236. balancers_[0]->Start();
  5237. args = AdsServiceImpl::EdsResourceArgs({
  5238. {"locality0", GetBackendPorts(kNumBackendsFirstPass)},
  5239. });
  5240. balancers_[0]->ads_service()->SetEdsResource(
  5241. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  5242. // Wait for queries to start going to one of the new backends.
  5243. // This tells us that we're now using the new serverlist.
  5244. std::tie(num_ok, num_failure, num_drops) =
  5245. WaitForAllBackends(/* start_index */ kNumBackendsFirstPass);
  5246. num_started += num_ok + num_failure + num_drops;
  5247. // Send one RPC per backend.
  5248. CheckRpcSendOk(kNumBackendsSecondPass);
  5249. num_started += kNumBackendsSecondPass;
  5250. // Check client stats.
  5251. load_report = balancers_[0]->lrs_service()->WaitForLoadReport();
  5252. ASSERT_EQ(load_report.size(), 1UL);
  5253. client_stats = std::move(load_report.front());
  5254. EXPECT_EQ(num_started, client_stats.total_successful_requests());
  5255. EXPECT_EQ(0U, client_stats.total_requests_in_progress());
  5256. EXPECT_EQ(0U, client_stats.total_error_requests());
  5257. EXPECT_EQ(0U, client_stats.total_dropped_requests());
  5258. }
  5259. class ClientLoadReportingWithDropTest : public XdsEnd2endTest {
  5260. public:
  5261. ClientLoadReportingWithDropTest() : XdsEnd2endTest(4, 1, 20) {}
  5262. };
  5263. // Tests that the drop stats are correctly reported by client load reporting.
  5264. TEST_P(ClientLoadReportingWithDropTest, Vanilla) {
  5265. if (!GetParam().use_xds_resolver()) {
  5266. balancers_[0]->lrs_service()->set_cluster_names({kServerName});
  5267. }
  5268. SetNextResolution({});
  5269. SetNextResolutionForLbChannelAllBalancers();
  5270. const size_t kNumRpcs = 3000;
  5271. const uint32_t kDropPerMillionForLb = 100000;
  5272. const uint32_t kDropPerMillionForThrottle = 200000;
  5273. const double kDropRateForLb = kDropPerMillionForLb / 1000000.0;
  5274. const double kDropRateForThrottle = kDropPerMillionForThrottle / 1000000.0;
  5275. const double KDropRateForLbAndThrottle =
  5276. kDropRateForLb + (1 - kDropRateForLb) * kDropRateForThrottle;
  5277. // The ADS response contains two drop categories.
  5278. AdsServiceImpl::EdsResourceArgs args({
  5279. {"locality0", GetBackendPorts()},
  5280. });
  5281. args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
  5282. {kThrottleDropType, kDropPerMillionForThrottle}};
  5283. balancers_[0]->ads_service()->SetEdsResource(
  5284. AdsServiceImpl::BuildEdsResource(args, DefaultEdsServiceName()));
  5285. int num_ok = 0;
  5286. int num_failure = 0;
  5287. int num_drops = 0;
  5288. std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
  5289. const size_t num_warmup = num_ok + num_failure + num_drops;
  5290. // Send kNumRpcs RPCs and count the drops.
  5291. for (size_t i = 0; i < kNumRpcs; ++i) {
  5292. EchoResponse response;
  5293. const Status status = SendRpc(RpcOptions(), &response);
  5294. if (!status.ok() &&
  5295. status.error_message() == "Call dropped by load balancing policy") {
  5296. ++num_drops;
  5297. } else {
  5298. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  5299. << " message=" << status.error_message();
  5300. EXPECT_EQ(response.message(), kRequestMessage);
  5301. }
  5302. }
  5303. // The drop rate should be roughly equal to the expectation.
  5304. const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
  5305. const double kErrorTolerance = 0.2;
  5306. EXPECT_THAT(
  5307. seen_drop_rate,
  5308. ::testing::AllOf(
  5309. ::testing::Ge(KDropRateForLbAndThrottle * (1 - kErrorTolerance)),
  5310. ::testing::Le(KDropRateForLbAndThrottle * (1 + kErrorTolerance))));
  5311. // Check client stats.
  5312. const size_t total_rpc = num_warmup + kNumRpcs;
  5313. ClientStats client_stats;
  5314. do {
  5315. std::vector<ClientStats> load_reports =
  5316. balancers_[0]->lrs_service()->WaitForLoadReport();
  5317. for (const auto& load_report : load_reports) {
  5318. client_stats += load_report;
  5319. }
  5320. } while (client_stats.total_issued_requests() +
  5321. client_stats.total_dropped_requests() <
  5322. total_rpc);
  5323. EXPECT_EQ(num_drops, client_stats.total_dropped_requests());
  5324. EXPECT_THAT(
  5325. client_stats.dropped_requests(kLbDropType),
  5326. ::testing::AllOf(
  5327. ::testing::Ge(total_rpc * kDropRateForLb * (1 - kErrorTolerance)),
  5328. ::testing::Le(total_rpc * kDropRateForLb * (1 + kErrorTolerance))));
  5329. EXPECT_THAT(client_stats.dropped_requests(kThrottleDropType),
  5330. ::testing::AllOf(
  5331. ::testing::Ge(total_rpc * (1 - kDropRateForLb) *
  5332. kDropRateForThrottle * (1 - kErrorTolerance)),
  5333. ::testing::Le(total_rpc * (1 - kDropRateForLb) *
  5334. kDropRateForThrottle * (1 + kErrorTolerance))));
  5335. }
  5336. std::string TestTypeName(const ::testing::TestParamInfo<TestType>& info) {
  5337. return info.param.AsString();
  5338. }
  5339. // TestType params:
  5340. // - use_xds_resolver
  5341. // - enable_load_reporting
  5342. // - enable_rds_testing = false
  5343. // - use_v2 = false
  5344. INSTANTIATE_TEST_SUITE_P(XdsTest, BasicTest,
  5345. ::testing::Values(TestType(false, true),
  5346. TestType(false, false),
  5347. TestType(true, false),
  5348. TestType(true, true)),
  5349. &TestTypeName);
  5350. // Run with both fake resolver and xds resolver.
  5351. // Don't run with load reporting or v2 or RDS, since they are irrelevant to
  5352. // the tests.
  5353. INSTANTIATE_TEST_SUITE_P(XdsTest, SecureNamingTest,
  5354. ::testing::Values(TestType(false, false),
  5355. TestType(true, false)),
  5356. &TestTypeName);
  5357. // LDS depends on XdsResolver.
  5358. INSTANTIATE_TEST_SUITE_P(XdsTest, LdsTest,
  5359. ::testing::Values(TestType(true, false),
  5360. TestType(true, true)),
  5361. &TestTypeName);
  5362. // LDS/RDS commmon tests depend on XdsResolver.
  5363. INSTANTIATE_TEST_SUITE_P(XdsTest, LdsRdsTest,
  5364. ::testing::Values(TestType(true, false),
  5365. TestType(true, true),
  5366. TestType(true, false, true),
  5367. TestType(true, true, true),
  5368. // Also test with xDS v2.
  5369. TestType(true, true, true, true)),
  5370. &TestTypeName);
  5371. // CDS depends on XdsResolver.
  5372. INSTANTIATE_TEST_SUITE_P(XdsTest, CdsTest,
  5373. ::testing::Values(TestType(true, false),
  5374. TestType(true, true)),
  5375. &TestTypeName);
  5376. // EDS could be tested with or without XdsResolver, but the tests would
  5377. // be the same either way, so we test it only with XdsResolver.
  5378. INSTANTIATE_TEST_SUITE_P(XdsTest, EdsTest,
  5379. ::testing::Values(TestType(true, false),
  5380. TestType(true, true)),
  5381. &TestTypeName);
  5382. // Test initial resource timeouts for each resource type.
  5383. // Do this only for XdsResolver with RDS enabled, so that we can test
  5384. // all resource types.
  5385. // Run with V3 only, since the functionality is no different in V2.
  5386. INSTANTIATE_TEST_SUITE_P(XdsTest, TimeoutTest,
  5387. ::testing::Values(TestType(true, false, true)),
  5388. &TestTypeName);
  5389. // XdsResolverOnlyTest depends on XdsResolver.
  5390. INSTANTIATE_TEST_SUITE_P(XdsTest, XdsResolverOnlyTest,
  5391. ::testing::Values(TestType(true, false),
  5392. TestType(true, true)),
  5393. &TestTypeName);
  5394. // XdsResolverLoadReprtingOnlyTest depends on XdsResolver and load reporting.
  5395. INSTANTIATE_TEST_SUITE_P(XdsTest, XdsResolverLoadReportingOnlyTest,
  5396. ::testing::Values(TestType(true, true)),
  5397. &TestTypeName);
  5398. INSTANTIATE_TEST_SUITE_P(XdsTest, LocalityMapTest,
  5399. ::testing::Values(TestType(false, true),
  5400. TestType(false, false),
  5401. TestType(true, false),
  5402. TestType(true, true)),
  5403. &TestTypeName);
  5404. INSTANTIATE_TEST_SUITE_P(XdsTest, FailoverTest,
  5405. ::testing::Values(TestType(false, true),
  5406. TestType(false, false),
  5407. TestType(true, false),
  5408. TestType(true, true)),
  5409. &TestTypeName);
  5410. INSTANTIATE_TEST_SUITE_P(XdsTest, DropTest,
  5411. ::testing::Values(TestType(false, true),
  5412. TestType(false, false),
  5413. TestType(true, false),
  5414. TestType(true, true)),
  5415. &TestTypeName);
  5416. INSTANTIATE_TEST_SUITE_P(XdsTest, BalancerUpdateTest,
  5417. ::testing::Values(TestType(false, true),
  5418. TestType(false, false),
  5419. TestType(true, true)),
  5420. &TestTypeName);
  5421. // Load reporting tests are not run with load reporting disabled.
  5422. INSTANTIATE_TEST_SUITE_P(XdsTest, ClientLoadReportingTest,
  5423. ::testing::Values(TestType(false, true),
  5424. TestType(true, true)),
  5425. &TestTypeName);
  5426. // Load reporting tests are not run with load reporting disabled.
  5427. INSTANTIATE_TEST_SUITE_P(XdsTest, ClientLoadReportingWithDropTest,
  5428. ::testing::Values(TestType(false, true),
  5429. TestType(true, true)),
  5430. &TestTypeName);
  5431. } // namespace
  5432. } // namespace testing
  5433. } // namespace grpc
  5434. int main(int argc, char** argv) {
  5435. grpc::testing::TestEnvironment env(argc, argv);
  5436. ::testing::InitGoogleTest(&argc, argv);
  5437. grpc::testing::WriteBootstrapFiles();
  5438. grpc::testing::g_port_saver = new grpc::testing::PortSaver();
  5439. const auto result = RUN_ALL_TESTS();
  5440. return result;
  5441. }