xds_end2end_test.cc 314 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350
  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/memory/memory.h"
  30. #include "absl/strings/str_cat.h"
  31. #include "absl/types/optional.h"
  32. #include <grpc/grpc.h>
  33. #include <grpc/grpc_security.h>
  34. #include <grpc/support/alloc.h>
  35. #include <grpc/support/log.h>
  36. #include <grpc/support/time.h>
  37. #include <grpcpp/channel.h>
  38. #include <grpcpp/client_context.h>
  39. #include <grpcpp/create_channel.h>
  40. #include <grpcpp/security/tls_certificate_provider.h>
  41. #include <grpcpp/server.h>
  42. #include <grpcpp/server_builder.h>
  43. #include "src/core/ext/filters/client_channel/backup_poller.h"
  44. #include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
  45. #include "src/core/ext/filters/client_channel/server_address.h"
  46. #include "src/core/ext/xds/certificate_provider_registry.h"
  47. #include "src/core/ext/xds/xds_api.h"
  48. #include "src/core/ext/xds/xds_channel_args.h"
  49. #include "src/core/ext/xds/xds_client.h"
  50. #include "src/core/lib/channel/channel_args.h"
  51. #include "src/core/lib/gpr/env.h"
  52. #include "src/core/lib/gpr/tmpfile.h"
  53. #include "src/core/lib/gprpp/ref_counted_ptr.h"
  54. #include "src/core/lib/gprpp/sync.h"
  55. #include "src/core/lib/iomgr/load_file.h"
  56. #include "src/core/lib/iomgr/parse_address.h"
  57. #include "src/core/lib/iomgr/sockaddr.h"
  58. #include "src/core/lib/security/credentials/fake/fake_credentials.h"
  59. #include "src/cpp/client/secure_credentials.h"
  60. #include "src/cpp/server/secure_server_credentials.h"
  61. #include "test/core/util/port.h"
  62. #include "test/core/util/resolve_localhost_ip46.h"
  63. #include "test/core/util/test_config.h"
  64. #include "test/cpp/end2end/test_service_impl.h"
  65. #include "src/proto/grpc/testing/echo.grpc.pb.h"
  66. #include "src/proto/grpc/testing/xds/ads_for_test.grpc.pb.h"
  67. #include "src/proto/grpc/testing/xds/cds_for_test.grpc.pb.h"
  68. #include "src/proto/grpc/testing/xds/eds_for_test.grpc.pb.h"
  69. #include "src/proto/grpc/testing/xds/lds_rds_for_test.grpc.pb.h"
  70. #include "src/proto/grpc/testing/xds/lrs_for_test.grpc.pb.h"
  71. #include "src/proto/grpc/testing/xds/v3/ads.grpc.pb.h"
  72. #include "src/proto/grpc/testing/xds/v3/cluster.grpc.pb.h"
  73. #include "src/proto/grpc/testing/xds/v3/discovery.grpc.pb.h"
  74. #include "src/proto/grpc/testing/xds/v3/endpoint.grpc.pb.h"
  75. #include "src/proto/grpc/testing/xds/v3/http_connection_manager.grpc.pb.h"
  76. #include "src/proto/grpc/testing/xds/v3/listener.grpc.pb.h"
  77. #include "src/proto/grpc/testing/xds/v3/lrs.grpc.pb.h"
  78. #include "src/proto/grpc/testing/xds/v3/route.grpc.pb.h"
  79. #include "src/proto/grpc/testing/xds/v3/tls.grpc.pb.h"
  80. namespace grpc {
  81. namespace testing {
  82. namespace {
  83. using std::chrono::system_clock;
  84. using ::envoy::config::cluster::v3::CircuitBreakers;
  85. using ::envoy::config::cluster::v3::Cluster;
  86. using ::envoy::config::cluster::v3::RoutingPriority;
  87. using ::envoy::config::endpoint::v3::ClusterLoadAssignment;
  88. using ::envoy::config::endpoint::v3::HealthStatus;
  89. using ::envoy::config::listener::v3::Listener;
  90. using ::envoy::config::route::v3::RouteConfiguration;
  91. using ::envoy::extensions::filters::network::http_connection_manager::v3::
  92. HttpConnectionManager;
  93. using ::envoy::extensions::transport_sockets::tls::v3::UpstreamTlsContext;
  94. using ::envoy::type::matcher::v3::StringMatcher;
  95. using ::envoy::type::v3::FractionalPercent;
  96. constexpr char kLdsTypeUrl[] =
  97. "type.googleapis.com/envoy.config.listener.v3.Listener";
  98. constexpr char kRdsTypeUrl[] =
  99. "type.googleapis.com/envoy.config.route.v3.RouteConfiguration";
  100. constexpr char kCdsTypeUrl[] =
  101. "type.googleapis.com/envoy.config.cluster.v3.Cluster";
  102. constexpr char kEdsTypeUrl[] =
  103. "type.googleapis.com/envoy.config.endpoint.v3.ClusterLoadAssignment";
  104. constexpr char kLdsV2TypeUrl[] = "type.googleapis.com/envoy.api.v2.Listener";
  105. constexpr char kRdsV2TypeUrl[] =
  106. "type.googleapis.com/envoy.api.v2.RouteConfiguration";
  107. constexpr char kCdsV2TypeUrl[] = "type.googleapis.com/envoy.api.v2.Cluster";
  108. constexpr char kEdsV2TypeUrl[] =
  109. "type.googleapis.com/envoy.api.v2.ClusterLoadAssignment";
  110. constexpr char kDefaultLocalityRegion[] = "xds_default_locality_region";
  111. constexpr char kDefaultLocalityZone[] = "xds_default_locality_zone";
  112. constexpr char kLbDropType[] = "lb";
  113. constexpr char kThrottleDropType[] = "throttle";
  114. constexpr char kServerName[] = "server.example.com";
  115. constexpr char kDefaultRouteConfigurationName[] = "route_config_name";
  116. constexpr char kDefaultClusterName[] = "cluster_name";
  117. constexpr char kDefaultEdsServiceName[] = "eds_service_name";
  118. constexpr int kDefaultLocalityWeight = 3;
  119. constexpr int kDefaultLocalityPriority = 0;
  120. constexpr char kRequestMessage[] = "Live long and prosper.";
  121. constexpr char kDefaultServiceConfig[] =
  122. "{\n"
  123. " \"loadBalancingConfig\":[\n"
  124. " { \"does_not_exist\":{} },\n"
  125. " { \"xds_cluster_resolver_experimental\":{\n"
  126. " \"discoveryMechanisms\": [\n"
  127. " { \"clusterName\": \"server.example.com\",\n"
  128. " \"type\": \"EDS\",\n"
  129. " \"lrsLoadReportingServerName\": \"\"\n"
  130. " } ]\n"
  131. " } }\n"
  132. " ]\n"
  133. "}";
  134. constexpr char kDefaultServiceConfigWithoutLoadReporting[] =
  135. "{\n"
  136. " \"loadBalancingConfig\":[\n"
  137. " { \"does_not_exist\":{} },\n"
  138. " { \"xds_cluster_resolver_experimental\":{\n"
  139. " \"discoveryMechanisms\": [\n"
  140. " { \"clusterName\": \"server.example.com\",\n"
  141. " \"type\": \"EDS\"\n"
  142. " } ]\n"
  143. " } }\n"
  144. " ]\n"
  145. "}";
  146. constexpr char kBootstrapFileV3[] =
  147. "{\n"
  148. " \"xds_servers\": [\n"
  149. " {\n"
  150. " \"server_uri\": \"fake:///xds_server\",\n"
  151. " \"channel_creds\": [\n"
  152. " {\n"
  153. " \"type\": \"fake\"\n"
  154. " }\n"
  155. " ],\n"
  156. " \"server_features\": [\"xds_v3\"]\n"
  157. " }\n"
  158. " ],\n"
  159. " \"node\": {\n"
  160. " \"id\": \"xds_end2end_test\",\n"
  161. " \"cluster\": \"test\",\n"
  162. " \"metadata\": {\n"
  163. " \"foo\": \"bar\"\n"
  164. " },\n"
  165. " \"locality\": {\n"
  166. " \"region\": \"corp\",\n"
  167. " \"zone\": \"svl\",\n"
  168. " \"subzone\": \"mp3\"\n"
  169. " }\n"
  170. " },\n"
  171. " \"certificate_providers\": {\n"
  172. " \"fake_plugin1\": {\n"
  173. " \"plugin_name\": \"fake1\"\n"
  174. " },\n"
  175. " \"fake_plugin2\": {\n"
  176. " \"plugin_name\": \"fake2\"\n"
  177. " },\n"
  178. " \"file_plugin\": {\n"
  179. " \"plugin_name\": \"file_watcher\",\n"
  180. " \"config\": {\n"
  181. " \"certificate_file\": \"src/core/tsi/test_creds/client.pem\",\n"
  182. " \"private_key_file\": \"src/core/tsi/test_creds/client.key\",\n"
  183. " \"ca_certificate_file\": \"src/core/tsi/test_creds/ca.pem\"\n"
  184. " }"
  185. " }\n"
  186. " }\n"
  187. "}\n";
  188. constexpr char kBootstrapFileV2[] =
  189. "{\n"
  190. " \"xds_servers\": [\n"
  191. " {\n"
  192. " \"server_uri\": \"fake:///xds_server\",\n"
  193. " \"channel_creds\": [\n"
  194. " {\n"
  195. " \"type\": \"fake\"\n"
  196. " }\n"
  197. " ]\n"
  198. " }\n"
  199. " ],\n"
  200. " \"node\": {\n"
  201. " \"id\": \"xds_end2end_test\",\n"
  202. " \"cluster\": \"test\",\n"
  203. " \"metadata\": {\n"
  204. " \"foo\": \"bar\"\n"
  205. " },\n"
  206. " \"locality\": {\n"
  207. " \"region\": \"corp\",\n"
  208. " \"zone\": \"svl\",\n"
  209. " \"subzone\": \"mp3\"\n"
  210. " }\n"
  211. " }\n"
  212. "}\n";
  213. constexpr char kCaCertPath[] = "src/core/tsi/test_creds/ca.pem";
  214. constexpr char kServerCertPath[] = "src/core/tsi/test_creds/server1.pem";
  215. constexpr char kServerKeyPath[] = "src/core/tsi/test_creds/server1.key";
  216. constexpr char kClientCertPath[] = "src/core/tsi/test_creds/client.pem";
  217. constexpr char kClientKeyPath[] = "src/core/tsi/test_creds/client.key";
  218. constexpr char kBadClientCertPath[] = "src/core/tsi/test_creds/badclient.pem";
  219. constexpr char kBadClientKeyPath[] = "src/core/tsi/test_creds/badclient.key";
  220. char* g_bootstrap_file_v3;
  221. char* g_bootstrap_file_v2;
  222. void WriteBootstrapFiles() {
  223. char* bootstrap_file;
  224. FILE* out = gpr_tmpfile("xds_bootstrap_v3", &bootstrap_file);
  225. fputs(kBootstrapFileV3, out);
  226. fclose(out);
  227. g_bootstrap_file_v3 = bootstrap_file;
  228. out = gpr_tmpfile("xds_bootstrap_v2", &bootstrap_file);
  229. fputs(kBootstrapFileV2, out);
  230. fclose(out);
  231. g_bootstrap_file_v2 = bootstrap_file;
  232. }
  233. // Helper class to minimize the number of unique ports we use for this test.
  234. class PortSaver {
  235. public:
  236. int GetPort() {
  237. if (idx_ >= ports_.size()) {
  238. ports_.push_back(grpc_pick_unused_port_or_die());
  239. }
  240. return ports_[idx_++];
  241. }
  242. void Reset() { idx_ = 0; }
  243. private:
  244. std::vector<int> ports_;
  245. size_t idx_ = 0;
  246. };
  247. PortSaver* g_port_saver = nullptr;
  248. template <typename ServiceType>
  249. class CountedService : public ServiceType {
  250. public:
  251. size_t request_count() {
  252. grpc_core::MutexLock lock(&mu_);
  253. return request_count_;
  254. }
  255. size_t response_count() {
  256. grpc_core::MutexLock lock(&mu_);
  257. return response_count_;
  258. }
  259. void IncreaseResponseCount() {
  260. grpc_core::MutexLock lock(&mu_);
  261. ++response_count_;
  262. }
  263. void IncreaseRequestCount() {
  264. grpc_core::MutexLock lock(&mu_);
  265. ++request_count_;
  266. }
  267. void ResetCounters() {
  268. grpc_core::MutexLock lock(&mu_);
  269. request_count_ = 0;
  270. response_count_ = 0;
  271. }
  272. private:
  273. grpc_core::Mutex mu_;
  274. size_t request_count_ = 0;
  275. size_t response_count_ = 0;
  276. };
  277. template <typename RpcService>
  278. class BackendServiceImpl
  279. : public CountedService<TestMultipleServiceImpl<RpcService>> {
  280. public:
  281. BackendServiceImpl() {}
  282. Status Echo(ServerContext* context, const EchoRequest* request,
  283. EchoResponse* response) override {
  284. auto peer_identity = context->auth_context()->GetPeerIdentity();
  285. CountedService<TestMultipleServiceImpl<RpcService>>::IncreaseRequestCount();
  286. const auto status =
  287. TestMultipleServiceImpl<RpcService>::Echo(context, request, response);
  288. CountedService<
  289. TestMultipleServiceImpl<RpcService>>::IncreaseResponseCount();
  290. {
  291. grpc_core::MutexLock lock(&mu_);
  292. clients_.insert(context->peer());
  293. last_peer_identity_.clear();
  294. for (const auto& entry : peer_identity) {
  295. last_peer_identity_.emplace_back(entry.data(), entry.size());
  296. }
  297. }
  298. return status;
  299. }
  300. Status Echo1(ServerContext* context, const EchoRequest* request,
  301. EchoResponse* response) override {
  302. return Echo(context, request, response);
  303. }
  304. Status Echo2(ServerContext* context, const EchoRequest* request,
  305. EchoResponse* response) override {
  306. return Echo(context, request, response);
  307. }
  308. void Start() {}
  309. void Shutdown() {}
  310. std::set<std::string> clients() {
  311. grpc_core::MutexLock lock(&mu_);
  312. return clients_;
  313. }
  314. const std::vector<std::string>& last_peer_identity() {
  315. grpc_core::MutexLock lock(&mu_);
  316. return last_peer_identity_;
  317. }
  318. private:
  319. grpc_core::Mutex mu_;
  320. std::set<std::string> clients_;
  321. std::vector<std::string> last_peer_identity_;
  322. };
  323. class ClientStats {
  324. public:
  325. struct LocalityStats {
  326. LocalityStats() {}
  327. // Converts from proto message class.
  328. template <class UpstreamLocalityStats>
  329. explicit LocalityStats(const UpstreamLocalityStats& upstream_locality_stats)
  330. : total_successful_requests(
  331. upstream_locality_stats.total_successful_requests()),
  332. total_requests_in_progress(
  333. upstream_locality_stats.total_requests_in_progress()),
  334. total_error_requests(upstream_locality_stats.total_error_requests()),
  335. total_issued_requests(
  336. upstream_locality_stats.total_issued_requests()) {}
  337. LocalityStats& operator+=(const LocalityStats& other) {
  338. total_successful_requests += other.total_successful_requests;
  339. total_requests_in_progress += other.total_requests_in_progress;
  340. total_error_requests += other.total_error_requests;
  341. total_issued_requests += other.total_issued_requests;
  342. return *this;
  343. }
  344. uint64_t total_successful_requests = 0;
  345. uint64_t total_requests_in_progress = 0;
  346. uint64_t total_error_requests = 0;
  347. uint64_t total_issued_requests = 0;
  348. };
  349. ClientStats() {}
  350. // Converts from proto message class.
  351. template <class ClusterStats>
  352. explicit ClientStats(const ClusterStats& cluster_stats)
  353. : cluster_name_(cluster_stats.cluster_name()),
  354. total_dropped_requests_(cluster_stats.total_dropped_requests()) {
  355. for (const auto& input_locality_stats :
  356. cluster_stats.upstream_locality_stats()) {
  357. locality_stats_.emplace(input_locality_stats.locality().sub_zone(),
  358. LocalityStats(input_locality_stats));
  359. }
  360. for (const auto& input_dropped_requests :
  361. cluster_stats.dropped_requests()) {
  362. dropped_requests_.emplace(input_dropped_requests.category(),
  363. input_dropped_requests.dropped_count());
  364. }
  365. }
  366. const std::string& cluster_name() const { return cluster_name_; }
  367. const std::map<std::string, LocalityStats>& locality_stats() const {
  368. return locality_stats_;
  369. }
  370. uint64_t total_successful_requests() const {
  371. uint64_t sum = 0;
  372. for (auto& p : locality_stats_) {
  373. sum += p.second.total_successful_requests;
  374. }
  375. return sum;
  376. }
  377. uint64_t total_requests_in_progress() const {
  378. uint64_t sum = 0;
  379. for (auto& p : locality_stats_) {
  380. sum += p.second.total_requests_in_progress;
  381. }
  382. return sum;
  383. }
  384. uint64_t total_error_requests() const {
  385. uint64_t sum = 0;
  386. for (auto& p : locality_stats_) {
  387. sum += p.second.total_error_requests;
  388. }
  389. return sum;
  390. }
  391. uint64_t total_issued_requests() const {
  392. uint64_t sum = 0;
  393. for (auto& p : locality_stats_) {
  394. sum += p.second.total_issued_requests;
  395. }
  396. return sum;
  397. }
  398. uint64_t total_dropped_requests() const { return total_dropped_requests_; }
  399. uint64_t dropped_requests(const std::string& category) const {
  400. auto iter = dropped_requests_.find(category);
  401. GPR_ASSERT(iter != dropped_requests_.end());
  402. return iter->second;
  403. }
  404. ClientStats& operator+=(const ClientStats& other) {
  405. for (const auto& p : other.locality_stats_) {
  406. locality_stats_[p.first] += p.second;
  407. }
  408. total_dropped_requests_ += other.total_dropped_requests_;
  409. for (const auto& p : other.dropped_requests_) {
  410. dropped_requests_[p.first] += p.second;
  411. }
  412. return *this;
  413. }
  414. private:
  415. std::string cluster_name_;
  416. std::map<std::string, LocalityStats> locality_stats_;
  417. uint64_t total_dropped_requests_ = 0;
  418. std::map<std::string, uint64_t> dropped_requests_;
  419. };
  420. // TODO(roth) move all of the code that deals with default resource contents out
  421. // of AdsServiceImpl and into XdsEnd2EndTest.
  422. class AdsServiceImpl : public std::enable_shared_from_this<AdsServiceImpl> {
  423. public:
  424. struct ResponseState {
  425. enum State { NOT_SENT, SENT, ACKED, NACKED };
  426. State state = NOT_SENT;
  427. std::string error_message;
  428. };
  429. struct EdsResourceArgs {
  430. struct Locality {
  431. Locality(std::string sub_zone, std::vector<int> ports,
  432. int lb_weight = kDefaultLocalityWeight,
  433. int priority = kDefaultLocalityPriority,
  434. std::vector<HealthStatus> health_statuses = {})
  435. : sub_zone(std::move(sub_zone)),
  436. ports(std::move(ports)),
  437. lb_weight(lb_weight),
  438. priority(priority),
  439. health_statuses(std::move(health_statuses)) {}
  440. const std::string sub_zone;
  441. std::vector<int> ports;
  442. int lb_weight;
  443. int priority;
  444. std::vector<HealthStatus> health_statuses;
  445. };
  446. EdsResourceArgs() = default;
  447. explicit EdsResourceArgs(std::vector<Locality> locality_list)
  448. : locality_list(std::move(locality_list)) {}
  449. std::vector<Locality> locality_list;
  450. std::map<std::string, uint32_t> drop_categories;
  451. FractionalPercent::DenominatorType drop_denominator =
  452. FractionalPercent::MILLION;
  453. };
  454. AdsServiceImpl()
  455. : v2_rpc_service_(this, /*is_v2=*/true),
  456. v3_rpc_service_(this, /*is_v2=*/false) {}
  457. bool seen_v2_client() const { return seen_v2_client_; }
  458. bool seen_v3_client() const { return seen_v3_client_; }
  459. ::envoy::service::discovery::v2::AggregatedDiscoveryService::Service*
  460. v2_rpc_service() {
  461. return &v2_rpc_service_;
  462. }
  463. ::envoy::service::discovery::v3::AggregatedDiscoveryService::Service*
  464. v3_rpc_service() {
  465. return &v3_rpc_service_;
  466. }
  467. ResponseState lds_response_state() {
  468. grpc_core::MutexLock lock(&ads_mu_);
  469. return resource_type_response_state_[kLdsTypeUrl];
  470. }
  471. ResponseState rds_response_state() {
  472. grpc_core::MutexLock lock(&ads_mu_);
  473. return resource_type_response_state_[kRdsTypeUrl];
  474. }
  475. ResponseState cds_response_state() {
  476. grpc_core::MutexLock lock(&ads_mu_);
  477. return resource_type_response_state_[kCdsTypeUrl];
  478. }
  479. ResponseState eds_response_state() {
  480. grpc_core::MutexLock lock(&ads_mu_);
  481. return resource_type_response_state_[kEdsTypeUrl];
  482. }
  483. void SetResourceIgnore(const std::string& type_url) {
  484. grpc_core::MutexLock lock(&ads_mu_);
  485. resource_types_to_ignore_.emplace(type_url);
  486. }
  487. void SetResourceMinVersion(const std::string& type_url, int version) {
  488. grpc_core::MutexLock lock(&ads_mu_);
  489. resource_type_min_versions_[type_url] = version;
  490. }
  491. void UnsetResource(const std::string& type_url, const std::string& name) {
  492. grpc_core::MutexLock lock(&ads_mu_);
  493. ResourceTypeState& resource_type_state = resource_map_[type_url];
  494. ++resource_type_state.resource_type_version;
  495. ResourceState& resource_state = resource_type_state.resource_name_map[name];
  496. resource_state.resource_type_version =
  497. resource_type_state.resource_type_version;
  498. resource_state.resource.reset();
  499. gpr_log(GPR_INFO,
  500. "ADS[%p]: Unsetting %s resource %s; resource_type_version now %u",
  501. this, type_url.c_str(), name.c_str(),
  502. resource_type_state.resource_type_version);
  503. for (SubscriptionState* subscription : resource_state.subscriptions) {
  504. subscription->update_queue->emplace_back(type_url, name);
  505. }
  506. }
  507. void SetResource(google::protobuf::Any resource, const std::string& type_url,
  508. const std::string& name) {
  509. grpc_core::MutexLock lock(&ads_mu_);
  510. ResourceTypeState& resource_type_state = resource_map_[type_url];
  511. ++resource_type_state.resource_type_version;
  512. ResourceState& resource_state = resource_type_state.resource_name_map[name];
  513. resource_state.resource_type_version =
  514. resource_type_state.resource_type_version;
  515. resource_state.resource = std::move(resource);
  516. gpr_log(GPR_INFO,
  517. "ADS[%p]: Updating %s resource %s; resource_type_version now %u",
  518. this, type_url.c_str(), name.c_str(),
  519. resource_type_state.resource_type_version);
  520. for (SubscriptionState* subscription : resource_state.subscriptions) {
  521. subscription->update_queue->emplace_back(type_url, name);
  522. }
  523. }
  524. void SetLdsResource(const Listener& listener) {
  525. google::protobuf::Any resource;
  526. resource.PackFrom(listener);
  527. SetResource(std::move(resource), kLdsTypeUrl, listener.name());
  528. }
  529. void SetRdsResource(const RouteConfiguration& route) {
  530. google::protobuf::Any resource;
  531. resource.PackFrom(route);
  532. SetResource(std::move(resource), kRdsTypeUrl, route.name());
  533. }
  534. void SetCdsResource(const Cluster& cluster) {
  535. google::protobuf::Any resource;
  536. resource.PackFrom(cluster);
  537. SetResource(std::move(resource), kCdsTypeUrl, cluster.name());
  538. }
  539. void SetEdsResource(const ClusterLoadAssignment& assignment) {
  540. google::protobuf::Any resource;
  541. resource.PackFrom(assignment);
  542. SetResource(std::move(resource), kEdsTypeUrl, assignment.cluster_name());
  543. }
  544. void Start() {
  545. grpc_core::MutexLock lock(&ads_mu_);
  546. ads_done_ = false;
  547. }
  548. void Shutdown() {
  549. {
  550. grpc_core::MutexLock lock(&ads_mu_);
  551. NotifyDoneWithAdsCallLocked();
  552. resource_type_response_state_.clear();
  553. }
  554. gpr_log(GPR_INFO, "ADS[%p]: shut down", this);
  555. }
  556. void NotifyDoneWithAdsCall() {
  557. grpc_core::MutexLock lock(&ads_mu_);
  558. NotifyDoneWithAdsCallLocked();
  559. }
  560. void NotifyDoneWithAdsCallLocked() {
  561. if (!ads_done_) {
  562. ads_done_ = true;
  563. ads_cond_.Broadcast();
  564. }
  565. }
  566. std::set<std::string> clients() {
  567. grpc_core::MutexLock lock(&clients_mu_);
  568. return clients_;
  569. }
  570. private:
  571. // A queue of resource type/name pairs that have changed since the client
  572. // subscribed to them.
  573. using UpdateQueue = std::deque<
  574. std::pair<std::string /* type url */, std::string /* resource name */>>;
  575. // A struct representing a client's subscription to a particular resource.
  576. struct SubscriptionState {
  577. // The queue upon which to place updates when the resource is updated.
  578. UpdateQueue* update_queue;
  579. };
  580. // A struct representing the a client's subscription to all the resources.
  581. using SubscriptionNameMap =
  582. std::map<std::string /* resource_name */, SubscriptionState>;
  583. using SubscriptionMap =
  584. std::map<std::string /* type_url */, SubscriptionNameMap>;
  585. // Sent state for a given resource type.
  586. struct SentState {
  587. int nonce = 0;
  588. int resource_type_version = 0;
  589. };
  590. // A struct representing the current state for an individual resource.
  591. struct ResourceState {
  592. // The resource itself, if present.
  593. absl::optional<google::protobuf::Any> resource;
  594. // The resource type version that this resource was last updated in.
  595. int resource_type_version = 0;
  596. // A list of subscriptions to this resource.
  597. std::set<SubscriptionState*> subscriptions;
  598. };
  599. // The current state for all individual resources of a given type.
  600. using ResourceNameMap =
  601. std::map<std::string /* resource_name */, ResourceState>;
  602. struct ResourceTypeState {
  603. int resource_type_version = 0;
  604. ResourceNameMap resource_name_map;
  605. };
  606. using ResourceMap = std::map<std::string /* type_url */, ResourceTypeState>;
  607. template <class RpcApi, class DiscoveryRequest, class DiscoveryResponse>
  608. class RpcService : public RpcApi::Service {
  609. public:
  610. using Stream = ServerReaderWriter<DiscoveryResponse, DiscoveryRequest>;
  611. RpcService(AdsServiceImpl* parent, bool is_v2)
  612. : parent_(parent), is_v2_(is_v2) {}
  613. Status StreamAggregatedResources(ServerContext* context,
  614. Stream* stream) override {
  615. gpr_log(GPR_INFO, "ADS[%p]: StreamAggregatedResources starts", this);
  616. parent_->AddClient(context->peer());
  617. if (is_v2_) {
  618. parent_->seen_v2_client_ = true;
  619. } else {
  620. parent_->seen_v3_client_ = true;
  621. }
  622. // Take a reference of the AdsServiceImpl object, which will go
  623. // out of scope when this request handler returns. This ensures
  624. // that the parent won't be destroyed until this stream is complete.
  625. std::shared_ptr<AdsServiceImpl> ads_service_impl =
  626. parent_->shared_from_this();
  627. // Resources (type/name pairs) that have changed since the client
  628. // subscribed to them.
  629. UpdateQueue update_queue;
  630. // Resources that the client will be subscribed to keyed by resource type
  631. // url.
  632. SubscriptionMap subscription_map;
  633. // Sent state for each resource type.
  634. std::map<std::string /*type_url*/, SentState> sent_state_map;
  635. // Spawn a thread to read requests from the stream.
  636. // Requests will be delivered to this thread in a queue.
  637. std::deque<DiscoveryRequest> requests;
  638. bool stream_closed = false;
  639. std::thread reader(std::bind(&RpcService::BlockingRead, this, stream,
  640. &requests, &stream_closed));
  641. // Main loop to process requests and updates.
  642. while (true) {
  643. // Boolean to keep track if the loop received any work to do: a
  644. // request or an update; regardless whether a response was actually
  645. // sent out.
  646. bool did_work = false;
  647. // Look for new requests and and decide what to handle.
  648. absl::optional<DiscoveryResponse> response;
  649. {
  650. grpc_core::MutexLock lock(&parent_->ads_mu_);
  651. // If the stream has been closed or our parent is being shut
  652. // down, stop immediately.
  653. if (stream_closed || parent_->ads_done_) break;
  654. // Otherwise, see if there's a request to read from the queue.
  655. if (!requests.empty()) {
  656. DiscoveryRequest request = std::move(requests.front());
  657. requests.pop_front();
  658. did_work = true;
  659. gpr_log(GPR_INFO,
  660. "ADS[%p]: Received request for type %s with content %s",
  661. this, request.type_url().c_str(),
  662. request.DebugString().c_str());
  663. const std::string v3_resource_type =
  664. TypeUrlToV3(request.type_url());
  665. SentState& sent_state = sent_state_map[v3_resource_type];
  666. // Process request.
  667. ProcessRequest(request, v3_resource_type, &update_queue,
  668. &subscription_map, &sent_state, &response);
  669. }
  670. }
  671. if (response.has_value()) {
  672. gpr_log(GPR_INFO, "ADS[%p]: Sending response: %s", this,
  673. response->DebugString().c_str());
  674. stream->Write(response.value());
  675. }
  676. response.reset();
  677. // Look for updates and decide what to handle.
  678. {
  679. grpc_core::MutexLock lock(&parent_->ads_mu_);
  680. if (!update_queue.empty()) {
  681. const std::string resource_type =
  682. std::move(update_queue.front().first);
  683. const std::string resource_name =
  684. std::move(update_queue.front().second);
  685. update_queue.pop_front();
  686. did_work = true;
  687. SentState& sent_state = sent_state_map[resource_type];
  688. ProcessUpdate(resource_type, resource_name, &subscription_map,
  689. &sent_state, &response);
  690. }
  691. }
  692. if (response.has_value()) {
  693. gpr_log(GPR_INFO, "ADS[%p]: Sending update response: %s", this,
  694. response->DebugString().c_str());
  695. stream->Write(response.value());
  696. }
  697. // If we didn't find anything to do, delay before the next loop
  698. // iteration; otherwise, check whether we should exit and then
  699. // immediately continue.
  700. gpr_timespec deadline =
  701. grpc_timeout_milliseconds_to_deadline(did_work ? 0 : 10);
  702. {
  703. grpc_core::MutexLock lock(&parent_->ads_mu_);
  704. if (!parent_->ads_cond_.WaitUntil(
  705. &parent_->ads_mu_, [this] { return parent_->ads_done_; },
  706. deadline)) {
  707. break;
  708. }
  709. }
  710. }
  711. // Done with main loop. Clean up before returning.
  712. // Join reader thread.
  713. reader.join();
  714. // Clean up any subscriptions that were still active when the call
  715. // finished.
  716. {
  717. grpc_core::MutexLock lock(&parent_->ads_mu_);
  718. for (auto& p : subscription_map) {
  719. const std::string& type_url = p.first;
  720. SubscriptionNameMap& subscription_name_map = p.second;
  721. for (auto& q : subscription_name_map) {
  722. const std::string& resource_name = q.first;
  723. SubscriptionState& subscription_state = q.second;
  724. ResourceNameMap& resource_name_map =
  725. parent_->resource_map_[type_url].resource_name_map;
  726. ResourceState& resource_state = resource_name_map[resource_name];
  727. resource_state.subscriptions.erase(&subscription_state);
  728. }
  729. }
  730. }
  731. gpr_log(GPR_INFO, "ADS[%p]: StreamAggregatedResources done", this);
  732. parent_->RemoveClient(context->peer());
  733. return Status::OK;
  734. }
  735. private:
  736. // Processes a response read from the client.
  737. // Populates response if needed.
  738. void ProcessRequest(const DiscoveryRequest& request,
  739. const std::string& v3_resource_type,
  740. UpdateQueue* update_queue,
  741. SubscriptionMap* subscription_map,
  742. SentState* sent_state,
  743. absl::optional<DiscoveryResponse>* response) {
  744. // Determine client resource type version.
  745. int client_resource_type_version = 0;
  746. if (!request.version_info().empty()) {
  747. GPR_ASSERT(absl::SimpleAtoi(request.version_info(),
  748. &client_resource_type_version));
  749. }
  750. // Check the nonce sent by the client, if any.
  751. // (This will be absent on the first request on a stream.)
  752. if (request.response_nonce().empty()) {
  753. EXPECT_GE(client_resource_type_version,
  754. parent_->resource_type_min_versions_[v3_resource_type])
  755. << "resource_type: " << v3_resource_type;
  756. } else {
  757. int client_nonce;
  758. GPR_ASSERT(absl::SimpleAtoi(request.response_nonce(), &client_nonce));
  759. // Ignore requests with stale nonces.
  760. if (client_nonce < sent_state->nonce) return;
  761. // Check for ACK or NACK.
  762. auto it = parent_->resource_type_response_state_.find(v3_resource_type);
  763. if (it != parent_->resource_type_response_state_.end()) {
  764. if (client_resource_type_version ==
  765. sent_state->resource_type_version) {
  766. it->second.state = ResponseState::ACKED;
  767. it->second.error_message.clear();
  768. gpr_log(GPR_INFO,
  769. "ADS[%p]: client ACKed resource_type=%s version=%s", this,
  770. request.type_url().c_str(), request.version_info().c_str());
  771. } else {
  772. it->second.state = ResponseState::NACKED;
  773. EXPECT_EQ(request.error_detail().code(),
  774. GRPC_STATUS_INVALID_ARGUMENT);
  775. it->second.error_message = request.error_detail().message();
  776. gpr_log(GPR_INFO,
  777. "ADS[%p]: client NACKed resource_type=%s version=%s: %s",
  778. this, request.type_url().c_str(),
  779. request.version_info().c_str(),
  780. it->second.error_message.c_str());
  781. }
  782. }
  783. }
  784. // Ignore resource types as requested by tests.
  785. if (parent_->resource_types_to_ignore_.find(v3_resource_type) !=
  786. parent_->resource_types_to_ignore_.end()) {
  787. return;
  788. }
  789. // Look at all the resource names in the request.
  790. auto& subscription_name_map = (*subscription_map)[v3_resource_type];
  791. auto& resource_type_state = parent_->resource_map_[v3_resource_type];
  792. auto& resource_name_map = resource_type_state.resource_name_map;
  793. std::set<std::string> resources_in_current_request;
  794. std::set<std::string> resources_added_to_response;
  795. for (const std::string& resource_name : request.resource_names()) {
  796. resources_in_current_request.emplace(resource_name);
  797. auto& subscription_state = subscription_name_map[resource_name];
  798. auto& resource_state = resource_name_map[resource_name];
  799. // Subscribe if needed.
  800. // Send the resource in the response if either (a) this is
  801. // a new subscription or (b) there is an updated version of
  802. // this resource to send.
  803. if (parent_->MaybeSubscribe(v3_resource_type, resource_name,
  804. &subscription_state, &resource_state,
  805. update_queue) ||
  806. ClientNeedsResourceUpdate(resource_type_state, resource_state,
  807. client_resource_type_version,
  808. &subscription_state)) {
  809. gpr_log(GPR_INFO, "ADS[%p]: Sending update for type=%s name=%s", this,
  810. request.type_url().c_str(), resource_name.c_str());
  811. resources_added_to_response.emplace(resource_name);
  812. if (!response->has_value()) response->emplace();
  813. if (resource_state.resource.has_value()) {
  814. auto* resource = (*response)->add_resources();
  815. resource->CopyFrom(resource_state.resource.value());
  816. if (is_v2_) {
  817. resource->set_type_url(request.type_url());
  818. }
  819. }
  820. } else {
  821. gpr_log(GPR_INFO,
  822. "ADS[%p]: client does not need update for type=%s name=%s",
  823. this, request.type_url().c_str(), resource_name.c_str());
  824. }
  825. }
  826. // Process unsubscriptions for any resource no longer
  827. // present in the request's resource list.
  828. parent_->ProcessUnsubscriptions(
  829. v3_resource_type, resources_in_current_request,
  830. &subscription_name_map, &resource_name_map);
  831. // Construct response if needed.
  832. if (!resources_added_to_response.empty()) {
  833. CompleteBuildingDiscoveryResponse(
  834. v3_resource_type, request.type_url(),
  835. resource_type_state.resource_type_version, subscription_name_map,
  836. resources_added_to_response, sent_state, &response->value());
  837. }
  838. }
  839. // Processes a resource update from the test.
  840. // Populates response if needed.
  841. void ProcessUpdate(const std::string& resource_type,
  842. const std::string& resource_name,
  843. SubscriptionMap* subscription_map, SentState* sent_state,
  844. absl::optional<DiscoveryResponse>* response) {
  845. const std::string v2_resource_type = TypeUrlToV2(resource_type);
  846. gpr_log(GPR_INFO, "ADS[%p]: Received update for type=%s name=%s", this,
  847. resource_type.c_str(), resource_name.c_str());
  848. auto& subscription_name_map = (*subscription_map)[resource_type];
  849. auto& resource_type_state = parent_->resource_map_[resource_type];
  850. auto& resource_name_map = resource_type_state.resource_name_map;
  851. auto it = subscription_name_map.find(resource_name);
  852. if (it != subscription_name_map.end()) {
  853. SubscriptionState& subscription_state = it->second;
  854. ResourceState& resource_state = resource_name_map[resource_name];
  855. if (ClientNeedsResourceUpdate(resource_type_state, resource_state,
  856. sent_state->resource_type_version,
  857. &subscription_state)) {
  858. gpr_log(GPR_INFO, "ADS[%p]: Sending update for type=%s name=%s", this,
  859. resource_type.c_str(), resource_name.c_str());
  860. response->emplace();
  861. if (resource_state.resource.has_value()) {
  862. auto* resource = (*response)->add_resources();
  863. resource->CopyFrom(resource_state.resource.value());
  864. if (is_v2_) {
  865. resource->set_type_url(v2_resource_type);
  866. }
  867. }
  868. CompleteBuildingDiscoveryResponse(
  869. resource_type, v2_resource_type,
  870. resource_type_state.resource_type_version, subscription_name_map,
  871. {resource_name}, sent_state, &response->value());
  872. }
  873. }
  874. }
  875. // Starting a thread to do blocking read on the stream until cancel.
  876. void BlockingRead(Stream* stream, std::deque<DiscoveryRequest>* requests,
  877. bool* stream_closed) {
  878. DiscoveryRequest request;
  879. bool seen_first_request = false;
  880. while (stream->Read(&request)) {
  881. if (!seen_first_request) {
  882. EXPECT_TRUE(request.has_node());
  883. ASSERT_FALSE(request.node().client_features().empty());
  884. EXPECT_EQ(request.node().client_features(0),
  885. "envoy.lb.does_not_support_overprovisioning");
  886. CheckBuildVersion(request);
  887. seen_first_request = true;
  888. }
  889. {
  890. grpc_core::MutexLock lock(&parent_->ads_mu_);
  891. requests->emplace_back(std::move(request));
  892. }
  893. }
  894. gpr_log(GPR_INFO, "ADS[%p]: Null read, stream closed", this);
  895. grpc_core::MutexLock lock(&parent_->ads_mu_);
  896. *stream_closed = true;
  897. }
  898. // Completing the building a DiscoveryResponse by adding common information
  899. // for all resources and by adding all subscribed resources for LDS and CDS.
  900. void CompleteBuildingDiscoveryResponse(
  901. const std::string& resource_type, const std::string& v2_resource_type,
  902. const int version, const SubscriptionNameMap& subscription_name_map,
  903. const std::set<std::string>& resources_added_to_response,
  904. SentState* sent_state, DiscoveryResponse* response) {
  905. auto& response_state =
  906. parent_->resource_type_response_state_[resource_type];
  907. if (response_state.state == ResponseState::NOT_SENT) {
  908. response_state.state = ResponseState::SENT;
  909. }
  910. response->set_type_url(is_v2_ ? v2_resource_type : resource_type);
  911. response->set_version_info(std::to_string(version));
  912. response->set_nonce(std::to_string(++sent_state->nonce));
  913. if (resource_type == kLdsTypeUrl || resource_type == kCdsTypeUrl) {
  914. // For LDS and CDS we must send back all subscribed resources
  915. // (even the unchanged ones)
  916. for (const auto& p : subscription_name_map) {
  917. const std::string& resource_name = p.first;
  918. if (resources_added_to_response.find(resource_name) ==
  919. resources_added_to_response.end()) {
  920. ResourceNameMap& resource_name_map =
  921. parent_->resource_map_[resource_type].resource_name_map;
  922. const ResourceState& resource_state =
  923. resource_name_map[resource_name];
  924. if (resource_state.resource.has_value()) {
  925. auto* resource = response->add_resources();
  926. resource->CopyFrom(resource_state.resource.value());
  927. if (is_v2_) {
  928. resource->set_type_url(v2_resource_type);
  929. }
  930. }
  931. }
  932. }
  933. }
  934. sent_state->resource_type_version = version;
  935. }
  936. static std::string TypeUrlToV2(const std::string& resource_type) {
  937. if (resource_type == kLdsTypeUrl) return kLdsV2TypeUrl;
  938. if (resource_type == kRdsTypeUrl) return kRdsV2TypeUrl;
  939. if (resource_type == kCdsTypeUrl) return kCdsV2TypeUrl;
  940. if (resource_type == kEdsTypeUrl) return kEdsV2TypeUrl;
  941. return resource_type;
  942. }
  943. static std::string TypeUrlToV3(const std::string& resource_type) {
  944. if (resource_type == kLdsV2TypeUrl) return kLdsTypeUrl;
  945. if (resource_type == kRdsV2TypeUrl) return kRdsTypeUrl;
  946. if (resource_type == kCdsV2TypeUrl) return kCdsTypeUrl;
  947. if (resource_type == kEdsV2TypeUrl) return kEdsTypeUrl;
  948. return resource_type;
  949. }
  950. static void CheckBuildVersion(
  951. const ::envoy::api::v2::DiscoveryRequest& request) {
  952. EXPECT_FALSE(request.node().build_version().empty());
  953. }
  954. static void CheckBuildVersion(
  955. const ::envoy::service::discovery::v3::DiscoveryRequest& request) {}
  956. AdsServiceImpl* parent_;
  957. const bool is_v2_;
  958. };
  959. // Checks whether the client needs to receive a newer version of
  960. // the resource.
  961. static bool ClientNeedsResourceUpdate(
  962. const ResourceTypeState& resource_type_state,
  963. const ResourceState& resource_state, int client_resource_type_version,
  964. SubscriptionState* subscription_state) {
  965. return client_resource_type_version <
  966. resource_type_state.resource_type_version &&
  967. resource_state.resource_type_version <=
  968. resource_type_state.resource_type_version;
  969. }
  970. // Subscribes to a resource if not already subscribed:
  971. // 1. Sets the update_queue field in subscription_state.
  972. // 2. Adds subscription_state to resource_state->subscriptions.
  973. bool MaybeSubscribe(const std::string& resource_type,
  974. const std::string& resource_name,
  975. SubscriptionState* subscription_state,
  976. ResourceState* resource_state,
  977. UpdateQueue* update_queue) {
  978. // The update_queue will be null if we were not previously subscribed.
  979. if (subscription_state->update_queue != nullptr) return false;
  980. subscription_state->update_queue = update_queue;
  981. resource_state->subscriptions.emplace(subscription_state);
  982. gpr_log(GPR_INFO, "ADS[%p]: subscribe to resource type %s name %s state %p",
  983. this, resource_type.c_str(), resource_name.c_str(),
  984. &subscription_state);
  985. return true;
  986. }
  987. // Removes subscriptions for resources no longer present in the
  988. // current request.
  989. void ProcessUnsubscriptions(
  990. const std::string& resource_type,
  991. const std::set<std::string>& resources_in_current_request,
  992. SubscriptionNameMap* subscription_name_map,
  993. ResourceNameMap* resource_name_map) {
  994. for (auto it = subscription_name_map->begin();
  995. it != subscription_name_map->end();) {
  996. const std::string& resource_name = it->first;
  997. SubscriptionState& subscription_state = it->second;
  998. if (resources_in_current_request.find(resource_name) !=
  999. resources_in_current_request.end()) {
  1000. ++it;
  1001. continue;
  1002. }
  1003. gpr_log(GPR_INFO, "ADS[%p]: Unsubscribe to type=%s name=%s state=%p",
  1004. this, resource_type.c_str(), resource_name.c_str(),
  1005. &subscription_state);
  1006. auto resource_it = resource_name_map->find(resource_name);
  1007. GPR_ASSERT(resource_it != resource_name_map->end());
  1008. auto& resource_state = resource_it->second;
  1009. resource_state.subscriptions.erase(&subscription_state);
  1010. if (resource_state.subscriptions.empty() &&
  1011. !resource_state.resource.has_value()) {
  1012. resource_name_map->erase(resource_it);
  1013. }
  1014. it = subscription_name_map->erase(it);
  1015. }
  1016. }
  1017. void AddClient(const std::string& client) {
  1018. grpc_core::MutexLock lock(&clients_mu_);
  1019. clients_.insert(client);
  1020. }
  1021. void RemoveClient(const std::string& client) {
  1022. grpc_core::MutexLock lock(&clients_mu_);
  1023. clients_.erase(client);
  1024. }
  1025. RpcService<::envoy::service::discovery::v2::AggregatedDiscoveryService,
  1026. ::envoy::api::v2::DiscoveryRequest,
  1027. ::envoy::api::v2::DiscoveryResponse>
  1028. v2_rpc_service_;
  1029. RpcService<::envoy::service::discovery::v3::AggregatedDiscoveryService,
  1030. ::envoy::service::discovery::v3::DiscoveryRequest,
  1031. ::envoy::service::discovery::v3::DiscoveryResponse>
  1032. v3_rpc_service_;
  1033. std::atomic_bool seen_v2_client_{false};
  1034. std::atomic_bool seen_v3_client_{false};
  1035. grpc_core::CondVar ads_cond_;
  1036. // Protect the members below.
  1037. grpc_core::Mutex ads_mu_;
  1038. bool ads_done_ = false;
  1039. std::map<std::string /* type_url */, ResponseState>
  1040. resource_type_response_state_;
  1041. std::set<std::string /*resource_type*/> resource_types_to_ignore_;
  1042. std::map<std::string /*resource_type*/, int> resource_type_min_versions_;
  1043. // An instance data member containing the current state of all resources.
  1044. // Note that an entry will exist whenever either of the following is true:
  1045. // - The resource exists (i.e., has been created by SetResource() and has not
  1046. // yet been destroyed by UnsetResource()).
  1047. // - There is at least one subscription for the resource.
  1048. ResourceMap resource_map_;
  1049. grpc_core::Mutex clients_mu_;
  1050. std::set<std::string> clients_;
  1051. };
  1052. class LrsServiceImpl : public std::enable_shared_from_this<LrsServiceImpl> {
  1053. public:
  1054. explicit LrsServiceImpl(int client_load_reporting_interval_seconds)
  1055. : v2_rpc_service_(this),
  1056. v3_rpc_service_(this),
  1057. client_load_reporting_interval_seconds_(
  1058. client_load_reporting_interval_seconds),
  1059. cluster_names_({kDefaultClusterName}) {}
  1060. ::envoy::service::load_stats::v2::LoadReportingService::Service*
  1061. v2_rpc_service() {
  1062. return &v2_rpc_service_;
  1063. }
  1064. ::envoy::service::load_stats::v3::LoadReportingService::Service*
  1065. v3_rpc_service() {
  1066. return &v3_rpc_service_;
  1067. }
  1068. size_t request_count() {
  1069. return v2_rpc_service_.request_count() + v3_rpc_service_.request_count();
  1070. }
  1071. size_t response_count() {
  1072. return v2_rpc_service_.response_count() + v3_rpc_service_.response_count();
  1073. }
  1074. // Must be called before the LRS call is started.
  1075. void set_send_all_clusters(bool send_all_clusters) {
  1076. send_all_clusters_ = send_all_clusters;
  1077. }
  1078. void set_cluster_names(const std::set<std::string>& cluster_names) {
  1079. cluster_names_ = cluster_names;
  1080. }
  1081. void Start() {
  1082. lrs_done_ = false;
  1083. result_queue_.clear();
  1084. }
  1085. void Shutdown() {
  1086. {
  1087. grpc_core::MutexLock lock(&lrs_mu_);
  1088. NotifyDoneWithLrsCallLocked();
  1089. }
  1090. gpr_log(GPR_INFO, "LRS[%p]: shut down", this);
  1091. }
  1092. std::vector<ClientStats> WaitForLoadReport() {
  1093. grpc_core::MutexLock lock(&load_report_mu_);
  1094. grpc_core::CondVar cv;
  1095. if (result_queue_.empty()) {
  1096. load_report_cond_ = &cv;
  1097. load_report_cond_->WaitUntil(&load_report_mu_,
  1098. [this] { return !result_queue_.empty(); });
  1099. load_report_cond_ = nullptr;
  1100. }
  1101. std::vector<ClientStats> result = std::move(result_queue_.front());
  1102. result_queue_.pop_front();
  1103. return result;
  1104. }
  1105. void NotifyDoneWithLrsCall() {
  1106. grpc_core::MutexLock lock(&lrs_mu_);
  1107. NotifyDoneWithLrsCallLocked();
  1108. }
  1109. private:
  1110. template <class RpcApi, class LoadStatsRequest, class LoadStatsResponse>
  1111. class RpcService : public CountedService<typename RpcApi::Service> {
  1112. public:
  1113. using Stream = ServerReaderWriter<LoadStatsResponse, LoadStatsRequest>;
  1114. explicit RpcService(LrsServiceImpl* parent) : parent_(parent) {}
  1115. Status StreamLoadStats(ServerContext* /*context*/,
  1116. Stream* stream) override {
  1117. gpr_log(GPR_INFO, "LRS[%p]: StreamLoadStats starts", this);
  1118. EXPECT_GT(parent_->client_load_reporting_interval_seconds_, 0);
  1119. // Take a reference of the LrsServiceImpl object, reference will go
  1120. // out of scope after this method exits.
  1121. std::shared_ptr<LrsServiceImpl> lrs_service_impl =
  1122. parent_->shared_from_this();
  1123. // Read initial request.
  1124. LoadStatsRequest request;
  1125. if (stream->Read(&request)) {
  1126. CountedService<typename RpcApi::Service>::IncreaseRequestCount();
  1127. // Verify client features.
  1128. EXPECT_THAT(
  1129. request.node().client_features(),
  1130. ::testing::Contains("envoy.lrs.supports_send_all_clusters"));
  1131. // Send initial response.
  1132. LoadStatsResponse response;
  1133. if (parent_->send_all_clusters_) {
  1134. response.set_send_all_clusters(true);
  1135. } else {
  1136. for (const std::string& cluster_name : parent_->cluster_names_) {
  1137. response.add_clusters(cluster_name);
  1138. }
  1139. }
  1140. response.mutable_load_reporting_interval()->set_seconds(
  1141. parent_->client_load_reporting_interval_seconds_);
  1142. stream->Write(response);
  1143. CountedService<typename RpcApi::Service>::IncreaseResponseCount();
  1144. // Wait for report.
  1145. request.Clear();
  1146. while (stream->Read(&request)) {
  1147. gpr_log(GPR_INFO, "LRS[%p]: received client load report message: %s",
  1148. this, request.DebugString().c_str());
  1149. std::vector<ClientStats> stats;
  1150. for (const auto& cluster_stats : request.cluster_stats()) {
  1151. stats.emplace_back(cluster_stats);
  1152. }
  1153. grpc_core::MutexLock lock(&parent_->load_report_mu_);
  1154. parent_->result_queue_.emplace_back(std::move(stats));
  1155. if (parent_->load_report_cond_ != nullptr) {
  1156. parent_->load_report_cond_->Signal();
  1157. }
  1158. }
  1159. // Wait until notified done.
  1160. grpc_core::MutexLock lock(&parent_->lrs_mu_);
  1161. parent_->lrs_cv_.WaitUntil(&parent_->lrs_mu_,
  1162. [this] { return parent_->lrs_done_; });
  1163. }
  1164. gpr_log(GPR_INFO, "LRS[%p]: StreamLoadStats done", this);
  1165. return Status::OK;
  1166. }
  1167. private:
  1168. LrsServiceImpl* parent_;
  1169. };
  1170. void NotifyDoneWithLrsCallLocked() {
  1171. if (!lrs_done_) {
  1172. lrs_done_ = true;
  1173. lrs_cv_.Broadcast();
  1174. }
  1175. }
  1176. RpcService<::envoy::service::load_stats::v2::LoadReportingService,
  1177. ::envoy::service::load_stats::v2::LoadStatsRequest,
  1178. ::envoy::service::load_stats::v2::LoadStatsResponse>
  1179. v2_rpc_service_;
  1180. RpcService<::envoy::service::load_stats::v3::LoadReportingService,
  1181. ::envoy::service::load_stats::v3::LoadStatsRequest,
  1182. ::envoy::service::load_stats::v3::LoadStatsResponse>
  1183. v3_rpc_service_;
  1184. const int client_load_reporting_interval_seconds_;
  1185. bool send_all_clusters_ = false;
  1186. std::set<std::string> cluster_names_;
  1187. grpc_core::CondVar lrs_cv_;
  1188. grpc_core::Mutex lrs_mu_; // Protects lrs_done_.
  1189. bool lrs_done_ = false;
  1190. grpc_core::Mutex load_report_mu_; // Protects the members below.
  1191. grpc_core::CondVar* load_report_cond_ = nullptr;
  1192. std::deque<std::vector<ClientStats>> result_queue_;
  1193. };
  1194. class TestType {
  1195. public:
  1196. TestType(bool use_xds_resolver, bool enable_load_reporting,
  1197. bool enable_rds_testing = false, bool use_v2 = false,
  1198. bool use_xds_credentials = false)
  1199. : use_xds_resolver_(use_xds_resolver),
  1200. enable_load_reporting_(enable_load_reporting),
  1201. enable_rds_testing_(enable_rds_testing),
  1202. use_v2_(use_v2),
  1203. use_xds_credentials_(use_xds_credentials) {}
  1204. bool use_xds_resolver() const { return use_xds_resolver_; }
  1205. bool enable_load_reporting() const { return enable_load_reporting_; }
  1206. bool enable_rds_testing() const { return enable_rds_testing_; }
  1207. bool use_v2() const { return use_v2_; }
  1208. bool use_xds_credentials() const { return use_xds_credentials_; }
  1209. std::string AsString() const {
  1210. std::string retval = (use_xds_resolver_ ? "XdsResolver" : "FakeResolver");
  1211. retval += (use_v2_ ? "V2" : "V3");
  1212. if (enable_load_reporting_) retval += "WithLoadReporting";
  1213. if (enable_rds_testing_) retval += "Rds";
  1214. if (use_xds_credentials_) retval += "XdsCreds";
  1215. return retval;
  1216. }
  1217. private:
  1218. const bool use_xds_resolver_;
  1219. const bool enable_load_reporting_;
  1220. const bool enable_rds_testing_;
  1221. const bool use_v2_;
  1222. const bool use_xds_credentials_;
  1223. };
  1224. std::string ReadFile(const char* file_path) {
  1225. grpc_slice slice;
  1226. GPR_ASSERT(
  1227. GRPC_LOG_IF_ERROR("load_file", grpc_load_file(file_path, 0, &slice)));
  1228. std::string file_contents(grpc_core::StringViewFromSlice(slice));
  1229. grpc_slice_unref(slice);
  1230. return file_contents;
  1231. }
  1232. grpc_core::PemKeyCertPairList ReadTlsIdentityPair(const char* key_path,
  1233. const char* cert_path) {
  1234. return grpc_core::PemKeyCertPairList{
  1235. grpc_core::PemKeyCertPair(ReadFile(key_path), ReadFile(cert_path))};
  1236. }
  1237. // Based on StaticDataCertificateProvider, but provides alternate certificates
  1238. // if the certificate name is not empty.
  1239. class FakeCertificateProvider final : public grpc_tls_certificate_provider {
  1240. public:
  1241. struct CertData {
  1242. std::string root_certificate;
  1243. grpc_core::PemKeyCertPairList identity_key_cert_pairs;
  1244. };
  1245. using CertDataMap = std::map<std::string /*cert_name */, CertData>;
  1246. explicit FakeCertificateProvider(CertDataMap cert_data_map)
  1247. : distributor_(
  1248. grpc_core::MakeRefCounted<grpc_tls_certificate_distributor>()),
  1249. cert_data_map_(std::move(cert_data_map)) {
  1250. distributor_->SetWatchStatusCallback([this](std::string cert_name,
  1251. bool root_being_watched,
  1252. bool identity_being_watched) {
  1253. if (!root_being_watched && !identity_being_watched) return;
  1254. auto it = cert_data_map_.find(cert_name);
  1255. if (it == cert_data_map_.end()) {
  1256. grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
  1257. absl::StrCat("No certificates available for cert_name \"",
  1258. cert_name, "\"")
  1259. .c_str());
  1260. distributor_->SetErrorForCert(cert_name, GRPC_ERROR_REF(error),
  1261. GRPC_ERROR_REF(error));
  1262. GRPC_ERROR_UNREF(error);
  1263. } else {
  1264. absl::optional<std::string> root_certificate;
  1265. absl::optional<grpc_core::PemKeyCertPairList> pem_key_cert_pairs;
  1266. if (root_being_watched) {
  1267. root_certificate = it->second.root_certificate;
  1268. }
  1269. if (identity_being_watched) {
  1270. pem_key_cert_pairs = it->second.identity_key_cert_pairs;
  1271. }
  1272. distributor_->SetKeyMaterials(cert_name, std::move(root_certificate),
  1273. std::move(pem_key_cert_pairs));
  1274. }
  1275. });
  1276. }
  1277. ~FakeCertificateProvider() override {
  1278. distributor_->SetWatchStatusCallback(nullptr);
  1279. }
  1280. grpc_core::RefCountedPtr<grpc_tls_certificate_distributor> distributor()
  1281. const override {
  1282. return distributor_;
  1283. }
  1284. private:
  1285. grpc_core::RefCountedPtr<grpc_tls_certificate_distributor> distributor_;
  1286. CertDataMap cert_data_map_;
  1287. };
  1288. class FakeCertificateProviderFactory
  1289. : public grpc_core::CertificateProviderFactory {
  1290. public:
  1291. class Config : public grpc_core::CertificateProviderFactory::Config {
  1292. public:
  1293. explicit Config(const char* name) : name_(name) {}
  1294. const char* name() const override { return name_; }
  1295. std::string ToString() const override { return "{}"; }
  1296. private:
  1297. const char* name_;
  1298. };
  1299. FakeCertificateProviderFactory(
  1300. const char* name, FakeCertificateProvider::CertDataMap** cert_data_map)
  1301. : name_(name), cert_data_map_(cert_data_map) {
  1302. GPR_ASSERT(cert_data_map != nullptr);
  1303. }
  1304. const char* name() const override { return name_; }
  1305. grpc_core::RefCountedPtr<grpc_core::CertificateProviderFactory::Config>
  1306. CreateCertificateProviderConfig(const grpc_core::Json& config_json,
  1307. grpc_error** error) override {
  1308. return grpc_core::MakeRefCounted<Config>(name_);
  1309. }
  1310. grpc_core::RefCountedPtr<grpc_tls_certificate_provider>
  1311. CreateCertificateProvider(
  1312. grpc_core::RefCountedPtr<grpc_core::CertificateProviderFactory::Config>
  1313. config) override {
  1314. if (*cert_data_map_ == nullptr) return nullptr;
  1315. return grpc_core::MakeRefCounted<FakeCertificateProvider>(**cert_data_map_);
  1316. }
  1317. private:
  1318. const char* name_;
  1319. FakeCertificateProvider::CertDataMap** cert_data_map_;
  1320. };
  1321. // Global variables for each provider.
  1322. FakeCertificateProvider::CertDataMap* g_fake1_cert_data_map = nullptr;
  1323. FakeCertificateProvider::CertDataMap* g_fake2_cert_data_map = nullptr;
  1324. int ServerAuthCheckSchedule(void* /* config_user_data */,
  1325. grpc_tls_server_authorization_check_arg* arg) {
  1326. arg->success = 1;
  1327. arg->status = GRPC_STATUS_OK;
  1328. return 0; /* synchronous check */
  1329. }
  1330. std::shared_ptr<ChannelCredentials> CreateTlsFallbackCredentials() {
  1331. // TODO(yashykt): Switch to using C++ API once b/173823806 is fixed.
  1332. grpc_tls_credentials_options* options = grpc_tls_credentials_options_create();
  1333. grpc_tls_credentials_options_set_server_verification_option(
  1334. options, GRPC_TLS_SKIP_HOSTNAME_VERIFICATION);
  1335. grpc_tls_credentials_options_set_certificate_provider(
  1336. options,
  1337. grpc_core::MakeRefCounted<grpc_core::StaticDataCertificateProvider>(
  1338. ReadFile(kCaCertPath),
  1339. ReadTlsIdentityPair(kServerKeyPath, kServerCertPath))
  1340. .get());
  1341. grpc_tls_credentials_options_watch_root_certs(options);
  1342. grpc_tls_credentials_options_watch_identity_key_cert_pairs(options);
  1343. grpc_tls_server_authorization_check_config* check_config =
  1344. grpc_tls_server_authorization_check_config_create(
  1345. nullptr, ServerAuthCheckSchedule, nullptr, nullptr);
  1346. grpc_tls_credentials_options_set_server_authorization_check_config(
  1347. options, check_config);
  1348. auto channel_creds = std::make_shared<SecureChannelCredentials>(
  1349. grpc_tls_credentials_create(options));
  1350. grpc_tls_server_authorization_check_config_release(check_config);
  1351. return channel_creds;
  1352. }
  1353. class XdsEnd2endTest : public ::testing::TestWithParam<TestType> {
  1354. protected:
  1355. XdsEnd2endTest(size_t num_backends, size_t num_balancers,
  1356. int client_load_reporting_interval_seconds = 100)
  1357. : num_backends_(num_backends),
  1358. num_balancers_(num_balancers),
  1359. client_load_reporting_interval_seconds_(
  1360. client_load_reporting_interval_seconds) {}
  1361. static void SetUpTestCase() {
  1362. // Make the backup poller poll very frequently in order to pick up
  1363. // updates from all the subchannels's FDs.
  1364. GPR_GLOBAL_CONFIG_SET(grpc_client_channel_backup_poll_interval_ms, 1);
  1365. #if TARGET_OS_IPHONE
  1366. // Workaround Apple CFStream bug
  1367. gpr_setenv("grpc_cfstream", "0");
  1368. #endif
  1369. grpc_init();
  1370. }
  1371. static void TearDownTestCase() { grpc_shutdown(); }
  1372. void SetUp() override {
  1373. gpr_setenv("GRPC_XDS_EXPERIMENTAL_V3_SUPPORT", "true");
  1374. gpr_setenv("GRPC_XDS_BOOTSTRAP",
  1375. GetParam().use_v2() ? g_bootstrap_file_v2 : g_bootstrap_file_v3);
  1376. g_port_saver->Reset();
  1377. bool localhost_resolves_to_ipv4 = false;
  1378. bool localhost_resolves_to_ipv6 = false;
  1379. grpc_core::LocalhostResolves(&localhost_resolves_to_ipv4,
  1380. &localhost_resolves_to_ipv6);
  1381. ipv6_only_ = !localhost_resolves_to_ipv4 && localhost_resolves_to_ipv6;
  1382. response_generator_ =
  1383. grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
  1384. // Inject xDS channel response generator.
  1385. lb_channel_response_generator_ =
  1386. grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
  1387. xds_channel_args_to_add_.emplace_back(
  1388. grpc_core::FakeResolverResponseGenerator::MakeChannelArg(
  1389. lb_channel_response_generator_.get()));
  1390. if (xds_resource_does_not_exist_timeout_ms_ > 0) {
  1391. xds_channel_args_to_add_.emplace_back(grpc_channel_arg_integer_create(
  1392. const_cast<char*>(GRPC_ARG_XDS_RESOURCE_DOES_NOT_EXIST_TIMEOUT_MS),
  1393. xds_resource_does_not_exist_timeout_ms_));
  1394. }
  1395. xds_channel_args_.num_args = xds_channel_args_to_add_.size();
  1396. xds_channel_args_.args = xds_channel_args_to_add_.data();
  1397. grpc_core::internal::SetXdsChannelArgsForTest(&xds_channel_args_);
  1398. // Make sure each test creates a new XdsClient instance rather than
  1399. // reusing the one from the previous test. This avoids spurious failures
  1400. // caused when a load reporting test runs after a non-load reporting test
  1401. // and the XdsClient is still talking to the old LRS server, which fails
  1402. // because it's not expecting the client to connect. It also
  1403. // ensures that each test can independently set the global channel
  1404. // args for the xDS channel.
  1405. grpc_core::internal::UnsetGlobalXdsClientForTest();
  1406. // Initialize default xDS resources.
  1407. // Construct LDS resource.
  1408. default_listener_.set_name(kServerName);
  1409. // Construct RDS resource.
  1410. default_route_config_.set_name(kDefaultRouteConfigurationName);
  1411. auto* virtual_host = default_route_config_.add_virtual_hosts();
  1412. virtual_host->add_domains("*");
  1413. auto* route = virtual_host->add_routes();
  1414. route->mutable_match()->set_prefix("");
  1415. route->mutable_route()->set_cluster(kDefaultClusterName);
  1416. // Construct CDS resource.
  1417. default_cluster_.set_name(kDefaultClusterName);
  1418. default_cluster_.set_type(Cluster::EDS);
  1419. auto* eds_config = default_cluster_.mutable_eds_cluster_config();
  1420. eds_config->mutable_eds_config()->mutable_ads();
  1421. eds_config->set_service_name(kDefaultEdsServiceName);
  1422. default_cluster_.set_lb_policy(Cluster::ROUND_ROBIN);
  1423. if (GetParam().enable_load_reporting()) {
  1424. default_cluster_.mutable_lrs_server()->mutable_self();
  1425. }
  1426. // Start the backends.
  1427. for (size_t i = 0; i < num_backends_; ++i) {
  1428. backends_.emplace_back(new BackendServerThread);
  1429. backends_.back()->Start();
  1430. }
  1431. // Start the load balancers.
  1432. for (size_t i = 0; i < num_balancers_; ++i) {
  1433. balancers_.emplace_back(
  1434. new BalancerServerThread(GetParam().enable_load_reporting()
  1435. ? client_load_reporting_interval_seconds_
  1436. : 0));
  1437. balancers_.back()->Start();
  1438. // Initialize resources.
  1439. SetListenerAndRouteConfiguration(i, default_listener_,
  1440. default_route_config_);
  1441. balancers_.back()->ads_service()->SetCdsResource(default_cluster_);
  1442. }
  1443. ResetStub();
  1444. }
  1445. const char* DefaultEdsServiceName() const {
  1446. return GetParam().use_xds_resolver() ? kDefaultEdsServiceName : kServerName;
  1447. }
  1448. void TearDown() override {
  1449. ShutdownAllBackends();
  1450. for (auto& balancer : balancers_) balancer->Shutdown();
  1451. // Clear global xDS channel args, since they will go out of scope
  1452. // when this test object is destroyed.
  1453. grpc_core::internal::SetXdsChannelArgsForTest(nullptr);
  1454. }
  1455. void StartAllBackends() {
  1456. for (auto& backend : backends_) backend->Start();
  1457. }
  1458. void StartBackend(size_t index) { backends_[index]->Start(); }
  1459. void ShutdownAllBackends() {
  1460. for (auto& backend : backends_) backend->Shutdown();
  1461. }
  1462. void ShutdownBackend(size_t index) { backends_[index]->Shutdown(); }
  1463. void ResetStub(int failover_timeout = 0) {
  1464. channel_ = CreateChannel(failover_timeout);
  1465. stub_ = grpc::testing::EchoTestService::NewStub(channel_);
  1466. stub1_ = grpc::testing::EchoTest1Service::NewStub(channel_);
  1467. stub2_ = grpc::testing::EchoTest2Service::NewStub(channel_);
  1468. }
  1469. std::shared_ptr<Channel> CreateChannel(
  1470. int failover_timeout = 0, const char* server_name = kServerName,
  1471. grpc_core::FakeResolverResponseGenerator* response_generator = nullptr) {
  1472. ChannelArguments args;
  1473. if (failover_timeout > 0) {
  1474. args.SetInt(GRPC_ARG_PRIORITY_FAILOVER_TIMEOUT_MS, failover_timeout);
  1475. }
  1476. // If the parent channel is using the fake resolver, we inject the
  1477. // response generator here.
  1478. if (!GetParam().use_xds_resolver()) {
  1479. if (response_generator == nullptr) {
  1480. response_generator = response_generator_.get();
  1481. }
  1482. args.SetPointer(GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR,
  1483. response_generator);
  1484. }
  1485. std::string uri = absl::StrCat(
  1486. GetParam().use_xds_resolver() ? "xds" : "fake", ":///", server_name);
  1487. std::shared_ptr<ChannelCredentials> channel_creds =
  1488. GetParam().use_xds_credentials()
  1489. ? experimental::XdsCredentials(CreateTlsFallbackCredentials())
  1490. : std::make_shared<SecureChannelCredentials>(
  1491. grpc_fake_transport_security_credentials_create());
  1492. return ::grpc::CreateCustomChannel(uri, channel_creds, args);
  1493. }
  1494. enum RpcService {
  1495. SERVICE_ECHO,
  1496. SERVICE_ECHO1,
  1497. SERVICE_ECHO2,
  1498. };
  1499. enum RpcMethod {
  1500. METHOD_ECHO,
  1501. METHOD_ECHO1,
  1502. METHOD_ECHO2,
  1503. };
  1504. struct RpcOptions {
  1505. RpcService service = SERVICE_ECHO;
  1506. RpcMethod method = METHOD_ECHO;
  1507. int timeout_ms = 1000;
  1508. bool wait_for_ready = false;
  1509. bool server_fail = false;
  1510. std::vector<std::pair<std::string, std::string>> metadata;
  1511. RpcOptions() {}
  1512. RpcOptions& set_rpc_service(RpcService rpc_service) {
  1513. service = rpc_service;
  1514. return *this;
  1515. }
  1516. RpcOptions& set_rpc_method(RpcMethod rpc_method) {
  1517. method = rpc_method;
  1518. return *this;
  1519. }
  1520. RpcOptions& set_timeout_ms(int rpc_timeout_ms) {
  1521. timeout_ms = rpc_timeout_ms;
  1522. return *this;
  1523. }
  1524. RpcOptions& set_wait_for_ready(bool rpc_wait_for_ready) {
  1525. wait_for_ready = rpc_wait_for_ready;
  1526. return *this;
  1527. }
  1528. RpcOptions& set_server_fail(bool rpc_server_fail) {
  1529. server_fail = rpc_server_fail;
  1530. return *this;
  1531. }
  1532. RpcOptions& set_metadata(
  1533. std::vector<std::pair<std::string, std::string>> rpc_metadata) {
  1534. metadata = std::move(rpc_metadata);
  1535. return *this;
  1536. }
  1537. };
  1538. template <typename Stub>
  1539. Status SendRpcMethod(Stub* stub, const RpcOptions& rpc_options,
  1540. ClientContext* context, EchoRequest& request,
  1541. EchoResponse* response) {
  1542. switch (rpc_options.method) {
  1543. case METHOD_ECHO:
  1544. return (*stub)->Echo(context, request, response);
  1545. case METHOD_ECHO1:
  1546. return (*stub)->Echo1(context, request, response);
  1547. case METHOD_ECHO2:
  1548. return (*stub)->Echo2(context, request, response);
  1549. }
  1550. }
  1551. void ResetBackendCounters(size_t start_index = 0, size_t stop_index = 0) {
  1552. if (stop_index == 0) stop_index = backends_.size();
  1553. for (size_t i = start_index; i < stop_index; ++i) {
  1554. backends_[i]->backend_service()->ResetCounters();
  1555. backends_[i]->backend_service1()->ResetCounters();
  1556. backends_[i]->backend_service2()->ResetCounters();
  1557. }
  1558. }
  1559. bool SeenAllBackends(size_t start_index = 0, size_t stop_index = 0,
  1560. const RpcOptions& rpc_options = RpcOptions()) {
  1561. if (stop_index == 0) stop_index = backends_.size();
  1562. for (size_t i = start_index; i < stop_index; ++i) {
  1563. switch (rpc_options.service) {
  1564. case SERVICE_ECHO:
  1565. if (backends_[i]->backend_service()->request_count() == 0) {
  1566. return false;
  1567. }
  1568. break;
  1569. case SERVICE_ECHO1:
  1570. if (backends_[i]->backend_service1()->request_count() == 0) {
  1571. return false;
  1572. }
  1573. break;
  1574. case SERVICE_ECHO2:
  1575. if (backends_[i]->backend_service2()->request_count() == 0) {
  1576. return false;
  1577. }
  1578. break;
  1579. }
  1580. }
  1581. return true;
  1582. }
  1583. void SendRpcAndCount(int* num_total, int* num_ok, int* num_failure,
  1584. int* num_drops,
  1585. const RpcOptions& rpc_options = RpcOptions()) {
  1586. const Status status = SendRpc(rpc_options);
  1587. if (status.ok()) {
  1588. ++*num_ok;
  1589. } else {
  1590. if (status.error_message() == "Call dropped by load balancing policy") {
  1591. ++*num_drops;
  1592. } else {
  1593. ++*num_failure;
  1594. }
  1595. }
  1596. ++*num_total;
  1597. }
  1598. std::tuple<int, int, int> WaitForAllBackends(
  1599. size_t start_index = 0, size_t stop_index = 0, bool reset_counters = true,
  1600. const RpcOptions& rpc_options = RpcOptions(),
  1601. bool allow_failures = false) {
  1602. int num_ok = 0;
  1603. int num_failure = 0;
  1604. int num_drops = 0;
  1605. int num_total = 0;
  1606. while (!SeenAllBackends(start_index, stop_index, rpc_options)) {
  1607. SendRpcAndCount(&num_total, &num_ok, &num_failure, &num_drops,
  1608. rpc_options);
  1609. }
  1610. if (reset_counters) ResetBackendCounters();
  1611. gpr_log(GPR_INFO,
  1612. "Performed %d warm up requests against the backends. "
  1613. "%d succeeded, %d failed, %d dropped.",
  1614. num_total, num_ok, num_failure, num_drops);
  1615. if (!allow_failures) EXPECT_EQ(num_failure, 0);
  1616. return std::make_tuple(num_ok, num_failure, num_drops);
  1617. }
  1618. void WaitForBackend(size_t backend_idx, bool reset_counters = true,
  1619. bool require_success = false) {
  1620. gpr_log(GPR_INFO, "========= WAITING FOR BACKEND %lu ==========",
  1621. static_cast<unsigned long>(backend_idx));
  1622. do {
  1623. Status status = SendRpc();
  1624. if (require_success) {
  1625. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  1626. << " message=" << status.error_message();
  1627. }
  1628. } while (backends_[backend_idx]->backend_service()->request_count() == 0);
  1629. if (reset_counters) ResetBackendCounters();
  1630. gpr_log(GPR_INFO, "========= BACKEND %lu READY ==========",
  1631. static_cast<unsigned long>(backend_idx));
  1632. }
  1633. grpc_core::ServerAddressList CreateAddressListFromPortList(
  1634. const std::vector<int>& ports) {
  1635. grpc_core::ServerAddressList addresses;
  1636. for (int port : ports) {
  1637. absl::StatusOr<grpc_core::URI> lb_uri = grpc_core::URI::Parse(
  1638. absl::StrCat(ipv6_only_ ? "ipv6:[::1]:" : "ipv4:127.0.0.1:", port));
  1639. GPR_ASSERT(lb_uri.ok());
  1640. grpc_resolved_address address;
  1641. GPR_ASSERT(grpc_parse_uri(*lb_uri, &address));
  1642. addresses.emplace_back(address.addr, address.len, nullptr);
  1643. }
  1644. return addresses;
  1645. }
  1646. void SetNextResolution(
  1647. const std::vector<int>& ports,
  1648. grpc_core::FakeResolverResponseGenerator* response_generator = nullptr) {
  1649. if (GetParam().use_xds_resolver()) return; // Not used with xds resolver.
  1650. grpc_core::ExecCtx exec_ctx;
  1651. grpc_core::Resolver::Result result;
  1652. result.addresses = CreateAddressListFromPortList(ports);
  1653. grpc_error* error = GRPC_ERROR_NONE;
  1654. const char* service_config_json =
  1655. GetParam().enable_load_reporting()
  1656. ? kDefaultServiceConfig
  1657. : kDefaultServiceConfigWithoutLoadReporting;
  1658. result.service_config =
  1659. grpc_core::ServiceConfig::Create(nullptr, service_config_json, &error);
  1660. ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_string(error);
  1661. ASSERT_NE(result.service_config.get(), nullptr);
  1662. if (response_generator == nullptr) {
  1663. response_generator = response_generator_.get();
  1664. }
  1665. response_generator->SetResponse(std::move(result));
  1666. }
  1667. void SetNextResolutionForLbChannelAllBalancers(
  1668. const char* service_config_json = nullptr,
  1669. const char* expected_targets = nullptr) {
  1670. std::vector<int> ports;
  1671. for (size_t i = 0; i < balancers_.size(); ++i) {
  1672. ports.emplace_back(balancers_[i]->port());
  1673. }
  1674. SetNextResolutionForLbChannel(ports, service_config_json, expected_targets);
  1675. }
  1676. void SetNextResolutionForLbChannel(const std::vector<int>& ports,
  1677. const char* service_config_json = nullptr,
  1678. const char* expected_targets = nullptr) {
  1679. grpc_core::ExecCtx exec_ctx;
  1680. grpc_core::Resolver::Result result;
  1681. result.addresses = CreateAddressListFromPortList(ports);
  1682. if (service_config_json != nullptr) {
  1683. grpc_error* error = GRPC_ERROR_NONE;
  1684. result.service_config = grpc_core::ServiceConfig::Create(
  1685. nullptr, service_config_json, &error);
  1686. ASSERT_NE(result.service_config.get(), nullptr);
  1687. ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_string(error);
  1688. }
  1689. if (expected_targets != nullptr) {
  1690. grpc_arg expected_targets_arg = grpc_channel_arg_string_create(
  1691. const_cast<char*>(GRPC_ARG_FAKE_SECURITY_EXPECTED_TARGETS),
  1692. const_cast<char*>(expected_targets));
  1693. result.args =
  1694. grpc_channel_args_copy_and_add(nullptr, &expected_targets_arg, 1);
  1695. }
  1696. lb_channel_response_generator_->SetResponse(std::move(result));
  1697. }
  1698. void SetNextReresolutionResponse(const std::vector<int>& ports) {
  1699. grpc_core::ExecCtx exec_ctx;
  1700. grpc_core::Resolver::Result result;
  1701. result.addresses = CreateAddressListFromPortList(ports);
  1702. response_generator_->SetReresolutionResponse(std::move(result));
  1703. }
  1704. const std::vector<int> GetBackendPorts(size_t start_index = 0,
  1705. size_t stop_index = 0) const {
  1706. if (stop_index == 0) stop_index = backends_.size();
  1707. std::vector<int> backend_ports;
  1708. for (size_t i = start_index; i < stop_index; ++i) {
  1709. backend_ports.push_back(backends_[i]->port());
  1710. }
  1711. return backend_ports;
  1712. }
  1713. Status SendRpc(const RpcOptions& rpc_options = RpcOptions(),
  1714. EchoResponse* response = nullptr) {
  1715. const bool local_response = (response == nullptr);
  1716. if (local_response) response = new EchoResponse;
  1717. EchoRequest request;
  1718. ClientContext context;
  1719. for (const auto& metadata : rpc_options.metadata) {
  1720. context.AddMetadata(metadata.first, metadata.second);
  1721. }
  1722. if (rpc_options.timeout_ms != 0) {
  1723. context.set_deadline(
  1724. grpc_timeout_milliseconds_to_deadline(rpc_options.timeout_ms));
  1725. }
  1726. if (rpc_options.wait_for_ready) context.set_wait_for_ready(true);
  1727. request.set_message(kRequestMessage);
  1728. if (rpc_options.server_fail) {
  1729. request.mutable_param()->mutable_expected_error()->set_code(
  1730. GRPC_STATUS_FAILED_PRECONDITION);
  1731. }
  1732. Status status;
  1733. switch (rpc_options.service) {
  1734. case SERVICE_ECHO:
  1735. status =
  1736. SendRpcMethod(&stub_, rpc_options, &context, request, response);
  1737. break;
  1738. case SERVICE_ECHO1:
  1739. status =
  1740. SendRpcMethod(&stub1_, rpc_options, &context, request, response);
  1741. break;
  1742. case SERVICE_ECHO2:
  1743. status =
  1744. SendRpcMethod(&stub2_, rpc_options, &context, request, response);
  1745. break;
  1746. }
  1747. if (local_response) delete response;
  1748. return status;
  1749. }
  1750. void CheckRpcSendOk(const size_t times = 1,
  1751. const RpcOptions& rpc_options = RpcOptions()) {
  1752. for (size_t i = 0; i < times; ++i) {
  1753. EchoResponse response;
  1754. const Status status = SendRpc(rpc_options, &response);
  1755. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  1756. << " message=" << status.error_message();
  1757. EXPECT_EQ(response.message(), kRequestMessage);
  1758. }
  1759. }
  1760. void CheckRpcSendFailure(
  1761. const size_t times = 1, const RpcOptions& rpc_options = RpcOptions(),
  1762. const StatusCode expected_error_code = StatusCode::OK) {
  1763. for (size_t i = 0; i < times; ++i) {
  1764. const Status status = SendRpc(rpc_options);
  1765. EXPECT_FALSE(status.ok());
  1766. if (expected_error_code != StatusCode::OK) {
  1767. EXPECT_EQ(expected_error_code, status.error_code());
  1768. }
  1769. }
  1770. }
  1771. static Listener BuildListener(const RouteConfiguration& route_config) {
  1772. HttpConnectionManager http_connection_manager;
  1773. *(http_connection_manager.mutable_route_config()) = route_config;
  1774. Listener listener;
  1775. listener.set_name(kServerName);
  1776. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  1777. http_connection_manager);
  1778. return listener;
  1779. }
  1780. ClusterLoadAssignment BuildEdsResource(
  1781. const AdsServiceImpl::EdsResourceArgs& args,
  1782. const char* eds_service_name = kDefaultEdsServiceName) {
  1783. ClusterLoadAssignment assignment;
  1784. assignment.set_cluster_name(eds_service_name);
  1785. for (const auto& locality : args.locality_list) {
  1786. auto* endpoints = assignment.add_endpoints();
  1787. endpoints->mutable_load_balancing_weight()->set_value(locality.lb_weight);
  1788. endpoints->set_priority(locality.priority);
  1789. endpoints->mutable_locality()->set_region(kDefaultLocalityRegion);
  1790. endpoints->mutable_locality()->set_zone(kDefaultLocalityZone);
  1791. endpoints->mutable_locality()->set_sub_zone(locality.sub_zone);
  1792. for (size_t i = 0; i < locality.ports.size(); ++i) {
  1793. const int& port = locality.ports[i];
  1794. auto* lb_endpoints = endpoints->add_lb_endpoints();
  1795. if (locality.health_statuses.size() > i &&
  1796. locality.health_statuses[i] != HealthStatus::UNKNOWN) {
  1797. lb_endpoints->set_health_status(locality.health_statuses[i]);
  1798. }
  1799. auto* endpoint = lb_endpoints->mutable_endpoint();
  1800. auto* address = endpoint->mutable_address();
  1801. auto* socket_address = address->mutable_socket_address();
  1802. socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
  1803. socket_address->set_port_value(port);
  1804. }
  1805. }
  1806. if (!args.drop_categories.empty()) {
  1807. auto* policy = assignment.mutable_policy();
  1808. for (const auto& p : args.drop_categories) {
  1809. const std::string& name = p.first;
  1810. const uint32_t parts_per_million = p.second;
  1811. auto* drop_overload = policy->add_drop_overloads();
  1812. drop_overload->set_category(name);
  1813. auto* drop_percentage = drop_overload->mutable_drop_percentage();
  1814. drop_percentage->set_numerator(parts_per_million);
  1815. drop_percentage->set_denominator(args.drop_denominator);
  1816. }
  1817. }
  1818. return assignment;
  1819. }
  1820. void SetListenerAndRouteConfiguration(
  1821. int idx, Listener listener, const RouteConfiguration& route_config) {
  1822. auto* api_listener =
  1823. listener.mutable_api_listener()->mutable_api_listener();
  1824. HttpConnectionManager http_connection_manager;
  1825. api_listener->UnpackTo(&http_connection_manager);
  1826. if (GetParam().enable_rds_testing()) {
  1827. auto* rds = http_connection_manager.mutable_rds();
  1828. rds->set_route_config_name(kDefaultRouteConfigurationName);
  1829. rds->mutable_config_source()->mutable_ads();
  1830. balancers_[idx]->ads_service()->SetRdsResource(route_config);
  1831. } else {
  1832. *http_connection_manager.mutable_route_config() = route_config;
  1833. }
  1834. api_listener->PackFrom(http_connection_manager);
  1835. balancers_[idx]->ads_service()->SetLdsResource(listener);
  1836. }
  1837. void SetRouteConfiguration(int idx, const RouteConfiguration& route_config) {
  1838. if (GetParam().enable_rds_testing()) {
  1839. balancers_[idx]->ads_service()->SetRdsResource(route_config);
  1840. } else {
  1841. balancers_[idx]->ads_service()->SetLdsResource(
  1842. BuildListener(route_config));
  1843. }
  1844. }
  1845. AdsServiceImpl::ResponseState RouteConfigurationResponseState(int idx) const {
  1846. AdsServiceImpl* ads_service = balancers_[idx]->ads_service();
  1847. if (GetParam().enable_rds_testing()) {
  1848. return ads_service->rds_response_state();
  1849. }
  1850. return ads_service->lds_response_state();
  1851. }
  1852. public:
  1853. // This method could benefit test subclasses; to make it accessible
  1854. // via bind with a qualified name, it needs to be public.
  1855. void SetEdsResourceWithDelay(size_t i,
  1856. const ClusterLoadAssignment& assignment,
  1857. int delay_ms) {
  1858. GPR_ASSERT(delay_ms > 0);
  1859. gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(delay_ms));
  1860. balancers_[i]->ads_service()->SetEdsResource(assignment);
  1861. }
  1862. protected:
  1863. class ServerThread {
  1864. public:
  1865. ServerThread() : port_(g_port_saver->GetPort()) {}
  1866. virtual ~ServerThread(){};
  1867. void Start() {
  1868. gpr_log(GPR_INFO, "starting %s server on port %d", Type(), port_);
  1869. GPR_ASSERT(!running_);
  1870. running_ = true;
  1871. StartAllServices();
  1872. grpc_core::Mutex mu;
  1873. // We need to acquire the lock here in order to prevent the notify_one
  1874. // by ServerThread::Serve from firing before the wait below is hit.
  1875. grpc_core::MutexLock lock(&mu);
  1876. grpc_core::CondVar cond;
  1877. thread_ = absl::make_unique<std::thread>(
  1878. std::bind(&ServerThread::Serve, this, &mu, &cond));
  1879. cond.Wait(&mu);
  1880. gpr_log(GPR_INFO, "%s server startup complete", Type());
  1881. }
  1882. void Serve(grpc_core::Mutex* mu, grpc_core::CondVar* cond) {
  1883. // We need to acquire the lock here in order to prevent the notify_one
  1884. // below from firing before its corresponding wait is executed.
  1885. grpc_core::MutexLock lock(mu);
  1886. std::ostringstream server_address;
  1887. server_address << "localhost:" << port_;
  1888. ServerBuilder builder;
  1889. builder.AddListeningPort(server_address.str(), Credentials());
  1890. RegisterAllServices(&builder);
  1891. server_ = builder.BuildAndStart();
  1892. cond->Signal();
  1893. }
  1894. void Shutdown() {
  1895. if (!running_) return;
  1896. gpr_log(GPR_INFO, "%s about to shutdown", Type());
  1897. ShutdownAllServices();
  1898. server_->Shutdown(grpc_timeout_milliseconds_to_deadline(0));
  1899. thread_->join();
  1900. gpr_log(GPR_INFO, "%s shutdown completed", Type());
  1901. running_ = false;
  1902. }
  1903. virtual std::shared_ptr<ServerCredentials> Credentials() {
  1904. return std::make_shared<SecureServerCredentials>(
  1905. grpc_fake_transport_security_server_credentials_create());
  1906. }
  1907. int port() const { return port_; }
  1908. private:
  1909. virtual void RegisterAllServices(ServerBuilder* builder) = 0;
  1910. virtual void StartAllServices() = 0;
  1911. virtual void ShutdownAllServices() = 0;
  1912. virtual const char* Type() = 0;
  1913. const int port_;
  1914. std::unique_ptr<Server> server_;
  1915. std::unique_ptr<std::thread> thread_;
  1916. bool running_ = false;
  1917. };
  1918. class BackendServerThread : public ServerThread {
  1919. public:
  1920. BackendServiceImpl<::grpc::testing::EchoTestService::Service>*
  1921. backend_service() {
  1922. return &backend_service_;
  1923. }
  1924. BackendServiceImpl<::grpc::testing::EchoTest1Service::Service>*
  1925. backend_service1() {
  1926. return &backend_service1_;
  1927. }
  1928. BackendServiceImpl<::grpc::testing::EchoTest2Service::Service>*
  1929. backend_service2() {
  1930. return &backend_service2_;
  1931. }
  1932. std::shared_ptr<ServerCredentials> Credentials() override {
  1933. if (GetParam().use_xds_credentials()) {
  1934. std::string root_cert = ReadFile(kCaCertPath);
  1935. std::string identity_cert = ReadFile(kServerCertPath);
  1936. std::string private_key = ReadFile(kServerKeyPath);
  1937. std::vector<experimental::IdentityKeyCertPair> identity_key_cert_pairs =
  1938. {{private_key, identity_cert}};
  1939. auto certificate_provider =
  1940. std::make_shared<grpc::experimental::StaticDataCertificateProvider>(
  1941. root_cert, identity_key_cert_pairs);
  1942. grpc::experimental::TlsServerCredentialsOptions options(
  1943. certificate_provider);
  1944. options.watch_root_certs();
  1945. options.watch_identity_key_cert_pairs();
  1946. options.set_cert_request_type(
  1947. GRPC_SSL_REQUEST_CLIENT_CERTIFICATE_AND_VERIFY);
  1948. return grpc::experimental::TlsServerCredentials(options);
  1949. }
  1950. return ServerThread::Credentials();
  1951. }
  1952. private:
  1953. void RegisterAllServices(ServerBuilder* builder) override {
  1954. builder->RegisterService(&backend_service_);
  1955. builder->RegisterService(&backend_service1_);
  1956. builder->RegisterService(&backend_service2_);
  1957. }
  1958. void StartAllServices() override {
  1959. backend_service_.Start();
  1960. backend_service1_.Start();
  1961. backend_service2_.Start();
  1962. }
  1963. void ShutdownAllServices() override {
  1964. backend_service_.Shutdown();
  1965. backend_service1_.Shutdown();
  1966. backend_service2_.Shutdown();
  1967. }
  1968. const char* Type() override { return "Backend"; }
  1969. BackendServiceImpl<::grpc::testing::EchoTestService::Service>
  1970. backend_service_;
  1971. BackendServiceImpl<::grpc::testing::EchoTest1Service::Service>
  1972. backend_service1_;
  1973. BackendServiceImpl<::grpc::testing::EchoTest2Service::Service>
  1974. backend_service2_;
  1975. };
  1976. class BalancerServerThread : public ServerThread {
  1977. public:
  1978. explicit BalancerServerThread(int client_load_reporting_interval = 0)
  1979. : ads_service_(new AdsServiceImpl()),
  1980. lrs_service_(new LrsServiceImpl(client_load_reporting_interval)) {}
  1981. AdsServiceImpl* ads_service() { return ads_service_.get(); }
  1982. LrsServiceImpl* lrs_service() { return lrs_service_.get(); }
  1983. private:
  1984. void RegisterAllServices(ServerBuilder* builder) override {
  1985. builder->RegisterService(ads_service_->v2_rpc_service());
  1986. builder->RegisterService(ads_service_->v3_rpc_service());
  1987. builder->RegisterService(lrs_service_->v2_rpc_service());
  1988. builder->RegisterService(lrs_service_->v3_rpc_service());
  1989. }
  1990. void StartAllServices() override {
  1991. ads_service_->Start();
  1992. lrs_service_->Start();
  1993. }
  1994. void ShutdownAllServices() override {
  1995. ads_service_->Shutdown();
  1996. lrs_service_->Shutdown();
  1997. }
  1998. const char* Type() override { return "Balancer"; }
  1999. std::shared_ptr<AdsServiceImpl> ads_service_;
  2000. std::shared_ptr<LrsServiceImpl> lrs_service_;
  2001. };
  2002. class LongRunningRpc {
  2003. public:
  2004. void StartRpc(grpc::testing::EchoTestService::Stub* stub) {
  2005. sender_thread_ = std::thread([this, stub]() {
  2006. EchoResponse response;
  2007. EchoRequest request;
  2008. request.mutable_param()->set_client_cancel_after_us(1 * 1000 * 1000);
  2009. request.set_message(kRequestMessage);
  2010. (void)stub->Echo(&context_, request, &response);
  2011. });
  2012. }
  2013. void CancelRpc() {
  2014. context_.TryCancel();
  2015. sender_thread_.join();
  2016. }
  2017. private:
  2018. std::thread sender_thread_;
  2019. ClientContext context_;
  2020. };
  2021. const size_t num_backends_;
  2022. const size_t num_balancers_;
  2023. const int client_load_reporting_interval_seconds_;
  2024. bool ipv6_only_ = false;
  2025. std::shared_ptr<Channel> channel_;
  2026. std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
  2027. std::unique_ptr<grpc::testing::EchoTest1Service::Stub> stub1_;
  2028. std::unique_ptr<grpc::testing::EchoTest2Service::Stub> stub2_;
  2029. std::vector<std::unique_ptr<BackendServerThread>> backends_;
  2030. std::vector<std::unique_ptr<BalancerServerThread>> balancers_;
  2031. grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
  2032. response_generator_;
  2033. grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
  2034. lb_channel_response_generator_;
  2035. int xds_resource_does_not_exist_timeout_ms_ = 0;
  2036. absl::InlinedVector<grpc_arg, 2> xds_channel_args_to_add_;
  2037. grpc_channel_args xds_channel_args_;
  2038. Listener default_listener_;
  2039. RouteConfiguration default_route_config_;
  2040. Cluster default_cluster_;
  2041. };
  2042. class BasicTest : public XdsEnd2endTest {
  2043. public:
  2044. BasicTest() : XdsEnd2endTest(4, 1) {}
  2045. };
  2046. // Tests that the balancer sends the correct response to the client, and the
  2047. // client sends RPCs to the backends using the default child policy.
  2048. TEST_P(BasicTest, Vanilla) {
  2049. SetNextResolution({});
  2050. SetNextResolutionForLbChannelAllBalancers();
  2051. const size_t kNumRpcsPerAddress = 100;
  2052. AdsServiceImpl::EdsResourceArgs args({
  2053. {"locality0", GetBackendPorts()},
  2054. });
  2055. balancers_[0]->ads_service()->SetEdsResource(
  2056. BuildEdsResource(args, DefaultEdsServiceName()));
  2057. // Make sure that trying to connect works without a call.
  2058. channel_->GetState(true /* try_to_connect */);
  2059. // We need to wait for all backends to come online.
  2060. WaitForAllBackends();
  2061. // Send kNumRpcsPerAddress RPCs per server.
  2062. CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
  2063. // Each backend should have gotten 100 requests.
  2064. for (size_t i = 0; i < backends_.size(); ++i) {
  2065. EXPECT_EQ(kNumRpcsPerAddress,
  2066. backends_[i]->backend_service()->request_count());
  2067. }
  2068. // Check LB policy name for the channel.
  2069. EXPECT_EQ(
  2070. (GetParam().use_xds_resolver() ? "xds_cluster_manager_experimental"
  2071. : "xds_cluster_resolver_experimental"),
  2072. channel_->GetLoadBalancingPolicyName());
  2073. }
  2074. TEST_P(BasicTest, IgnoresUnhealthyEndpoints) {
  2075. SetNextResolution({});
  2076. SetNextResolutionForLbChannelAllBalancers();
  2077. const size_t kNumRpcsPerAddress = 100;
  2078. AdsServiceImpl::EdsResourceArgs args({
  2079. {"locality0",
  2080. GetBackendPorts(),
  2081. kDefaultLocalityWeight,
  2082. kDefaultLocalityPriority,
  2083. {HealthStatus::DRAINING}},
  2084. });
  2085. balancers_[0]->ads_service()->SetEdsResource(
  2086. BuildEdsResource(args, DefaultEdsServiceName()));
  2087. // Make sure that trying to connect works without a call.
  2088. channel_->GetState(true /* try_to_connect */);
  2089. // We need to wait for all backends to come online.
  2090. WaitForAllBackends(/*start_index=*/1);
  2091. // Send kNumRpcsPerAddress RPCs per server.
  2092. CheckRpcSendOk(kNumRpcsPerAddress * (num_backends_ - 1));
  2093. // Each backend should have gotten 100 requests.
  2094. for (size_t i = 1; i < backends_.size(); ++i) {
  2095. EXPECT_EQ(kNumRpcsPerAddress,
  2096. backends_[i]->backend_service()->request_count());
  2097. }
  2098. }
  2099. // Tests that subchannel sharing works when the same backend is listed multiple
  2100. // times.
  2101. TEST_P(BasicTest, SameBackendListedMultipleTimes) {
  2102. SetNextResolution({});
  2103. SetNextResolutionForLbChannelAllBalancers();
  2104. // Same backend listed twice.
  2105. std::vector<int> ports(2, backends_[0]->port());
  2106. AdsServiceImpl::EdsResourceArgs args({
  2107. {"locality0", ports},
  2108. });
  2109. const size_t kNumRpcsPerAddress = 10;
  2110. balancers_[0]->ads_service()->SetEdsResource(
  2111. BuildEdsResource(args, DefaultEdsServiceName()));
  2112. // We need to wait for the backend to come online.
  2113. WaitForBackend(0);
  2114. // Send kNumRpcsPerAddress RPCs per server.
  2115. CheckRpcSendOk(kNumRpcsPerAddress * ports.size());
  2116. // Backend should have gotten 20 requests.
  2117. EXPECT_EQ(kNumRpcsPerAddress * ports.size(),
  2118. backends_[0]->backend_service()->request_count());
  2119. // And they should have come from a single client port, because of
  2120. // subchannel sharing.
  2121. EXPECT_EQ(1UL, backends_[0]->backend_service()->clients().size());
  2122. }
  2123. // Tests that RPCs will be blocked until a non-empty serverlist is received.
  2124. TEST_P(BasicTest, InitiallyEmptyServerlist) {
  2125. SetNextResolution({});
  2126. SetNextResolutionForLbChannelAllBalancers();
  2127. const int kServerlistDelayMs = 500 * grpc_test_slowdown_factor();
  2128. const int kCallDeadlineMs = kServerlistDelayMs * 2;
  2129. // First response is an empty serverlist, sent right away.
  2130. AdsServiceImpl::EdsResourceArgs::Locality empty_locality("locality0", {});
  2131. AdsServiceImpl::EdsResourceArgs args({
  2132. empty_locality,
  2133. });
  2134. balancers_[0]->ads_service()->SetEdsResource(
  2135. BuildEdsResource(args, DefaultEdsServiceName()));
  2136. // Send non-empty serverlist only after kServerlistDelayMs.
  2137. args = AdsServiceImpl::EdsResourceArgs({
  2138. {"locality0", GetBackendPorts()},
  2139. });
  2140. std::thread delayed_resource_setter(std::bind(
  2141. &BasicTest::SetEdsResourceWithDelay, this, 0,
  2142. BuildEdsResource(args, DefaultEdsServiceName()), kServerlistDelayMs));
  2143. const auto t0 = system_clock::now();
  2144. // Client will block: LB will initially send empty serverlist.
  2145. CheckRpcSendOk(
  2146. 1, RpcOptions().set_timeout_ms(kCallDeadlineMs).set_wait_for_ready(true));
  2147. const auto ellapsed_ms =
  2148. std::chrono::duration_cast<std::chrono::milliseconds>(
  2149. system_clock::now() - t0);
  2150. // but eventually, the LB sends a serverlist update that allows the call to
  2151. // proceed. The call delay must be larger than the delay in sending the
  2152. // populated serverlist but under the call's deadline (which is enforced by
  2153. // the call's deadline).
  2154. EXPECT_GT(ellapsed_ms.count(), kServerlistDelayMs);
  2155. delayed_resource_setter.join();
  2156. }
  2157. // Tests that RPCs will fail with UNAVAILABLE instead of DEADLINE_EXCEEDED if
  2158. // all the servers are unreachable.
  2159. TEST_P(BasicTest, AllServersUnreachableFailFast) {
  2160. SetNextResolution({});
  2161. SetNextResolutionForLbChannelAllBalancers();
  2162. const size_t kNumUnreachableServers = 5;
  2163. std::vector<int> ports;
  2164. for (size_t i = 0; i < kNumUnreachableServers; ++i) {
  2165. ports.push_back(g_port_saver->GetPort());
  2166. }
  2167. AdsServiceImpl::EdsResourceArgs args({
  2168. {"locality0", ports},
  2169. });
  2170. balancers_[0]->ads_service()->SetEdsResource(
  2171. BuildEdsResource(args, DefaultEdsServiceName()));
  2172. const Status status = SendRpc();
  2173. // The error shouldn't be DEADLINE_EXCEEDED.
  2174. EXPECT_EQ(StatusCode::UNAVAILABLE, status.error_code());
  2175. }
  2176. // Tests that RPCs fail when the backends are down, and will succeed again after
  2177. // the backends are restarted.
  2178. TEST_P(BasicTest, BackendsRestart) {
  2179. SetNextResolution({});
  2180. SetNextResolutionForLbChannelAllBalancers();
  2181. AdsServiceImpl::EdsResourceArgs args({
  2182. {"locality0", GetBackendPorts()},
  2183. });
  2184. balancers_[0]->ads_service()->SetEdsResource(
  2185. BuildEdsResource(args, DefaultEdsServiceName()));
  2186. WaitForAllBackends();
  2187. // Stop backends. RPCs should fail.
  2188. ShutdownAllBackends();
  2189. // Sending multiple failed requests instead of just one to ensure that the
  2190. // client notices that all backends are down before we restart them. If we
  2191. // didn't do this, then a single RPC could fail here due to the race condition
  2192. // between the LB pick and the GOAWAY from the chosen backend being shut down,
  2193. // which would not actually prove that the client noticed that all of the
  2194. // backends are down. Then, when we send another request below (which we
  2195. // expect to succeed), if the callbacks happen in the wrong order, the same
  2196. // race condition could happen again due to the client not yet having noticed
  2197. // that the backends were all down.
  2198. CheckRpcSendFailure(num_backends_);
  2199. // Restart all backends. RPCs should start succeeding again.
  2200. StartAllBackends();
  2201. CheckRpcSendOk(1, RpcOptions().set_timeout_ms(2000).set_wait_for_ready(true));
  2202. }
  2203. TEST_P(BasicTest, IgnoresDuplicateUpdates) {
  2204. const size_t kNumRpcsPerAddress = 100;
  2205. SetNextResolution({});
  2206. SetNextResolutionForLbChannelAllBalancers();
  2207. AdsServiceImpl::EdsResourceArgs args({
  2208. {"locality0", GetBackendPorts()},
  2209. });
  2210. balancers_[0]->ads_service()->SetEdsResource(
  2211. BuildEdsResource(args, DefaultEdsServiceName()));
  2212. // Wait for all backends to come online.
  2213. WaitForAllBackends();
  2214. // Send kNumRpcsPerAddress RPCs per server, but send an EDS update in
  2215. // between. If the update is not ignored, this will cause the
  2216. // round_robin policy to see an update, which will randomly reset its
  2217. // position in the address list.
  2218. for (size_t i = 0; i < kNumRpcsPerAddress; ++i) {
  2219. CheckRpcSendOk(2);
  2220. balancers_[0]->ads_service()->SetEdsResource(
  2221. BuildEdsResource(args, DefaultEdsServiceName()));
  2222. CheckRpcSendOk(2);
  2223. }
  2224. // Each backend should have gotten the right number of requests.
  2225. for (size_t i = 1; i < backends_.size(); ++i) {
  2226. EXPECT_EQ(kNumRpcsPerAddress,
  2227. backends_[i]->backend_service()->request_count());
  2228. }
  2229. }
  2230. using XdsResolverOnlyTest = BasicTest;
  2231. TEST_P(XdsResolverOnlyTest, ResourceTypeVersionPersistsAcrossStreamRestarts) {
  2232. SetNextResolution({});
  2233. SetNextResolutionForLbChannelAllBalancers();
  2234. AdsServiceImpl::EdsResourceArgs args({
  2235. {"locality0", GetBackendPorts(0, 1)},
  2236. });
  2237. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  2238. // Wait for backends to come online.
  2239. WaitForAllBackends(0, 1);
  2240. // Stop balancer.
  2241. balancers_[0]->Shutdown();
  2242. // Tell balancer to require minimum version 1 for all resource types.
  2243. balancers_[0]->ads_service()->SetResourceMinVersion(kLdsTypeUrl, 1);
  2244. balancers_[0]->ads_service()->SetResourceMinVersion(kRdsTypeUrl, 1);
  2245. balancers_[0]->ads_service()->SetResourceMinVersion(kCdsTypeUrl, 1);
  2246. balancers_[0]->ads_service()->SetResourceMinVersion(kEdsTypeUrl, 1);
  2247. // Update backend, just so we can be sure that the client has
  2248. // reconnected to the balancer.
  2249. AdsServiceImpl::EdsResourceArgs args2({
  2250. {"locality0", GetBackendPorts(1, 2)},
  2251. });
  2252. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args2));
  2253. // Restart balancer.
  2254. balancers_[0]->Start();
  2255. // Make sure client has reconnected.
  2256. WaitForAllBackends(1, 2);
  2257. }
  2258. // Tests switching over from one cluster to another.
  2259. TEST_P(XdsResolverOnlyTest, ChangeClusters) {
  2260. const char* kNewClusterName = "new_cluster_name";
  2261. const char* kNewEdsServiceName = "new_eds_service_name";
  2262. SetNextResolution({});
  2263. SetNextResolutionForLbChannelAllBalancers();
  2264. AdsServiceImpl::EdsResourceArgs args({
  2265. {"locality0", GetBackendPorts(0, 2)},
  2266. });
  2267. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  2268. // We need to wait for all backends to come online.
  2269. WaitForAllBackends(0, 2);
  2270. // Populate new EDS resource.
  2271. AdsServiceImpl::EdsResourceArgs args2({
  2272. {"locality0", GetBackendPorts(2, 4)},
  2273. });
  2274. balancers_[0]->ads_service()->SetEdsResource(
  2275. BuildEdsResource(args2, kNewEdsServiceName));
  2276. // Populate new CDS resource.
  2277. Cluster new_cluster = default_cluster_;
  2278. new_cluster.set_name(kNewClusterName);
  2279. new_cluster.mutable_eds_cluster_config()->set_service_name(
  2280. kNewEdsServiceName);
  2281. balancers_[0]->ads_service()->SetCdsResource(new_cluster);
  2282. // Change RDS resource to point to new cluster.
  2283. RouteConfiguration new_route_config = default_route_config_;
  2284. new_route_config.mutable_virtual_hosts(0)
  2285. ->mutable_routes(0)
  2286. ->mutable_route()
  2287. ->set_cluster(kNewClusterName);
  2288. SetListenerAndRouteConfiguration(0, default_listener_, new_route_config);
  2289. // Wait for all new backends to be used.
  2290. std::tuple<int, int, int> counts = WaitForAllBackends(2, 4);
  2291. // Make sure no RPCs failed in the transition.
  2292. EXPECT_EQ(0, std::get<1>(counts));
  2293. }
  2294. // Tests that we go into TRANSIENT_FAILURE if the Cluster disappears.
  2295. TEST_P(XdsResolverOnlyTest, ClusterRemoved) {
  2296. SetNextResolution({});
  2297. SetNextResolutionForLbChannelAllBalancers();
  2298. AdsServiceImpl::EdsResourceArgs args({
  2299. {"locality0", GetBackendPorts()},
  2300. });
  2301. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  2302. // We need to wait for all backends to come online.
  2303. WaitForAllBackends();
  2304. // Unset CDS resource.
  2305. balancers_[0]->ads_service()->UnsetResource(kCdsTypeUrl, kDefaultClusterName);
  2306. // Wait for RPCs to start failing.
  2307. do {
  2308. } while (SendRpc(RpcOptions(), nullptr).ok());
  2309. // Make sure RPCs are still failing.
  2310. CheckRpcSendFailure(1000);
  2311. // Make sure we ACK'ed the update.
  2312. EXPECT_EQ(balancers_[0]->ads_service()->cds_response_state().state,
  2313. AdsServiceImpl::ResponseState::ACKED);
  2314. }
  2315. // Tests that we restart all xDS requests when we reestablish the ADS call.
  2316. TEST_P(XdsResolverOnlyTest, RestartsRequestsUponReconnection) {
  2317. // Manually configure use of RDS.
  2318. auto listener = default_listener_;
  2319. HttpConnectionManager http_connection_manager;
  2320. auto* rds = http_connection_manager.mutable_rds();
  2321. rds->set_route_config_name(kDefaultRouteConfigurationName);
  2322. rds->mutable_config_source()->mutable_ads();
  2323. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  2324. http_connection_manager);
  2325. balancers_[0]->ads_service()->SetLdsResource(listener);
  2326. balancers_[0]->ads_service()->SetRdsResource(default_route_config_);
  2327. const char* kNewClusterName = "new_cluster_name";
  2328. const char* kNewEdsServiceName = "new_eds_service_name";
  2329. SetNextResolution({});
  2330. SetNextResolutionForLbChannelAllBalancers();
  2331. AdsServiceImpl::EdsResourceArgs args({
  2332. {"locality0", GetBackendPorts(0, 2)},
  2333. });
  2334. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  2335. // We need to wait for all backends to come online.
  2336. WaitForAllBackends(0, 2);
  2337. // Now shut down and restart the balancer. When the client
  2338. // reconnects, it should automatically restart the requests for all
  2339. // resource types.
  2340. balancers_[0]->Shutdown();
  2341. balancers_[0]->Start();
  2342. // Make sure things are still working.
  2343. CheckRpcSendOk(100);
  2344. // Populate new EDS resource.
  2345. AdsServiceImpl::EdsResourceArgs args2({
  2346. {"locality0", GetBackendPorts(2, 4)},
  2347. });
  2348. balancers_[0]->ads_service()->SetEdsResource(
  2349. BuildEdsResource(args2, kNewEdsServiceName));
  2350. // Populate new CDS resource.
  2351. Cluster new_cluster = default_cluster_;
  2352. new_cluster.set_name(kNewClusterName);
  2353. new_cluster.mutable_eds_cluster_config()->set_service_name(
  2354. kNewEdsServiceName);
  2355. balancers_[0]->ads_service()->SetCdsResource(new_cluster);
  2356. // Change RDS resource to point to new cluster.
  2357. RouteConfiguration new_route_config = default_route_config_;
  2358. new_route_config.mutable_virtual_hosts(0)
  2359. ->mutable_routes(0)
  2360. ->mutable_route()
  2361. ->set_cluster(kNewClusterName);
  2362. balancers_[0]->ads_service()->SetRdsResource(new_route_config);
  2363. // Wait for all new backends to be used.
  2364. std::tuple<int, int, int> counts = WaitForAllBackends(2, 4);
  2365. // Make sure no RPCs failed in the transition.
  2366. EXPECT_EQ(0, std::get<1>(counts));
  2367. }
  2368. TEST_P(XdsResolverOnlyTest, DefaultRouteSpecifiesSlashPrefix) {
  2369. RouteConfiguration route_config = default_route_config_;
  2370. route_config.mutable_virtual_hosts(0)
  2371. ->mutable_routes(0)
  2372. ->mutable_match()
  2373. ->set_prefix("/");
  2374. SetListenerAndRouteConfiguration(0, default_listener_, route_config);
  2375. SetNextResolution({});
  2376. SetNextResolutionForLbChannelAllBalancers();
  2377. AdsServiceImpl::EdsResourceArgs args({
  2378. {"locality0", GetBackendPorts()},
  2379. });
  2380. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  2381. // We need to wait for all backends to come online.
  2382. WaitForAllBackends();
  2383. }
  2384. TEST_P(XdsResolverOnlyTest, CircuitBreaking) {
  2385. gpr_setenv("GRPC_XDS_EXPERIMENTAL_CIRCUIT_BREAKING", "true");
  2386. constexpr size_t kMaxConcurrentRequests = 10;
  2387. SetNextResolution({});
  2388. SetNextResolutionForLbChannelAllBalancers();
  2389. // Populate new EDS resources.
  2390. AdsServiceImpl::EdsResourceArgs args({
  2391. {"locality0", GetBackendPorts(0, 1)},
  2392. });
  2393. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  2394. // Update CDS resource to set max concurrent request.
  2395. CircuitBreakers circuit_breaks;
  2396. Cluster cluster = default_cluster_;
  2397. auto* threshold = cluster.mutable_circuit_breakers()->add_thresholds();
  2398. threshold->set_priority(RoutingPriority::DEFAULT);
  2399. threshold->mutable_max_requests()->set_value(kMaxConcurrentRequests);
  2400. balancers_[0]->ads_service()->SetCdsResource(cluster);
  2401. // Send exactly max_concurrent_requests long RPCs.
  2402. LongRunningRpc rpcs[kMaxConcurrentRequests];
  2403. for (size_t i = 0; i < kMaxConcurrentRequests; ++i) {
  2404. rpcs[i].StartRpc(stub_.get());
  2405. }
  2406. // Wait for all RPCs to be in flight.
  2407. while (backends_[0]->backend_service()->RpcsWaitingForClientCancel() <
  2408. kMaxConcurrentRequests) {
  2409. gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
  2410. gpr_time_from_micros(1 * 1000, GPR_TIMESPAN)));
  2411. }
  2412. // Sending a RPC now should fail, the error message should tell us
  2413. // we hit the max concurrent requests limit and got dropped.
  2414. Status status = SendRpc();
  2415. EXPECT_FALSE(status.ok());
  2416. EXPECT_EQ(status.error_message(), "Call dropped by load balancing policy");
  2417. // Cancel one RPC to allow another one through
  2418. rpcs[0].CancelRpc();
  2419. status = SendRpc();
  2420. EXPECT_TRUE(status.ok());
  2421. for (size_t i = 1; i < kMaxConcurrentRequests; ++i) {
  2422. rpcs[i].CancelRpc();
  2423. }
  2424. // Make sure RPCs go to the correct backend:
  2425. EXPECT_EQ(kMaxConcurrentRequests + 1,
  2426. backends_[0]->backend_service()->request_count());
  2427. gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_CIRCUIT_BREAKING");
  2428. }
  2429. TEST_P(XdsResolverOnlyTest, CircuitBreakingMultipleChannelsShareCallCounter) {
  2430. gpr_setenv("GRPC_XDS_EXPERIMENTAL_CIRCUIT_BREAKING", "true");
  2431. constexpr size_t kMaxConcurrentRequests = 10;
  2432. // Populate new EDS resources.
  2433. AdsServiceImpl::EdsResourceArgs args({
  2434. {"locality0", GetBackendPorts(0, 1)},
  2435. });
  2436. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  2437. // Update CDS resource to set max concurrent request.
  2438. CircuitBreakers circuit_breaks;
  2439. Cluster cluster = default_cluster_;
  2440. auto* threshold = cluster.mutable_circuit_breakers()->add_thresholds();
  2441. threshold->set_priority(RoutingPriority::DEFAULT);
  2442. threshold->mutable_max_requests()->set_value(kMaxConcurrentRequests);
  2443. balancers_[0]->ads_service()->SetCdsResource(cluster);
  2444. // Create second channel.
  2445. auto response_generator2 =
  2446. grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
  2447. auto channel2 = CreateChannel(
  2448. /*failover_timeout=*/0, /*server_name=*/kServerName,
  2449. response_generator2.get());
  2450. auto stub2 = grpc::testing::EchoTestService::NewStub(channel2);
  2451. // Set resolution results for both channels and for the xDS channel.
  2452. SetNextResolution({});
  2453. SetNextResolution({}, response_generator2.get());
  2454. SetNextResolutionForLbChannelAllBalancers();
  2455. // Send exactly max_concurrent_requests long RPCs, alternating between
  2456. // the two channels.
  2457. LongRunningRpc rpcs[kMaxConcurrentRequests];
  2458. for (size_t i = 0; i < kMaxConcurrentRequests; ++i) {
  2459. rpcs[i].StartRpc(i % 2 == 0 ? stub_.get() : stub2.get());
  2460. }
  2461. // Wait for all RPCs to be in flight.
  2462. while (backends_[0]->backend_service()->RpcsWaitingForClientCancel() <
  2463. kMaxConcurrentRequests) {
  2464. gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
  2465. gpr_time_from_micros(1 * 1000, GPR_TIMESPAN)));
  2466. }
  2467. // Sending a RPC now should fail, the error message should tell us
  2468. // we hit the max concurrent requests limit and got dropped.
  2469. Status status = SendRpc();
  2470. EXPECT_FALSE(status.ok());
  2471. EXPECT_EQ(status.error_message(), "Call dropped by load balancing policy");
  2472. // Cancel one RPC to allow another one through
  2473. rpcs[0].CancelRpc();
  2474. status = SendRpc();
  2475. EXPECT_TRUE(status.ok());
  2476. for (size_t i = 1; i < kMaxConcurrentRequests; ++i) {
  2477. rpcs[i].CancelRpc();
  2478. }
  2479. // Make sure RPCs go to the correct backend:
  2480. EXPECT_EQ(kMaxConcurrentRequests + 1,
  2481. backends_[0]->backend_service()->request_count());
  2482. gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_CIRCUIT_BREAKING");
  2483. }
  2484. TEST_P(XdsResolverOnlyTest, CircuitBreakingDisabled) {
  2485. constexpr size_t kMaxConcurrentRequests = 10;
  2486. SetNextResolution({});
  2487. SetNextResolutionForLbChannelAllBalancers();
  2488. // Populate new EDS resources.
  2489. AdsServiceImpl::EdsResourceArgs args({
  2490. {"locality0", GetBackendPorts(0, 1)},
  2491. });
  2492. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  2493. // Update CDS resource to set max concurrent request.
  2494. CircuitBreakers circuit_breaks;
  2495. Cluster cluster = default_cluster_;
  2496. auto* threshold = cluster.mutable_circuit_breakers()->add_thresholds();
  2497. threshold->set_priority(RoutingPriority::DEFAULT);
  2498. threshold->mutable_max_requests()->set_value(kMaxConcurrentRequests);
  2499. balancers_[0]->ads_service()->SetCdsResource(cluster);
  2500. // Send exactly max_concurrent_requests long RPCs.
  2501. LongRunningRpc rpcs[kMaxConcurrentRequests];
  2502. for (size_t i = 0; i < kMaxConcurrentRequests; ++i) {
  2503. rpcs[i].StartRpc(stub_.get());
  2504. }
  2505. // Wait for all RPCs to be in flight.
  2506. while (backends_[0]->backend_service()->RpcsWaitingForClientCancel() <
  2507. kMaxConcurrentRequests) {
  2508. gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
  2509. gpr_time_from_micros(1 * 1000, GPR_TIMESPAN)));
  2510. }
  2511. // Sending a RPC now should not fail as circuit breaking is disabled.
  2512. Status status = SendRpc();
  2513. EXPECT_TRUE(status.ok());
  2514. for (size_t i = 0; i < kMaxConcurrentRequests; ++i) {
  2515. rpcs[i].CancelRpc();
  2516. }
  2517. // Make sure RPCs go to the correct backend:
  2518. EXPECT_EQ(kMaxConcurrentRequests + 1,
  2519. backends_[0]->backend_service()->request_count());
  2520. }
  2521. TEST_P(XdsResolverOnlyTest, MultipleChannelsShareXdsClient) {
  2522. const char* kNewServerName = "new-server.example.com";
  2523. Listener listener = default_listener_;
  2524. listener.set_name(kNewServerName);
  2525. SetListenerAndRouteConfiguration(0, listener, default_route_config_);
  2526. SetNextResolution({});
  2527. SetNextResolutionForLbChannelAllBalancers();
  2528. AdsServiceImpl::EdsResourceArgs args({
  2529. {"locality0", GetBackendPorts()},
  2530. });
  2531. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  2532. WaitForAllBackends();
  2533. // Create second channel and tell it to connect to kNewServerName.
  2534. auto channel2 = CreateChannel(/*failover_timeout=*/0, kNewServerName);
  2535. channel2->GetState(/*try_to_connect=*/true);
  2536. ASSERT_TRUE(
  2537. channel2->WaitForConnected(grpc_timeout_milliseconds_to_deadline(100)));
  2538. // Make sure there's only one client connected.
  2539. EXPECT_EQ(1UL, balancers_[0]->ads_service()->clients().size());
  2540. }
  2541. class XdsResolverLoadReportingOnlyTest : public XdsEnd2endTest {
  2542. public:
  2543. XdsResolverLoadReportingOnlyTest() : XdsEnd2endTest(4, 1, 3) {}
  2544. };
  2545. // Tests load reporting when switching over from one cluster to another.
  2546. TEST_P(XdsResolverLoadReportingOnlyTest, ChangeClusters) {
  2547. const char* kNewClusterName = "new_cluster_name";
  2548. const char* kNewEdsServiceName = "new_eds_service_name";
  2549. balancers_[0]->lrs_service()->set_cluster_names(
  2550. {kDefaultClusterName, kNewClusterName});
  2551. SetNextResolution({});
  2552. SetNextResolutionForLbChannelAllBalancers();
  2553. // cluster kDefaultClusterName -> locality0 -> backends 0 and 1
  2554. AdsServiceImpl::EdsResourceArgs args({
  2555. {"locality0", GetBackendPorts(0, 2)},
  2556. });
  2557. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  2558. // cluster kNewClusterName -> locality1 -> backends 2 and 3
  2559. AdsServiceImpl::EdsResourceArgs args2({
  2560. {"locality1", GetBackendPorts(2, 4)},
  2561. });
  2562. balancers_[0]->ads_service()->SetEdsResource(
  2563. BuildEdsResource(args2, kNewEdsServiceName));
  2564. // CDS resource for kNewClusterName.
  2565. Cluster new_cluster = default_cluster_;
  2566. new_cluster.set_name(kNewClusterName);
  2567. new_cluster.mutable_eds_cluster_config()->set_service_name(
  2568. kNewEdsServiceName);
  2569. balancers_[0]->ads_service()->SetCdsResource(new_cluster);
  2570. // Wait for all backends to come online.
  2571. int num_ok = 0;
  2572. int num_failure = 0;
  2573. int num_drops = 0;
  2574. std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends(0, 2);
  2575. // The load report received at the balancer should be correct.
  2576. std::vector<ClientStats> load_report =
  2577. balancers_[0]->lrs_service()->WaitForLoadReport();
  2578. EXPECT_THAT(
  2579. load_report,
  2580. ::testing::ElementsAre(::testing::AllOf(
  2581. ::testing::Property(&ClientStats::cluster_name, kDefaultClusterName),
  2582. ::testing::Property(
  2583. &ClientStats::locality_stats,
  2584. ::testing::ElementsAre(::testing::Pair(
  2585. "locality0",
  2586. ::testing::AllOf(
  2587. ::testing::Field(&ClientStats::LocalityStats::
  2588. total_successful_requests,
  2589. num_ok),
  2590. ::testing::Field(&ClientStats::LocalityStats::
  2591. total_requests_in_progress,
  2592. 0UL),
  2593. ::testing::Field(
  2594. &ClientStats::LocalityStats::total_error_requests,
  2595. num_failure),
  2596. ::testing::Field(
  2597. &ClientStats::LocalityStats::total_issued_requests,
  2598. num_failure + num_ok))))),
  2599. ::testing::Property(&ClientStats::total_dropped_requests,
  2600. num_drops))));
  2601. // Change RDS resource to point to new cluster.
  2602. RouteConfiguration new_route_config = default_route_config_;
  2603. new_route_config.mutable_virtual_hosts(0)
  2604. ->mutable_routes(0)
  2605. ->mutable_route()
  2606. ->set_cluster(kNewClusterName);
  2607. SetListenerAndRouteConfiguration(0, default_listener_, new_route_config);
  2608. // Wait for all new backends to be used.
  2609. std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends(2, 4);
  2610. // The load report received at the balancer should be correct.
  2611. load_report = balancers_[0]->lrs_service()->WaitForLoadReport();
  2612. EXPECT_THAT(
  2613. load_report,
  2614. ::testing::ElementsAre(
  2615. ::testing::AllOf(
  2616. ::testing::Property(&ClientStats::cluster_name,
  2617. kDefaultClusterName),
  2618. ::testing::Property(
  2619. &ClientStats::locality_stats,
  2620. ::testing::ElementsAre(::testing::Pair(
  2621. "locality0",
  2622. ::testing::AllOf(
  2623. ::testing::Field(&ClientStats::LocalityStats::
  2624. total_successful_requests,
  2625. ::testing::Lt(num_ok)),
  2626. ::testing::Field(&ClientStats::LocalityStats::
  2627. total_requests_in_progress,
  2628. 0UL),
  2629. ::testing::Field(
  2630. &ClientStats::LocalityStats::total_error_requests,
  2631. ::testing::Le(num_failure)),
  2632. ::testing::Field(
  2633. &ClientStats::LocalityStats::
  2634. total_issued_requests,
  2635. ::testing::Le(num_failure + num_ok)))))),
  2636. ::testing::Property(&ClientStats::total_dropped_requests,
  2637. num_drops)),
  2638. ::testing::AllOf(
  2639. ::testing::Property(&ClientStats::cluster_name, kNewClusterName),
  2640. ::testing::Property(
  2641. &ClientStats::locality_stats,
  2642. ::testing::ElementsAre(::testing::Pair(
  2643. "locality1",
  2644. ::testing::AllOf(
  2645. ::testing::Field(&ClientStats::LocalityStats::
  2646. total_successful_requests,
  2647. ::testing::Le(num_ok)),
  2648. ::testing::Field(&ClientStats::LocalityStats::
  2649. total_requests_in_progress,
  2650. 0UL),
  2651. ::testing::Field(
  2652. &ClientStats::LocalityStats::total_error_requests,
  2653. ::testing::Le(num_failure)),
  2654. ::testing::Field(
  2655. &ClientStats::LocalityStats::
  2656. total_issued_requests,
  2657. ::testing::Le(num_failure + num_ok)))))),
  2658. ::testing::Property(&ClientStats::total_dropped_requests,
  2659. num_drops))));
  2660. int total_ok = 0;
  2661. int total_failure = 0;
  2662. for (const ClientStats& client_stats : load_report) {
  2663. total_ok += client_stats.total_successful_requests();
  2664. total_failure += client_stats.total_error_requests();
  2665. }
  2666. EXPECT_EQ(total_ok, num_ok);
  2667. EXPECT_EQ(total_failure, num_failure);
  2668. // The LRS service got a single request, and sent a single response.
  2669. EXPECT_EQ(1U, balancers_[0]->lrs_service()->request_count());
  2670. EXPECT_EQ(1U, balancers_[0]->lrs_service()->response_count());
  2671. }
  2672. using SecureNamingTest = BasicTest;
  2673. // Tests that secure naming check passes if target name is expected.
  2674. TEST_P(SecureNamingTest, TargetNameIsExpected) {
  2675. SetNextResolution({});
  2676. SetNextResolutionForLbChannel({balancers_[0]->port()}, nullptr, "xds_server");
  2677. AdsServiceImpl::EdsResourceArgs args({
  2678. {"locality0", GetBackendPorts()},
  2679. });
  2680. balancers_[0]->ads_service()->SetEdsResource(
  2681. BuildEdsResource(args, DefaultEdsServiceName()));
  2682. CheckRpcSendOk();
  2683. }
  2684. // Tests that secure naming check fails if target name is unexpected.
  2685. TEST_P(SecureNamingTest, TargetNameIsUnexpected) {
  2686. ::testing::FLAGS_gtest_death_test_style = "threadsafe";
  2687. SetNextResolution({});
  2688. SetNextResolutionForLbChannel({balancers_[0]->port()}, nullptr,
  2689. "incorrect_server_name");
  2690. AdsServiceImpl::EdsResourceArgs args({
  2691. {"locality0", GetBackendPorts()},
  2692. });
  2693. balancers_[0]->ads_service()->SetEdsResource(
  2694. BuildEdsResource(args, DefaultEdsServiceName()));
  2695. // Make sure that we blow up (via abort() from the security connector) when
  2696. // the name from the balancer doesn't match expectations.
  2697. ASSERT_DEATH_IF_SUPPORTED({ CheckRpcSendOk(); }, "");
  2698. }
  2699. using LdsTest = BasicTest;
  2700. // Tests that LDS client should send a NACK if there is no API listener in the
  2701. // Listener in the LDS response.
  2702. TEST_P(LdsTest, NoApiListener) {
  2703. auto listener = default_listener_;
  2704. listener.clear_api_listener();
  2705. balancers_[0]->ads_service()->SetLdsResource(listener);
  2706. SetNextResolution({});
  2707. SetNextResolutionForLbChannelAllBalancers();
  2708. CheckRpcSendFailure();
  2709. const auto& response_state =
  2710. balancers_[0]->ads_service()->lds_response_state();
  2711. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2712. EXPECT_EQ(response_state.error_message, "Listener has no ApiListener.");
  2713. }
  2714. // Tests that LDS client should send a NACK if the route_specifier in the
  2715. // http_connection_manager is neither inlined route_config nor RDS.
  2716. TEST_P(LdsTest, WrongRouteSpecifier) {
  2717. auto listener = default_listener_;
  2718. HttpConnectionManager http_connection_manager;
  2719. http_connection_manager.mutable_scoped_routes();
  2720. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  2721. http_connection_manager);
  2722. balancers_[0]->ads_service()->SetLdsResource(listener);
  2723. SetNextResolution({});
  2724. SetNextResolutionForLbChannelAllBalancers();
  2725. CheckRpcSendFailure();
  2726. const auto& response_state =
  2727. balancers_[0]->ads_service()->lds_response_state();
  2728. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2729. EXPECT_EQ(response_state.error_message,
  2730. "HttpConnectionManager neither has inlined route_config nor RDS.");
  2731. }
  2732. // Tests that LDS client should send a NACK if the rds message in the
  2733. // http_connection_manager is missing the config_source field.
  2734. TEST_P(LdsTest, RdsMissingConfigSource) {
  2735. auto listener = default_listener_;
  2736. HttpConnectionManager http_connection_manager;
  2737. http_connection_manager.mutable_rds()->set_route_config_name(
  2738. kDefaultRouteConfigurationName);
  2739. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  2740. http_connection_manager);
  2741. balancers_[0]->ads_service()->SetLdsResource(listener);
  2742. SetNextResolution({});
  2743. SetNextResolutionForLbChannelAllBalancers();
  2744. CheckRpcSendFailure();
  2745. const auto& response_state =
  2746. balancers_[0]->ads_service()->lds_response_state();
  2747. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2748. EXPECT_EQ(response_state.error_message,
  2749. "HttpConnectionManager missing config_source for RDS.");
  2750. }
  2751. // Tests that LDS client should send a NACK if the rds message in the
  2752. // http_connection_manager has a config_source field that does not specify ADS.
  2753. TEST_P(LdsTest, RdsConfigSourceDoesNotSpecifyAds) {
  2754. auto listener = default_listener_;
  2755. HttpConnectionManager http_connection_manager;
  2756. auto* rds = http_connection_manager.mutable_rds();
  2757. rds->set_route_config_name(kDefaultRouteConfigurationName);
  2758. rds->mutable_config_source()->mutable_self();
  2759. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  2760. http_connection_manager);
  2761. balancers_[0]->ads_service()->SetLdsResource(listener);
  2762. SetNextResolution({});
  2763. SetNextResolutionForLbChannelAllBalancers();
  2764. CheckRpcSendFailure();
  2765. const auto& response_state =
  2766. balancers_[0]->ads_service()->lds_response_state();
  2767. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2768. EXPECT_EQ(response_state.error_message,
  2769. "HttpConnectionManager ConfigSource for RDS does not specify ADS.");
  2770. }
  2771. using LdsRdsTest = BasicTest;
  2772. // Tests that LDS client should send an ACK upon correct LDS response (with
  2773. // inlined RDS result).
  2774. TEST_P(LdsRdsTest, Vanilla) {
  2775. SetNextResolution({});
  2776. SetNextResolutionForLbChannelAllBalancers();
  2777. (void)SendRpc();
  2778. EXPECT_EQ(RouteConfigurationResponseState(0).state,
  2779. AdsServiceImpl::ResponseState::ACKED);
  2780. // Make sure we actually used the RPC service for the right version of xDS.
  2781. EXPECT_EQ(balancers_[0]->ads_service()->seen_v2_client(),
  2782. GetParam().use_v2());
  2783. EXPECT_NE(balancers_[0]->ads_service()->seen_v3_client(),
  2784. GetParam().use_v2());
  2785. }
  2786. // Tests that we go into TRANSIENT_FAILURE if the Listener is removed.
  2787. TEST_P(LdsRdsTest, ListenerRemoved) {
  2788. SetNextResolution({});
  2789. SetNextResolutionForLbChannelAllBalancers();
  2790. AdsServiceImpl::EdsResourceArgs args({
  2791. {"locality0", GetBackendPorts()},
  2792. });
  2793. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  2794. // We need to wait for all backends to come online.
  2795. WaitForAllBackends();
  2796. // Unset LDS resource.
  2797. balancers_[0]->ads_service()->UnsetResource(kLdsTypeUrl, kServerName);
  2798. // Wait for RPCs to start failing.
  2799. do {
  2800. } while (SendRpc(RpcOptions(), nullptr).ok());
  2801. // Make sure RPCs are still failing.
  2802. CheckRpcSendFailure(1000);
  2803. // Make sure we ACK'ed the update.
  2804. EXPECT_EQ(balancers_[0]->ads_service()->lds_response_state().state,
  2805. AdsServiceImpl::ResponseState::ACKED);
  2806. }
  2807. // Tests that LDS client ACKs but fails if matching domain can't be found in
  2808. // the LDS response.
  2809. TEST_P(LdsRdsTest, NoMatchedDomain) {
  2810. RouteConfiguration route_config = default_route_config_;
  2811. route_config.mutable_virtual_hosts(0)->clear_domains();
  2812. route_config.mutable_virtual_hosts(0)->add_domains("unmatched_domain");
  2813. SetRouteConfiguration(0, route_config);
  2814. SetNextResolution({});
  2815. SetNextResolutionForLbChannelAllBalancers();
  2816. CheckRpcSendFailure();
  2817. // Do a bit of polling, to allow the ACK to get to the ADS server.
  2818. channel_->WaitForConnected(grpc_timeout_milliseconds_to_deadline(100));
  2819. const auto& response_state = RouteConfigurationResponseState(0);
  2820. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
  2821. }
  2822. // Tests that LDS client should choose the virtual host with matching domain if
  2823. // multiple virtual hosts exist in the LDS response.
  2824. TEST_P(LdsRdsTest, ChooseMatchedDomain) {
  2825. RouteConfiguration route_config = default_route_config_;
  2826. *(route_config.add_virtual_hosts()) = route_config.virtual_hosts(0);
  2827. route_config.mutable_virtual_hosts(0)->clear_domains();
  2828. route_config.mutable_virtual_hosts(0)->add_domains("unmatched_domain");
  2829. SetRouteConfiguration(0, route_config);
  2830. SetNextResolution({});
  2831. SetNextResolutionForLbChannelAllBalancers();
  2832. (void)SendRpc();
  2833. EXPECT_EQ(RouteConfigurationResponseState(0).state,
  2834. AdsServiceImpl::ResponseState::ACKED);
  2835. }
  2836. // Tests that LDS client should choose the last route in the virtual host if
  2837. // multiple routes exist in the LDS response.
  2838. TEST_P(LdsRdsTest, ChooseLastRoute) {
  2839. RouteConfiguration route_config = default_route_config_;
  2840. *(route_config.mutable_virtual_hosts(0)->add_routes()) =
  2841. route_config.virtual_hosts(0).routes(0);
  2842. route_config.mutable_virtual_hosts(0)
  2843. ->mutable_routes(0)
  2844. ->mutable_route()
  2845. ->mutable_cluster_header();
  2846. SetRouteConfiguration(0, route_config);
  2847. SetNextResolution({});
  2848. SetNextResolutionForLbChannelAllBalancers();
  2849. (void)SendRpc();
  2850. EXPECT_EQ(RouteConfigurationResponseState(0).state,
  2851. AdsServiceImpl::ResponseState::ACKED);
  2852. }
  2853. // Tests that LDS client should ignore route which has query_parameters.
  2854. TEST_P(LdsRdsTest, RouteMatchHasQueryParameters) {
  2855. RouteConfiguration route_config = default_route_config_;
  2856. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2857. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  2858. route1->mutable_match()->add_query_parameters();
  2859. SetRouteConfiguration(0, route_config);
  2860. SetNextResolution({});
  2861. SetNextResolutionForLbChannelAllBalancers();
  2862. CheckRpcSendFailure();
  2863. const auto& response_state = RouteConfigurationResponseState(0);
  2864. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2865. EXPECT_EQ(response_state.error_message, "No valid routes specified.");
  2866. }
  2867. // Tests that LDS client should send a ACK if route match has a prefix
  2868. // that is either empty or a single slash
  2869. TEST_P(LdsRdsTest, RouteMatchHasValidPrefixEmptyOrSingleSlash) {
  2870. RouteConfiguration route_config = default_route_config_;
  2871. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2872. route1->mutable_match()->set_prefix("");
  2873. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  2874. default_route->mutable_match()->set_prefix("/");
  2875. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  2876. SetRouteConfiguration(0, route_config);
  2877. SetNextResolution({});
  2878. SetNextResolutionForLbChannelAllBalancers();
  2879. (void)SendRpc();
  2880. const auto& response_state = RouteConfigurationResponseState(0);
  2881. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
  2882. }
  2883. // Tests that LDS client should ignore route which has a path
  2884. // prefix string does not start with "/".
  2885. TEST_P(LdsRdsTest, RouteMatchHasInvalidPrefixNoLeadingSlash) {
  2886. RouteConfiguration route_config = default_route_config_;
  2887. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2888. route1->mutable_match()->set_prefix("grpc.testing.EchoTest1Service/");
  2889. SetRouteConfiguration(0, route_config);
  2890. SetNextResolution({});
  2891. SetNextResolutionForLbChannelAllBalancers();
  2892. CheckRpcSendFailure();
  2893. const auto& response_state = RouteConfigurationResponseState(0);
  2894. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2895. EXPECT_EQ(response_state.error_message, "No valid routes specified.");
  2896. }
  2897. // Tests that LDS client should ignore route which has a prefix
  2898. // string with more than 2 slashes.
  2899. TEST_P(LdsRdsTest, RouteMatchHasInvalidPrefixExtraContent) {
  2900. RouteConfiguration route_config = default_route_config_;
  2901. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2902. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/Echo1/");
  2903. SetRouteConfiguration(0, route_config);
  2904. SetNextResolution({});
  2905. SetNextResolutionForLbChannelAllBalancers();
  2906. CheckRpcSendFailure();
  2907. const auto& response_state = RouteConfigurationResponseState(0);
  2908. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2909. EXPECT_EQ(response_state.error_message, "No valid routes specified.");
  2910. }
  2911. // Tests that LDS client should ignore route which has a prefix
  2912. // string "//".
  2913. TEST_P(LdsRdsTest, RouteMatchHasInvalidPrefixDoubleSlash) {
  2914. RouteConfiguration route_config = default_route_config_;
  2915. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2916. route1->mutable_match()->set_prefix("//");
  2917. SetRouteConfiguration(0, route_config);
  2918. SetNextResolution({});
  2919. SetNextResolutionForLbChannelAllBalancers();
  2920. CheckRpcSendFailure();
  2921. const auto& response_state = RouteConfigurationResponseState(0);
  2922. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2923. EXPECT_EQ(response_state.error_message, "No valid routes specified.");
  2924. }
  2925. // Tests that LDS client should ignore route which has path
  2926. // but it's empty.
  2927. TEST_P(LdsRdsTest, RouteMatchHasInvalidPathEmptyPath) {
  2928. RouteConfiguration route_config = default_route_config_;
  2929. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2930. route1->mutable_match()->set_path("");
  2931. SetRouteConfiguration(0, route_config);
  2932. SetNextResolution({});
  2933. SetNextResolutionForLbChannelAllBalancers();
  2934. CheckRpcSendFailure();
  2935. const auto& response_state = RouteConfigurationResponseState(0);
  2936. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2937. EXPECT_EQ(response_state.error_message, "No valid routes specified.");
  2938. }
  2939. // Tests that LDS client should ignore route which has path
  2940. // string does not start with "/".
  2941. TEST_P(LdsRdsTest, RouteMatchHasInvalidPathNoLeadingSlash) {
  2942. RouteConfiguration route_config = default_route_config_;
  2943. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2944. route1->mutable_match()->set_path("grpc.testing.EchoTest1Service/Echo1");
  2945. SetRouteConfiguration(0, route_config);
  2946. SetNextResolution({});
  2947. SetNextResolutionForLbChannelAllBalancers();
  2948. CheckRpcSendFailure();
  2949. const auto& response_state = RouteConfigurationResponseState(0);
  2950. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2951. EXPECT_EQ(response_state.error_message, "No valid routes specified.");
  2952. }
  2953. // Tests that LDS client should ignore route which has path
  2954. // string that has too many slashes; for example, ends with "/".
  2955. TEST_P(LdsRdsTest, RouteMatchHasInvalidPathTooManySlashes) {
  2956. RouteConfiguration route_config = default_route_config_;
  2957. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2958. route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service/Echo1/");
  2959. SetRouteConfiguration(0, route_config);
  2960. SetNextResolution({});
  2961. SetNextResolutionForLbChannelAllBalancers();
  2962. CheckRpcSendFailure();
  2963. const auto& response_state = RouteConfigurationResponseState(0);
  2964. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2965. EXPECT_EQ(response_state.error_message, "No valid routes specified.");
  2966. }
  2967. // Tests that LDS client should ignore route which has path
  2968. // string that has only 1 slash: missing "/" between service and method.
  2969. TEST_P(LdsRdsTest, RouteMatchHasInvalidPathOnlyOneSlash) {
  2970. RouteConfiguration route_config = default_route_config_;
  2971. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2972. route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service.Echo1");
  2973. SetRouteConfiguration(0, route_config);
  2974. SetNextResolution({});
  2975. SetNextResolutionForLbChannelAllBalancers();
  2976. CheckRpcSendFailure();
  2977. const auto& response_state = RouteConfigurationResponseState(0);
  2978. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2979. EXPECT_EQ(response_state.error_message, "No valid routes specified.");
  2980. }
  2981. // Tests that LDS client should ignore route which has path
  2982. // string that is missing service.
  2983. TEST_P(LdsRdsTest, RouteMatchHasInvalidPathMissingService) {
  2984. RouteConfiguration route_config = default_route_config_;
  2985. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  2986. route1->mutable_match()->set_path("//Echo1");
  2987. SetRouteConfiguration(0, route_config);
  2988. SetNextResolution({});
  2989. SetNextResolutionForLbChannelAllBalancers();
  2990. CheckRpcSendFailure();
  2991. const auto& response_state = RouteConfigurationResponseState(0);
  2992. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  2993. EXPECT_EQ(response_state.error_message, "No valid routes specified.");
  2994. }
  2995. // Tests that LDS client should ignore route which has path
  2996. // string that is missing method.
  2997. TEST_P(LdsRdsTest, RouteMatchHasInvalidPathMissingMethod) {
  2998. RouteConfiguration route_config = default_route_config_;
  2999. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3000. route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service/");
  3001. SetRouteConfiguration(0, route_config);
  3002. SetNextResolution({});
  3003. SetNextResolutionForLbChannelAllBalancers();
  3004. CheckRpcSendFailure();
  3005. const auto& response_state = RouteConfigurationResponseState(0);
  3006. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  3007. EXPECT_EQ(response_state.error_message, "No valid routes specified.");
  3008. }
  3009. // Test that LDS client should reject route which has invalid path regex.
  3010. TEST_P(LdsRdsTest, RouteMatchHasInvalidPathRegex) {
  3011. const char* kNewCluster1Name = "new_cluster_1";
  3012. RouteConfiguration route_config = default_route_config_;
  3013. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3014. route1->mutable_match()->mutable_safe_regex()->set_regex("a[z-a]");
  3015. route1->mutable_route()->set_cluster(kNewCluster1Name);
  3016. SetRouteConfiguration(0, route_config);
  3017. SetNextResolution({});
  3018. SetNextResolutionForLbChannelAllBalancers();
  3019. CheckRpcSendFailure();
  3020. const auto& response_state = RouteConfigurationResponseState(0);
  3021. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  3022. EXPECT_EQ(response_state.error_message,
  3023. "Invalid regex string specified in path matcher.");
  3024. }
  3025. // Tests that LDS client should send a NACK if route has an action other than
  3026. // RouteAction in the LDS response.
  3027. TEST_P(LdsRdsTest, RouteHasNoRouteAction) {
  3028. RouteConfiguration route_config = default_route_config_;
  3029. route_config.mutable_virtual_hosts(0)->mutable_routes(0)->mutable_redirect();
  3030. SetRouteConfiguration(0, route_config);
  3031. SetNextResolution({});
  3032. SetNextResolutionForLbChannelAllBalancers();
  3033. CheckRpcSendFailure();
  3034. const auto& response_state = RouteConfigurationResponseState(0);
  3035. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  3036. EXPECT_EQ(response_state.error_message, "No RouteAction found in route.");
  3037. }
  3038. TEST_P(LdsRdsTest, RouteActionClusterHasEmptyClusterName) {
  3039. RouteConfiguration route_config = default_route_config_;
  3040. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3041. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3042. route1->mutable_route()->set_cluster("");
  3043. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  3044. default_route->mutable_match()->set_prefix("");
  3045. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3046. SetRouteConfiguration(0, route_config);
  3047. SetNextResolution({});
  3048. SetNextResolutionForLbChannelAllBalancers();
  3049. CheckRpcSendFailure();
  3050. const auto& response_state = RouteConfigurationResponseState(0);
  3051. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  3052. EXPECT_EQ(response_state.error_message,
  3053. "RouteAction cluster contains empty cluster name.");
  3054. }
  3055. TEST_P(LdsRdsTest, RouteActionWeightedTargetHasIncorrectTotalWeightSet) {
  3056. const size_t kWeight75 = 75;
  3057. const char* kNewCluster1Name = "new_cluster_1";
  3058. RouteConfiguration route_config = default_route_config_;
  3059. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3060. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3061. auto* weighted_cluster1 =
  3062. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3063. weighted_cluster1->set_name(kNewCluster1Name);
  3064. weighted_cluster1->mutable_weight()->set_value(kWeight75);
  3065. route1->mutable_route()
  3066. ->mutable_weighted_clusters()
  3067. ->mutable_total_weight()
  3068. ->set_value(kWeight75 + 1);
  3069. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  3070. default_route->mutable_match()->set_prefix("");
  3071. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3072. SetRouteConfiguration(0, route_config);
  3073. SetNextResolution({});
  3074. SetNextResolutionForLbChannelAllBalancers();
  3075. CheckRpcSendFailure();
  3076. const auto& response_state = RouteConfigurationResponseState(0);
  3077. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  3078. EXPECT_EQ(response_state.error_message,
  3079. "RouteAction weighted_cluster has incorrect total weight");
  3080. }
  3081. TEST_P(LdsRdsTest, RouteActionWeightedClusterHasZeroTotalWeight) {
  3082. const char* kNewCluster1Name = "new_cluster_1";
  3083. RouteConfiguration route_config = default_route_config_;
  3084. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3085. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3086. auto* weighted_cluster1 =
  3087. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3088. weighted_cluster1->set_name(kNewCluster1Name);
  3089. weighted_cluster1->mutable_weight()->set_value(0);
  3090. route1->mutable_route()
  3091. ->mutable_weighted_clusters()
  3092. ->mutable_total_weight()
  3093. ->set_value(0);
  3094. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  3095. default_route->mutable_match()->set_prefix("");
  3096. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3097. SetRouteConfiguration(0, route_config);
  3098. SetNextResolution({});
  3099. SetNextResolutionForLbChannelAllBalancers();
  3100. CheckRpcSendFailure();
  3101. const auto& response_state = RouteConfigurationResponseState(0);
  3102. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  3103. EXPECT_EQ(response_state.error_message,
  3104. "RouteAction weighted_cluster has no valid clusters specified.");
  3105. }
  3106. TEST_P(LdsRdsTest, RouteActionWeightedTargetClusterHasEmptyClusterName) {
  3107. const size_t kWeight75 = 75;
  3108. RouteConfiguration route_config = default_route_config_;
  3109. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3110. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3111. auto* weighted_cluster1 =
  3112. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3113. weighted_cluster1->set_name("");
  3114. weighted_cluster1->mutable_weight()->set_value(kWeight75);
  3115. route1->mutable_route()
  3116. ->mutable_weighted_clusters()
  3117. ->mutable_total_weight()
  3118. ->set_value(kWeight75);
  3119. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  3120. default_route->mutable_match()->set_prefix("");
  3121. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3122. SetRouteConfiguration(0, route_config);
  3123. SetNextResolution({});
  3124. SetNextResolutionForLbChannelAllBalancers();
  3125. CheckRpcSendFailure();
  3126. const auto& response_state = RouteConfigurationResponseState(0);
  3127. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  3128. EXPECT_EQ(
  3129. response_state.error_message,
  3130. "RouteAction weighted_cluster cluster contains empty cluster name.");
  3131. }
  3132. TEST_P(LdsRdsTest, RouteActionWeightedTargetClusterHasNoWeight) {
  3133. const size_t kWeight75 = 75;
  3134. const char* kNewCluster1Name = "new_cluster_1";
  3135. RouteConfiguration route_config = default_route_config_;
  3136. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3137. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3138. auto* weighted_cluster1 =
  3139. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3140. weighted_cluster1->set_name(kNewCluster1Name);
  3141. route1->mutable_route()
  3142. ->mutable_weighted_clusters()
  3143. ->mutable_total_weight()
  3144. ->set_value(kWeight75);
  3145. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  3146. default_route->mutable_match()->set_prefix("");
  3147. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3148. SetRouteConfiguration(0, route_config);
  3149. SetNextResolution({});
  3150. SetNextResolutionForLbChannelAllBalancers();
  3151. CheckRpcSendFailure();
  3152. const auto& response_state = RouteConfigurationResponseState(0);
  3153. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  3154. EXPECT_EQ(response_state.error_message,
  3155. "RouteAction weighted_cluster cluster missing weight");
  3156. }
  3157. TEST_P(LdsRdsTest, RouteHeaderMatchInvalidRegex) {
  3158. const char* kNewCluster1Name = "new_cluster_1";
  3159. RouteConfiguration route_config = default_route_config_;
  3160. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3161. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3162. auto* header_matcher1 = route1->mutable_match()->add_headers();
  3163. header_matcher1->set_name("header1");
  3164. header_matcher1->mutable_safe_regex_match()->set_regex("a[z-a]");
  3165. route1->mutable_route()->set_cluster(kNewCluster1Name);
  3166. SetRouteConfiguration(0, route_config);
  3167. SetNextResolution({});
  3168. SetNextResolutionForLbChannelAllBalancers();
  3169. CheckRpcSendFailure();
  3170. const auto& response_state = RouteConfigurationResponseState(0);
  3171. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  3172. EXPECT_EQ(response_state.error_message,
  3173. "Invalid regex string specified in header matcher.");
  3174. }
  3175. TEST_P(LdsRdsTest, RouteHeaderMatchInvalidRange) {
  3176. const char* kNewCluster1Name = "new_cluster_1";
  3177. RouteConfiguration route_config = default_route_config_;
  3178. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3179. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3180. auto* header_matcher1 = route1->mutable_match()->add_headers();
  3181. header_matcher1->set_name("header1");
  3182. header_matcher1->mutable_range_match()->set_start(1001);
  3183. header_matcher1->mutable_range_match()->set_end(1000);
  3184. route1->mutable_route()->set_cluster(kNewCluster1Name);
  3185. SetRouteConfiguration(0, route_config);
  3186. SetNextResolution({});
  3187. SetNextResolutionForLbChannelAllBalancers();
  3188. CheckRpcSendFailure();
  3189. const auto& response_state = RouteConfigurationResponseState(0);
  3190. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  3191. EXPECT_EQ(response_state.error_message,
  3192. "Invalid range header matcher specifier specified: end "
  3193. "cannot be smaller than start.");
  3194. }
  3195. // Tests that LDS client should choose the default route (with no matching
  3196. // specified) after unable to find a match with previous routes.
  3197. TEST_P(LdsRdsTest, XdsRoutingPathMatching) {
  3198. const char* kNewCluster1Name = "new_cluster_1";
  3199. const char* kNewEdsService1Name = "new_eds_service_name_1";
  3200. const char* kNewCluster2Name = "new_cluster_2";
  3201. const char* kNewEdsService2Name = "new_eds_service_name_2";
  3202. const size_t kNumEcho1Rpcs = 10;
  3203. const size_t kNumEcho2Rpcs = 20;
  3204. const size_t kNumEchoRpcs = 30;
  3205. SetNextResolution({});
  3206. SetNextResolutionForLbChannelAllBalancers();
  3207. // Populate new EDS resources.
  3208. AdsServiceImpl::EdsResourceArgs args({
  3209. {"locality0", GetBackendPorts(0, 2)},
  3210. });
  3211. AdsServiceImpl::EdsResourceArgs args1({
  3212. {"locality0", GetBackendPorts(2, 3)},
  3213. });
  3214. AdsServiceImpl::EdsResourceArgs args2({
  3215. {"locality0", GetBackendPorts(3, 4)},
  3216. });
  3217. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  3218. balancers_[0]->ads_service()->SetEdsResource(
  3219. BuildEdsResource(args1, kNewEdsService1Name));
  3220. balancers_[0]->ads_service()->SetEdsResource(
  3221. BuildEdsResource(args2, kNewEdsService2Name));
  3222. // Populate new CDS resources.
  3223. Cluster new_cluster1 = default_cluster_;
  3224. new_cluster1.set_name(kNewCluster1Name);
  3225. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  3226. kNewEdsService1Name);
  3227. balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
  3228. Cluster new_cluster2 = default_cluster_;
  3229. new_cluster2.set_name(kNewCluster2Name);
  3230. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  3231. kNewEdsService2Name);
  3232. balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
  3233. // Populating Route Configurations for LDS.
  3234. RouteConfiguration new_route_config = default_route_config_;
  3235. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3236. route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service/Echo1");
  3237. route1->mutable_route()->set_cluster(kNewCluster1Name);
  3238. auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3239. route2->mutable_match()->set_path("/grpc.testing.EchoTest2Service/Echo2");
  3240. route2->mutable_route()->set_cluster(kNewCluster2Name);
  3241. auto* route3 = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3242. route3->mutable_match()->set_path("/grpc.testing.EchoTest3Service/Echo3");
  3243. route3->mutable_route()->set_cluster(kDefaultClusterName);
  3244. auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3245. default_route->mutable_match()->set_prefix("");
  3246. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3247. SetRouteConfiguration(0, new_route_config);
  3248. WaitForAllBackends(0, 2);
  3249. CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
  3250. CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions()
  3251. .set_rpc_service(SERVICE_ECHO1)
  3252. .set_rpc_method(METHOD_ECHO1)
  3253. .set_wait_for_ready(true));
  3254. CheckRpcSendOk(kNumEcho2Rpcs, RpcOptions()
  3255. .set_rpc_service(SERVICE_ECHO2)
  3256. .set_rpc_method(METHOD_ECHO2)
  3257. .set_wait_for_ready(true));
  3258. // Make sure RPCs all go to the correct backend.
  3259. for (size_t i = 0; i < 2; ++i) {
  3260. EXPECT_EQ(kNumEchoRpcs / 2,
  3261. backends_[i]->backend_service()->request_count());
  3262. EXPECT_EQ(0, backends_[i]->backend_service1()->request_count());
  3263. EXPECT_EQ(0, backends_[i]->backend_service2()->request_count());
  3264. }
  3265. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  3266. EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
  3267. EXPECT_EQ(0, backends_[2]->backend_service2()->request_count());
  3268. EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
  3269. EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
  3270. EXPECT_EQ(kNumEcho2Rpcs, backends_[3]->backend_service2()->request_count());
  3271. }
  3272. TEST_P(LdsRdsTest, XdsRoutingPathMatchingCaseInsensitive) {
  3273. const char* kNewCluster1Name = "new_cluster_1";
  3274. const char* kNewEdsService1Name = "new_eds_service_name_1";
  3275. const char* kNewCluster2Name = "new_cluster_2";
  3276. const char* kNewEdsService2Name = "new_eds_service_name_2";
  3277. const size_t kNumEcho1Rpcs = 10;
  3278. const size_t kNumEchoRpcs = 30;
  3279. SetNextResolution({});
  3280. SetNextResolutionForLbChannelAllBalancers();
  3281. // Populate new EDS resources.
  3282. AdsServiceImpl::EdsResourceArgs args({
  3283. {"locality0", GetBackendPorts(0, 1)},
  3284. });
  3285. AdsServiceImpl::EdsResourceArgs args1({
  3286. {"locality0", GetBackendPorts(1, 2)},
  3287. });
  3288. AdsServiceImpl::EdsResourceArgs args2({
  3289. {"locality0", GetBackendPorts(2, 3)},
  3290. });
  3291. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  3292. balancers_[0]->ads_service()->SetEdsResource(
  3293. BuildEdsResource(args1, kNewEdsService1Name));
  3294. balancers_[0]->ads_service()->SetEdsResource(
  3295. BuildEdsResource(args2, kNewEdsService2Name));
  3296. // Populate new CDS resources.
  3297. Cluster new_cluster1 = default_cluster_;
  3298. new_cluster1.set_name(kNewCluster1Name);
  3299. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  3300. kNewEdsService1Name);
  3301. balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
  3302. Cluster new_cluster2 = default_cluster_;
  3303. new_cluster2.set_name(kNewCluster2Name);
  3304. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  3305. kNewEdsService2Name);
  3306. balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
  3307. // Populating Route Configurations for LDS.
  3308. RouteConfiguration new_route_config = default_route_config_;
  3309. // First route will not match, since it's case-sensitive.
  3310. // Second route will match with same path.
  3311. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3312. route1->mutable_match()->set_path("/GrPc.TeStInG.EcHoTeSt1SErViCe/EcHo1");
  3313. route1->mutable_route()->set_cluster(kNewCluster1Name);
  3314. auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3315. route2->mutable_match()->set_path("/GrPc.TeStInG.EcHoTeSt1SErViCe/EcHo1");
  3316. route2->mutable_match()->mutable_case_sensitive()->set_value(false);
  3317. route2->mutable_route()->set_cluster(kNewCluster2Name);
  3318. auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3319. default_route->mutable_match()->set_prefix("");
  3320. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3321. SetRouteConfiguration(0, new_route_config);
  3322. CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
  3323. CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions()
  3324. .set_rpc_service(SERVICE_ECHO1)
  3325. .set_rpc_method(METHOD_ECHO1)
  3326. .set_wait_for_ready(true));
  3327. // Make sure RPCs all go to the correct backend.
  3328. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  3329. EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
  3330. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  3331. EXPECT_EQ(0, backends_[1]->backend_service1()->request_count());
  3332. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  3333. EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
  3334. }
  3335. TEST_P(LdsRdsTest, XdsRoutingPrefixMatching) {
  3336. const char* kNewCluster1Name = "new_cluster_1";
  3337. const char* kNewEdsService1Name = "new_eds_service_name_1";
  3338. const char* kNewCluster2Name = "new_cluster_2";
  3339. const char* kNewEdsService2Name = "new_eds_service_name_2";
  3340. const size_t kNumEcho1Rpcs = 10;
  3341. const size_t kNumEcho2Rpcs = 20;
  3342. const size_t kNumEchoRpcs = 30;
  3343. SetNextResolution({});
  3344. SetNextResolutionForLbChannelAllBalancers();
  3345. // Populate new EDS resources.
  3346. AdsServiceImpl::EdsResourceArgs args({
  3347. {"locality0", GetBackendPorts(0, 2)},
  3348. });
  3349. AdsServiceImpl::EdsResourceArgs args1({
  3350. {"locality0", GetBackendPorts(2, 3)},
  3351. });
  3352. AdsServiceImpl::EdsResourceArgs args2({
  3353. {"locality0", GetBackendPorts(3, 4)},
  3354. });
  3355. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  3356. balancers_[0]->ads_service()->SetEdsResource(
  3357. BuildEdsResource(args1, kNewEdsService1Name));
  3358. balancers_[0]->ads_service()->SetEdsResource(
  3359. BuildEdsResource(args2, kNewEdsService2Name));
  3360. // Populate new CDS resources.
  3361. Cluster new_cluster1 = default_cluster_;
  3362. new_cluster1.set_name(kNewCluster1Name);
  3363. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  3364. kNewEdsService1Name);
  3365. balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
  3366. Cluster new_cluster2 = default_cluster_;
  3367. new_cluster2.set_name(kNewCluster2Name);
  3368. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  3369. kNewEdsService2Name);
  3370. balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
  3371. // Populating Route Configurations for LDS.
  3372. RouteConfiguration new_route_config = default_route_config_;
  3373. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3374. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3375. route1->mutable_route()->set_cluster(kNewCluster1Name);
  3376. auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3377. route2->mutable_match()->set_prefix("/grpc.testing.EchoTest2Service/");
  3378. route2->mutable_route()->set_cluster(kNewCluster2Name);
  3379. auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3380. default_route->mutable_match()->set_prefix("");
  3381. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3382. SetRouteConfiguration(0, new_route_config);
  3383. WaitForAllBackends(0, 2);
  3384. CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
  3385. CheckRpcSendOk(
  3386. kNumEcho1Rpcs,
  3387. RpcOptions().set_rpc_service(SERVICE_ECHO1).set_wait_for_ready(true));
  3388. CheckRpcSendOk(
  3389. kNumEcho2Rpcs,
  3390. RpcOptions().set_rpc_service(SERVICE_ECHO2).set_wait_for_ready(true));
  3391. // Make sure RPCs all go to the correct backend.
  3392. for (size_t i = 0; i < 2; ++i) {
  3393. EXPECT_EQ(kNumEchoRpcs / 2,
  3394. backends_[i]->backend_service()->request_count());
  3395. EXPECT_EQ(0, backends_[i]->backend_service1()->request_count());
  3396. EXPECT_EQ(0, backends_[i]->backend_service2()->request_count());
  3397. }
  3398. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  3399. EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
  3400. EXPECT_EQ(0, backends_[2]->backend_service2()->request_count());
  3401. EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
  3402. EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
  3403. EXPECT_EQ(kNumEcho2Rpcs, backends_[3]->backend_service2()->request_count());
  3404. }
  3405. TEST_P(LdsRdsTest, XdsRoutingPrefixMatchingCaseInsensitive) {
  3406. const char* kNewCluster1Name = "new_cluster_1";
  3407. const char* kNewEdsService1Name = "new_eds_service_name_1";
  3408. const char* kNewCluster2Name = "new_cluster_2";
  3409. const char* kNewEdsService2Name = "new_eds_service_name_2";
  3410. const size_t kNumEcho1Rpcs = 10;
  3411. const size_t kNumEchoRpcs = 30;
  3412. SetNextResolution({});
  3413. SetNextResolutionForLbChannelAllBalancers();
  3414. // Populate new EDS resources.
  3415. AdsServiceImpl::EdsResourceArgs args({
  3416. {"locality0", GetBackendPorts(0, 1)},
  3417. });
  3418. AdsServiceImpl::EdsResourceArgs args1({
  3419. {"locality0", GetBackendPorts(1, 2)},
  3420. });
  3421. AdsServiceImpl::EdsResourceArgs args2({
  3422. {"locality0", GetBackendPorts(2, 3)},
  3423. });
  3424. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  3425. balancers_[0]->ads_service()->SetEdsResource(
  3426. BuildEdsResource(args1, kNewEdsService1Name));
  3427. balancers_[0]->ads_service()->SetEdsResource(
  3428. BuildEdsResource(args2, kNewEdsService2Name));
  3429. // Populate new CDS resources.
  3430. Cluster new_cluster1 = default_cluster_;
  3431. new_cluster1.set_name(kNewCluster1Name);
  3432. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  3433. kNewEdsService1Name);
  3434. balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
  3435. Cluster new_cluster2 = default_cluster_;
  3436. new_cluster2.set_name(kNewCluster2Name);
  3437. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  3438. kNewEdsService2Name);
  3439. balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
  3440. // Populating Route Configurations for LDS.
  3441. RouteConfiguration new_route_config = default_route_config_;
  3442. // First route will not match, since it's case-sensitive.
  3443. // Second route will match with same path.
  3444. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3445. route1->mutable_match()->set_prefix("/GrPc.TeStInG.EcHoTeSt1SErViCe");
  3446. route1->mutable_route()->set_cluster(kNewCluster1Name);
  3447. auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3448. route2->mutable_match()->set_prefix("/GrPc.TeStInG.EcHoTeSt1SErViCe");
  3449. route2->mutable_match()->mutable_case_sensitive()->set_value(false);
  3450. route2->mutable_route()->set_cluster(kNewCluster2Name);
  3451. auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3452. default_route->mutable_match()->set_prefix("");
  3453. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3454. SetRouteConfiguration(0, new_route_config);
  3455. CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
  3456. CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions()
  3457. .set_rpc_service(SERVICE_ECHO1)
  3458. .set_rpc_method(METHOD_ECHO1)
  3459. .set_wait_for_ready(true));
  3460. // Make sure RPCs all go to the correct backend.
  3461. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  3462. EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
  3463. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  3464. EXPECT_EQ(0, backends_[1]->backend_service1()->request_count());
  3465. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  3466. EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
  3467. }
  3468. TEST_P(LdsRdsTest, XdsRoutingPathRegexMatching) {
  3469. const char* kNewCluster1Name = "new_cluster_1";
  3470. const char* kNewEdsService1Name = "new_eds_service_name_1";
  3471. const char* kNewCluster2Name = "new_cluster_2";
  3472. const char* kNewEdsService2Name = "new_eds_service_name_2";
  3473. const size_t kNumEcho1Rpcs = 10;
  3474. const size_t kNumEcho2Rpcs = 20;
  3475. const size_t kNumEchoRpcs = 30;
  3476. SetNextResolution({});
  3477. SetNextResolutionForLbChannelAllBalancers();
  3478. // Populate new EDS resources.
  3479. AdsServiceImpl::EdsResourceArgs args({
  3480. {"locality0", GetBackendPorts(0, 2)},
  3481. });
  3482. AdsServiceImpl::EdsResourceArgs args1({
  3483. {"locality0", GetBackendPorts(2, 3)},
  3484. });
  3485. AdsServiceImpl::EdsResourceArgs args2({
  3486. {"locality0", GetBackendPorts(3, 4)},
  3487. });
  3488. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  3489. balancers_[0]->ads_service()->SetEdsResource(
  3490. BuildEdsResource(args1, kNewEdsService1Name));
  3491. balancers_[0]->ads_service()->SetEdsResource(
  3492. BuildEdsResource(args2, kNewEdsService2Name));
  3493. // Populate new CDS resources.
  3494. Cluster new_cluster1 = default_cluster_;
  3495. new_cluster1.set_name(kNewCluster1Name);
  3496. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  3497. kNewEdsService1Name);
  3498. balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
  3499. Cluster new_cluster2 = default_cluster_;
  3500. new_cluster2.set_name(kNewCluster2Name);
  3501. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  3502. kNewEdsService2Name);
  3503. balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
  3504. // Populating Route Configurations for LDS.
  3505. RouteConfiguration new_route_config = default_route_config_;
  3506. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3507. // Will match "/grpc.testing.EchoTest1Service/"
  3508. route1->mutable_match()->mutable_safe_regex()->set_regex(".*1.*");
  3509. route1->mutable_route()->set_cluster(kNewCluster1Name);
  3510. auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3511. // Will match "/grpc.testing.EchoTest2Service/"
  3512. route2->mutable_match()->mutable_safe_regex()->set_regex(".*2.*");
  3513. route2->mutable_route()->set_cluster(kNewCluster2Name);
  3514. auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3515. default_route->mutable_match()->set_prefix("");
  3516. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3517. SetRouteConfiguration(0, new_route_config);
  3518. WaitForAllBackends(0, 2);
  3519. CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
  3520. CheckRpcSendOk(
  3521. kNumEcho1Rpcs,
  3522. RpcOptions().set_rpc_service(SERVICE_ECHO1).set_wait_for_ready(true));
  3523. CheckRpcSendOk(
  3524. kNumEcho2Rpcs,
  3525. RpcOptions().set_rpc_service(SERVICE_ECHO2).set_wait_for_ready(true));
  3526. // Make sure RPCs all go to the correct backend.
  3527. for (size_t i = 0; i < 2; ++i) {
  3528. EXPECT_EQ(kNumEchoRpcs / 2,
  3529. backends_[i]->backend_service()->request_count());
  3530. EXPECT_EQ(0, backends_[i]->backend_service1()->request_count());
  3531. EXPECT_EQ(0, backends_[i]->backend_service2()->request_count());
  3532. }
  3533. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  3534. EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
  3535. EXPECT_EQ(0, backends_[2]->backend_service2()->request_count());
  3536. EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
  3537. EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
  3538. EXPECT_EQ(kNumEcho2Rpcs, backends_[3]->backend_service2()->request_count());
  3539. }
  3540. TEST_P(LdsRdsTest, XdsRoutingPathRegexMatchingCaseInsensitive) {
  3541. const char* kNewCluster1Name = "new_cluster_1";
  3542. const char* kNewEdsService1Name = "new_eds_service_name_1";
  3543. const char* kNewCluster2Name = "new_cluster_2";
  3544. const char* kNewEdsService2Name = "new_eds_service_name_2";
  3545. const size_t kNumEcho1Rpcs = 10;
  3546. const size_t kNumEchoRpcs = 30;
  3547. SetNextResolution({});
  3548. SetNextResolutionForLbChannelAllBalancers();
  3549. // Populate new EDS resources.
  3550. AdsServiceImpl::EdsResourceArgs args({
  3551. {"locality0", GetBackendPorts(0, 1)},
  3552. });
  3553. AdsServiceImpl::EdsResourceArgs args1({
  3554. {"locality0", GetBackendPorts(1, 2)},
  3555. });
  3556. AdsServiceImpl::EdsResourceArgs args2({
  3557. {"locality0", GetBackendPorts(2, 3)},
  3558. });
  3559. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  3560. balancers_[0]->ads_service()->SetEdsResource(
  3561. BuildEdsResource(args1, kNewEdsService1Name));
  3562. balancers_[0]->ads_service()->SetEdsResource(
  3563. BuildEdsResource(args2, kNewEdsService2Name));
  3564. // Populate new CDS resources.
  3565. Cluster new_cluster1 = default_cluster_;
  3566. new_cluster1.set_name(kNewCluster1Name);
  3567. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  3568. kNewEdsService1Name);
  3569. balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
  3570. Cluster new_cluster2 = default_cluster_;
  3571. new_cluster2.set_name(kNewCluster2Name);
  3572. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  3573. kNewEdsService2Name);
  3574. balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
  3575. // Populating Route Configurations for LDS.
  3576. RouteConfiguration new_route_config = default_route_config_;
  3577. // First route will not match, since it's case-sensitive.
  3578. // Second route will match with same path.
  3579. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3580. route1->mutable_match()->mutable_safe_regex()->set_regex(
  3581. ".*EcHoTeSt1SErViCe.*");
  3582. route1->mutable_route()->set_cluster(kNewCluster1Name);
  3583. auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3584. route2->mutable_match()->mutable_safe_regex()->set_regex(
  3585. ".*EcHoTeSt1SErViCe.*");
  3586. route2->mutable_match()->mutable_case_sensitive()->set_value(false);
  3587. route2->mutable_route()->set_cluster(kNewCluster2Name);
  3588. auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3589. default_route->mutable_match()->set_prefix("");
  3590. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3591. SetRouteConfiguration(0, new_route_config);
  3592. CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
  3593. CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions()
  3594. .set_rpc_service(SERVICE_ECHO1)
  3595. .set_rpc_method(METHOD_ECHO1)
  3596. .set_wait_for_ready(true));
  3597. // Make sure RPCs all go to the correct backend.
  3598. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  3599. EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
  3600. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  3601. EXPECT_EQ(0, backends_[1]->backend_service1()->request_count());
  3602. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  3603. EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
  3604. }
  3605. TEST_P(LdsRdsTest, XdsRoutingWeightedCluster) {
  3606. const char* kNewCluster1Name = "new_cluster_1";
  3607. const char* kNewEdsService1Name = "new_eds_service_name_1";
  3608. const char* kNewCluster2Name = "new_cluster_2";
  3609. const char* kNewEdsService2Name = "new_eds_service_name_2";
  3610. const char* kNotUsedClusterName = "not_used_cluster";
  3611. const size_t kNumEcho1Rpcs = 1000;
  3612. const size_t kNumEchoRpcs = 10;
  3613. const size_t kWeight75 = 75;
  3614. const size_t kWeight25 = 25;
  3615. SetNextResolution({});
  3616. SetNextResolutionForLbChannelAllBalancers();
  3617. // Populate new EDS resources.
  3618. AdsServiceImpl::EdsResourceArgs args({
  3619. {"locality0", GetBackendPorts(0, 1)},
  3620. });
  3621. AdsServiceImpl::EdsResourceArgs args1({
  3622. {"locality0", GetBackendPorts(1, 2)},
  3623. });
  3624. AdsServiceImpl::EdsResourceArgs args2({
  3625. {"locality0", GetBackendPorts(2, 3)},
  3626. });
  3627. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  3628. balancers_[0]->ads_service()->SetEdsResource(
  3629. BuildEdsResource(args1, kNewEdsService1Name));
  3630. balancers_[0]->ads_service()->SetEdsResource(
  3631. BuildEdsResource(args2, kNewEdsService2Name));
  3632. // Populate new CDS resources.
  3633. Cluster new_cluster1 = default_cluster_;
  3634. new_cluster1.set_name(kNewCluster1Name);
  3635. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  3636. kNewEdsService1Name);
  3637. balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
  3638. Cluster new_cluster2 = default_cluster_;
  3639. new_cluster2.set_name(kNewCluster2Name);
  3640. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  3641. kNewEdsService2Name);
  3642. balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
  3643. // Populating Route Configurations for LDS.
  3644. RouteConfiguration new_route_config = default_route_config_;
  3645. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3646. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3647. auto* weighted_cluster1 =
  3648. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3649. weighted_cluster1->set_name(kNewCluster1Name);
  3650. weighted_cluster1->mutable_weight()->set_value(kWeight75);
  3651. auto* weighted_cluster2 =
  3652. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3653. weighted_cluster2->set_name(kNewCluster2Name);
  3654. weighted_cluster2->mutable_weight()->set_value(kWeight25);
  3655. // Cluster with weight 0 will not be used.
  3656. auto* weighted_cluster3 =
  3657. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3658. weighted_cluster3->set_name(kNotUsedClusterName);
  3659. weighted_cluster3->mutable_weight()->set_value(0);
  3660. route1->mutable_route()
  3661. ->mutable_weighted_clusters()
  3662. ->mutable_total_weight()
  3663. ->set_value(kWeight75 + kWeight25);
  3664. auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3665. default_route->mutable_match()->set_prefix("");
  3666. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3667. SetRouteConfiguration(0, new_route_config);
  3668. WaitForAllBackends(0, 1);
  3669. WaitForAllBackends(1, 3, true, RpcOptions().set_rpc_service(SERVICE_ECHO1));
  3670. CheckRpcSendOk(kNumEchoRpcs);
  3671. CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
  3672. // Make sure RPCs all go to the correct backend.
  3673. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  3674. EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
  3675. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  3676. const int weight_75_request_count =
  3677. backends_[1]->backend_service1()->request_count();
  3678. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  3679. const int weight_25_request_count =
  3680. backends_[2]->backend_service1()->request_count();
  3681. const double kErrorTolerance = 0.2;
  3682. EXPECT_THAT(
  3683. weight_75_request_count,
  3684. ::testing::AllOf(::testing::Ge(static_cast<double>(kNumEcho1Rpcs) *
  3685. kWeight75 / 100 * (1 - kErrorTolerance)),
  3686. ::testing::Le(static_cast<double>(kNumEcho1Rpcs) *
  3687. kWeight75 / 100 * (1 + kErrorTolerance))));
  3688. // TODO(@donnadionne): Reduce tolerance: increased the tolerance to keep the
  3689. // test from flaking while debugging potential root cause.
  3690. const double kErrorToleranceSmallLoad = 0.3;
  3691. gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
  3692. weight_75_request_count, weight_25_request_count);
  3693. EXPECT_THAT(weight_25_request_count,
  3694. ::testing::AllOf(
  3695. ::testing::Ge(static_cast<double>(kNumEcho1Rpcs) * kWeight25 /
  3696. 100 * (1 - kErrorToleranceSmallLoad)),
  3697. ::testing::Le(static_cast<double>(kNumEcho1Rpcs) * kWeight25 /
  3698. 100 * (1 + kErrorToleranceSmallLoad))));
  3699. }
  3700. TEST_P(LdsRdsTest, RouteActionWeightedTargetDefaultRoute) {
  3701. const char* kNewCluster1Name = "new_cluster_1";
  3702. const char* kNewEdsService1Name = "new_eds_service_name_1";
  3703. const char* kNewCluster2Name = "new_cluster_2";
  3704. const char* kNewEdsService2Name = "new_eds_service_name_2";
  3705. const size_t kNumEchoRpcs = 1000;
  3706. const size_t kWeight75 = 75;
  3707. const size_t kWeight25 = 25;
  3708. SetNextResolution({});
  3709. SetNextResolutionForLbChannelAllBalancers();
  3710. // Populate new EDS resources.
  3711. AdsServiceImpl::EdsResourceArgs args({
  3712. {"locality0", GetBackendPorts(0, 1)},
  3713. });
  3714. AdsServiceImpl::EdsResourceArgs args1({
  3715. {"locality0", GetBackendPorts(1, 2)},
  3716. });
  3717. AdsServiceImpl::EdsResourceArgs args2({
  3718. {"locality0", GetBackendPorts(2, 3)},
  3719. });
  3720. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  3721. balancers_[0]->ads_service()->SetEdsResource(
  3722. BuildEdsResource(args1, kNewEdsService1Name));
  3723. balancers_[0]->ads_service()->SetEdsResource(
  3724. BuildEdsResource(args2, kNewEdsService2Name));
  3725. // Populate new CDS resources.
  3726. Cluster new_cluster1 = default_cluster_;
  3727. new_cluster1.set_name(kNewCluster1Name);
  3728. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  3729. kNewEdsService1Name);
  3730. balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
  3731. Cluster new_cluster2 = default_cluster_;
  3732. new_cluster2.set_name(kNewCluster2Name);
  3733. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  3734. kNewEdsService2Name);
  3735. balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
  3736. // Populating Route Configurations for LDS.
  3737. RouteConfiguration new_route_config = default_route_config_;
  3738. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3739. route1->mutable_match()->set_prefix("");
  3740. auto* weighted_cluster1 =
  3741. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3742. weighted_cluster1->set_name(kNewCluster1Name);
  3743. weighted_cluster1->mutable_weight()->set_value(kWeight75);
  3744. auto* weighted_cluster2 =
  3745. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3746. weighted_cluster2->set_name(kNewCluster2Name);
  3747. weighted_cluster2->mutable_weight()->set_value(kWeight25);
  3748. route1->mutable_route()
  3749. ->mutable_weighted_clusters()
  3750. ->mutable_total_weight()
  3751. ->set_value(kWeight75 + kWeight25);
  3752. SetRouteConfiguration(0, new_route_config);
  3753. WaitForAllBackends(1, 3);
  3754. CheckRpcSendOk(kNumEchoRpcs);
  3755. // Make sure RPCs all go to the correct backend.
  3756. EXPECT_EQ(0, backends_[0]->backend_service()->request_count());
  3757. const int weight_75_request_count =
  3758. backends_[1]->backend_service()->request_count();
  3759. const int weight_25_request_count =
  3760. backends_[2]->backend_service()->request_count();
  3761. const double kErrorTolerance = 0.2;
  3762. EXPECT_THAT(
  3763. weight_75_request_count,
  3764. ::testing::AllOf(::testing::Ge(static_cast<double>(kNumEchoRpcs) *
  3765. kWeight75 / 100 * (1 - kErrorTolerance)),
  3766. ::testing::Le(static_cast<double>(kNumEchoRpcs) *
  3767. kWeight75 / 100 * (1 + kErrorTolerance))));
  3768. // TODO(@donnadionne): Reduce tolerance: increased the tolerance to keep the
  3769. // test from flaking while debugging potential root cause.
  3770. const double kErrorToleranceSmallLoad = 0.3;
  3771. gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
  3772. weight_75_request_count, weight_25_request_count);
  3773. EXPECT_THAT(weight_25_request_count,
  3774. ::testing::AllOf(
  3775. ::testing::Ge(static_cast<double>(kNumEchoRpcs) * kWeight25 /
  3776. 100 * (1 - kErrorToleranceSmallLoad)),
  3777. ::testing::Le(static_cast<double>(kNumEchoRpcs) * kWeight25 /
  3778. 100 * (1 + kErrorToleranceSmallLoad))));
  3779. }
  3780. TEST_P(LdsRdsTest, XdsRoutingWeightedClusterUpdateWeights) {
  3781. const char* kNewCluster1Name = "new_cluster_1";
  3782. const char* kNewEdsService1Name = "new_eds_service_name_1";
  3783. const char* kNewCluster2Name = "new_cluster_2";
  3784. const char* kNewEdsService2Name = "new_eds_service_name_2";
  3785. const char* kNewCluster3Name = "new_cluster_3";
  3786. const char* kNewEdsService3Name = "new_eds_service_name_3";
  3787. const size_t kNumEcho1Rpcs = 1000;
  3788. const size_t kNumEchoRpcs = 10;
  3789. const size_t kWeight75 = 75;
  3790. const size_t kWeight25 = 25;
  3791. const size_t kWeight50 = 50;
  3792. SetNextResolution({});
  3793. SetNextResolutionForLbChannelAllBalancers();
  3794. // Populate new EDS resources.
  3795. AdsServiceImpl::EdsResourceArgs args({
  3796. {"locality0", GetBackendPorts(0, 1)},
  3797. });
  3798. AdsServiceImpl::EdsResourceArgs args1({
  3799. {"locality0", GetBackendPorts(1, 2)},
  3800. });
  3801. AdsServiceImpl::EdsResourceArgs args2({
  3802. {"locality0", GetBackendPorts(2, 3)},
  3803. });
  3804. AdsServiceImpl::EdsResourceArgs args3({
  3805. {"locality0", GetBackendPorts(3, 4)},
  3806. });
  3807. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  3808. balancers_[0]->ads_service()->SetEdsResource(
  3809. BuildEdsResource(args1, kNewEdsService1Name));
  3810. balancers_[0]->ads_service()->SetEdsResource(
  3811. BuildEdsResource(args2, kNewEdsService2Name));
  3812. balancers_[0]->ads_service()->SetEdsResource(
  3813. BuildEdsResource(args3, kNewEdsService3Name));
  3814. // Populate new CDS resources.
  3815. Cluster new_cluster1 = default_cluster_;
  3816. new_cluster1.set_name(kNewCluster1Name);
  3817. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  3818. kNewEdsService1Name);
  3819. balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
  3820. Cluster new_cluster2 = default_cluster_;
  3821. new_cluster2.set_name(kNewCluster2Name);
  3822. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  3823. kNewEdsService2Name);
  3824. balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
  3825. Cluster new_cluster3 = default_cluster_;
  3826. new_cluster3.set_name(kNewCluster3Name);
  3827. new_cluster3.mutable_eds_cluster_config()->set_service_name(
  3828. kNewEdsService3Name);
  3829. balancers_[0]->ads_service()->SetCdsResource(new_cluster3);
  3830. // Populating Route Configurations.
  3831. RouteConfiguration new_route_config = default_route_config_;
  3832. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3833. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3834. auto* weighted_cluster1 =
  3835. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3836. weighted_cluster1->set_name(kNewCluster1Name);
  3837. weighted_cluster1->mutable_weight()->set_value(kWeight75);
  3838. auto* weighted_cluster2 =
  3839. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3840. weighted_cluster2->set_name(kNewCluster2Name);
  3841. weighted_cluster2->mutable_weight()->set_value(kWeight25);
  3842. route1->mutable_route()
  3843. ->mutable_weighted_clusters()
  3844. ->mutable_total_weight()
  3845. ->set_value(kWeight75 + kWeight25);
  3846. auto* default_route = new_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, new_route_config);
  3850. WaitForAllBackends(0, 1);
  3851. WaitForAllBackends(1, 3, true, RpcOptions().set_rpc_service(SERVICE_ECHO1));
  3852. CheckRpcSendOk(kNumEchoRpcs);
  3853. CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
  3854. // Make sure RPCs all go to the correct backend.
  3855. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  3856. EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
  3857. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  3858. const int weight_75_request_count =
  3859. backends_[1]->backend_service1()->request_count();
  3860. EXPECT_EQ(0, backends_[1]->backend_service2()->request_count());
  3861. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  3862. const int weight_25_request_count =
  3863. backends_[2]->backend_service1()->request_count();
  3864. EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
  3865. EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
  3866. const double kErrorTolerance = 0.2;
  3867. EXPECT_THAT(
  3868. weight_75_request_count,
  3869. ::testing::AllOf(::testing::Ge(static_cast<double>(kNumEcho1Rpcs) *
  3870. kWeight75 / 100 * (1 - kErrorTolerance)),
  3871. ::testing::Le(static_cast<double>(kNumEcho1Rpcs) *
  3872. kWeight75 / 100 * (1 + kErrorTolerance))));
  3873. // TODO(@donnadionne): Reduce tolerance: increased the tolerance to keep the
  3874. // test from flaking while debugging potential root cause.
  3875. const double kErrorToleranceSmallLoad = 0.3;
  3876. gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
  3877. weight_75_request_count, weight_25_request_count);
  3878. EXPECT_THAT(weight_25_request_count,
  3879. ::testing::AllOf(
  3880. ::testing::Ge(static_cast<double>(kNumEcho1Rpcs) * kWeight25 /
  3881. 100 * (1 - kErrorToleranceSmallLoad)),
  3882. ::testing::Le(static_cast<double>(kNumEcho1Rpcs) * kWeight25 /
  3883. 100 * (1 + kErrorToleranceSmallLoad))));
  3884. // Change Route Configurations: same clusters different weights.
  3885. weighted_cluster1->mutable_weight()->set_value(kWeight50);
  3886. weighted_cluster2->mutable_weight()->set_value(kWeight50);
  3887. // Change default route to a new cluster to help to identify when new polices
  3888. // are seen by the client.
  3889. default_route->mutable_route()->set_cluster(kNewCluster3Name);
  3890. SetRouteConfiguration(0, new_route_config);
  3891. ResetBackendCounters();
  3892. WaitForAllBackends(3, 4);
  3893. CheckRpcSendOk(kNumEchoRpcs);
  3894. CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
  3895. // Make sure RPCs all go to the correct backend.
  3896. EXPECT_EQ(0, backends_[0]->backend_service()->request_count());
  3897. EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
  3898. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  3899. const int weight_50_request_count_1 =
  3900. backends_[1]->backend_service1()->request_count();
  3901. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  3902. const int weight_50_request_count_2 =
  3903. backends_[2]->backend_service1()->request_count();
  3904. EXPECT_EQ(kNumEchoRpcs, backends_[3]->backend_service()->request_count());
  3905. EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
  3906. EXPECT_THAT(
  3907. weight_50_request_count_1,
  3908. ::testing::AllOf(::testing::Ge(static_cast<double>(kNumEcho1Rpcs) *
  3909. kWeight50 / 100 * (1 - kErrorTolerance)),
  3910. ::testing::Le(static_cast<double>(kNumEcho1Rpcs) *
  3911. kWeight50 / 100 * (1 + kErrorTolerance))));
  3912. EXPECT_THAT(
  3913. weight_50_request_count_2,
  3914. ::testing::AllOf(::testing::Ge(static_cast<double>(kNumEcho1Rpcs) *
  3915. kWeight50 / 100 * (1 - kErrorTolerance)),
  3916. ::testing::Le(static_cast<double>(kNumEcho1Rpcs) *
  3917. kWeight50 / 100 * (1 + kErrorTolerance))));
  3918. }
  3919. TEST_P(LdsRdsTest, XdsRoutingWeightedClusterUpdateClusters) {
  3920. const char* kNewCluster1Name = "new_cluster_1";
  3921. const char* kNewEdsService1Name = "new_eds_service_name_1";
  3922. const char* kNewCluster2Name = "new_cluster_2";
  3923. const char* kNewEdsService2Name = "new_eds_service_name_2";
  3924. const char* kNewCluster3Name = "new_cluster_3";
  3925. const char* kNewEdsService3Name = "new_eds_service_name_3";
  3926. const size_t kNumEcho1Rpcs = 1000;
  3927. const size_t kNumEchoRpcs = 10;
  3928. const size_t kWeight75 = 75;
  3929. const size_t kWeight25 = 25;
  3930. const size_t kWeight50 = 50;
  3931. SetNextResolution({});
  3932. SetNextResolutionForLbChannelAllBalancers();
  3933. // Populate new EDS resources.
  3934. AdsServiceImpl::EdsResourceArgs args({
  3935. {"locality0", GetBackendPorts(0, 1)},
  3936. });
  3937. AdsServiceImpl::EdsResourceArgs args1({
  3938. {"locality0", GetBackendPorts(1, 2)},
  3939. });
  3940. AdsServiceImpl::EdsResourceArgs args2({
  3941. {"locality0", GetBackendPorts(2, 3)},
  3942. });
  3943. AdsServiceImpl::EdsResourceArgs args3({
  3944. {"locality0", GetBackendPorts(3, 4)},
  3945. });
  3946. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  3947. balancers_[0]->ads_service()->SetEdsResource(
  3948. BuildEdsResource(args1, kNewEdsService1Name));
  3949. balancers_[0]->ads_service()->SetEdsResource(
  3950. BuildEdsResource(args2, kNewEdsService2Name));
  3951. balancers_[0]->ads_service()->SetEdsResource(
  3952. BuildEdsResource(args3, kNewEdsService3Name));
  3953. // Populate new CDS resources.
  3954. Cluster new_cluster1 = default_cluster_;
  3955. new_cluster1.set_name(kNewCluster1Name);
  3956. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  3957. kNewEdsService1Name);
  3958. balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
  3959. Cluster new_cluster2 = default_cluster_;
  3960. new_cluster2.set_name(kNewCluster2Name);
  3961. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  3962. kNewEdsService2Name);
  3963. balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
  3964. Cluster new_cluster3 = default_cluster_;
  3965. new_cluster3.set_name(kNewCluster3Name);
  3966. new_cluster3.mutable_eds_cluster_config()->set_service_name(
  3967. kNewEdsService3Name);
  3968. balancers_[0]->ads_service()->SetCdsResource(new_cluster3);
  3969. // Populating Route Configurations.
  3970. RouteConfiguration new_route_config = default_route_config_;
  3971. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3972. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3973. auto* weighted_cluster1 =
  3974. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3975. weighted_cluster1->set_name(kNewCluster1Name);
  3976. weighted_cluster1->mutable_weight()->set_value(kWeight75);
  3977. auto* weighted_cluster2 =
  3978. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3979. weighted_cluster2->set_name(kDefaultClusterName);
  3980. weighted_cluster2->mutable_weight()->set_value(kWeight25);
  3981. route1->mutable_route()
  3982. ->mutable_weighted_clusters()
  3983. ->mutable_total_weight()
  3984. ->set_value(kWeight75 + kWeight25);
  3985. auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3986. default_route->mutable_match()->set_prefix("");
  3987. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3988. SetRouteConfiguration(0, new_route_config);
  3989. WaitForAllBackends(0, 1);
  3990. WaitForAllBackends(1, 2, true, RpcOptions().set_rpc_service(SERVICE_ECHO1));
  3991. CheckRpcSendOk(kNumEchoRpcs);
  3992. CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
  3993. // Make sure RPCs all go to the correct backend.
  3994. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  3995. int weight_25_request_count =
  3996. backends_[0]->backend_service1()->request_count();
  3997. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  3998. int weight_75_request_count =
  3999. backends_[1]->backend_service1()->request_count();
  4000. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  4001. EXPECT_EQ(0, backends_[2]->backend_service1()->request_count());
  4002. EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
  4003. EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
  4004. const double kErrorTolerance = 0.2;
  4005. EXPECT_THAT(
  4006. weight_75_request_count,
  4007. ::testing::AllOf(::testing::Ge(static_cast<double>(kNumEcho1Rpcs) *
  4008. kWeight75 / 100 * (1 - kErrorTolerance)),
  4009. ::testing::Le(static_cast<double>(kNumEcho1Rpcs) *
  4010. kWeight75 / 100 * (1 + kErrorTolerance))));
  4011. // TODO(@donnadionne): Reduce tolerance: increased the tolerance to keep the
  4012. // test from flaking while debugging potential root cause.
  4013. const double kErrorToleranceSmallLoad = 0.3;
  4014. gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
  4015. weight_75_request_count, weight_25_request_count);
  4016. EXPECT_THAT(weight_25_request_count,
  4017. ::testing::AllOf(
  4018. ::testing::Ge(static_cast<double>(kNumEcho1Rpcs) * kWeight25 /
  4019. 100 * (1 - kErrorToleranceSmallLoad)),
  4020. ::testing::Le(static_cast<double>(kNumEcho1Rpcs) * kWeight25 /
  4021. 100 * (1 + kErrorToleranceSmallLoad))));
  4022. // Change Route Configurations: new set of clusters with different weights.
  4023. weighted_cluster1->mutable_weight()->set_value(kWeight50);
  4024. weighted_cluster2->set_name(kNewCluster2Name);
  4025. weighted_cluster2->mutable_weight()->set_value(kWeight50);
  4026. SetRouteConfiguration(0, new_route_config);
  4027. ResetBackendCounters();
  4028. WaitForAllBackends(2, 3, true, RpcOptions().set_rpc_service(SERVICE_ECHO1));
  4029. CheckRpcSendOk(kNumEchoRpcs);
  4030. CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
  4031. // Make sure RPCs all go to the correct backend.
  4032. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  4033. EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
  4034. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  4035. const int weight_50_request_count_1 =
  4036. backends_[1]->backend_service1()->request_count();
  4037. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  4038. const int weight_50_request_count_2 =
  4039. backends_[2]->backend_service1()->request_count();
  4040. EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
  4041. EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
  4042. EXPECT_THAT(
  4043. weight_50_request_count_1,
  4044. ::testing::AllOf(::testing::Ge(static_cast<double>(kNumEcho1Rpcs) *
  4045. kWeight50 / 100 * (1 - kErrorTolerance)),
  4046. ::testing::Le(static_cast<double>(kNumEcho1Rpcs) *
  4047. kWeight50 / 100 * (1 + kErrorTolerance))));
  4048. EXPECT_THAT(
  4049. weight_50_request_count_2,
  4050. ::testing::AllOf(::testing::Ge(static_cast<double>(kNumEcho1Rpcs) *
  4051. kWeight50 / 100 * (1 - kErrorTolerance)),
  4052. ::testing::Le(static_cast<double>(kNumEcho1Rpcs) *
  4053. kWeight50 / 100 * (1 + kErrorTolerance))));
  4054. // Change Route Configurations.
  4055. weighted_cluster1->mutable_weight()->set_value(kWeight75);
  4056. weighted_cluster2->set_name(kNewCluster3Name);
  4057. weighted_cluster2->mutable_weight()->set_value(kWeight25);
  4058. SetRouteConfiguration(0, new_route_config);
  4059. ResetBackendCounters();
  4060. WaitForAllBackends(3, 4, true, RpcOptions().set_rpc_service(SERVICE_ECHO1));
  4061. CheckRpcSendOk(kNumEchoRpcs);
  4062. CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
  4063. // Make sure RPCs all go to the correct backend.
  4064. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  4065. EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
  4066. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  4067. weight_75_request_count = backends_[1]->backend_service1()->request_count();
  4068. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  4069. EXPECT_EQ(0, backends_[2]->backend_service1()->request_count());
  4070. EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
  4071. weight_25_request_count = backends_[3]->backend_service1()->request_count();
  4072. EXPECT_THAT(
  4073. weight_75_request_count,
  4074. ::testing::AllOf(::testing::Ge(static_cast<double>(kNumEcho1Rpcs) *
  4075. kWeight75 / 100 * (1 - kErrorTolerance)),
  4076. ::testing::Le(static_cast<double>(kNumEcho1Rpcs) *
  4077. kWeight75 / 100 * (1 + kErrorTolerance))));
  4078. // TODO(@donnadionne): Reduce tolerance: increased the tolerance to keep the
  4079. // test from flaking while debugging potential root cause.
  4080. gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
  4081. weight_75_request_count, weight_25_request_count);
  4082. EXPECT_THAT(weight_25_request_count,
  4083. ::testing::AllOf(
  4084. ::testing::Ge(static_cast<double>(kNumEcho1Rpcs) * kWeight25 /
  4085. 100 * (1 - kErrorToleranceSmallLoad)),
  4086. ::testing::Le(static_cast<double>(kNumEcho1Rpcs) * kWeight25 /
  4087. 100 * (1 + kErrorToleranceSmallLoad))));
  4088. }
  4089. TEST_P(LdsRdsTest, XdsRoutingClusterUpdateClusters) {
  4090. const char* kNewClusterName = "new_cluster";
  4091. const char* kNewEdsServiceName = "new_eds_service_name";
  4092. const size_t kNumEchoRpcs = 5;
  4093. SetNextResolution({});
  4094. SetNextResolutionForLbChannelAllBalancers();
  4095. // Populate new EDS resources.
  4096. AdsServiceImpl::EdsResourceArgs args({
  4097. {"locality0", GetBackendPorts(0, 1)},
  4098. });
  4099. AdsServiceImpl::EdsResourceArgs args1({
  4100. {"locality0", GetBackendPorts(1, 2)},
  4101. });
  4102. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  4103. balancers_[0]->ads_service()->SetEdsResource(
  4104. BuildEdsResource(args1, kNewEdsServiceName));
  4105. // Populate new CDS resources.
  4106. Cluster new_cluster = default_cluster_;
  4107. new_cluster.set_name(kNewClusterName);
  4108. new_cluster.mutable_eds_cluster_config()->set_service_name(
  4109. kNewEdsServiceName);
  4110. balancers_[0]->ads_service()->SetCdsResource(new_cluster);
  4111. // Send Route Configuration.
  4112. RouteConfiguration new_route_config = default_route_config_;
  4113. SetRouteConfiguration(0, new_route_config);
  4114. WaitForAllBackends(0, 1);
  4115. CheckRpcSendOk(kNumEchoRpcs);
  4116. // Make sure RPCs all go to the correct backend.
  4117. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  4118. // Change Route Configurations: new default cluster.
  4119. auto* default_route =
  4120. new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  4121. default_route->mutable_route()->set_cluster(kNewClusterName);
  4122. SetRouteConfiguration(0, new_route_config);
  4123. WaitForAllBackends(1, 2);
  4124. CheckRpcSendOk(kNumEchoRpcs);
  4125. // Make sure RPCs all go to the correct backend.
  4126. EXPECT_EQ(kNumEchoRpcs, backends_[1]->backend_service()->request_count());
  4127. }
  4128. TEST_P(LdsRdsTest, XdsRoutingClusterUpdateClustersWithPickingDelays) {
  4129. const char* kNewClusterName = "new_cluster";
  4130. const char* kNewEdsServiceName = "new_eds_service_name";
  4131. SetNextResolution({});
  4132. SetNextResolutionForLbChannelAllBalancers();
  4133. // Populate new EDS resources.
  4134. AdsServiceImpl::EdsResourceArgs args({
  4135. {"locality0", GetBackendPorts(0, 1)},
  4136. });
  4137. AdsServiceImpl::EdsResourceArgs args1({
  4138. {"locality0", GetBackendPorts(1, 2)},
  4139. });
  4140. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  4141. balancers_[0]->ads_service()->SetEdsResource(
  4142. BuildEdsResource(args1, kNewEdsServiceName));
  4143. // Populate new CDS resources.
  4144. Cluster new_cluster = default_cluster_;
  4145. new_cluster.set_name(kNewClusterName);
  4146. new_cluster.mutable_eds_cluster_config()->set_service_name(
  4147. kNewEdsServiceName);
  4148. balancers_[0]->ads_service()->SetCdsResource(new_cluster);
  4149. // Bring down the current backend: 0, this will delay route picking time,
  4150. // resulting in un-committed RPCs.
  4151. ShutdownBackend(0);
  4152. // Send a RouteConfiguration with a default route that points to
  4153. // backend 0.
  4154. RouteConfiguration new_route_config = default_route_config_;
  4155. SetRouteConfiguration(0, new_route_config);
  4156. // Send exactly one RPC with no deadline and with wait_for_ready=true.
  4157. // This RPC will not complete until after backend 0 is started.
  4158. std::thread sending_rpc([this]() {
  4159. CheckRpcSendOk(1, RpcOptions().set_wait_for_ready(true).set_timeout_ms(0));
  4160. });
  4161. // Send a non-wait_for_ready RPC which should fail, this will tell us
  4162. // that the client has received the update and attempted to connect.
  4163. const Status status = SendRpc(RpcOptions().set_timeout_ms(0));
  4164. EXPECT_FALSE(status.ok());
  4165. // Send a update RouteConfiguration to use backend 1.
  4166. auto* default_route =
  4167. new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  4168. default_route->mutable_route()->set_cluster(kNewClusterName);
  4169. SetRouteConfiguration(0, new_route_config);
  4170. // Wait for RPCs to go to the new backend: 1, this ensures that the client has
  4171. // processed the update.
  4172. WaitForAllBackends(1, 2, false, RpcOptions(), true);
  4173. // Bring up the previous backend: 0, this will allow the delayed RPC to
  4174. // finally call on_call_committed upon completion.
  4175. StartBackend(0);
  4176. sending_rpc.join();
  4177. // Make sure RPCs go to the correct backend:
  4178. EXPECT_EQ(1, backends_[0]->backend_service()->request_count());
  4179. EXPECT_EQ(1, backends_[1]->backend_service()->request_count());
  4180. }
  4181. TEST_P(LdsRdsTest, XdsRoutingApplyXdsTimeout) {
  4182. // TODO(https://github.com/grpc/grpc/issues/24549): TSAN won't work here.
  4183. if (BuiltUnderAsan() || BuiltUnderTsan()) return;
  4184. gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_TIMEOUT", "true");
  4185. const int64_t kTimeoutNano = 500000000;
  4186. const int64_t kTimeoutGrpcTimeoutHeaderMaxSecond = 1;
  4187. const int64_t kTimeoutMaxStreamDurationSecond = 2;
  4188. const int64_t kTimeoutHttpMaxStreamDurationSecond = 3;
  4189. const int64_t kTimeoutApplicationSecond = 4;
  4190. const char* kNewCluster1Name = "new_cluster_1";
  4191. const char* kNewEdsService1Name = "new_eds_service_name_1";
  4192. const char* kNewCluster2Name = "new_cluster_2";
  4193. const char* kNewEdsService2Name = "new_eds_service_name_2";
  4194. const char* kNewCluster3Name = "new_cluster_3";
  4195. const char* kNewEdsService3Name = "new_eds_service_name_3";
  4196. SetNextResolution({});
  4197. SetNextResolutionForLbChannelAllBalancers();
  4198. // Populate new EDS resources.
  4199. AdsServiceImpl::EdsResourceArgs args({
  4200. {"locality0", {g_port_saver->GetPort()}},
  4201. });
  4202. AdsServiceImpl::EdsResourceArgs args1({
  4203. {"locality0", {g_port_saver->GetPort()}},
  4204. });
  4205. AdsServiceImpl::EdsResourceArgs args2({
  4206. {"locality0", {g_port_saver->GetPort()}},
  4207. });
  4208. AdsServiceImpl::EdsResourceArgs args3({
  4209. {"locality0", {g_port_saver->GetPort()}},
  4210. });
  4211. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  4212. balancers_[0]->ads_service()->SetEdsResource(
  4213. BuildEdsResource(args1, kNewEdsService1Name));
  4214. balancers_[0]->ads_service()->SetEdsResource(
  4215. BuildEdsResource(args2, kNewEdsService2Name));
  4216. balancers_[0]->ads_service()->SetEdsResource(
  4217. BuildEdsResource(args3, kNewEdsService3Name));
  4218. // Populate new CDS resources.
  4219. Cluster new_cluster1 = default_cluster_;
  4220. new_cluster1.set_name(kNewCluster1Name);
  4221. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  4222. kNewEdsService1Name);
  4223. balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
  4224. Cluster new_cluster2 = default_cluster_;
  4225. new_cluster2.set_name(kNewCluster2Name);
  4226. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  4227. kNewEdsService2Name);
  4228. balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
  4229. Cluster new_cluster3 = default_cluster_;
  4230. new_cluster3.set_name(kNewCluster3Name);
  4231. new_cluster3.mutable_eds_cluster_config()->set_service_name(
  4232. kNewEdsService3Name);
  4233. balancers_[0]->ads_service()->SetCdsResource(new_cluster3);
  4234. // Construct listener.
  4235. auto listener = default_listener_;
  4236. HttpConnectionManager http_connection_manager;
  4237. // Set up HTTP max_stream_duration of 3.5 seconds
  4238. auto* duration =
  4239. http_connection_manager.mutable_common_http_protocol_options()
  4240. ->mutable_max_stream_duration();
  4241. duration->set_seconds(kTimeoutHttpMaxStreamDurationSecond);
  4242. duration->set_nanos(kTimeoutNano);
  4243. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  4244. http_connection_manager);
  4245. // Construct route config.
  4246. RouteConfiguration new_route_config = default_route_config_;
  4247. // route 1: Set max_stream_duration of 2.5 seconds, Set
  4248. // grpc_timeout_header_max of 1.5
  4249. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  4250. route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service/Echo1");
  4251. route1->mutable_route()->set_cluster(kNewCluster1Name);
  4252. auto* max_stream_duration =
  4253. route1->mutable_route()->mutable_max_stream_duration();
  4254. duration = max_stream_duration->mutable_max_stream_duration();
  4255. duration->set_seconds(kTimeoutMaxStreamDurationSecond);
  4256. duration->set_nanos(kTimeoutNano);
  4257. duration = max_stream_duration->mutable_grpc_timeout_header_max();
  4258. duration->set_seconds(kTimeoutGrpcTimeoutHeaderMaxSecond);
  4259. duration->set_nanos(kTimeoutNano);
  4260. // route 2: Set max_stream_duration of 2.5 seconds
  4261. auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
  4262. route2->mutable_match()->set_path("/grpc.testing.EchoTest2Service/Echo2");
  4263. route2->mutable_route()->set_cluster(kNewCluster2Name);
  4264. max_stream_duration = route2->mutable_route()->mutable_max_stream_duration();
  4265. duration = max_stream_duration->mutable_max_stream_duration();
  4266. duration->set_seconds(kTimeoutMaxStreamDurationSecond);
  4267. duration->set_nanos(kTimeoutNano);
  4268. // route 3: No timeout values in route configuration
  4269. auto* route3 = new_route_config.mutable_virtual_hosts(0)->add_routes();
  4270. route3->mutable_match()->set_path("/grpc.testing.EchoTestService/Echo");
  4271. route3->mutable_route()->set_cluster(kNewCluster3Name);
  4272. // Set listener and route config.
  4273. SetListenerAndRouteConfiguration(0, std::move(listener), new_route_config);
  4274. // Test grpc_timeout_header_max of 1.5 seconds applied
  4275. auto t0 = system_clock::now();
  4276. CheckRpcSendFailure(1,
  4277. RpcOptions()
  4278. .set_rpc_service(SERVICE_ECHO1)
  4279. .set_rpc_method(METHOD_ECHO1)
  4280. .set_wait_for_ready(true)
  4281. .set_timeout_ms(kTimeoutApplicationSecond * 1000),
  4282. StatusCode::DEADLINE_EXCEEDED);
  4283. auto ellapsed_nano_seconds =
  4284. std::chrono::duration_cast<std::chrono::nanoseconds>(system_clock::now() -
  4285. t0);
  4286. EXPECT_GT(ellapsed_nano_seconds.count(),
  4287. kTimeoutGrpcTimeoutHeaderMaxSecond * 1000000000 + kTimeoutNano);
  4288. EXPECT_LT(ellapsed_nano_seconds.count(),
  4289. kTimeoutMaxStreamDurationSecond * 1000000000);
  4290. // Test max_stream_duration of 2.5 seconds applied
  4291. t0 = system_clock::now();
  4292. CheckRpcSendFailure(1,
  4293. RpcOptions()
  4294. .set_rpc_service(SERVICE_ECHO2)
  4295. .set_rpc_method(METHOD_ECHO2)
  4296. .set_wait_for_ready(true)
  4297. .set_timeout_ms(kTimeoutApplicationSecond * 1000),
  4298. StatusCode::DEADLINE_EXCEEDED);
  4299. ellapsed_nano_seconds = std::chrono::duration_cast<std::chrono::nanoseconds>(
  4300. system_clock::now() - t0);
  4301. EXPECT_GT(ellapsed_nano_seconds.count(),
  4302. kTimeoutMaxStreamDurationSecond * 1000000000 + kTimeoutNano);
  4303. EXPECT_LT(ellapsed_nano_seconds.count(),
  4304. kTimeoutHttpMaxStreamDurationSecond * 1000000000);
  4305. // Test http_stream_duration of 3.5 seconds applied
  4306. t0 = system_clock::now();
  4307. CheckRpcSendFailure(1,
  4308. RpcOptions().set_wait_for_ready(true).set_timeout_ms(
  4309. kTimeoutApplicationSecond * 1000),
  4310. StatusCode::DEADLINE_EXCEEDED);
  4311. ellapsed_nano_seconds = std::chrono::duration_cast<std::chrono::nanoseconds>(
  4312. system_clock::now() - t0);
  4313. EXPECT_GT(ellapsed_nano_seconds.count(),
  4314. kTimeoutHttpMaxStreamDurationSecond * 1000000000 + kTimeoutNano);
  4315. EXPECT_LT(ellapsed_nano_seconds.count(),
  4316. kTimeoutApplicationSecond * 1000000000);
  4317. gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_ENABLE_TIMEOUT");
  4318. }
  4319. TEST_P(LdsRdsTest, XdsRoutingXdsTimeoutDisabled) {
  4320. const int64_t kTimeoutMillis = 500;
  4321. const int64_t kTimeoutNano = kTimeoutMillis * 1000000;
  4322. const int64_t kTimeoutGrpcTimeoutHeaderMaxSecond = 1;
  4323. const int64_t kTimeoutApplicationSecond = 4;
  4324. SetNextResolution({});
  4325. SetNextResolutionForLbChannelAllBalancers();
  4326. // Populate new EDS resources.
  4327. AdsServiceImpl::EdsResourceArgs args({
  4328. {"locality0", {g_port_saver->GetPort()}},
  4329. });
  4330. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  4331. RouteConfiguration new_route_config = default_route_config_;
  4332. // route 1: Set grpc_timeout_header_max of 1.5
  4333. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  4334. auto* max_stream_duration =
  4335. route1->mutable_route()->mutable_max_stream_duration();
  4336. auto* duration = max_stream_duration->mutable_grpc_timeout_header_max();
  4337. duration->set_seconds(kTimeoutGrpcTimeoutHeaderMaxSecond);
  4338. duration->set_nanos(kTimeoutNano);
  4339. SetRouteConfiguration(0, new_route_config);
  4340. // Test grpc_timeout_header_max of 1.5 seconds is not applied
  4341. gpr_timespec t0 = gpr_now(GPR_CLOCK_MONOTONIC);
  4342. gpr_timespec est_timeout_time = gpr_time_add(
  4343. t0, gpr_time_from_millis(
  4344. kTimeoutGrpcTimeoutHeaderMaxSecond * 1000 + kTimeoutMillis,
  4345. GPR_TIMESPAN));
  4346. CheckRpcSendFailure(1,
  4347. RpcOptions()
  4348. .set_rpc_service(SERVICE_ECHO1)
  4349. .set_rpc_method(METHOD_ECHO1)
  4350. .set_wait_for_ready(true)
  4351. .set_timeout_ms(kTimeoutApplicationSecond * 1000),
  4352. StatusCode::DEADLINE_EXCEEDED);
  4353. gpr_timespec timeout_time = gpr_now(GPR_CLOCK_MONOTONIC);
  4354. EXPECT_GT(gpr_time_cmp(timeout_time, est_timeout_time), 0);
  4355. }
  4356. TEST_P(LdsRdsTest, XdsRoutingHttpTimeoutDisabled) {
  4357. const int64_t kTimeoutMillis = 500;
  4358. const int64_t kTimeoutNano = kTimeoutMillis * 1000000;
  4359. const int64_t kTimeoutHttpMaxStreamDurationSecond = 3;
  4360. const int64_t kTimeoutApplicationSecond = 4;
  4361. SetNextResolution({});
  4362. SetNextResolutionForLbChannelAllBalancers();
  4363. // Populate new EDS resources.
  4364. AdsServiceImpl::EdsResourceArgs args({
  4365. {"locality0", {g_port_saver->GetPort()}},
  4366. });
  4367. // Construct listener.
  4368. auto listener = default_listener_;
  4369. HttpConnectionManager http_connection_manager;
  4370. // Set up HTTP max_stream_duration of 3.5 seconds
  4371. auto* duration =
  4372. http_connection_manager.mutable_common_http_protocol_options()
  4373. ->mutable_max_stream_duration();
  4374. duration->set_seconds(kTimeoutHttpMaxStreamDurationSecond);
  4375. duration->set_nanos(kTimeoutNano);
  4376. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  4377. http_connection_manager);
  4378. SetListenerAndRouteConfiguration(0, std::move(listener),
  4379. default_route_config_);
  4380. // Test http_stream_duration of 3.5 seconds is not applied
  4381. auto t0 = gpr_now(GPR_CLOCK_MONOTONIC);
  4382. auto est_timeout_time = gpr_time_add(
  4383. t0, gpr_time_from_millis(
  4384. kTimeoutHttpMaxStreamDurationSecond * 1000 + kTimeoutMillis,
  4385. GPR_TIMESPAN));
  4386. CheckRpcSendFailure(1,
  4387. RpcOptions().set_wait_for_ready(true).set_timeout_ms(
  4388. kTimeoutApplicationSecond * 1000),
  4389. StatusCode::DEADLINE_EXCEEDED);
  4390. auto timeout_time = gpr_now(GPR_CLOCK_MONOTONIC);
  4391. EXPECT_GT(gpr_time_cmp(timeout_time, est_timeout_time), 0);
  4392. }
  4393. TEST_P(LdsRdsTest, XdsRoutingApplyApplicationTimeoutWhenXdsTimeoutExplicit0) {
  4394. gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_TIMEOUT", "true");
  4395. const int64_t kTimeoutNano = 500000000;
  4396. const int64_t kTimeoutMaxStreamDurationSecond = 2;
  4397. const int64_t kTimeoutHttpMaxStreamDurationSecond = 3;
  4398. const int64_t kTimeoutApplicationSecond = 4;
  4399. const char* kNewCluster1Name = "new_cluster_1";
  4400. const char* kNewEdsService1Name = "new_eds_service_name_1";
  4401. const char* kNewCluster2Name = "new_cluster_2";
  4402. const char* kNewEdsService2Name = "new_eds_service_name_2";
  4403. SetNextResolution({});
  4404. SetNextResolutionForLbChannelAllBalancers();
  4405. // Populate new EDS resources.
  4406. AdsServiceImpl::EdsResourceArgs args({
  4407. {"locality0", {g_port_saver->GetPort()}},
  4408. });
  4409. AdsServiceImpl::EdsResourceArgs args1({
  4410. {"locality0", {g_port_saver->GetPort()}},
  4411. });
  4412. AdsServiceImpl::EdsResourceArgs args2({
  4413. {"locality0", {g_port_saver->GetPort()}},
  4414. });
  4415. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  4416. balancers_[0]->ads_service()->SetEdsResource(
  4417. BuildEdsResource(args1, kNewEdsService1Name));
  4418. balancers_[0]->ads_service()->SetEdsResource(
  4419. BuildEdsResource(args2, kNewEdsService2Name));
  4420. // Populate new CDS resources.
  4421. Cluster new_cluster1 = default_cluster_;
  4422. new_cluster1.set_name(kNewCluster1Name);
  4423. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  4424. kNewEdsService1Name);
  4425. balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
  4426. Cluster new_cluster2 = default_cluster_;
  4427. new_cluster2.set_name(kNewCluster2Name);
  4428. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  4429. kNewEdsService2Name);
  4430. balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
  4431. // Construct listener.
  4432. auto listener = default_listener_;
  4433. HttpConnectionManager http_connection_manager;
  4434. // Set up HTTP max_stream_duration of 3.5 seconds
  4435. auto* duration =
  4436. http_connection_manager.mutable_common_http_protocol_options()
  4437. ->mutable_max_stream_duration();
  4438. duration->set_seconds(kTimeoutHttpMaxStreamDurationSecond);
  4439. duration->set_nanos(kTimeoutNano);
  4440. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  4441. http_connection_manager);
  4442. // Construct route config.
  4443. RouteConfiguration new_route_config = default_route_config_;
  4444. // route 1: Set max_stream_duration of 2.5 seconds, Set
  4445. // grpc_timeout_header_max of 0
  4446. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  4447. route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service/Echo1");
  4448. route1->mutable_route()->set_cluster(kNewCluster1Name);
  4449. auto* max_stream_duration =
  4450. route1->mutable_route()->mutable_max_stream_duration();
  4451. duration = max_stream_duration->mutable_max_stream_duration();
  4452. duration->set_seconds(kTimeoutMaxStreamDurationSecond);
  4453. duration->set_nanos(kTimeoutNano);
  4454. duration = max_stream_duration->mutable_grpc_timeout_header_max();
  4455. duration->set_seconds(0);
  4456. duration->set_nanos(0);
  4457. // route 2: Set max_stream_duration to 0
  4458. auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
  4459. route2->mutable_match()->set_path("/grpc.testing.EchoTest2Service/Echo2");
  4460. route2->mutable_route()->set_cluster(kNewCluster2Name);
  4461. max_stream_duration = route2->mutable_route()->mutable_max_stream_duration();
  4462. duration = max_stream_duration->mutable_max_stream_duration();
  4463. duration->set_seconds(0);
  4464. duration->set_nanos(0);
  4465. // Set listener and route config.
  4466. SetListenerAndRouteConfiguration(0, std::move(listener), new_route_config);
  4467. // Test application timeout is applied for route 1
  4468. auto t0 = system_clock::now();
  4469. CheckRpcSendFailure(1,
  4470. RpcOptions()
  4471. .set_rpc_service(SERVICE_ECHO1)
  4472. .set_rpc_method(METHOD_ECHO1)
  4473. .set_wait_for_ready(true)
  4474. .set_timeout_ms(kTimeoutApplicationSecond * 1000),
  4475. StatusCode::DEADLINE_EXCEEDED);
  4476. auto ellapsed_nano_seconds =
  4477. std::chrono::duration_cast<std::chrono::nanoseconds>(system_clock::now() -
  4478. t0);
  4479. EXPECT_GT(ellapsed_nano_seconds.count(),
  4480. kTimeoutApplicationSecond * 1000000000);
  4481. // Test application timeout is applied for route 2
  4482. t0 = system_clock::now();
  4483. CheckRpcSendFailure(1,
  4484. RpcOptions()
  4485. .set_rpc_service(SERVICE_ECHO2)
  4486. .set_rpc_method(METHOD_ECHO2)
  4487. .set_wait_for_ready(true)
  4488. .set_timeout_ms(kTimeoutApplicationSecond * 1000),
  4489. StatusCode::DEADLINE_EXCEEDED);
  4490. ellapsed_nano_seconds = std::chrono::duration_cast<std::chrono::nanoseconds>(
  4491. system_clock::now() - t0);
  4492. EXPECT_GT(ellapsed_nano_seconds.count(),
  4493. kTimeoutApplicationSecond * 1000000000);
  4494. gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_ENABLE_TIMEOUT");
  4495. }
  4496. TEST_P(LdsRdsTest, XdsRoutingApplyApplicationTimeoutWhenHttpTimeoutExplicit0) {
  4497. gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_TIMEOUT", "true");
  4498. const int64_t kTimeoutApplicationSecond = 4;
  4499. SetNextResolution({});
  4500. SetNextResolutionForLbChannelAllBalancers();
  4501. // Populate new EDS resources.
  4502. AdsServiceImpl::EdsResourceArgs args({
  4503. {"locality0", {g_port_saver->GetPort()}},
  4504. });
  4505. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  4506. HttpConnectionManager http_connection_manager;
  4507. // Set up HTTP max_stream_duration to be explicit 0
  4508. auto* duration =
  4509. http_connection_manager.mutable_common_http_protocol_options()
  4510. ->mutable_max_stream_duration();
  4511. duration->set_seconds(0);
  4512. duration->set_nanos(0);
  4513. auto listener = default_listener_;
  4514. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  4515. http_connection_manager);
  4516. // Set listener and route config.
  4517. SetListenerAndRouteConfiguration(0, std::move(listener),
  4518. default_route_config_);
  4519. // Test application timeout is applied for route 1
  4520. auto t0 = system_clock::now();
  4521. CheckRpcSendFailure(1,
  4522. RpcOptions().set_wait_for_ready(true).set_timeout_ms(
  4523. kTimeoutApplicationSecond * 1000),
  4524. StatusCode::DEADLINE_EXCEEDED);
  4525. auto ellapsed_nano_seconds =
  4526. std::chrono::duration_cast<std::chrono::nanoseconds>(system_clock::now() -
  4527. t0);
  4528. EXPECT_GT(ellapsed_nano_seconds.count(),
  4529. kTimeoutApplicationSecond * 1000000000);
  4530. gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_ENABLE_TIMEOUT");
  4531. }
  4532. // Test to ensure application-specified deadline won't be affected when
  4533. // the xDS config does not specify a timeout.
  4534. TEST_P(LdsRdsTest, XdsRoutingWithOnlyApplicationTimeout) {
  4535. gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_TIMEOUT", "true");
  4536. const int64_t kTimeoutApplicationSecond = 4;
  4537. SetNextResolution({});
  4538. SetNextResolutionForLbChannelAllBalancers();
  4539. // Populate new EDS resources.
  4540. AdsServiceImpl::EdsResourceArgs args({
  4541. {"locality0", {g_port_saver->GetPort()}},
  4542. });
  4543. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  4544. auto t0 = system_clock::now();
  4545. CheckRpcSendFailure(1,
  4546. RpcOptions().set_wait_for_ready(true).set_timeout_ms(
  4547. kTimeoutApplicationSecond * 1000),
  4548. StatusCode::DEADLINE_EXCEEDED);
  4549. auto ellapsed_nano_seconds =
  4550. std::chrono::duration_cast<std::chrono::nanoseconds>(system_clock::now() -
  4551. t0);
  4552. EXPECT_GT(ellapsed_nano_seconds.count(),
  4553. kTimeoutApplicationSecond * 1000000000);
  4554. gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_ENABLE_TIMEOUT");
  4555. }
  4556. TEST_P(LdsRdsTest, XdsRoutingHeadersMatching) {
  4557. const char* kNewClusterName = "new_cluster";
  4558. const char* kNewEdsServiceName = "new_eds_service_name";
  4559. const size_t kNumEcho1Rpcs = 100;
  4560. const size_t kNumEchoRpcs = 5;
  4561. SetNextResolution({});
  4562. SetNextResolutionForLbChannelAllBalancers();
  4563. // Populate new EDS resources.
  4564. AdsServiceImpl::EdsResourceArgs args({
  4565. {"locality0", GetBackendPorts(0, 1)},
  4566. });
  4567. AdsServiceImpl::EdsResourceArgs args1({
  4568. {"locality0", GetBackendPorts(1, 2)},
  4569. });
  4570. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  4571. balancers_[0]->ads_service()->SetEdsResource(
  4572. BuildEdsResource(args1, kNewEdsServiceName));
  4573. // Populate new CDS resources.
  4574. Cluster new_cluster = default_cluster_;
  4575. new_cluster.set_name(kNewClusterName);
  4576. new_cluster.mutable_eds_cluster_config()->set_service_name(
  4577. kNewEdsServiceName);
  4578. balancers_[0]->ads_service()->SetCdsResource(new_cluster);
  4579. // Populating Route Configurations for LDS.
  4580. RouteConfiguration route_config = default_route_config_;
  4581. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  4582. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  4583. auto* header_matcher1 = route1->mutable_match()->add_headers();
  4584. header_matcher1->set_name("header1");
  4585. header_matcher1->set_exact_match("POST,PUT,GET");
  4586. auto* header_matcher2 = route1->mutable_match()->add_headers();
  4587. header_matcher2->set_name("header2");
  4588. header_matcher2->mutable_safe_regex_match()->set_regex("[a-z]*");
  4589. auto* header_matcher3 = route1->mutable_match()->add_headers();
  4590. header_matcher3->set_name("header3");
  4591. header_matcher3->mutable_range_match()->set_start(1);
  4592. header_matcher3->mutable_range_match()->set_end(1000);
  4593. auto* header_matcher4 = route1->mutable_match()->add_headers();
  4594. header_matcher4->set_name("header4");
  4595. header_matcher4->set_present_match(false);
  4596. auto* header_matcher5 = route1->mutable_match()->add_headers();
  4597. header_matcher5->set_name("header5");
  4598. header_matcher5->set_present_match(true);
  4599. auto* header_matcher6 = route1->mutable_match()->add_headers();
  4600. header_matcher6->set_name("header6");
  4601. header_matcher6->set_prefix_match("/grpc");
  4602. auto* header_matcher7 = route1->mutable_match()->add_headers();
  4603. header_matcher7->set_name("header7");
  4604. header_matcher7->set_suffix_match(".cc");
  4605. header_matcher7->set_invert_match(true);
  4606. route1->mutable_route()->set_cluster(kNewClusterName);
  4607. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  4608. default_route->mutable_match()->set_prefix("");
  4609. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  4610. SetRouteConfiguration(0, route_config);
  4611. std::vector<std::pair<std::string, std::string>> metadata = {
  4612. {"header1", "POST"},
  4613. {"header2", "blah"},
  4614. {"header3", "1"},
  4615. {"header5", "anything"},
  4616. {"header6", "/grpc.testing.EchoTest1Service/"},
  4617. {"header1", "PUT"},
  4618. {"header7", "grpc.java"},
  4619. {"header1", "GET"},
  4620. };
  4621. const auto header_match_rpc_options = RpcOptions()
  4622. .set_rpc_service(SERVICE_ECHO1)
  4623. .set_rpc_method(METHOD_ECHO1)
  4624. .set_metadata(std::move(metadata));
  4625. // Make sure all backends are up.
  4626. WaitForAllBackends(0, 1);
  4627. WaitForAllBackends(1, 2, true, header_match_rpc_options);
  4628. // Send RPCs.
  4629. CheckRpcSendOk(kNumEchoRpcs);
  4630. CheckRpcSendOk(kNumEcho1Rpcs, header_match_rpc_options);
  4631. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  4632. EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
  4633. EXPECT_EQ(0, backends_[0]->backend_service2()->request_count());
  4634. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  4635. EXPECT_EQ(kNumEcho1Rpcs, backends_[1]->backend_service1()->request_count());
  4636. EXPECT_EQ(0, backends_[1]->backend_service2()->request_count());
  4637. const auto& response_state = RouteConfigurationResponseState(0);
  4638. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
  4639. }
  4640. TEST_P(LdsRdsTest, XdsRoutingHeadersMatchingSpecialHeaderContentType) {
  4641. const char* kNewClusterName = "new_cluster";
  4642. const char* kNewEdsServiceName = "new_eds_service_name";
  4643. const size_t kNumEchoRpcs = 100;
  4644. SetNextResolution({});
  4645. SetNextResolutionForLbChannelAllBalancers();
  4646. // Populate new EDS resources.
  4647. AdsServiceImpl::EdsResourceArgs args({
  4648. {"locality0", GetBackendPorts(0, 1)},
  4649. });
  4650. AdsServiceImpl::EdsResourceArgs args1({
  4651. {"locality0", GetBackendPorts(1, 2)},
  4652. });
  4653. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  4654. balancers_[0]->ads_service()->SetEdsResource(
  4655. BuildEdsResource(args1, kNewEdsServiceName));
  4656. // Populate new CDS resources.
  4657. Cluster new_cluster = default_cluster_;
  4658. new_cluster.set_name(kNewClusterName);
  4659. new_cluster.mutable_eds_cluster_config()->set_service_name(
  4660. kNewEdsServiceName);
  4661. balancers_[0]->ads_service()->SetCdsResource(new_cluster);
  4662. // Populating Route Configurations for LDS.
  4663. RouteConfiguration route_config = default_route_config_;
  4664. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  4665. route1->mutable_match()->set_prefix("");
  4666. auto* header_matcher1 = route1->mutable_match()->add_headers();
  4667. header_matcher1->set_name("content-type");
  4668. header_matcher1->set_exact_match("notapplication/grpc");
  4669. route1->mutable_route()->set_cluster(kNewClusterName);
  4670. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  4671. default_route->mutable_match()->set_prefix("");
  4672. auto* header_matcher2 = default_route->mutable_match()->add_headers();
  4673. header_matcher2->set_name("content-type");
  4674. header_matcher2->set_exact_match("application/grpc");
  4675. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  4676. SetRouteConfiguration(0, route_config);
  4677. // Make sure the backend is up.
  4678. WaitForAllBackends(0, 1);
  4679. // Send RPCs.
  4680. CheckRpcSendOk(kNumEchoRpcs);
  4681. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  4682. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  4683. const auto& response_state = RouteConfigurationResponseState(0);
  4684. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
  4685. }
  4686. TEST_P(LdsRdsTest, XdsRoutingHeadersMatchingSpecialCasesToIgnore) {
  4687. const char* kNewCluster1Name = "new_cluster_1";
  4688. const char* kNewEdsService1Name = "new_eds_service_name_1";
  4689. const char* kNewCluster2Name = "new_cluster_2";
  4690. const char* kNewEdsService2Name = "new_eds_service_name_2";
  4691. const size_t kNumEchoRpcs = 100;
  4692. SetNextResolution({});
  4693. SetNextResolutionForLbChannelAllBalancers();
  4694. // Populate new EDS resources.
  4695. AdsServiceImpl::EdsResourceArgs args({
  4696. {"locality0", GetBackendPorts(0, 1)},
  4697. });
  4698. AdsServiceImpl::EdsResourceArgs args1({
  4699. {"locality0", GetBackendPorts(1, 2)},
  4700. });
  4701. AdsServiceImpl::EdsResourceArgs args2({
  4702. {"locality0", GetBackendPorts(2, 3)},
  4703. });
  4704. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  4705. balancers_[0]->ads_service()->SetEdsResource(
  4706. BuildEdsResource(args1, kNewEdsService1Name));
  4707. balancers_[0]->ads_service()->SetEdsResource(
  4708. BuildEdsResource(args2, kNewEdsService2Name));
  4709. // Populate new CDS resources.
  4710. Cluster new_cluster1 = default_cluster_;
  4711. new_cluster1.set_name(kNewCluster1Name);
  4712. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  4713. kNewEdsService1Name);
  4714. balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
  4715. Cluster new_cluster2 = default_cluster_;
  4716. new_cluster2.set_name(kNewCluster2Name);
  4717. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  4718. kNewEdsService2Name);
  4719. balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
  4720. // Populating Route Configurations for LDS.
  4721. RouteConfiguration route_config = default_route_config_;
  4722. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  4723. route1->mutable_match()->set_prefix("");
  4724. auto* header_matcher1 = route1->mutable_match()->add_headers();
  4725. header_matcher1->set_name("grpc-foo-bin");
  4726. header_matcher1->set_present_match(true);
  4727. route1->mutable_route()->set_cluster(kNewCluster1Name);
  4728. auto route2 = route_config.mutable_virtual_hosts(0)->add_routes();
  4729. route2->mutable_match()->set_prefix("");
  4730. auto* header_matcher2 = route2->mutable_match()->add_headers();
  4731. header_matcher2->set_name("grpc-previous-rpc-attempts");
  4732. header_matcher2->set_present_match(true);
  4733. route2->mutable_route()->set_cluster(kNewCluster2Name);
  4734. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  4735. default_route->mutable_match()->set_prefix("");
  4736. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  4737. SetRouteConfiguration(0, route_config);
  4738. // Send headers which will mismatch each route
  4739. std::vector<std::pair<std::string, std::string>> metadata = {
  4740. {"grpc-foo-bin", "grpc-foo-bin"},
  4741. {"grpc-previous-rpc-attempts", "grpc-previous-rpc-attempts"},
  4742. };
  4743. WaitForAllBackends(0, 1);
  4744. CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_metadata(metadata));
  4745. // Verify that only the default backend got RPCs since all previous routes
  4746. // were mismatched.
  4747. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  4748. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  4749. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  4750. const auto& response_state = RouteConfigurationResponseState(0);
  4751. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
  4752. }
  4753. TEST_P(LdsRdsTest, XdsRoutingRuntimeFractionMatching) {
  4754. const char* kNewClusterName = "new_cluster";
  4755. const char* kNewEdsServiceName = "new_eds_service_name";
  4756. const size_t kNumRpcs = 1000;
  4757. SetNextResolution({});
  4758. SetNextResolutionForLbChannelAllBalancers();
  4759. // Populate new EDS resources.
  4760. AdsServiceImpl::EdsResourceArgs args({
  4761. {"locality0", GetBackendPorts(0, 1)},
  4762. });
  4763. AdsServiceImpl::EdsResourceArgs args1({
  4764. {"locality0", GetBackendPorts(1, 2)},
  4765. });
  4766. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  4767. balancers_[0]->ads_service()->SetEdsResource(
  4768. BuildEdsResource(args1, kNewEdsServiceName));
  4769. // Populate new CDS resources.
  4770. Cluster new_cluster = default_cluster_;
  4771. new_cluster.set_name(kNewClusterName);
  4772. new_cluster.mutable_eds_cluster_config()->set_service_name(
  4773. kNewEdsServiceName);
  4774. balancers_[0]->ads_service()->SetCdsResource(new_cluster);
  4775. // Populating Route Configurations for LDS.
  4776. RouteConfiguration route_config = default_route_config_;
  4777. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  4778. route1->mutable_match()
  4779. ->mutable_runtime_fraction()
  4780. ->mutable_default_value()
  4781. ->set_numerator(25);
  4782. route1->mutable_route()->set_cluster(kNewClusterName);
  4783. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  4784. default_route->mutable_match()->set_prefix("");
  4785. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  4786. SetRouteConfiguration(0, route_config);
  4787. WaitForAllBackends(0, 2);
  4788. CheckRpcSendOk(kNumRpcs);
  4789. const int default_backend_count =
  4790. backends_[0]->backend_service()->request_count();
  4791. const int matched_backend_count =
  4792. backends_[1]->backend_service()->request_count();
  4793. const double kErrorTolerance = 0.2;
  4794. EXPECT_THAT(
  4795. default_backend_count,
  4796. ::testing::AllOf(::testing::Ge(static_cast<double>(kNumRpcs) * 75 / 100 *
  4797. (1 - kErrorTolerance)),
  4798. ::testing::Le(static_cast<double>(kNumRpcs) * 75 / 100 *
  4799. (1 + kErrorTolerance))));
  4800. EXPECT_THAT(
  4801. matched_backend_count,
  4802. ::testing::AllOf(::testing::Ge(static_cast<double>(kNumRpcs) * 25 / 100 *
  4803. (1 - kErrorTolerance)),
  4804. ::testing::Le(static_cast<double>(kNumRpcs) * 25 / 100 *
  4805. (1 + kErrorTolerance))));
  4806. const auto& response_state = RouteConfigurationResponseState(0);
  4807. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
  4808. }
  4809. TEST_P(LdsRdsTest, XdsRoutingHeadersMatchingUnmatchCases) {
  4810. const char* kNewCluster1Name = "new_cluster_1";
  4811. const char* kNewEdsService1Name = "new_eds_service_name_1";
  4812. const char* kNewCluster2Name = "new_cluster_2";
  4813. const char* kNewEdsService2Name = "new_eds_service_name_2";
  4814. const char* kNewCluster3Name = "new_cluster_3";
  4815. const char* kNewEdsService3Name = "new_eds_service_name_3";
  4816. const size_t kNumEcho1Rpcs = 100;
  4817. const size_t kNumEchoRpcs = 5;
  4818. SetNextResolution({});
  4819. SetNextResolutionForLbChannelAllBalancers();
  4820. // Populate new EDS resources.
  4821. AdsServiceImpl::EdsResourceArgs args({
  4822. {"locality0", GetBackendPorts(0, 1)},
  4823. });
  4824. AdsServiceImpl::EdsResourceArgs args1({
  4825. {"locality0", GetBackendPorts(1, 2)},
  4826. });
  4827. AdsServiceImpl::EdsResourceArgs args2({
  4828. {"locality0", GetBackendPorts(2, 3)},
  4829. });
  4830. AdsServiceImpl::EdsResourceArgs args3({
  4831. {"locality0", GetBackendPorts(3, 4)},
  4832. });
  4833. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  4834. balancers_[0]->ads_service()->SetEdsResource(
  4835. BuildEdsResource(args1, kNewEdsService1Name));
  4836. balancers_[0]->ads_service()->SetEdsResource(
  4837. BuildEdsResource(args2, kNewEdsService2Name));
  4838. balancers_[0]->ads_service()->SetEdsResource(
  4839. BuildEdsResource(args3, kNewEdsService3Name));
  4840. // Populate new CDS resources.
  4841. Cluster new_cluster1 = default_cluster_;
  4842. new_cluster1.set_name(kNewCluster1Name);
  4843. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  4844. kNewEdsService1Name);
  4845. balancers_[0]->ads_service()->SetCdsResource(new_cluster1);
  4846. Cluster new_cluster2 = default_cluster_;
  4847. new_cluster2.set_name(kNewCluster2Name);
  4848. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  4849. kNewEdsService2Name);
  4850. balancers_[0]->ads_service()->SetCdsResource(new_cluster2);
  4851. Cluster new_cluster3 = default_cluster_;
  4852. new_cluster3.set_name(kNewCluster3Name);
  4853. new_cluster3.mutable_eds_cluster_config()->set_service_name(
  4854. kNewEdsService3Name);
  4855. balancers_[0]->ads_service()->SetCdsResource(new_cluster3);
  4856. // Populating Route Configurations for LDS.
  4857. RouteConfiguration route_config = default_route_config_;
  4858. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  4859. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  4860. auto* header_matcher1 = route1->mutable_match()->add_headers();
  4861. header_matcher1->set_name("header1");
  4862. header_matcher1->set_exact_match("POST");
  4863. route1->mutable_route()->set_cluster(kNewCluster1Name);
  4864. auto route2 = route_config.mutable_virtual_hosts(0)->add_routes();
  4865. route2->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  4866. auto* header_matcher2 = route2->mutable_match()->add_headers();
  4867. header_matcher2->set_name("header2");
  4868. header_matcher2->mutable_range_match()->set_start(1);
  4869. header_matcher2->mutable_range_match()->set_end(1000);
  4870. route2->mutable_route()->set_cluster(kNewCluster2Name);
  4871. auto route3 = route_config.mutable_virtual_hosts(0)->add_routes();
  4872. route3->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  4873. auto* header_matcher3 = route3->mutable_match()->add_headers();
  4874. header_matcher3->set_name("header3");
  4875. header_matcher3->mutable_safe_regex_match()->set_regex("[a-z]*");
  4876. route3->mutable_route()->set_cluster(kNewCluster3Name);
  4877. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  4878. default_route->mutable_match()->set_prefix("");
  4879. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  4880. SetRouteConfiguration(0, route_config);
  4881. // Send headers which will mismatch each route
  4882. std::vector<std::pair<std::string, std::string>> metadata = {
  4883. {"header1", "POST"},
  4884. {"header2", "1000"},
  4885. {"header3", "123"},
  4886. {"header1", "GET"},
  4887. };
  4888. WaitForAllBackends(0, 1);
  4889. CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_metadata(metadata));
  4890. CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions()
  4891. .set_rpc_service(SERVICE_ECHO1)
  4892. .set_rpc_method(METHOD_ECHO1)
  4893. .set_metadata(metadata));
  4894. // Verify that only the default backend got RPCs since all previous routes
  4895. // were mismatched.
  4896. for (size_t i = 1; i < 4; ++i) {
  4897. EXPECT_EQ(0, backends_[i]->backend_service()->request_count());
  4898. EXPECT_EQ(0, backends_[i]->backend_service1()->request_count());
  4899. EXPECT_EQ(0, backends_[i]->backend_service2()->request_count());
  4900. }
  4901. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  4902. EXPECT_EQ(kNumEcho1Rpcs, backends_[0]->backend_service1()->request_count());
  4903. EXPECT_EQ(0, backends_[0]->backend_service2()->request_count());
  4904. const auto& response_state = RouteConfigurationResponseState(0);
  4905. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::ACKED);
  4906. }
  4907. TEST_P(LdsRdsTest, XdsRoutingChangeRoutesWithoutChangingClusters) {
  4908. const char* kNewClusterName = "new_cluster";
  4909. const char* kNewEdsServiceName = "new_eds_service_name";
  4910. SetNextResolution({});
  4911. SetNextResolutionForLbChannelAllBalancers();
  4912. // Populate new EDS resources.
  4913. AdsServiceImpl::EdsResourceArgs args({
  4914. {"locality0", GetBackendPorts(0, 1)},
  4915. });
  4916. AdsServiceImpl::EdsResourceArgs args1({
  4917. {"locality0", GetBackendPorts(1, 2)},
  4918. });
  4919. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  4920. balancers_[0]->ads_service()->SetEdsResource(
  4921. BuildEdsResource(args1, kNewEdsServiceName));
  4922. // Populate new CDS resources.
  4923. Cluster new_cluster = default_cluster_;
  4924. new_cluster.set_name(kNewClusterName);
  4925. new_cluster.mutable_eds_cluster_config()->set_service_name(
  4926. kNewEdsServiceName);
  4927. balancers_[0]->ads_service()->SetCdsResource(new_cluster);
  4928. // Populating Route Configurations for LDS.
  4929. RouteConfiguration route_config = default_route_config_;
  4930. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  4931. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  4932. route1->mutable_route()->set_cluster(kNewClusterName);
  4933. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  4934. default_route->mutable_match()->set_prefix("");
  4935. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  4936. SetRouteConfiguration(0, route_config);
  4937. // Make sure all backends are up and that requests for each RPC
  4938. // service go to the right backends.
  4939. WaitForAllBackends(0, 1, false);
  4940. WaitForAllBackends(1, 2, false, RpcOptions().set_rpc_service(SERVICE_ECHO1));
  4941. WaitForAllBackends(0, 1, false, RpcOptions().set_rpc_service(SERVICE_ECHO2));
  4942. // Requests for services Echo and Echo2 should have gone to backend 0.
  4943. EXPECT_EQ(1, backends_[0]->backend_service()->request_count());
  4944. EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
  4945. EXPECT_EQ(1, backends_[0]->backend_service2()->request_count());
  4946. // Requests for service Echo1 should have gone to backend 1.
  4947. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  4948. EXPECT_EQ(1, backends_[1]->backend_service1()->request_count());
  4949. EXPECT_EQ(0, backends_[1]->backend_service2()->request_count());
  4950. // Now send an update that changes the first route to match a
  4951. // different RPC service, and wait for the client to make the change.
  4952. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest2Service/");
  4953. SetRouteConfiguration(0, route_config);
  4954. WaitForAllBackends(1, 2, true, RpcOptions().set_rpc_service(SERVICE_ECHO2));
  4955. // Now repeat the earlier test, making sure all traffic goes to the
  4956. // right place.
  4957. WaitForAllBackends(0, 1, false);
  4958. WaitForAllBackends(0, 1, false, RpcOptions().set_rpc_service(SERVICE_ECHO1));
  4959. WaitForAllBackends(1, 2, false, RpcOptions().set_rpc_service(SERVICE_ECHO2));
  4960. // Requests for services Echo and Echo1 should have gone to backend 0.
  4961. EXPECT_EQ(1, backends_[0]->backend_service()->request_count());
  4962. EXPECT_EQ(1, backends_[0]->backend_service1()->request_count());
  4963. EXPECT_EQ(0, backends_[0]->backend_service2()->request_count());
  4964. // Requests for service Echo2 should have gone to backend 1.
  4965. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  4966. EXPECT_EQ(0, backends_[1]->backend_service1()->request_count());
  4967. EXPECT_EQ(1, backends_[1]->backend_service2()->request_count());
  4968. }
  4969. using CdsTest = BasicTest;
  4970. // Tests that CDS client should send an ACK upon correct CDS response.
  4971. TEST_P(CdsTest, Vanilla) {
  4972. SetNextResolution({});
  4973. SetNextResolutionForLbChannelAllBalancers();
  4974. (void)SendRpc();
  4975. EXPECT_EQ(balancers_[0]->ads_service()->cds_response_state().state,
  4976. AdsServiceImpl::ResponseState::ACKED);
  4977. }
  4978. // Tests that CDS client should send a NACK if the cluster type in CDS response
  4979. // is other than EDS.
  4980. TEST_P(CdsTest, WrongClusterType) {
  4981. auto cluster = default_cluster_;
  4982. cluster.set_type(Cluster::STATIC);
  4983. balancers_[0]->ads_service()->SetCdsResource(cluster);
  4984. SetNextResolution({});
  4985. SetNextResolutionForLbChannelAllBalancers();
  4986. CheckRpcSendFailure();
  4987. const auto& response_state =
  4988. balancers_[0]->ads_service()->cds_response_state();
  4989. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  4990. EXPECT_EQ(response_state.error_message, "DiscoveryType is not EDS.");
  4991. }
  4992. // Tests that CDS client should send a NACK if the eds_config in CDS response is
  4993. // other than ADS.
  4994. TEST_P(CdsTest, WrongEdsConfig) {
  4995. auto cluster = default_cluster_;
  4996. cluster.mutable_eds_cluster_config()->mutable_eds_config()->mutable_self();
  4997. balancers_[0]->ads_service()->SetCdsResource(cluster);
  4998. SetNextResolution({});
  4999. SetNextResolutionForLbChannelAllBalancers();
  5000. CheckRpcSendFailure();
  5001. const auto& response_state =
  5002. balancers_[0]->ads_service()->cds_response_state();
  5003. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  5004. EXPECT_EQ(response_state.error_message, "EDS ConfigSource is not ADS.");
  5005. }
  5006. // Tests that CDS client should send a NACK if the lb_policy in CDS response is
  5007. // other than ROUND_ROBIN.
  5008. TEST_P(CdsTest, WrongLbPolicy) {
  5009. auto cluster = default_cluster_;
  5010. cluster.set_lb_policy(Cluster::LEAST_REQUEST);
  5011. balancers_[0]->ads_service()->SetCdsResource(cluster);
  5012. SetNextResolution({});
  5013. SetNextResolutionForLbChannelAllBalancers();
  5014. CheckRpcSendFailure();
  5015. const auto& response_state =
  5016. balancers_[0]->ads_service()->cds_response_state();
  5017. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  5018. EXPECT_EQ(response_state.error_message, "LB policy is not ROUND_ROBIN.");
  5019. }
  5020. // Tests that CDS client should send a NACK if the lrs_server in CDS response is
  5021. // other than SELF.
  5022. TEST_P(CdsTest, WrongLrsServer) {
  5023. auto cluster = default_cluster_;
  5024. cluster.mutable_lrs_server()->mutable_ads();
  5025. balancers_[0]->ads_service()->SetCdsResource(cluster);
  5026. SetNextResolution({});
  5027. SetNextResolutionForLbChannelAllBalancers();
  5028. CheckRpcSendFailure();
  5029. const auto& response_state =
  5030. balancers_[0]->ads_service()->cds_response_state();
  5031. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  5032. EXPECT_EQ(response_state.error_message, "LRS ConfigSource is not self.");
  5033. }
  5034. class XdsSecurityTest : public BasicTest {
  5035. protected:
  5036. static void SetUpTestCase() {
  5037. gpr_setenv("GRPC_XDS_EXPERIMENTAL_SECURITY_SUPPORT", "true");
  5038. BasicTest::SetUpTestCase();
  5039. grpc_core::CertificateProviderRegistry::RegisterCertificateProviderFactory(
  5040. absl::make_unique<FakeCertificateProviderFactory>(
  5041. "fake1", &g_fake1_cert_data_map));
  5042. grpc_core::CertificateProviderRegistry::RegisterCertificateProviderFactory(
  5043. absl::make_unique<FakeCertificateProviderFactory>(
  5044. "fake2", &g_fake2_cert_data_map));
  5045. }
  5046. static void TearDownTestCase() {
  5047. BasicTest::TearDownTestCase();
  5048. gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_SECURITY_SUPPORT");
  5049. }
  5050. void SetUp() override {
  5051. BasicTest::SetUp();
  5052. root_cert_ = ReadFile(kCaCertPath);
  5053. bad_root_cert_ = ReadFile(kBadClientCertPath);
  5054. identity_pair_ = ReadTlsIdentityPair(kClientKeyPath, kClientCertPath);
  5055. // TODO(yashykt): Use different client certs here instead of reusing server
  5056. // certs after https://github.com/grpc/grpc/pull/24876 is merged
  5057. fallback_identity_pair_ =
  5058. ReadTlsIdentityPair(kServerKeyPath, kServerCertPath);
  5059. bad_identity_pair_ =
  5060. ReadTlsIdentityPair(kBadClientKeyPath, kBadClientCertPath);
  5061. server_san_exact_.set_exact("*.test.google.fr");
  5062. server_san_prefix_.set_prefix("waterzooi.test.google");
  5063. server_san_suffix_.set_suffix("google.fr");
  5064. server_san_contains_.set_contains("google");
  5065. server_san_regex_.mutable_safe_regex()->mutable_google_re2();
  5066. server_san_regex_.mutable_safe_regex()->set_regex(
  5067. "(foo|waterzooi).test.google.(fr|be)");
  5068. bad_san_1_.set_exact("192.168.1.4");
  5069. bad_san_2_.set_exact("foo.test.google.in");
  5070. authenticated_identity_ = {"testclient"};
  5071. fallback_authenticated_identity_ = {"*.test.google.fr",
  5072. "waterzooi.test.google.be",
  5073. "*.test.youtube.com", "192.168.1.3"};
  5074. AdsServiceImpl::EdsResourceArgs args({
  5075. {"locality0", GetBackendPorts(0, 1)},
  5076. });
  5077. balancers_[0]->ads_service()->SetEdsResource(
  5078. BuildEdsResource(args, DefaultEdsServiceName()));
  5079. SetNextResolutionForLbChannelAllBalancers();
  5080. }
  5081. void TearDown() override {
  5082. g_fake1_cert_data_map = nullptr;
  5083. g_fake2_cert_data_map = nullptr;
  5084. BasicTest::TearDown();
  5085. }
  5086. // Sends CDS updates with the new security configuration and verifies that
  5087. // after propagation, this new configuration is used for connections. If \a
  5088. // identity_instance_name and \a root_instance_name are both empty,
  5089. // connections are expected to use fallback credentials.
  5090. void UpdateAndVerifyXdsSecurityConfiguration(
  5091. absl::string_view root_instance_name,
  5092. absl::string_view root_certificate_name,
  5093. absl::string_view identity_instance_name,
  5094. absl::string_view identity_certificate_name,
  5095. const std::vector<StringMatcher>& san_matchers,
  5096. const std::vector<std::string>& expected_authenticated_identity,
  5097. bool test_expects_failure = false) {
  5098. auto cluster = default_cluster_;
  5099. if (!identity_instance_name.empty() || !root_instance_name.empty()) {
  5100. auto* transport_socket = cluster.mutable_transport_socket();
  5101. transport_socket->set_name("envoy.transport_sockets.tls");
  5102. UpstreamTlsContext upstream_tls_context;
  5103. if (!identity_instance_name.empty()) {
  5104. upstream_tls_context.mutable_common_tls_context()
  5105. ->mutable_tls_certificate_certificate_provider_instance()
  5106. ->set_instance_name(std::string(identity_instance_name));
  5107. upstream_tls_context.mutable_common_tls_context()
  5108. ->mutable_tls_certificate_certificate_provider_instance()
  5109. ->set_certificate_name(std::string(identity_certificate_name));
  5110. }
  5111. if (!root_instance_name.empty()) {
  5112. upstream_tls_context.mutable_common_tls_context()
  5113. ->mutable_combined_validation_context()
  5114. ->mutable_validation_context_certificate_provider_instance()
  5115. ->set_instance_name(std::string(root_instance_name));
  5116. upstream_tls_context.mutable_common_tls_context()
  5117. ->mutable_combined_validation_context()
  5118. ->mutable_validation_context_certificate_provider_instance()
  5119. ->set_certificate_name(std::string(root_certificate_name));
  5120. }
  5121. if (!san_matchers.empty()) {
  5122. auto* validation_context =
  5123. upstream_tls_context.mutable_common_tls_context()
  5124. ->mutable_combined_validation_context()
  5125. ->mutable_default_validation_context();
  5126. for (const auto& san_matcher : san_matchers) {
  5127. *validation_context->add_match_subject_alt_names() = san_matcher;
  5128. }
  5129. }
  5130. transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
  5131. }
  5132. balancers_[0]->ads_service()->SetCdsResource(cluster);
  5133. // The updates might take time to have an effect, so use a retry loop.
  5134. constexpr int kRetryCount = 10;
  5135. int num_tries = 0;
  5136. for (; num_tries < kRetryCount; num_tries++) {
  5137. // Give some time for the updates to propagate.
  5138. gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(100));
  5139. ShutdownBackend(0);
  5140. StartBackend(0);
  5141. ResetBackendCounters();
  5142. if (test_expects_failure) {
  5143. if (!SendRpc().ok()) break;
  5144. } else {
  5145. WaitForBackend(0);
  5146. if (SendRpc().ok() &&
  5147. backends_[0]->backend_service()->request_count() == 1UL &&
  5148. backends_[0]->backend_service()->last_peer_identity() ==
  5149. expected_authenticated_identity) {
  5150. break;
  5151. }
  5152. }
  5153. }
  5154. EXPECT_TRUE(num_tries < kRetryCount);
  5155. }
  5156. std::string root_cert_;
  5157. std::string bad_root_cert_;
  5158. grpc_core::PemKeyCertPairList identity_pair_;
  5159. grpc_core::PemKeyCertPairList fallback_identity_pair_;
  5160. grpc_core::PemKeyCertPairList bad_identity_pair_;
  5161. StringMatcher server_san_exact_;
  5162. StringMatcher server_san_prefix_;
  5163. StringMatcher server_san_suffix_;
  5164. StringMatcher server_san_contains_;
  5165. StringMatcher server_san_regex_;
  5166. StringMatcher bad_san_1_;
  5167. StringMatcher bad_san_2_;
  5168. std::vector<std::string> authenticated_identity_;
  5169. std::vector<std::string> fallback_authenticated_identity_;
  5170. };
  5171. TEST_P(XdsSecurityTest,
  5172. TLSConfigurationWithoutValidationContextCertificateProviderInstance) {
  5173. auto cluster = default_cluster_;
  5174. auto* transport_socket = cluster.mutable_transport_socket();
  5175. transport_socket->set_name("envoy.transport_sockets.tls");
  5176. balancers_[0]->ads_service()->SetCdsResource(cluster);
  5177. CheckRpcSendFailure();
  5178. const auto& response_state =
  5179. balancers_[0]->ads_service()->cds_response_state();
  5180. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  5181. EXPECT_EQ(response_state.error_message,
  5182. "TLS configuration provided but no "
  5183. "validation_context_certificate_provider_instance found.");
  5184. }
  5185. TEST_P(
  5186. XdsSecurityTest,
  5187. MatchSubjectAltNamesProvidedWithoutValidationContextCertificateProviderInstance) {
  5188. auto cluster = default_cluster_;
  5189. auto* transport_socket = cluster.mutable_transport_socket();
  5190. transport_socket->set_name("envoy.transport_sockets.tls");
  5191. UpstreamTlsContext upstream_tls_context;
  5192. auto* validation_context = upstream_tls_context.mutable_common_tls_context()
  5193. ->mutable_combined_validation_context()
  5194. ->mutable_default_validation_context();
  5195. *validation_context->add_match_subject_alt_names() = server_san_exact_;
  5196. transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
  5197. balancers_[0]->ads_service()->SetCdsResource(cluster);
  5198. CheckRpcSendFailure();
  5199. const auto& response_state =
  5200. balancers_[0]->ads_service()->cds_response_state();
  5201. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  5202. EXPECT_EQ(response_state.error_message,
  5203. "TLS configuration provided but no "
  5204. "validation_context_certificate_provider_instance found.");
  5205. }
  5206. TEST_P(
  5207. XdsSecurityTest,
  5208. TlsCertificateCertificateProviderInstanceWithoutValidationContextCertificateProviderInstance) {
  5209. auto cluster = default_cluster_;
  5210. auto* transport_socket = cluster.mutable_transport_socket();
  5211. transport_socket->set_name("envoy.transport_sockets.tls");
  5212. UpstreamTlsContext upstream_tls_context;
  5213. upstream_tls_context.mutable_common_tls_context()
  5214. ->mutable_tls_certificate_certificate_provider_instance()
  5215. ->set_instance_name(std::string("instance_name"));
  5216. transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
  5217. balancers_[0]->ads_service()->SetCdsResource(cluster);
  5218. CheckRpcSendFailure();
  5219. const auto& response_state =
  5220. balancers_[0]->ads_service()->cds_response_state();
  5221. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  5222. EXPECT_EQ(response_state.error_message,
  5223. "TLS configuration provided but no "
  5224. "validation_context_certificate_provider_instance found.");
  5225. }
  5226. TEST_P(XdsSecurityTest, RegexSanMatcherDoesNotAllowIgnoreCase) {
  5227. auto cluster = default_cluster_;
  5228. auto* transport_socket = cluster.mutable_transport_socket();
  5229. transport_socket->set_name("envoy.transport_sockets.tls");
  5230. UpstreamTlsContext upstream_tls_context;
  5231. upstream_tls_context.mutable_common_tls_context()
  5232. ->mutable_combined_validation_context()
  5233. ->mutable_validation_context_certificate_provider_instance()
  5234. ->set_instance_name(std::string("fake_plugin1"));
  5235. auto* validation_context = upstream_tls_context.mutable_common_tls_context()
  5236. ->mutable_combined_validation_context()
  5237. ->mutable_default_validation_context();
  5238. StringMatcher matcher;
  5239. matcher.mutable_safe_regex()->mutable_google_re2();
  5240. matcher.mutable_safe_regex()->set_regex(
  5241. "(foo|waterzooi).test.google.(fr|be)");
  5242. matcher.set_ignore_case(true);
  5243. *validation_context->add_match_subject_alt_names() = matcher;
  5244. transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
  5245. balancers_[0]->ads_service()->SetCdsResource(cluster);
  5246. CheckRpcSendFailure();
  5247. const auto& response_state =
  5248. balancers_[0]->ads_service()->cds_response_state();
  5249. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  5250. EXPECT_EQ(response_state.error_message,
  5251. "StringMatcher: ignore_case has no effect for SAFE_REGEX.");
  5252. }
  5253. TEST_P(XdsSecurityTest, UnknownRootCertificateProvider) {
  5254. auto cluster = default_cluster_;
  5255. auto* transport_socket = cluster.mutable_transport_socket();
  5256. transport_socket->set_name("envoy.transport_sockets.tls");
  5257. UpstreamTlsContext upstream_tls_context;
  5258. upstream_tls_context.mutable_common_tls_context()
  5259. ->mutable_combined_validation_context()
  5260. ->mutable_validation_context_certificate_provider_instance()
  5261. ->set_instance_name("unknown");
  5262. transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
  5263. balancers_[0]->ads_service()->SetCdsResource(cluster);
  5264. CheckRpcSendFailure(1, RpcOptions(), StatusCode::UNAVAILABLE);
  5265. }
  5266. TEST_P(XdsSecurityTest, UnknownIdentityCertificateProvider) {
  5267. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  5268. {"", {root_cert_, identity_pair_}}};
  5269. g_fake1_cert_data_map = &fake1_cert_map;
  5270. auto cluster = default_cluster_;
  5271. auto* transport_socket = cluster.mutable_transport_socket();
  5272. transport_socket->set_name("envoy.transport_sockets.tls");
  5273. UpstreamTlsContext upstream_tls_context;
  5274. upstream_tls_context.mutable_common_tls_context()
  5275. ->mutable_tls_certificate_certificate_provider_instance()
  5276. ->set_instance_name("unknown");
  5277. upstream_tls_context.mutable_common_tls_context()
  5278. ->mutable_combined_validation_context()
  5279. ->mutable_validation_context_certificate_provider_instance()
  5280. ->set_instance_name("fake_plugin1");
  5281. transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
  5282. balancers_[0]->ads_service()->SetCdsResource(cluster);
  5283. CheckRpcSendFailure(1, RpcOptions(), StatusCode::UNAVAILABLE);
  5284. g_fake1_cert_data_map = nullptr;
  5285. }
  5286. TEST_P(XdsSecurityTest, TestMtlsConfigurationWithNoSanMatchers) {
  5287. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  5288. {"", {root_cert_, identity_pair_}}};
  5289. g_fake1_cert_data_map = &fake1_cert_map;
  5290. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  5291. "", {}, authenticated_identity_);
  5292. g_fake1_cert_data_map = nullptr;
  5293. }
  5294. TEST_P(XdsSecurityTest, TestMtlsConfigurationWithExactSanMatcher) {
  5295. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  5296. {"", {root_cert_, identity_pair_}}};
  5297. g_fake1_cert_data_map = &fake1_cert_map;
  5298. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  5299. "", {server_san_exact_},
  5300. authenticated_identity_);
  5301. g_fake1_cert_data_map = nullptr;
  5302. }
  5303. TEST_P(XdsSecurityTest, TestMtlsConfigurationWithPrefixSanMatcher) {
  5304. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  5305. {"", {root_cert_, identity_pair_}}};
  5306. g_fake1_cert_data_map = &fake1_cert_map;
  5307. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  5308. "", {server_san_prefix_},
  5309. authenticated_identity_);
  5310. g_fake1_cert_data_map = nullptr;
  5311. }
  5312. TEST_P(XdsSecurityTest, TestMtlsConfigurationWithSuffixSanMatcher) {
  5313. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  5314. {"", {root_cert_, identity_pair_}}};
  5315. g_fake1_cert_data_map = &fake1_cert_map;
  5316. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  5317. "", {server_san_suffix_},
  5318. authenticated_identity_);
  5319. g_fake1_cert_data_map = nullptr;
  5320. }
  5321. TEST_P(XdsSecurityTest, TestMtlsConfigurationWithContainsSanMatcher) {
  5322. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  5323. {"", {root_cert_, identity_pair_}}};
  5324. g_fake1_cert_data_map = &fake1_cert_map;
  5325. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  5326. "", {server_san_contains_},
  5327. authenticated_identity_);
  5328. g_fake1_cert_data_map = nullptr;
  5329. }
  5330. TEST_P(XdsSecurityTest, TestMtlsConfigurationWithRegexSanMatcher) {
  5331. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  5332. {"", {root_cert_, identity_pair_}}};
  5333. g_fake1_cert_data_map = &fake1_cert_map;
  5334. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  5335. "", {server_san_regex_},
  5336. authenticated_identity_);
  5337. g_fake1_cert_data_map = nullptr;
  5338. }
  5339. TEST_P(XdsSecurityTest, TestMtlsConfigurationWithSanMatchersUpdate) {
  5340. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  5341. {"", {root_cert_, identity_pair_}}};
  5342. g_fake1_cert_data_map = &fake1_cert_map;
  5343. UpdateAndVerifyXdsSecurityConfiguration(
  5344. "fake_plugin1", "", "fake_plugin1", "",
  5345. {server_san_exact_, server_san_prefix_}, authenticated_identity_);
  5346. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  5347. "", {bad_san_1_, bad_san_2_}, {},
  5348. true /* failure */);
  5349. UpdateAndVerifyXdsSecurityConfiguration(
  5350. "fake_plugin1", "", "fake_plugin1", "",
  5351. {server_san_prefix_, server_san_regex_}, authenticated_identity_);
  5352. g_fake1_cert_data_map = nullptr;
  5353. }
  5354. TEST_P(XdsSecurityTest, TestMtlsConfigurationWithRootPluginUpdate) {
  5355. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  5356. {"", {root_cert_, identity_pair_}}};
  5357. g_fake1_cert_data_map = &fake1_cert_map;
  5358. FakeCertificateProvider::CertDataMap fake2_cert_map = {
  5359. {"", {bad_root_cert_, bad_identity_pair_}}};
  5360. g_fake2_cert_data_map = &fake2_cert_map;
  5361. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  5362. "", {server_san_exact_},
  5363. authenticated_identity_);
  5364. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin2" /* bad root */, "",
  5365. "fake_plugin1", "", {}, {},
  5366. true /* failure */);
  5367. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  5368. "", {server_san_exact_},
  5369. authenticated_identity_);
  5370. g_fake1_cert_data_map = nullptr;
  5371. g_fake2_cert_data_map = nullptr;
  5372. }
  5373. TEST_P(XdsSecurityTest, TestMtlsConfigurationWithIdentityPluginUpdate) {
  5374. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  5375. {"", {root_cert_, identity_pair_}}};
  5376. g_fake1_cert_data_map = &fake1_cert_map;
  5377. FakeCertificateProvider::CertDataMap fake2_cert_map = {
  5378. {"", {root_cert_, fallback_identity_pair_}}};
  5379. g_fake2_cert_data_map = &fake2_cert_map;
  5380. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  5381. "", {server_san_exact_},
  5382. authenticated_identity_);
  5383. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin2",
  5384. "", {server_san_exact_},
  5385. fallback_authenticated_identity_);
  5386. g_fake1_cert_data_map = nullptr;
  5387. g_fake2_cert_data_map = nullptr;
  5388. }
  5389. TEST_P(XdsSecurityTest, TestMtlsConfigurationWithBothPluginsUpdated) {
  5390. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  5391. {"", {root_cert_, identity_pair_}}};
  5392. g_fake1_cert_data_map = &fake1_cert_map;
  5393. FakeCertificateProvider::CertDataMap fake2_cert_map = {
  5394. {"", {bad_root_cert_, bad_identity_pair_}},
  5395. {"good", {root_cert_, fallback_identity_pair_}}};
  5396. g_fake2_cert_data_map = &fake2_cert_map;
  5397. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin2", "", "fake_plugin2",
  5398. "", {}, {}, true /* failure */);
  5399. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  5400. "", {server_san_prefix_},
  5401. authenticated_identity_);
  5402. UpdateAndVerifyXdsSecurityConfiguration(
  5403. "fake_plugin2", "good", "fake_plugin2", "good", {server_san_prefix_},
  5404. fallback_authenticated_identity_);
  5405. g_fake1_cert_data_map = nullptr;
  5406. g_fake2_cert_data_map = nullptr;
  5407. }
  5408. TEST_P(XdsSecurityTest, TestMtlsConfigurationWithRootCertificateNameUpdate) {
  5409. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  5410. {"", {root_cert_, identity_pair_}},
  5411. {"bad", {bad_root_cert_, bad_identity_pair_}}};
  5412. g_fake1_cert_data_map = &fake1_cert_map;
  5413. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  5414. "", {server_san_regex_},
  5415. authenticated_identity_);
  5416. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "bad", "fake_plugin1",
  5417. "", {server_san_regex_}, {},
  5418. true /* failure */);
  5419. g_fake1_cert_data_map = nullptr;
  5420. }
  5421. TEST_P(XdsSecurityTest,
  5422. TestMtlsConfigurationWithIdentityCertificateNameUpdate) {
  5423. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  5424. {"", {root_cert_, identity_pair_}},
  5425. {"bad", {bad_root_cert_, bad_identity_pair_}}};
  5426. g_fake1_cert_data_map = &fake1_cert_map;
  5427. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  5428. "", {server_san_exact_},
  5429. authenticated_identity_);
  5430. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  5431. "bad", {server_san_exact_}, {},
  5432. true /* failure */);
  5433. g_fake1_cert_data_map = nullptr;
  5434. }
  5435. TEST_P(XdsSecurityTest,
  5436. TestMtlsConfigurationWithIdentityCertificateNameUpdateGoodCerts) {
  5437. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  5438. {"", {root_cert_, identity_pair_}},
  5439. {"good", {root_cert_, fallback_identity_pair_}}};
  5440. g_fake1_cert_data_map = &fake1_cert_map;
  5441. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  5442. "", {server_san_exact_},
  5443. authenticated_identity_);
  5444. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  5445. "good", {server_san_exact_},
  5446. fallback_authenticated_identity_);
  5447. g_fake1_cert_data_map = nullptr;
  5448. }
  5449. TEST_P(XdsSecurityTest, TestMtlsConfigurationWithBothCertificateNamesUpdated) {
  5450. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  5451. {"", {root_cert_, identity_pair_}},
  5452. {"bad", {bad_root_cert_, bad_identity_pair_}}};
  5453. g_fake1_cert_data_map = &fake1_cert_map;
  5454. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "bad", "fake_plugin1",
  5455. "bad", {server_san_prefix_}, {},
  5456. true /* failure */);
  5457. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  5458. "", {server_san_prefix_},
  5459. authenticated_identity_);
  5460. g_fake1_cert_data_map = nullptr;
  5461. }
  5462. TEST_P(XdsSecurityTest, TestTlsConfigurationWithNoSanMatchers) {
  5463. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  5464. {"", {root_cert_, identity_pair_}}};
  5465. g_fake1_cert_data_map = &fake1_cert_map;
  5466. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "", {},
  5467. {} /* unauthenticated */);
  5468. g_fake1_cert_data_map = nullptr;
  5469. }
  5470. TEST_P(XdsSecurityTest, TestTlsConfigurationWithSanMatchers) {
  5471. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  5472. {"", {root_cert_, identity_pair_}}};
  5473. g_fake1_cert_data_map = &fake1_cert_map;
  5474. UpdateAndVerifyXdsSecurityConfiguration(
  5475. "fake_plugin1", "", "", "",
  5476. {server_san_exact_, server_san_prefix_, server_san_regex_},
  5477. {} /* unauthenticated */);
  5478. g_fake1_cert_data_map = nullptr;
  5479. }
  5480. TEST_P(XdsSecurityTest, TestTlsConfigurationWithSanMatchersUpdate) {
  5481. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  5482. {"", {root_cert_, identity_pair_}}};
  5483. g_fake1_cert_data_map = &fake1_cert_map;
  5484. UpdateAndVerifyXdsSecurityConfiguration(
  5485. "fake_plugin1", "", "", "", {server_san_exact_, server_san_prefix_},
  5486. {} /* unauthenticated */);
  5487. UpdateAndVerifyXdsSecurityConfiguration(
  5488. "fake_plugin1", "", "", "", {bad_san_1_, bad_san_2_},
  5489. {} /* unauthenticated */, true /* failure */);
  5490. UpdateAndVerifyXdsSecurityConfiguration(
  5491. "fake_plugin1", "", "", "", {server_san_prefix_, server_san_regex_},
  5492. {} /* unauthenticated */);
  5493. g_fake1_cert_data_map = nullptr;
  5494. }
  5495. TEST_P(XdsSecurityTest, TestTlsConfigurationWithRootCertificateNameUpdate) {
  5496. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  5497. {"", {root_cert_, identity_pair_}},
  5498. {"bad", {bad_root_cert_, bad_identity_pair_}}};
  5499. g_fake1_cert_data_map = &fake1_cert_map;
  5500. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
  5501. {server_san_exact_},
  5502. {} /* unauthenticated */);
  5503. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "bad", "", "",
  5504. {server_san_exact_}, {},
  5505. true /* failure */);
  5506. g_fake1_cert_data_map = nullptr;
  5507. }
  5508. TEST_P(XdsSecurityTest, TestTlsConfigurationWithRootPluginUpdate) {
  5509. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  5510. {"", {root_cert_, identity_pair_}}};
  5511. g_fake1_cert_data_map = &fake1_cert_map;
  5512. FakeCertificateProvider::CertDataMap fake2_cert_map = {
  5513. {"", {bad_root_cert_, bad_identity_pair_}}};
  5514. g_fake2_cert_data_map = &fake2_cert_map;
  5515. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
  5516. {server_san_exact_},
  5517. {} /* unauthenticated */);
  5518. UpdateAndVerifyXdsSecurityConfiguration(
  5519. "fake_plugin2", "", "", "", {server_san_exact_}, {}, true /* failure */);
  5520. g_fake1_cert_data_map = nullptr;
  5521. g_fake2_cert_data_map = nullptr;
  5522. }
  5523. TEST_P(XdsSecurityTest, TestFallbackConfiguration) {
  5524. UpdateAndVerifyXdsSecurityConfiguration("", "", "", "", {},
  5525. fallback_authenticated_identity_);
  5526. g_fake1_cert_data_map = nullptr;
  5527. }
  5528. TEST_P(XdsSecurityTest, TestMtlsToTls) {
  5529. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  5530. {"", {root_cert_, identity_pair_}}};
  5531. g_fake1_cert_data_map = &fake1_cert_map;
  5532. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  5533. "", {server_san_exact_},
  5534. authenticated_identity_);
  5535. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
  5536. {server_san_exact_},
  5537. {} /* unauthenticated */);
  5538. g_fake1_cert_data_map = nullptr;
  5539. }
  5540. TEST_P(XdsSecurityTest, TestMtlsToFallback) {
  5541. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  5542. {"", {root_cert_, identity_pair_}}};
  5543. g_fake1_cert_data_map = &fake1_cert_map;
  5544. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  5545. "", {server_san_exact_},
  5546. authenticated_identity_);
  5547. UpdateAndVerifyXdsSecurityConfiguration("", "", "", "", {},
  5548. fallback_authenticated_identity_);
  5549. g_fake1_cert_data_map = nullptr;
  5550. }
  5551. TEST_P(XdsSecurityTest, TestTlsToMtls) {
  5552. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  5553. {"", {root_cert_, identity_pair_}}};
  5554. g_fake1_cert_data_map = &fake1_cert_map;
  5555. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
  5556. {server_san_exact_},
  5557. {} /* unauthenticated */);
  5558. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  5559. "", {server_san_exact_},
  5560. authenticated_identity_);
  5561. g_fake1_cert_data_map = nullptr;
  5562. }
  5563. TEST_P(XdsSecurityTest, TestTlsToFallback) {
  5564. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  5565. {"", {root_cert_, identity_pair_}}};
  5566. g_fake1_cert_data_map = &fake1_cert_map;
  5567. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
  5568. {server_san_exact_},
  5569. {} /* unauthenticated */);
  5570. UpdateAndVerifyXdsSecurityConfiguration("", "", "", "", {},
  5571. fallback_authenticated_identity_);
  5572. g_fake1_cert_data_map = nullptr;
  5573. }
  5574. TEST_P(XdsSecurityTest, TestFallbackToMtls) {
  5575. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  5576. {"", {root_cert_, identity_pair_}}};
  5577. g_fake1_cert_data_map = &fake1_cert_map;
  5578. UpdateAndVerifyXdsSecurityConfiguration("", "", "", "", {},
  5579. fallback_authenticated_identity_);
  5580. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  5581. "", {server_san_exact_},
  5582. authenticated_identity_);
  5583. g_fake1_cert_data_map = nullptr;
  5584. }
  5585. TEST_P(XdsSecurityTest, TestFallbackToTls) {
  5586. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  5587. {"", {root_cert_, identity_pair_}}};
  5588. g_fake1_cert_data_map = &fake1_cert_map;
  5589. UpdateAndVerifyXdsSecurityConfiguration("", "", "", "", {},
  5590. fallback_authenticated_identity_);
  5591. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
  5592. {server_san_exact_},
  5593. {} /* unauthenticated */);
  5594. g_fake1_cert_data_map = nullptr;
  5595. }
  5596. TEST_P(XdsSecurityTest, TestFileWatcherCertificateProvider) {
  5597. UpdateAndVerifyXdsSecurityConfiguration("file_plugin", "", "file_plugin", "",
  5598. {server_san_exact_},
  5599. authenticated_identity_);
  5600. }
  5601. using EdsTest = BasicTest;
  5602. // Tests that EDS client should send a NACK if the EDS update contains
  5603. // sparse priorities.
  5604. TEST_P(EdsTest, NacksSparsePriorityList) {
  5605. SetNextResolution({});
  5606. SetNextResolutionForLbChannelAllBalancers();
  5607. AdsServiceImpl::EdsResourceArgs args({
  5608. {"locality0", GetBackendPorts(), kDefaultLocalityWeight, 1},
  5609. });
  5610. balancers_[0]->ads_service()->SetEdsResource(BuildEdsResource(args));
  5611. CheckRpcSendFailure();
  5612. const auto& response_state =
  5613. balancers_[0]->ads_service()->eds_response_state();
  5614. EXPECT_EQ(response_state.state, AdsServiceImpl::ResponseState::NACKED);
  5615. EXPECT_EQ(response_state.error_message,
  5616. "EDS update includes sparse priority list");
  5617. }
  5618. // In most of our tests, we use different names for different resource
  5619. // types, to make sure that there are no cut-and-paste errors in the code
  5620. // that cause us to look at data for the wrong resource type. So we add
  5621. // this test to make sure that the EDS resource name defaults to the
  5622. // cluster name if not specified in the CDS resource.
  5623. TEST_P(EdsTest, EdsServiceNameDefaultsToClusterName) {
  5624. AdsServiceImpl::EdsResourceArgs args({
  5625. {"locality0", GetBackendPorts()},
  5626. });
  5627. balancers_[0]->ads_service()->SetEdsResource(
  5628. BuildEdsResource(args, kDefaultClusterName));
  5629. Cluster cluster = default_cluster_;
  5630. cluster.mutable_eds_cluster_config()->clear_service_name();
  5631. balancers_[0]->ads_service()->SetCdsResource(cluster);
  5632. SetNextResolution({});
  5633. SetNextResolutionForLbChannelAllBalancers();
  5634. CheckRpcSendOk();
  5635. }
  5636. class TimeoutTest : public BasicTest {
  5637. protected:
  5638. void SetUp() override {
  5639. xds_resource_does_not_exist_timeout_ms_ = 500;
  5640. BasicTest::SetUp();
  5641. }
  5642. };
  5643. // Tests that LDS client times out when no response received.
  5644. TEST_P(TimeoutTest, Lds) {
  5645. balancers_[0]->ads_service()->SetResourceIgnore(kLdsTypeUrl);
  5646. SetNextResolution({});
  5647. SetNextResolutionForLbChannelAllBalancers();
  5648. CheckRpcSendFailure();
  5649. }
  5650. TEST_P(TimeoutTest, Rds) {
  5651. balancers_[0]->ads_service()->SetResourceIgnore(kRdsTypeUrl);
  5652. SetNextResolution({});
  5653. SetNextResolutionForLbChannelAllBalancers();
  5654. CheckRpcSendFailure();
  5655. }
  5656. // Tests that CDS client times out when no response received.
  5657. TEST_P(TimeoutTest, Cds) {
  5658. balancers_[0]->ads_service()->SetResourceIgnore(kCdsTypeUrl);
  5659. SetNextResolution({});
  5660. SetNextResolutionForLbChannelAllBalancers();
  5661. CheckRpcSendFailure();
  5662. }
  5663. TEST_P(TimeoutTest, Eds) {
  5664. balancers_[0]->ads_service()->SetResourceIgnore(kEdsTypeUrl);
  5665. SetNextResolution({});
  5666. SetNextResolutionForLbChannelAllBalancers();
  5667. CheckRpcSendFailure();
  5668. }
  5669. using LocalityMapTest = BasicTest;
  5670. // Tests that the localities in a locality map are picked according to their
  5671. // weights.
  5672. TEST_P(LocalityMapTest, WeightedRoundRobin) {
  5673. SetNextResolution({});
  5674. SetNextResolutionForLbChannelAllBalancers();
  5675. const size_t kNumRpcs = 5000;
  5676. const int kLocalityWeight0 = 2;
  5677. const int kLocalityWeight1 = 8;
  5678. const int kTotalLocalityWeight = kLocalityWeight0 + kLocalityWeight1;
  5679. const double kLocalityWeightRate0 =
  5680. static_cast<double>(kLocalityWeight0) / kTotalLocalityWeight;
  5681. const double kLocalityWeightRate1 =
  5682. static_cast<double>(kLocalityWeight1) / kTotalLocalityWeight;
  5683. // ADS response contains 2 localities, each of which contains 1 backend.
  5684. AdsServiceImpl::EdsResourceArgs args({
  5685. {"locality0", GetBackendPorts(0, 1), kLocalityWeight0},
  5686. {"locality1", GetBackendPorts(1, 2), kLocalityWeight1},
  5687. });
  5688. balancers_[0]->ads_service()->SetEdsResource(
  5689. BuildEdsResource(args, DefaultEdsServiceName()));
  5690. // Wait for both backends to be ready.
  5691. WaitForAllBackends(0, 2);
  5692. // Send kNumRpcs RPCs.
  5693. CheckRpcSendOk(kNumRpcs);
  5694. // The locality picking rates should be roughly equal to the expectation.
  5695. const double locality_picked_rate_0 =
  5696. static_cast<double>(backends_[0]->backend_service()->request_count()) /
  5697. kNumRpcs;
  5698. const double locality_picked_rate_1 =
  5699. static_cast<double>(backends_[1]->backend_service()->request_count()) /
  5700. kNumRpcs;
  5701. const double kErrorTolerance = 0.2;
  5702. EXPECT_THAT(locality_picked_rate_0,
  5703. ::testing::AllOf(
  5704. ::testing::Ge(kLocalityWeightRate0 * (1 - kErrorTolerance)),
  5705. ::testing::Le(kLocalityWeightRate0 * (1 + kErrorTolerance))));
  5706. EXPECT_THAT(locality_picked_rate_1,
  5707. ::testing::AllOf(
  5708. ::testing::Ge(kLocalityWeightRate1 * (1 - kErrorTolerance)),
  5709. ::testing::Le(kLocalityWeightRate1 * (1 + kErrorTolerance))));
  5710. }
  5711. // Tests that we correctly handle a locality containing no endpoints.
  5712. TEST_P(LocalityMapTest, LocalityContainingNoEndpoints) {
  5713. SetNextResolution({});
  5714. SetNextResolutionForLbChannelAllBalancers();
  5715. const size_t kNumRpcs = 5000;
  5716. // EDS response contains 2 localities, one with no endpoints.
  5717. AdsServiceImpl::EdsResourceArgs args({
  5718. {"locality0", GetBackendPorts()},
  5719. {"locality1", {}},
  5720. });
  5721. balancers_[0]->ads_service()->SetEdsResource(
  5722. BuildEdsResource(args, DefaultEdsServiceName()));
  5723. // Wait for both backends to be ready.
  5724. WaitForAllBackends();
  5725. // Send kNumRpcs RPCs.
  5726. CheckRpcSendOk(kNumRpcs);
  5727. // All traffic should go to the reachable locality.
  5728. EXPECT_EQ(backends_[0]->backend_service()->request_count(),
  5729. kNumRpcs / backends_.size());
  5730. EXPECT_EQ(backends_[1]->backend_service()->request_count(),
  5731. kNumRpcs / backends_.size());
  5732. EXPECT_EQ(backends_[2]->backend_service()->request_count(),
  5733. kNumRpcs / backends_.size());
  5734. EXPECT_EQ(backends_[3]->backend_service()->request_count(),
  5735. kNumRpcs / backends_.size());
  5736. }
  5737. // EDS update with no localities.
  5738. TEST_P(LocalityMapTest, NoLocalities) {
  5739. SetNextResolution({});
  5740. SetNextResolutionForLbChannelAllBalancers();
  5741. balancers_[0]->ads_service()->SetEdsResource(
  5742. BuildEdsResource({}, DefaultEdsServiceName()));
  5743. Status status = SendRpc();
  5744. EXPECT_FALSE(status.ok());
  5745. EXPECT_EQ(status.error_code(), StatusCode::UNAVAILABLE);
  5746. }
  5747. // Tests that the locality map can work properly even when it contains a large
  5748. // number of localities.
  5749. TEST_P(LocalityMapTest, StressTest) {
  5750. SetNextResolution({});
  5751. SetNextResolutionForLbChannelAllBalancers();
  5752. const size_t kNumLocalities = 100;
  5753. // The first ADS response contains kNumLocalities localities, each of which
  5754. // contains backend 0.
  5755. AdsServiceImpl::EdsResourceArgs args;
  5756. for (size_t i = 0; i < kNumLocalities; ++i) {
  5757. std::string name = absl::StrCat("locality", i);
  5758. AdsServiceImpl::EdsResourceArgs::Locality locality(name,
  5759. {backends_[0]->port()});
  5760. args.locality_list.emplace_back(std::move(locality));
  5761. }
  5762. balancers_[0]->ads_service()->SetEdsResource(
  5763. BuildEdsResource(args, DefaultEdsServiceName()));
  5764. // The second ADS response contains 1 locality, which contains backend 1.
  5765. args = AdsServiceImpl::EdsResourceArgs({
  5766. {"locality0", GetBackendPorts(1, 2)},
  5767. });
  5768. std::thread delayed_resource_setter(
  5769. std::bind(&BasicTest::SetEdsResourceWithDelay, this, 0,
  5770. BuildEdsResource(args, DefaultEdsServiceName()), 60 * 1000));
  5771. // Wait until backend 0 is ready, before which kNumLocalities localities are
  5772. // received and handled by the xds policy.
  5773. WaitForBackend(0, /*reset_counters=*/false);
  5774. EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
  5775. // Wait until backend 1 is ready, before which kNumLocalities localities are
  5776. // removed by the xds policy.
  5777. WaitForBackend(1);
  5778. delayed_resource_setter.join();
  5779. }
  5780. // Tests that the localities in a locality map are picked correctly after update
  5781. // (addition, modification, deletion).
  5782. TEST_P(LocalityMapTest, UpdateMap) {
  5783. SetNextResolution({});
  5784. SetNextResolutionForLbChannelAllBalancers();
  5785. const size_t kNumRpcs = 3000;
  5786. // The locality weight for the first 3 localities.
  5787. const std::vector<int> kLocalityWeights0 = {2, 3, 4};
  5788. const double kTotalLocalityWeight0 =
  5789. std::accumulate(kLocalityWeights0.begin(), kLocalityWeights0.end(), 0);
  5790. std::vector<double> locality_weight_rate_0;
  5791. locality_weight_rate_0.reserve(kLocalityWeights0.size());
  5792. for (int weight : kLocalityWeights0) {
  5793. locality_weight_rate_0.push_back(weight / kTotalLocalityWeight0);
  5794. }
  5795. // Delete the first locality, keep the second locality, change the third
  5796. // locality's weight from 4 to 2, and add a new locality with weight 6.
  5797. const std::vector<int> kLocalityWeights1 = {3, 2, 6};
  5798. const double kTotalLocalityWeight1 =
  5799. std::accumulate(kLocalityWeights1.begin(), kLocalityWeights1.end(), 0);
  5800. std::vector<double> locality_weight_rate_1 = {
  5801. 0 /* placeholder for locality 0 */};
  5802. for (int weight : kLocalityWeights1) {
  5803. locality_weight_rate_1.push_back(weight / kTotalLocalityWeight1);
  5804. }
  5805. AdsServiceImpl::EdsResourceArgs args({
  5806. {"locality0", GetBackendPorts(0, 1), 2},
  5807. {"locality1", GetBackendPorts(1, 2), 3},
  5808. {"locality2", GetBackendPorts(2, 3), 4},
  5809. });
  5810. balancers_[0]->ads_service()->SetEdsResource(
  5811. BuildEdsResource(args, DefaultEdsServiceName()));
  5812. // Wait for the first 3 backends to be ready.
  5813. WaitForAllBackends(0, 3);
  5814. gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
  5815. // Send kNumRpcs RPCs.
  5816. CheckRpcSendOk(kNumRpcs);
  5817. gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
  5818. // The picking rates of the first 3 backends should be roughly equal to the
  5819. // expectation.
  5820. std::vector<double> locality_picked_rates;
  5821. for (size_t i = 0; i < 3; ++i) {
  5822. locality_picked_rates.push_back(
  5823. static_cast<double>(backends_[i]->backend_service()->request_count()) /
  5824. kNumRpcs);
  5825. }
  5826. const double kErrorTolerance = 0.2;
  5827. for (size_t i = 0; i < 3; ++i) {
  5828. gpr_log(GPR_INFO, "Locality %" PRIuPTR " rate %f", i,
  5829. locality_picked_rates[i]);
  5830. EXPECT_THAT(
  5831. locality_picked_rates[i],
  5832. ::testing::AllOf(
  5833. ::testing::Ge(locality_weight_rate_0[i] * (1 - kErrorTolerance)),
  5834. ::testing::Le(locality_weight_rate_0[i] * (1 + kErrorTolerance))));
  5835. }
  5836. args = AdsServiceImpl::EdsResourceArgs({
  5837. {"locality1", GetBackendPorts(1, 2), 3},
  5838. {"locality2", GetBackendPorts(2, 3), 2},
  5839. {"locality3", GetBackendPorts(3, 4), 6},
  5840. });
  5841. balancers_[0]->ads_service()->SetEdsResource(
  5842. BuildEdsResource(args, DefaultEdsServiceName()));
  5843. // Backend 3 hasn't received any request.
  5844. EXPECT_EQ(0U, backends_[3]->backend_service()->request_count());
  5845. // Wait until the locality update has been processed, as signaled by backend 3
  5846. // receiving a request.
  5847. WaitForAllBackends(3, 4);
  5848. gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
  5849. // Send kNumRpcs RPCs.
  5850. CheckRpcSendOk(kNumRpcs);
  5851. gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
  5852. // Backend 0 no longer receives any request.
  5853. EXPECT_EQ(0U, backends_[0]->backend_service()->request_count());
  5854. // The picking rates of the last 3 backends should be roughly equal to the
  5855. // expectation.
  5856. locality_picked_rates = {0 /* placeholder for backend 0 */};
  5857. for (size_t i = 1; i < 4; ++i) {
  5858. locality_picked_rates.push_back(
  5859. static_cast<double>(backends_[i]->backend_service()->request_count()) /
  5860. kNumRpcs);
  5861. }
  5862. for (size_t i = 1; i < 4; ++i) {
  5863. gpr_log(GPR_INFO, "Locality %" PRIuPTR " rate %f", i,
  5864. locality_picked_rates[i]);
  5865. EXPECT_THAT(
  5866. locality_picked_rates[i],
  5867. ::testing::AllOf(
  5868. ::testing::Ge(locality_weight_rate_1[i] * (1 - kErrorTolerance)),
  5869. ::testing::Le(locality_weight_rate_1[i] * (1 + kErrorTolerance))));
  5870. }
  5871. }
  5872. // Tests that we don't fail RPCs when replacing all of the localities in
  5873. // a given priority.
  5874. TEST_P(LocalityMapTest, ReplaceAllLocalitiesInPriority) {
  5875. SetNextResolution({});
  5876. SetNextResolutionForLbChannelAllBalancers();
  5877. AdsServiceImpl::EdsResourceArgs args({
  5878. {"locality0", GetBackendPorts(0, 1)},
  5879. });
  5880. balancers_[0]->ads_service()->SetEdsResource(
  5881. BuildEdsResource(args, DefaultEdsServiceName()));
  5882. args = AdsServiceImpl::EdsResourceArgs({
  5883. {"locality1", GetBackendPorts(1, 2)},
  5884. });
  5885. std::thread delayed_resource_setter(
  5886. std::bind(&BasicTest::SetEdsResourceWithDelay, this, 0,
  5887. BuildEdsResource(args, DefaultEdsServiceName()), 5000));
  5888. // Wait for the first backend to be ready.
  5889. WaitForBackend(0);
  5890. // Keep sending RPCs until we switch over to backend 1, which tells us
  5891. // that we received the update. No RPCs should fail during this
  5892. // transition.
  5893. WaitForBackend(1, /*reset_counters=*/true, /*require_success=*/true);
  5894. delayed_resource_setter.join();
  5895. }
  5896. class FailoverTest : public BasicTest {
  5897. public:
  5898. void SetUp() override {
  5899. BasicTest::SetUp();
  5900. ResetStub(500);
  5901. }
  5902. };
  5903. // Localities with the highest priority are used when multiple priority exist.
  5904. TEST_P(FailoverTest, ChooseHighestPriority) {
  5905. SetNextResolution({});
  5906. SetNextResolutionForLbChannelAllBalancers();
  5907. AdsServiceImpl::EdsResourceArgs args({
  5908. {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
  5909. {"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
  5910. {"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
  5911. {"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
  5912. });
  5913. balancers_[0]->ads_service()->SetEdsResource(
  5914. BuildEdsResource(args, DefaultEdsServiceName()));
  5915. WaitForBackend(3, false);
  5916. for (size_t i = 0; i < 3; ++i) {
  5917. EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
  5918. }
  5919. }
  5920. // Does not choose priority with no endpoints.
  5921. TEST_P(FailoverTest, DoesNotUsePriorityWithNoEndpoints) {
  5922. SetNextResolution({});
  5923. SetNextResolutionForLbChannelAllBalancers();
  5924. AdsServiceImpl::EdsResourceArgs args({
  5925. {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
  5926. {"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
  5927. {"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
  5928. {"locality3", {}, kDefaultLocalityWeight, 0},
  5929. });
  5930. balancers_[0]->ads_service()->SetEdsResource(
  5931. BuildEdsResource(args, DefaultEdsServiceName()));
  5932. WaitForBackend(0, false);
  5933. for (size_t i = 1; i < 3; ++i) {
  5934. EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
  5935. }
  5936. }
  5937. // Does not choose locality with no endpoints.
  5938. TEST_P(FailoverTest, DoesNotUseLocalityWithNoEndpoints) {
  5939. SetNextResolution({});
  5940. SetNextResolutionForLbChannelAllBalancers();
  5941. AdsServiceImpl::EdsResourceArgs args({
  5942. {"locality0", {}, kDefaultLocalityWeight, 0},
  5943. {"locality1", GetBackendPorts(), kDefaultLocalityWeight, 0},
  5944. });
  5945. balancers_[0]->ads_service()->SetEdsResource(
  5946. BuildEdsResource(args, DefaultEdsServiceName()));
  5947. // Wait for all backends to be used.
  5948. std::tuple<int, int, int> counts = WaitForAllBackends();
  5949. // Make sure no RPCs failed in the transition.
  5950. EXPECT_EQ(0, std::get<1>(counts));
  5951. }
  5952. // If the higher priority localities are not reachable, failover to the highest
  5953. // priority among the rest.
  5954. TEST_P(FailoverTest, Failover) {
  5955. SetNextResolution({});
  5956. SetNextResolutionForLbChannelAllBalancers();
  5957. AdsServiceImpl::EdsResourceArgs args({
  5958. {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
  5959. {"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
  5960. {"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
  5961. {"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
  5962. });
  5963. ShutdownBackend(3);
  5964. ShutdownBackend(0);
  5965. balancers_[0]->ads_service()->SetEdsResource(
  5966. BuildEdsResource(args, DefaultEdsServiceName()));
  5967. WaitForBackend(1, false);
  5968. for (size_t i = 0; i < 4; ++i) {
  5969. if (i == 1) continue;
  5970. EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
  5971. }
  5972. }
  5973. // If a locality with higher priority than the current one becomes ready,
  5974. // switch to it.
  5975. TEST_P(FailoverTest, SwitchBackToHigherPriority) {
  5976. SetNextResolution({});
  5977. SetNextResolutionForLbChannelAllBalancers();
  5978. const size_t kNumRpcs = 100;
  5979. AdsServiceImpl::EdsResourceArgs args({
  5980. {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
  5981. {"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
  5982. {"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
  5983. {"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
  5984. });
  5985. ShutdownBackend(3);
  5986. ShutdownBackend(0);
  5987. balancers_[0]->ads_service()->SetEdsResource(
  5988. BuildEdsResource(args, DefaultEdsServiceName()));
  5989. WaitForBackend(1, false);
  5990. for (size_t i = 0; i < 4; ++i) {
  5991. if (i == 1) continue;
  5992. EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
  5993. }
  5994. StartBackend(0);
  5995. WaitForBackend(0);
  5996. CheckRpcSendOk(kNumRpcs);
  5997. EXPECT_EQ(kNumRpcs, backends_[0]->backend_service()->request_count());
  5998. }
  5999. // The first update only contains unavailable priorities. The second update
  6000. // contains available priorities.
  6001. TEST_P(FailoverTest, UpdateInitialUnavailable) {
  6002. SetNextResolution({});
  6003. SetNextResolutionForLbChannelAllBalancers();
  6004. AdsServiceImpl::EdsResourceArgs args({
  6005. {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 0},
  6006. {"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 1},
  6007. });
  6008. balancers_[0]->ads_service()->SetEdsResource(
  6009. BuildEdsResource(args, DefaultEdsServiceName()));
  6010. args = AdsServiceImpl::EdsResourceArgs({
  6011. {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 0},
  6012. {"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 1},
  6013. {"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 2},
  6014. {"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 3},
  6015. });
  6016. ShutdownBackend(0);
  6017. ShutdownBackend(1);
  6018. std::thread delayed_resource_setter(
  6019. std::bind(&BasicTest::SetEdsResourceWithDelay, this, 0,
  6020. BuildEdsResource(args, DefaultEdsServiceName()), 1000));
  6021. gpr_timespec deadline = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
  6022. gpr_time_from_millis(500, GPR_TIMESPAN));
  6023. // Send 0.5 second worth of RPCs.
  6024. do {
  6025. CheckRpcSendFailure();
  6026. } while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
  6027. WaitForBackend(2, false);
  6028. for (size_t i = 0; i < 4; ++i) {
  6029. if (i == 2) continue;
  6030. EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
  6031. }
  6032. delayed_resource_setter.join();
  6033. }
  6034. // Tests that after the localities' priorities are updated, we still choose the
  6035. // highest READY priority with the updated localities.
  6036. TEST_P(FailoverTest, UpdatePriority) {
  6037. SetNextResolution({});
  6038. SetNextResolutionForLbChannelAllBalancers();
  6039. const size_t kNumRpcs = 100;
  6040. AdsServiceImpl::EdsResourceArgs args({
  6041. {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 1},
  6042. {"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 2},
  6043. {"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 3},
  6044. {"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 0},
  6045. });
  6046. balancers_[0]->ads_service()->SetEdsResource(
  6047. BuildEdsResource(args, DefaultEdsServiceName()));
  6048. args = AdsServiceImpl::EdsResourceArgs({
  6049. {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 2},
  6050. {"locality1", GetBackendPorts(1, 2), kDefaultLocalityWeight, 0},
  6051. {"locality2", GetBackendPorts(2, 3), kDefaultLocalityWeight, 1},
  6052. {"locality3", GetBackendPorts(3, 4), kDefaultLocalityWeight, 3},
  6053. });
  6054. std::thread delayed_resource_setter(
  6055. std::bind(&BasicTest::SetEdsResourceWithDelay, this, 0,
  6056. BuildEdsResource(args, DefaultEdsServiceName()), 1000));
  6057. WaitForBackend(3, false);
  6058. for (size_t i = 0; i < 3; ++i) {
  6059. EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
  6060. }
  6061. WaitForBackend(1);
  6062. CheckRpcSendOk(kNumRpcs);
  6063. EXPECT_EQ(kNumRpcs, backends_[1]->backend_service()->request_count());
  6064. delayed_resource_setter.join();
  6065. }
  6066. // Moves all localities in the current priority to a higher priority.
  6067. TEST_P(FailoverTest, MoveAllLocalitiesInCurrentPriorityToHigherPriority) {
  6068. SetNextResolution({});
  6069. SetNextResolutionForLbChannelAllBalancers();
  6070. // First update:
  6071. // - Priority 0 is locality 0, containing backend 0, which is down.
  6072. // - Priority 1 is locality 1, containing backends 1 and 2, which are up.
  6073. ShutdownBackend(0);
  6074. AdsServiceImpl::EdsResourceArgs args({
  6075. {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 0},
  6076. {"locality1", GetBackendPorts(1, 3), kDefaultLocalityWeight, 1},
  6077. });
  6078. balancers_[0]->ads_service()->SetEdsResource(
  6079. BuildEdsResource(args, DefaultEdsServiceName()));
  6080. // Second update:
  6081. // - Priority 0 contains both localities 0 and 1.
  6082. // - Priority 1 is not present.
  6083. // - We add backend 3 to locality 1, just so we have a way to know
  6084. // when the update has been seen by the client.
  6085. args = AdsServiceImpl::EdsResourceArgs({
  6086. {"locality0", GetBackendPorts(0, 1), kDefaultLocalityWeight, 0},
  6087. {"locality1", GetBackendPorts(1, 4), kDefaultLocalityWeight, 0},
  6088. });
  6089. std::thread delayed_resource_setter(
  6090. std::bind(&BasicTest::SetEdsResourceWithDelay, this, 0,
  6091. BuildEdsResource(args, DefaultEdsServiceName()), 1000));
  6092. // When we get the first update, all backends in priority 0 are down,
  6093. // so we will create priority 1. Backends 1 and 2 should have traffic,
  6094. // but backend 3 should not.
  6095. WaitForAllBackends(1, 3, false);
  6096. EXPECT_EQ(0UL, backends_[3]->backend_service()->request_count());
  6097. // When backend 3 gets traffic, we know the second update has been seen.
  6098. WaitForBackend(3);
  6099. // The ADS service of balancer 0 got at least 1 response.
  6100. EXPECT_GT(balancers_[0]->ads_service()->eds_response_state().state,
  6101. AdsServiceImpl::ResponseState::NOT_SENT);
  6102. delayed_resource_setter.join();
  6103. }
  6104. using DropTest = BasicTest;
  6105. // Tests that RPCs are dropped according to the drop config.
  6106. TEST_P(DropTest, Vanilla) {
  6107. SetNextResolution({});
  6108. SetNextResolutionForLbChannelAllBalancers();
  6109. const size_t kNumRpcs = 5000;
  6110. const uint32_t kDropPerMillionForLb = 100000;
  6111. const uint32_t kDropPerMillionForThrottle = 200000;
  6112. const double kDropRateForLb = kDropPerMillionForLb / 1000000.0;
  6113. const double kDropRateForThrottle = kDropPerMillionForThrottle / 1000000.0;
  6114. const double KDropRateForLbAndThrottle =
  6115. kDropRateForLb + (1 - kDropRateForLb) * kDropRateForThrottle;
  6116. // The ADS response contains two drop categories.
  6117. AdsServiceImpl::EdsResourceArgs args({
  6118. {"locality0", GetBackendPorts()},
  6119. });
  6120. args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
  6121. {kThrottleDropType, kDropPerMillionForThrottle}};
  6122. balancers_[0]->ads_service()->SetEdsResource(
  6123. BuildEdsResource(args, DefaultEdsServiceName()));
  6124. WaitForAllBackends();
  6125. // Send kNumRpcs RPCs and count the drops.
  6126. size_t num_drops = 0;
  6127. for (size_t i = 0; i < kNumRpcs; ++i) {
  6128. EchoResponse response;
  6129. const Status status = SendRpc(RpcOptions(), &response);
  6130. if (!status.ok() &&
  6131. status.error_message() == "Call dropped by load balancing policy") {
  6132. ++num_drops;
  6133. } else {
  6134. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  6135. << " message=" << status.error_message();
  6136. EXPECT_EQ(response.message(), kRequestMessage);
  6137. }
  6138. }
  6139. // The drop rate should be roughly equal to the expectation.
  6140. const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
  6141. const double kErrorTolerance = 0.2;
  6142. EXPECT_THAT(
  6143. seen_drop_rate,
  6144. ::testing::AllOf(
  6145. ::testing::Ge(KDropRateForLbAndThrottle * (1 - kErrorTolerance)),
  6146. ::testing::Le(KDropRateForLbAndThrottle * (1 + kErrorTolerance))));
  6147. }
  6148. // Tests that drop config is converted correctly from per hundred.
  6149. TEST_P(DropTest, DropPerHundred) {
  6150. SetNextResolution({});
  6151. SetNextResolutionForLbChannelAllBalancers();
  6152. const size_t kNumRpcs = 5000;
  6153. const uint32_t kDropPerHundredForLb = 10;
  6154. const double kDropRateForLb = kDropPerHundredForLb / 100.0;
  6155. // The ADS response contains one drop category.
  6156. AdsServiceImpl::EdsResourceArgs args({
  6157. {"locality0", GetBackendPorts()},
  6158. });
  6159. args.drop_categories = {{kLbDropType, kDropPerHundredForLb}};
  6160. args.drop_denominator = FractionalPercent::HUNDRED;
  6161. balancers_[0]->ads_service()->SetEdsResource(
  6162. BuildEdsResource(args, DefaultEdsServiceName()));
  6163. WaitForAllBackends();
  6164. // Send kNumRpcs RPCs and count the drops.
  6165. size_t num_drops = 0;
  6166. for (size_t i = 0; i < kNumRpcs; ++i) {
  6167. EchoResponse response;
  6168. const Status status = SendRpc(RpcOptions(), &response);
  6169. if (!status.ok() &&
  6170. status.error_message() == "Call dropped by load balancing policy") {
  6171. ++num_drops;
  6172. } else {
  6173. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  6174. << " message=" << status.error_message();
  6175. EXPECT_EQ(response.message(), kRequestMessage);
  6176. }
  6177. }
  6178. // The drop rate should be roughly equal to the expectation.
  6179. const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
  6180. const double kErrorTolerance = 0.2;
  6181. EXPECT_THAT(
  6182. seen_drop_rate,
  6183. ::testing::AllOf(::testing::Ge(kDropRateForLb * (1 - kErrorTolerance)),
  6184. ::testing::Le(kDropRateForLb * (1 + kErrorTolerance))));
  6185. }
  6186. // Tests that drop config is converted correctly from per ten thousand.
  6187. TEST_P(DropTest, DropPerTenThousand) {
  6188. SetNextResolution({});
  6189. SetNextResolutionForLbChannelAllBalancers();
  6190. const size_t kNumRpcs = 5000;
  6191. const uint32_t kDropPerTenThousandForLb = 1000;
  6192. const double kDropRateForLb = kDropPerTenThousandForLb / 10000.0;
  6193. // The ADS response contains one drop category.
  6194. AdsServiceImpl::EdsResourceArgs args({
  6195. {"locality0", GetBackendPorts()},
  6196. });
  6197. args.drop_categories = {{kLbDropType, kDropPerTenThousandForLb}};
  6198. args.drop_denominator = FractionalPercent::TEN_THOUSAND;
  6199. balancers_[0]->ads_service()->SetEdsResource(
  6200. BuildEdsResource(args, DefaultEdsServiceName()));
  6201. WaitForAllBackends();
  6202. // Send kNumRpcs RPCs and count the drops.
  6203. size_t num_drops = 0;
  6204. for (size_t i = 0; i < kNumRpcs; ++i) {
  6205. EchoResponse response;
  6206. const Status status = SendRpc(RpcOptions(), &response);
  6207. if (!status.ok() &&
  6208. status.error_message() == "Call dropped by load balancing policy") {
  6209. ++num_drops;
  6210. } else {
  6211. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  6212. << " message=" << status.error_message();
  6213. EXPECT_EQ(response.message(), kRequestMessage);
  6214. }
  6215. }
  6216. // The drop rate should be roughly equal to the expectation.
  6217. const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
  6218. const double kErrorTolerance = 0.2;
  6219. EXPECT_THAT(
  6220. seen_drop_rate,
  6221. ::testing::AllOf(::testing::Ge(kDropRateForLb * (1 - kErrorTolerance)),
  6222. ::testing::Le(kDropRateForLb * (1 + kErrorTolerance))));
  6223. }
  6224. // Tests that drop is working correctly after update.
  6225. TEST_P(DropTest, Update) {
  6226. SetNextResolution({});
  6227. SetNextResolutionForLbChannelAllBalancers();
  6228. const size_t kNumRpcs = 3000;
  6229. const uint32_t kDropPerMillionForLb = 100000;
  6230. const uint32_t kDropPerMillionForThrottle = 200000;
  6231. const double kDropRateForLb = kDropPerMillionForLb / 1000000.0;
  6232. const double kDropRateForThrottle = kDropPerMillionForThrottle / 1000000.0;
  6233. const double KDropRateForLbAndThrottle =
  6234. kDropRateForLb + (1 - kDropRateForLb) * kDropRateForThrottle;
  6235. // The first ADS response contains one drop category.
  6236. AdsServiceImpl::EdsResourceArgs args({
  6237. {"locality0", GetBackendPorts()},
  6238. });
  6239. args.drop_categories = {{kLbDropType, kDropPerMillionForLb}};
  6240. balancers_[0]->ads_service()->SetEdsResource(
  6241. BuildEdsResource(args, DefaultEdsServiceName()));
  6242. WaitForAllBackends();
  6243. // Send kNumRpcs RPCs and count the drops.
  6244. size_t num_drops = 0;
  6245. gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
  6246. for (size_t i = 0; i < kNumRpcs; ++i) {
  6247. EchoResponse response;
  6248. const Status status = SendRpc(RpcOptions(), &response);
  6249. if (!status.ok() &&
  6250. status.error_message() == "Call dropped by load balancing policy") {
  6251. ++num_drops;
  6252. } else {
  6253. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  6254. << " message=" << status.error_message();
  6255. EXPECT_EQ(response.message(), kRequestMessage);
  6256. }
  6257. }
  6258. gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
  6259. // The drop rate should be roughly equal to the expectation.
  6260. double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
  6261. gpr_log(GPR_INFO, "First batch drop rate %f", seen_drop_rate);
  6262. const double kErrorTolerance = 0.3;
  6263. EXPECT_THAT(
  6264. seen_drop_rate,
  6265. ::testing::AllOf(::testing::Ge(kDropRateForLb * (1 - kErrorTolerance)),
  6266. ::testing::Le(kDropRateForLb * (1 + kErrorTolerance))));
  6267. // The second ADS response contains two drop categories, send an update EDS
  6268. // response.
  6269. args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
  6270. {kThrottleDropType, kDropPerMillionForThrottle}};
  6271. balancers_[0]->ads_service()->SetEdsResource(
  6272. BuildEdsResource(args, DefaultEdsServiceName()));
  6273. // Wait until the drop rate increases to the middle of the two configs, which
  6274. // implies that the update has been in effect.
  6275. const double kDropRateThreshold =
  6276. (kDropRateForLb + KDropRateForLbAndThrottle) / 2;
  6277. size_t num_rpcs = kNumRpcs;
  6278. while (seen_drop_rate < kDropRateThreshold) {
  6279. EchoResponse response;
  6280. const Status status = SendRpc(RpcOptions(), &response);
  6281. ++num_rpcs;
  6282. if (!status.ok() &&
  6283. status.error_message() == "Call dropped by load balancing policy") {
  6284. ++num_drops;
  6285. } else {
  6286. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  6287. << " message=" << status.error_message();
  6288. EXPECT_EQ(response.message(), kRequestMessage);
  6289. }
  6290. seen_drop_rate = static_cast<double>(num_drops) / num_rpcs;
  6291. }
  6292. // Send kNumRpcs RPCs and count the drops.
  6293. num_drops = 0;
  6294. gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
  6295. for (size_t i = 0; i < kNumRpcs; ++i) {
  6296. EchoResponse response;
  6297. const Status status = SendRpc(RpcOptions(), &response);
  6298. if (!status.ok() &&
  6299. status.error_message() == "Call dropped by load balancing policy") {
  6300. ++num_drops;
  6301. } else {
  6302. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  6303. << " message=" << status.error_message();
  6304. EXPECT_EQ(response.message(), kRequestMessage);
  6305. }
  6306. }
  6307. gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
  6308. // The new drop rate should be roughly equal to the expectation.
  6309. seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
  6310. gpr_log(GPR_INFO, "Second batch drop rate %f", seen_drop_rate);
  6311. EXPECT_THAT(
  6312. seen_drop_rate,
  6313. ::testing::AllOf(
  6314. ::testing::Ge(KDropRateForLbAndThrottle * (1 - kErrorTolerance)),
  6315. ::testing::Le(KDropRateForLbAndThrottle * (1 + kErrorTolerance))));
  6316. }
  6317. // Tests that all the RPCs are dropped if any drop category drops 100%.
  6318. TEST_P(DropTest, DropAll) {
  6319. SetNextResolution({});
  6320. SetNextResolutionForLbChannelAllBalancers();
  6321. const size_t kNumRpcs = 1000;
  6322. const uint32_t kDropPerMillionForLb = 100000;
  6323. const uint32_t kDropPerMillionForThrottle = 1000000;
  6324. // The ADS response contains two drop categories.
  6325. AdsServiceImpl::EdsResourceArgs args;
  6326. args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
  6327. {kThrottleDropType, kDropPerMillionForThrottle}};
  6328. balancers_[0]->ads_service()->SetEdsResource(
  6329. BuildEdsResource(args, DefaultEdsServiceName()));
  6330. // Send kNumRpcs RPCs and all of them are dropped.
  6331. for (size_t i = 0; i < kNumRpcs; ++i) {
  6332. EchoResponse response;
  6333. const Status status = SendRpc(RpcOptions(), &response);
  6334. EXPECT_EQ(status.error_code(), StatusCode::UNAVAILABLE);
  6335. EXPECT_EQ(status.error_message(), "Call dropped by load balancing policy");
  6336. }
  6337. }
  6338. class BalancerUpdateTest : public XdsEnd2endTest {
  6339. public:
  6340. BalancerUpdateTest() : XdsEnd2endTest(4, 3) {}
  6341. };
  6342. // Tests that the old LB call is still used after the balancer address update as
  6343. // long as that call is still alive.
  6344. TEST_P(BalancerUpdateTest, UpdateBalancersButKeepUsingOriginalBalancer) {
  6345. SetNextResolution({});
  6346. SetNextResolutionForLbChannelAllBalancers();
  6347. AdsServiceImpl::EdsResourceArgs args({
  6348. {"locality0", {backends_[0]->port()}},
  6349. });
  6350. balancers_[0]->ads_service()->SetEdsResource(
  6351. BuildEdsResource(args, DefaultEdsServiceName()));
  6352. args = AdsServiceImpl::EdsResourceArgs({
  6353. {"locality0", {backends_[1]->port()}},
  6354. });
  6355. balancers_[1]->ads_service()->SetEdsResource(
  6356. BuildEdsResource(args, DefaultEdsServiceName()));
  6357. // Wait until the first backend is ready.
  6358. WaitForBackend(0);
  6359. // Send 10 requests.
  6360. gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
  6361. CheckRpcSendOk(10);
  6362. gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
  6363. // All 10 requests should have gone to the first backend.
  6364. EXPECT_EQ(10U, backends_[0]->backend_service()->request_count());
  6365. // The ADS service of balancer 0 sent at least 1 response.
  6366. EXPECT_GT(balancers_[0]->ads_service()->eds_response_state().state,
  6367. AdsServiceImpl::ResponseState::NOT_SENT);
  6368. EXPECT_EQ(balancers_[1]->ads_service()->eds_response_state().state,
  6369. AdsServiceImpl::ResponseState::NOT_SENT)
  6370. << "Error Message:"
  6371. << balancers_[1]->ads_service()->eds_response_state().error_message;
  6372. EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
  6373. AdsServiceImpl::ResponseState::NOT_SENT)
  6374. << "Error Message:"
  6375. << balancers_[2]->ads_service()->eds_response_state().error_message;
  6376. gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
  6377. SetNextResolutionForLbChannel({balancers_[1]->port()});
  6378. gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
  6379. EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
  6380. gpr_timespec deadline = gpr_time_add(
  6381. gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_millis(10000, GPR_TIMESPAN));
  6382. // Send 10 seconds worth of RPCs
  6383. do {
  6384. CheckRpcSendOk();
  6385. } while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
  6386. // The current LB call is still working, so xds continued using it to the
  6387. // first balancer, which doesn't assign the second backend.
  6388. EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
  6389. // The ADS service of balancer 0 sent at least 1 response.
  6390. EXPECT_GT(balancers_[0]->ads_service()->eds_response_state().state,
  6391. AdsServiceImpl::ResponseState::NOT_SENT);
  6392. EXPECT_EQ(balancers_[1]->ads_service()->eds_response_state().state,
  6393. AdsServiceImpl::ResponseState::NOT_SENT)
  6394. << "Error Message:"
  6395. << balancers_[1]->ads_service()->eds_response_state().error_message;
  6396. EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
  6397. AdsServiceImpl::ResponseState::NOT_SENT)
  6398. << "Error Message:"
  6399. << balancers_[2]->ads_service()->eds_response_state().error_message;
  6400. }
  6401. // Tests that the old LB call is still used after multiple balancer address
  6402. // updates as long as that call is still alive. Send an update with the same set
  6403. // of LBs as the one in SetUp() in order to verify that the LB channel inside
  6404. // xds keeps the initial connection (which by definition is also present in the
  6405. // update).
  6406. TEST_P(BalancerUpdateTest, Repeated) {
  6407. SetNextResolution({});
  6408. SetNextResolutionForLbChannelAllBalancers();
  6409. AdsServiceImpl::EdsResourceArgs args({
  6410. {"locality0", {backends_[0]->port()}},
  6411. });
  6412. balancers_[0]->ads_service()->SetEdsResource(
  6413. BuildEdsResource(args, DefaultEdsServiceName()));
  6414. args = AdsServiceImpl::EdsResourceArgs({
  6415. {"locality0", {backends_[1]->port()}},
  6416. });
  6417. balancers_[1]->ads_service()->SetEdsResource(
  6418. BuildEdsResource(args, DefaultEdsServiceName()));
  6419. // Wait until the first backend is ready.
  6420. WaitForBackend(0);
  6421. // Send 10 requests.
  6422. gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
  6423. CheckRpcSendOk(10);
  6424. gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
  6425. // All 10 requests should have gone to the first backend.
  6426. EXPECT_EQ(10U, backends_[0]->backend_service()->request_count());
  6427. // The ADS service of balancer 0 sent at least 1 response.
  6428. EXPECT_GT(balancers_[0]->ads_service()->eds_response_state().state,
  6429. AdsServiceImpl::ResponseState::NOT_SENT);
  6430. EXPECT_EQ(balancers_[1]->ads_service()->eds_response_state().state,
  6431. AdsServiceImpl::ResponseState::NOT_SENT)
  6432. << "Error Message:"
  6433. << balancers_[1]->ads_service()->eds_response_state().error_message;
  6434. EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
  6435. AdsServiceImpl::ResponseState::NOT_SENT)
  6436. << "Error Message:"
  6437. << balancers_[2]->ads_service()->eds_response_state().error_message;
  6438. std::vector<int> ports;
  6439. ports.emplace_back(balancers_[0]->port());
  6440. ports.emplace_back(balancers_[1]->port());
  6441. ports.emplace_back(balancers_[2]->port());
  6442. gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
  6443. SetNextResolutionForLbChannel(ports);
  6444. gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
  6445. EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
  6446. gpr_timespec deadline = gpr_time_add(
  6447. gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_millis(10000, GPR_TIMESPAN));
  6448. // Send 10 seconds worth of RPCs
  6449. do {
  6450. CheckRpcSendOk();
  6451. } while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
  6452. // xds continued using the original LB call to the first balancer, which
  6453. // doesn't assign the second backend.
  6454. EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
  6455. ports.clear();
  6456. ports.emplace_back(balancers_[0]->port());
  6457. ports.emplace_back(balancers_[1]->port());
  6458. gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 2 ==========");
  6459. SetNextResolutionForLbChannel(ports);
  6460. gpr_log(GPR_INFO, "========= UPDATE 2 DONE ==========");
  6461. EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
  6462. deadline = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
  6463. gpr_time_from_millis(10000, GPR_TIMESPAN));
  6464. // Send 10 seconds worth of RPCs
  6465. do {
  6466. CheckRpcSendOk();
  6467. } while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
  6468. // xds continued using the original LB call to the first balancer, which
  6469. // doesn't assign the second backend.
  6470. EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
  6471. }
  6472. // Tests that if the balancer is down, the RPCs will still be sent to the
  6473. // backends according to the last balancer response, until a new balancer is
  6474. // reachable.
  6475. TEST_P(BalancerUpdateTest, DeadUpdate) {
  6476. SetNextResolution({});
  6477. SetNextResolutionForLbChannel({balancers_[0]->port()});
  6478. AdsServiceImpl::EdsResourceArgs args({
  6479. {"locality0", {backends_[0]->port()}},
  6480. });
  6481. balancers_[0]->ads_service()->SetEdsResource(
  6482. BuildEdsResource(args, DefaultEdsServiceName()));
  6483. args = AdsServiceImpl::EdsResourceArgs({
  6484. {"locality0", {backends_[1]->port()}},
  6485. });
  6486. balancers_[1]->ads_service()->SetEdsResource(
  6487. BuildEdsResource(args, DefaultEdsServiceName()));
  6488. // Start servers and send 10 RPCs per server.
  6489. gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
  6490. CheckRpcSendOk(10);
  6491. gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
  6492. // All 10 requests should have gone to the first backend.
  6493. EXPECT_EQ(10U, backends_[0]->backend_service()->request_count());
  6494. // The ADS service of balancer 0 sent at least 1 response.
  6495. EXPECT_GT(balancers_[0]->ads_service()->eds_response_state().state,
  6496. AdsServiceImpl::ResponseState::NOT_SENT);
  6497. EXPECT_EQ(balancers_[1]->ads_service()->eds_response_state().state,
  6498. AdsServiceImpl::ResponseState::NOT_SENT)
  6499. << "Error Message:"
  6500. << balancers_[1]->ads_service()->eds_response_state().error_message;
  6501. EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
  6502. AdsServiceImpl::ResponseState::NOT_SENT)
  6503. << "Error Message:"
  6504. << balancers_[2]->ads_service()->eds_response_state().error_message;
  6505. // Kill balancer 0
  6506. gpr_log(GPR_INFO, "********** ABOUT TO KILL BALANCER 0 *************");
  6507. balancers_[0]->Shutdown();
  6508. gpr_log(GPR_INFO, "********** KILLED BALANCER 0 *************");
  6509. // This is serviced by the existing child policy.
  6510. gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
  6511. CheckRpcSendOk(10);
  6512. gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
  6513. // All 10 requests should again have gone to the first backend.
  6514. EXPECT_EQ(20U, backends_[0]->backend_service()->request_count());
  6515. EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
  6516. // The ADS service of no balancers sent anything
  6517. EXPECT_EQ(balancers_[0]->ads_service()->eds_response_state().state,
  6518. AdsServiceImpl::ResponseState::NOT_SENT)
  6519. << "Error Message:"
  6520. << balancers_[0]->ads_service()->eds_response_state().error_message;
  6521. EXPECT_EQ(balancers_[1]->ads_service()->eds_response_state().state,
  6522. AdsServiceImpl::ResponseState::NOT_SENT)
  6523. << "Error Message:"
  6524. << balancers_[1]->ads_service()->eds_response_state().error_message;
  6525. EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
  6526. AdsServiceImpl::ResponseState::NOT_SENT)
  6527. << "Error Message:"
  6528. << balancers_[2]->ads_service()->eds_response_state().error_message;
  6529. gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
  6530. SetNextResolutionForLbChannel({balancers_[1]->port()});
  6531. gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
  6532. // Wait until update has been processed, as signaled by the second backend
  6533. // receiving a request. In the meantime, the client continues to be serviced
  6534. // (by the first backend) without interruption.
  6535. EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
  6536. WaitForBackend(1);
  6537. // This is serviced by the updated RR policy
  6538. backends_[1]->backend_service()->ResetCounters();
  6539. gpr_log(GPR_INFO, "========= BEFORE THIRD BATCH ==========");
  6540. CheckRpcSendOk(10);
  6541. gpr_log(GPR_INFO, "========= DONE WITH THIRD BATCH ==========");
  6542. // All 10 requests should have gone to the second backend.
  6543. EXPECT_EQ(10U, backends_[1]->backend_service()->request_count());
  6544. // The ADS service of balancer 1 sent at least 1 response.
  6545. EXPECT_EQ(balancers_[0]->ads_service()->eds_response_state().state,
  6546. AdsServiceImpl::ResponseState::NOT_SENT)
  6547. << "Error Message:"
  6548. << balancers_[0]->ads_service()->eds_response_state().error_message;
  6549. EXPECT_GT(balancers_[1]->ads_service()->eds_response_state().state,
  6550. AdsServiceImpl::ResponseState::NOT_SENT);
  6551. EXPECT_EQ(balancers_[2]->ads_service()->eds_response_state().state,
  6552. AdsServiceImpl::ResponseState::NOT_SENT)
  6553. << "Error Message:"
  6554. << balancers_[2]->ads_service()->eds_response_state().error_message;
  6555. }
  6556. class ClientLoadReportingTest : public XdsEnd2endTest {
  6557. public:
  6558. ClientLoadReportingTest() : XdsEnd2endTest(4, 1, 3) {}
  6559. };
  6560. // Tests that the load report received at the balancer is correct.
  6561. TEST_P(ClientLoadReportingTest, Vanilla) {
  6562. if (!GetParam().use_xds_resolver()) {
  6563. balancers_[0]->lrs_service()->set_cluster_names({kServerName});
  6564. }
  6565. SetNextResolution({});
  6566. SetNextResolutionForLbChannel({balancers_[0]->port()});
  6567. const size_t kNumRpcsPerAddress = 10;
  6568. const size_t kNumFailuresPerAddress = 3;
  6569. // TODO(juanlishen): Partition the backends after multiple localities is
  6570. // tested.
  6571. AdsServiceImpl::EdsResourceArgs args({
  6572. {"locality0", GetBackendPorts()},
  6573. });
  6574. balancers_[0]->ads_service()->SetEdsResource(
  6575. BuildEdsResource(args, DefaultEdsServiceName()));
  6576. // Wait until all backends are ready.
  6577. int num_ok = 0;
  6578. int num_failure = 0;
  6579. int num_drops = 0;
  6580. std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
  6581. // Send kNumRpcsPerAddress RPCs per server.
  6582. CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
  6583. CheckRpcSendFailure(kNumFailuresPerAddress * num_backends_,
  6584. RpcOptions().set_server_fail(true));
  6585. // Check that each backend got the right number of requests.
  6586. for (size_t i = 0; i < backends_.size(); ++i) {
  6587. EXPECT_EQ(kNumRpcsPerAddress + kNumFailuresPerAddress,
  6588. backends_[i]->backend_service()->request_count());
  6589. }
  6590. // The load report received at the balancer should be correct.
  6591. std::vector<ClientStats> load_report =
  6592. balancers_[0]->lrs_service()->WaitForLoadReport();
  6593. ASSERT_EQ(load_report.size(), 1UL);
  6594. ClientStats& client_stats = load_report.front();
  6595. EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + num_ok,
  6596. client_stats.total_successful_requests());
  6597. EXPECT_EQ(0U, client_stats.total_requests_in_progress());
  6598. EXPECT_EQ((kNumRpcsPerAddress + kNumFailuresPerAddress) * num_backends_ +
  6599. num_ok + num_failure,
  6600. client_stats.total_issued_requests());
  6601. EXPECT_EQ(kNumFailuresPerAddress * num_backends_ + num_failure,
  6602. client_stats.total_error_requests());
  6603. EXPECT_EQ(0U, client_stats.total_dropped_requests());
  6604. // The LRS service got a single request, and sent a single response.
  6605. EXPECT_EQ(1U, balancers_[0]->lrs_service()->request_count());
  6606. EXPECT_EQ(1U, balancers_[0]->lrs_service()->response_count());
  6607. }
  6608. // Tests send_all_clusters.
  6609. TEST_P(ClientLoadReportingTest, SendAllClusters) {
  6610. balancers_[0]->lrs_service()->set_send_all_clusters(true);
  6611. SetNextResolution({});
  6612. SetNextResolutionForLbChannel({balancers_[0]->port()});
  6613. const size_t kNumRpcsPerAddress = 10;
  6614. const size_t kNumFailuresPerAddress = 3;
  6615. // TODO(juanlishen): Partition the backends after multiple localities is
  6616. // tested.
  6617. AdsServiceImpl::EdsResourceArgs args({
  6618. {"locality0", GetBackendPorts()},
  6619. });
  6620. balancers_[0]->ads_service()->SetEdsResource(
  6621. BuildEdsResource(args, DefaultEdsServiceName()));
  6622. // Wait until all backends are ready.
  6623. int num_ok = 0;
  6624. int num_failure = 0;
  6625. int num_drops = 0;
  6626. std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
  6627. // Send kNumRpcsPerAddress RPCs per server.
  6628. CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
  6629. CheckRpcSendFailure(kNumFailuresPerAddress * num_backends_,
  6630. RpcOptions().set_server_fail(true));
  6631. // Check that each backend got the right number of requests.
  6632. for (size_t i = 0; i < backends_.size(); ++i) {
  6633. EXPECT_EQ(kNumRpcsPerAddress + kNumFailuresPerAddress,
  6634. backends_[i]->backend_service()->request_count());
  6635. }
  6636. // The load report received at the balancer should be correct.
  6637. std::vector<ClientStats> load_report =
  6638. balancers_[0]->lrs_service()->WaitForLoadReport();
  6639. ASSERT_EQ(load_report.size(), 1UL);
  6640. ClientStats& client_stats = load_report.front();
  6641. EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + num_ok,
  6642. client_stats.total_successful_requests());
  6643. EXPECT_EQ(0U, client_stats.total_requests_in_progress());
  6644. EXPECT_EQ((kNumRpcsPerAddress + kNumFailuresPerAddress) * num_backends_ +
  6645. num_ok + num_failure,
  6646. client_stats.total_issued_requests());
  6647. EXPECT_EQ(kNumFailuresPerAddress * num_backends_ + num_failure,
  6648. client_stats.total_error_requests());
  6649. EXPECT_EQ(0U, client_stats.total_dropped_requests());
  6650. // The LRS service got a single request, and sent a single response.
  6651. EXPECT_EQ(1U, balancers_[0]->lrs_service()->request_count());
  6652. EXPECT_EQ(1U, balancers_[0]->lrs_service()->response_count());
  6653. }
  6654. // Tests that we don't include stats for clusters that are not requested
  6655. // by the LRS server.
  6656. TEST_P(ClientLoadReportingTest, HonorsClustersRequestedByLrsServer) {
  6657. balancers_[0]->lrs_service()->set_cluster_names({"bogus"});
  6658. SetNextResolution({});
  6659. SetNextResolutionForLbChannel({balancers_[0]->port()});
  6660. const size_t kNumRpcsPerAddress = 100;
  6661. AdsServiceImpl::EdsResourceArgs args({
  6662. {"locality0", GetBackendPorts()},
  6663. });
  6664. balancers_[0]->ads_service()->SetEdsResource(
  6665. BuildEdsResource(args, DefaultEdsServiceName()));
  6666. // Wait until all backends are ready.
  6667. int num_ok = 0;
  6668. int num_failure = 0;
  6669. int num_drops = 0;
  6670. std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
  6671. // Send kNumRpcsPerAddress RPCs per server.
  6672. CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
  6673. // Each backend should have gotten 100 requests.
  6674. for (size_t i = 0; i < backends_.size(); ++i) {
  6675. EXPECT_EQ(kNumRpcsPerAddress,
  6676. backends_[i]->backend_service()->request_count());
  6677. }
  6678. // The LRS service got a single request, and sent a single response.
  6679. EXPECT_EQ(1U, balancers_[0]->lrs_service()->request_count());
  6680. EXPECT_EQ(1U, balancers_[0]->lrs_service()->response_count());
  6681. // The load report received at the balancer should be correct.
  6682. std::vector<ClientStats> load_report =
  6683. balancers_[0]->lrs_service()->WaitForLoadReport();
  6684. ASSERT_EQ(load_report.size(), 0UL);
  6685. }
  6686. // Tests that if the balancer restarts, the client load report contains the
  6687. // stats before and after the restart correctly.
  6688. TEST_P(ClientLoadReportingTest, BalancerRestart) {
  6689. if (!GetParam().use_xds_resolver()) {
  6690. balancers_[0]->lrs_service()->set_cluster_names({kServerName});
  6691. }
  6692. SetNextResolution({});
  6693. SetNextResolutionForLbChannel({balancers_[0]->port()});
  6694. const size_t kNumBackendsFirstPass = backends_.size() / 2;
  6695. const size_t kNumBackendsSecondPass =
  6696. backends_.size() - kNumBackendsFirstPass;
  6697. AdsServiceImpl::EdsResourceArgs args({
  6698. {"locality0", GetBackendPorts(0, kNumBackendsFirstPass)},
  6699. });
  6700. balancers_[0]->ads_service()->SetEdsResource(
  6701. BuildEdsResource(args, DefaultEdsServiceName()));
  6702. // Wait until all backends returned by the balancer are ready.
  6703. int num_ok = 0;
  6704. int num_failure = 0;
  6705. int num_drops = 0;
  6706. std::tie(num_ok, num_failure, num_drops) =
  6707. WaitForAllBackends(/* start_index */ 0,
  6708. /* stop_index */ kNumBackendsFirstPass);
  6709. std::vector<ClientStats> load_report =
  6710. balancers_[0]->lrs_service()->WaitForLoadReport();
  6711. ASSERT_EQ(load_report.size(), 1UL);
  6712. ClientStats client_stats = std::move(load_report.front());
  6713. EXPECT_EQ(static_cast<size_t>(num_ok),
  6714. client_stats.total_successful_requests());
  6715. EXPECT_EQ(0U, client_stats.total_requests_in_progress());
  6716. EXPECT_EQ(0U, client_stats.total_error_requests());
  6717. EXPECT_EQ(0U, client_stats.total_dropped_requests());
  6718. // Shut down the balancer.
  6719. balancers_[0]->Shutdown();
  6720. // We should continue using the last EDS response we received from the
  6721. // balancer before it was shut down.
  6722. // Note: We need to use WaitForAllBackends() here instead of just
  6723. // CheckRpcSendOk(kNumBackendsFirstPass), because when the balancer
  6724. // shuts down, the XdsClient will generate an error to the
  6725. // ServiceConfigWatcher, which will cause the xds resolver to send a
  6726. // no-op update to the LB policy. When this update gets down to the
  6727. // round_robin child policy for the locality, it will generate a new
  6728. // subchannel list, which resets the start index randomly. So we need
  6729. // to be a little more permissive here to avoid spurious failures.
  6730. ResetBackendCounters();
  6731. int num_started = std::get<0>(WaitForAllBackends(
  6732. /* start_index */ 0, /* stop_index */ kNumBackendsFirstPass));
  6733. // Now restart the balancer, this time pointing to the new backends.
  6734. balancers_[0]->Start();
  6735. args = AdsServiceImpl::EdsResourceArgs({
  6736. {"locality0", GetBackendPorts(kNumBackendsFirstPass)},
  6737. });
  6738. balancers_[0]->ads_service()->SetEdsResource(
  6739. BuildEdsResource(args, DefaultEdsServiceName()));
  6740. // Wait for queries to start going to one of the new backends.
  6741. // This tells us that we're now using the new serverlist.
  6742. std::tie(num_ok, num_failure, num_drops) =
  6743. WaitForAllBackends(/* start_index */ kNumBackendsFirstPass);
  6744. num_started += num_ok + num_failure + num_drops;
  6745. // Send one RPC per backend.
  6746. CheckRpcSendOk(kNumBackendsSecondPass);
  6747. num_started += kNumBackendsSecondPass;
  6748. // Check client stats.
  6749. load_report = balancers_[0]->lrs_service()->WaitForLoadReport();
  6750. ASSERT_EQ(load_report.size(), 1UL);
  6751. client_stats = std::move(load_report.front());
  6752. EXPECT_EQ(num_started, client_stats.total_successful_requests());
  6753. EXPECT_EQ(0U, client_stats.total_requests_in_progress());
  6754. EXPECT_EQ(0U, client_stats.total_error_requests());
  6755. EXPECT_EQ(0U, client_stats.total_dropped_requests());
  6756. }
  6757. class ClientLoadReportingWithDropTest : public XdsEnd2endTest {
  6758. public:
  6759. ClientLoadReportingWithDropTest() : XdsEnd2endTest(4, 1, 20) {}
  6760. };
  6761. // Tests that the drop stats are correctly reported by client load reporting.
  6762. TEST_P(ClientLoadReportingWithDropTest, Vanilla) {
  6763. if (!GetParam().use_xds_resolver()) {
  6764. balancers_[0]->lrs_service()->set_cluster_names({kServerName});
  6765. }
  6766. SetNextResolution({});
  6767. SetNextResolutionForLbChannelAllBalancers();
  6768. const size_t kNumRpcs = 3000;
  6769. const uint32_t kDropPerMillionForLb = 100000;
  6770. const uint32_t kDropPerMillionForThrottle = 200000;
  6771. const double kDropRateForLb = kDropPerMillionForLb / 1000000.0;
  6772. const double kDropRateForThrottle = kDropPerMillionForThrottle / 1000000.0;
  6773. const double KDropRateForLbAndThrottle =
  6774. kDropRateForLb + (1 - kDropRateForLb) * kDropRateForThrottle;
  6775. // The ADS response contains two drop categories.
  6776. AdsServiceImpl::EdsResourceArgs args({
  6777. {"locality0", GetBackendPorts()},
  6778. });
  6779. args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
  6780. {kThrottleDropType, kDropPerMillionForThrottle}};
  6781. balancers_[0]->ads_service()->SetEdsResource(
  6782. BuildEdsResource(args, DefaultEdsServiceName()));
  6783. int num_ok = 0;
  6784. int num_failure = 0;
  6785. int num_drops = 0;
  6786. std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
  6787. const size_t num_warmup = num_ok + num_failure + num_drops;
  6788. // Send kNumRpcs RPCs and count the drops.
  6789. for (size_t i = 0; i < kNumRpcs; ++i) {
  6790. EchoResponse response;
  6791. const Status status = SendRpc(RpcOptions(), &response);
  6792. if (!status.ok() &&
  6793. status.error_message() == "Call dropped by load balancing policy") {
  6794. ++num_drops;
  6795. } else {
  6796. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  6797. << " message=" << status.error_message();
  6798. EXPECT_EQ(response.message(), kRequestMessage);
  6799. }
  6800. }
  6801. // The drop rate should be roughly equal to the expectation.
  6802. const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
  6803. const double kErrorTolerance = 0.2;
  6804. EXPECT_THAT(
  6805. seen_drop_rate,
  6806. ::testing::AllOf(
  6807. ::testing::Ge(KDropRateForLbAndThrottle * (1 - kErrorTolerance)),
  6808. ::testing::Le(KDropRateForLbAndThrottle * (1 + kErrorTolerance))));
  6809. // Check client stats.
  6810. const size_t total_rpc = num_warmup + kNumRpcs;
  6811. ClientStats client_stats;
  6812. do {
  6813. std::vector<ClientStats> load_reports =
  6814. balancers_[0]->lrs_service()->WaitForLoadReport();
  6815. for (const auto& load_report : load_reports) {
  6816. client_stats += load_report;
  6817. }
  6818. } while (client_stats.total_issued_requests() +
  6819. client_stats.total_dropped_requests() <
  6820. total_rpc);
  6821. EXPECT_EQ(num_drops, client_stats.total_dropped_requests());
  6822. EXPECT_THAT(
  6823. client_stats.dropped_requests(kLbDropType),
  6824. ::testing::AllOf(
  6825. ::testing::Ge(total_rpc * kDropRateForLb * (1 - kErrorTolerance)),
  6826. ::testing::Le(total_rpc * kDropRateForLb * (1 + kErrorTolerance))));
  6827. EXPECT_THAT(client_stats.dropped_requests(kThrottleDropType),
  6828. ::testing::AllOf(
  6829. ::testing::Ge(total_rpc * (1 - kDropRateForLb) *
  6830. kDropRateForThrottle * (1 - kErrorTolerance)),
  6831. ::testing::Le(total_rpc * (1 - kDropRateForLb) *
  6832. kDropRateForThrottle * (1 + kErrorTolerance))));
  6833. }
  6834. std::string TestTypeName(const ::testing::TestParamInfo<TestType>& info) {
  6835. return info.param.AsString();
  6836. }
  6837. // TestType params:
  6838. // - use_xds_resolver
  6839. // - enable_load_reporting
  6840. // - enable_rds_testing = false
  6841. // - use_v2 = false
  6842. // - use_xds_credentials = false
  6843. INSTANTIATE_TEST_SUITE_P(XdsTest, BasicTest,
  6844. ::testing::Values(TestType(false, true),
  6845. TestType(false, false),
  6846. TestType(true, false),
  6847. TestType(true, true)),
  6848. &TestTypeName);
  6849. // Run with both fake resolver and xds resolver.
  6850. // Don't run with load reporting or v2 or RDS, since they are irrelevant to
  6851. // the tests.
  6852. INSTANTIATE_TEST_SUITE_P(XdsTest, SecureNamingTest,
  6853. ::testing::Values(TestType(false, false),
  6854. TestType(true, false)),
  6855. &TestTypeName);
  6856. // LDS depends on XdsResolver.
  6857. INSTANTIATE_TEST_SUITE_P(XdsTest, LdsTest,
  6858. ::testing::Values(TestType(true, false),
  6859. TestType(true, true)),
  6860. &TestTypeName);
  6861. // LDS/RDS commmon tests depend on XdsResolver.
  6862. INSTANTIATE_TEST_SUITE_P(XdsTest, LdsRdsTest,
  6863. ::testing::Values(TestType(true, false),
  6864. TestType(true, true),
  6865. TestType(true, false, true),
  6866. TestType(true, true, true),
  6867. // Also test with xDS v2.
  6868. TestType(true, true, true, true)),
  6869. &TestTypeName);
  6870. // CDS depends on XdsResolver.
  6871. INSTANTIATE_TEST_SUITE_P(XdsTest, CdsTest,
  6872. ::testing::Values(TestType(true, false),
  6873. TestType(true, true)),
  6874. &TestTypeName);
  6875. // CDS depends on XdsResolver.
  6876. // Security depends on v3.
  6877. // Not enabling load reporting or RDS, since those are irrelevant to these
  6878. // tests.
  6879. INSTANTIATE_TEST_SUITE_P(XdsTest, XdsSecurityTest,
  6880. ::testing::Values(TestType(true, false, false, false,
  6881. true)),
  6882. &TestTypeName);
  6883. // EDS could be tested with or without XdsResolver, but the tests would
  6884. // be the same either way, so we test it only with XdsResolver.
  6885. INSTANTIATE_TEST_SUITE_P(XdsTest, EdsTest,
  6886. ::testing::Values(TestType(true, false),
  6887. TestType(true, true)),
  6888. &TestTypeName);
  6889. // Test initial resource timeouts for each resource type.
  6890. // Do this only for XdsResolver with RDS enabled, so that we can test
  6891. // all resource types.
  6892. // Run with V3 only, since the functionality is no different in V2.
  6893. INSTANTIATE_TEST_SUITE_P(XdsTest, TimeoutTest,
  6894. ::testing::Values(TestType(true, false, true)),
  6895. &TestTypeName);
  6896. // XdsResolverOnlyTest depends on XdsResolver.
  6897. INSTANTIATE_TEST_SUITE_P(XdsTest, XdsResolverOnlyTest,
  6898. ::testing::Values(TestType(true, false),
  6899. TestType(true, true)),
  6900. &TestTypeName);
  6901. // XdsResolverLoadReprtingOnlyTest depends on XdsResolver and load reporting.
  6902. INSTANTIATE_TEST_SUITE_P(XdsTest, XdsResolverLoadReportingOnlyTest,
  6903. ::testing::Values(TestType(true, true)),
  6904. &TestTypeName);
  6905. INSTANTIATE_TEST_SUITE_P(XdsTest, LocalityMapTest,
  6906. ::testing::Values(TestType(false, true),
  6907. TestType(false, false),
  6908. TestType(true, false),
  6909. TestType(true, true)),
  6910. &TestTypeName);
  6911. INSTANTIATE_TEST_SUITE_P(XdsTest, FailoverTest,
  6912. ::testing::Values(TestType(false, true),
  6913. TestType(false, false),
  6914. TestType(true, false),
  6915. TestType(true, true)),
  6916. &TestTypeName);
  6917. INSTANTIATE_TEST_SUITE_P(XdsTest, DropTest,
  6918. ::testing::Values(TestType(false, true),
  6919. TestType(false, false),
  6920. TestType(true, false),
  6921. TestType(true, true)),
  6922. &TestTypeName);
  6923. INSTANTIATE_TEST_SUITE_P(XdsTest, BalancerUpdateTest,
  6924. ::testing::Values(TestType(false, true),
  6925. TestType(false, false),
  6926. TestType(true, true)),
  6927. &TestTypeName);
  6928. // Load reporting tests are not run with load reporting disabled.
  6929. INSTANTIATE_TEST_SUITE_P(XdsTest, ClientLoadReportingTest,
  6930. ::testing::Values(TestType(false, true),
  6931. TestType(true, true)),
  6932. &TestTypeName);
  6933. // Load reporting tests are not run with load reporting disabled.
  6934. INSTANTIATE_TEST_SUITE_P(XdsTest, ClientLoadReportingWithDropTest,
  6935. ::testing::Values(TestType(false, true),
  6936. TestType(true, true)),
  6937. &TestTypeName);
  6938. } // namespace
  6939. } // namespace testing
  6940. } // namespace grpc
  6941. int main(int argc, char** argv) {
  6942. grpc::testing::TestEnvironment env(argc, argv);
  6943. ::testing::InitGoogleTest(&argc, argv);
  6944. grpc::testing::WriteBootstrapFiles();
  6945. grpc::testing::g_port_saver = new grpc::testing::PortSaver();
  6946. const auto result = RUN_ALL_TESTS();
  6947. return result;
  6948. }