xds_end2end_test.cc 617 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987
  1. // Copyright 2017 gRPC authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. // TODO(roth): Split this file up into a common test framework and a set
  16. // of test files that use that framework. Need to figure out the best
  17. // way to split up the tests. One option would be to split it up by xDS
  18. // resource type; another approach would be to have all of the "core"
  19. // xDS functionality in one file and then move specific features to
  20. // their own files (e.g., mTLS security, fault injection, circuit
  21. // breaking, etc).
  22. #include <deque>
  23. #include <memory>
  24. #include <mutex>
  25. #include <numeric>
  26. #include <set>
  27. #include <sstream>
  28. #include <string>
  29. #include <thread>
  30. #include <vector>
  31. #include <gmock/gmock.h>
  32. #include <gtest/gtest.h>
  33. #include "absl/functional/bind_front.h"
  34. #include "absl/memory/memory.h"
  35. #include "absl/strings/match.h"
  36. #include "absl/strings/str_cat.h"
  37. #include "absl/strings/str_format.h"
  38. #include "absl/strings/str_join.h"
  39. #include "absl/strings/str_replace.h"
  40. #include "absl/types/optional.h"
  41. #include <grpc/grpc.h>
  42. #include <grpc/grpc_security.h>
  43. #include <grpc/support/alloc.h>
  44. #include <grpc/support/log.h>
  45. #include <grpc/support/time.h>
  46. #include <grpcpp/channel.h>
  47. #include <grpcpp/client_context.h>
  48. #include <grpcpp/create_channel.h>
  49. #include <grpcpp/security/tls_certificate_provider.h>
  50. #include <grpcpp/server.h>
  51. #include <grpcpp/server_builder.h>
  52. #include <grpcpp/xds_server_builder.h>
  53. #include "src/core/ext/filters/client_channel/backup_poller.h"
  54. #include "src/core/ext/filters/client_channel/lb_policy/xds/xds_channel_args.h"
  55. #include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
  56. #include "src/core/ext/xds/certificate_provider_registry.h"
  57. #include "src/core/ext/xds/xds_api.h"
  58. #include "src/core/ext/xds/xds_channel_args.h"
  59. #include "src/core/ext/xds/xds_client.h"
  60. #include "src/core/ext/xds/xds_listener.h"
  61. #include "src/core/lib/address_utils/parse_address.h"
  62. #include "src/core/lib/channel/channel_args.h"
  63. #include "src/core/lib/gpr/env.h"
  64. #include "src/core/lib/gpr/string.h"
  65. #include "src/core/lib/gpr/time_precise.h"
  66. #include "src/core/lib/gpr/tmpfile.h"
  67. #include "src/core/lib/gprpp/ref_counted_ptr.h"
  68. #include "src/core/lib/gprpp/sync.h"
  69. #include "src/core/lib/gprpp/time.h"
  70. #include "src/core/lib/gprpp/time_util.h"
  71. #include "src/core/lib/iomgr/load_file.h"
  72. #include "src/core/lib/iomgr/sockaddr.h"
  73. #include "src/core/lib/resolver/server_address.h"
  74. #include "src/core/lib/security/credentials/fake/fake_credentials.h"
  75. #include "src/cpp/client/secure_credentials.h"
  76. #include "src/cpp/server/secure_server_credentials.h"
  77. #include "src/proto/grpc/testing/echo.grpc.pb.h"
  78. #include "src/proto/grpc/testing/xds/ads_for_test.grpc.pb.h"
  79. #include "src/proto/grpc/testing/xds/cds_for_test.grpc.pb.h"
  80. #include "src/proto/grpc/testing/xds/eds_for_test.grpc.pb.h"
  81. #include "src/proto/grpc/testing/xds/lds_rds_for_test.grpc.pb.h"
  82. #include "src/proto/grpc/testing/xds/lrs_for_test.grpc.pb.h"
  83. #include "src/proto/grpc/testing/xds/v3/ads.grpc.pb.h"
  84. #include "src/proto/grpc/testing/xds/v3/aggregate_cluster.grpc.pb.h"
  85. #include "src/proto/grpc/testing/xds/v3/cluster.grpc.pb.h"
  86. #include "src/proto/grpc/testing/xds/v3/discovery.grpc.pb.h"
  87. #include "src/proto/grpc/testing/xds/v3/endpoint.grpc.pb.h"
  88. #include "src/proto/grpc/testing/xds/v3/fault.grpc.pb.h"
  89. #include "src/proto/grpc/testing/xds/v3/http_connection_manager.grpc.pb.h"
  90. #include "src/proto/grpc/testing/xds/v3/http_filter_rbac.grpc.pb.h"
  91. #include "src/proto/grpc/testing/xds/v3/listener.grpc.pb.h"
  92. #include "src/proto/grpc/testing/xds/v3/lrs.grpc.pb.h"
  93. #include "src/proto/grpc/testing/xds/v3/route.grpc.pb.h"
  94. #include "src/proto/grpc/testing/xds/v3/router.grpc.pb.h"
  95. #include "src/proto/grpc/testing/xds/v3/tls.grpc.pb.h"
  96. #include "test/core/util/port.h"
  97. #include "test/core/util/resolve_localhost_ip46.h"
  98. #include "test/core/util/test_config.h"
  99. #include "test/cpp/end2end/counted_service.h"
  100. #include "test/cpp/end2end/test_service_impl.h"
  101. #include "test/cpp/end2end/xds/xds_server.h"
  102. #include "test/cpp/util/test_config.h"
  103. #include "test/cpp/util/tls_test_utils.h"
  104. #ifndef DISABLED_XDS_PROTO_IN_CC
  105. #include "src/cpp/server/csds/csds.h"
  106. #include "src/proto/grpc/testing/xds/v3/csds.grpc.pb.h"
  107. #endif // DISABLED_XDS_PROTO_IN_CC
  108. namespace grpc {
  109. namespace testing {
  110. namespace {
  111. using std::chrono::system_clock;
  112. #ifndef DISABLED_XDS_PROTO_IN_CC
  113. using ::envoy::admin::v3::ClientResourceStatus;
  114. #endif // DISABLED_XDS_PROTO_IN_CC
  115. using ::envoy::config::cluster::v3::CircuitBreakers;
  116. using ::envoy::config::cluster::v3::Cluster;
  117. using ::envoy::config::cluster::v3::CustomClusterType;
  118. using ::envoy::config::cluster::v3::RoutingPriority;
  119. using ::envoy::config::endpoint::v3::ClusterLoadAssignment;
  120. using ::envoy::config::endpoint::v3::HealthStatus;
  121. using ::envoy::config::listener::v3::FilterChainMatch;
  122. using ::envoy::config::listener::v3::Listener;
  123. using ::envoy::config::rbac::v3::Policy;
  124. using ::envoy::config::rbac::v3::RBAC_Action;
  125. using ::envoy::config::rbac::v3::RBAC_Action_ALLOW;
  126. using ::envoy::config::rbac::v3::RBAC_Action_DENY;
  127. using ::envoy::config::rbac::v3::RBAC_Action_LOG;
  128. using ::envoy::config::route::v3::RouteConfiguration;
  129. using ::envoy::extensions::clusters::aggregate::v3::ClusterConfig;
  130. using ::envoy::extensions::filters::http::fault::v3::HTTPFault;
  131. using ::envoy::extensions::filters::http::rbac::v3::RBAC;
  132. using ::envoy::extensions::filters::http::rbac::v3::RBACPerRoute;
  133. using ::envoy::extensions::filters::network::http_connection_manager::v3::
  134. HttpConnectionManager;
  135. using ::envoy::extensions::filters::network::http_connection_manager::v3::
  136. HttpFilter;
  137. using ::envoy::extensions::transport_sockets::tls::v3::DownstreamTlsContext;
  138. using ::envoy::extensions::transport_sockets::tls::v3::UpstreamTlsContext;
  139. using ::envoy::type::matcher::v3::StringMatcher;
  140. using ::envoy::type::v3::FractionalPercent;
  141. using ClientStats = LrsServiceImpl::ClientStats;
  142. using ::grpc::experimental::ExternalCertificateVerifier;
  143. using ::grpc::experimental::IdentityKeyCertPair;
  144. using ::grpc::experimental::StaticDataCertificateProvider;
  145. constexpr char kDefaultLocalityRegion[] = "xds_default_locality_region";
  146. constexpr char kDefaultLocalityZone[] = "xds_default_locality_zone";
  147. constexpr char kLbDropType[] = "lb";
  148. constexpr char kThrottleDropType[] = "throttle";
  149. constexpr char kServerName[] = "server.example.com";
  150. constexpr char kDefaultRouteConfigurationName[] = "route_config_name";
  151. constexpr char kDefaultServerRouteConfigurationName[] =
  152. "default_server_route_config_name";
  153. constexpr char kDefaultClusterName[] = "cluster_name";
  154. constexpr char kDefaultEdsServiceName[] = "eds_service_name";
  155. constexpr int kDefaultLocalityWeight = 3;
  156. constexpr int kDefaultLocalityPriority = 0;
  157. constexpr char kRequestMessage[] = "Live long and prosper.";
  158. constexpr char kCaCertPath[] = "src/core/tsi/test_creds/ca.pem";
  159. constexpr char kServerCertPath[] = "src/core/tsi/test_creds/server1.pem";
  160. constexpr char kServerKeyPath[] = "src/core/tsi/test_creds/server1.key";
  161. constexpr char kClientCertPath[] = "src/core/tsi/test_creds/client.pem";
  162. constexpr char kClientKeyPath[] = "src/core/tsi/test_creds/client.key";
  163. constexpr char kBadClientCertPath[] = "src/core/tsi/test_creds/badclient.pem";
  164. constexpr char kBadClientKeyPath[] = "src/core/tsi/test_creds/badclient.key";
  165. template <typename RpcService>
  166. class BackendServiceImpl
  167. : public CountedService<TestMultipleServiceImpl<RpcService>> {
  168. public:
  169. BackendServiceImpl() {}
  170. Status Echo(ServerContext* context, const EchoRequest* request,
  171. EchoResponse* response) override {
  172. auto peer_identity = context->auth_context()->GetPeerIdentity();
  173. CountedService<TestMultipleServiceImpl<RpcService>>::IncreaseRequestCount();
  174. const auto status =
  175. TestMultipleServiceImpl<RpcService>::Echo(context, request, response);
  176. CountedService<
  177. TestMultipleServiceImpl<RpcService>>::IncreaseResponseCount();
  178. {
  179. grpc_core::MutexLock lock(&mu_);
  180. clients_.insert(context->peer());
  181. last_peer_identity_.clear();
  182. for (const auto& entry : peer_identity) {
  183. last_peer_identity_.emplace_back(entry.data(), entry.size());
  184. }
  185. }
  186. return status;
  187. }
  188. Status Echo1(ServerContext* context, const EchoRequest* request,
  189. EchoResponse* response) override {
  190. return Echo(context, request, response);
  191. }
  192. Status Echo2(ServerContext* context, const EchoRequest* request,
  193. EchoResponse* response) override {
  194. return Echo(context, request, response);
  195. }
  196. void Start() {}
  197. void Shutdown() {}
  198. std::set<std::string> clients() {
  199. grpc_core::MutexLock lock(&mu_);
  200. return clients_;
  201. }
  202. const std::vector<std::string>& last_peer_identity() {
  203. grpc_core::MutexLock lock(&mu_);
  204. return last_peer_identity_;
  205. }
  206. private:
  207. grpc_core::Mutex mu_;
  208. std::set<std::string> clients_ ABSL_GUARDED_BY(mu_);
  209. std::vector<std::string> last_peer_identity_ ABSL_GUARDED_BY(mu_);
  210. };
  211. class TestType {
  212. public:
  213. enum FilterConfigSetup {
  214. // Set the fault injection filter directly from LDS
  215. kHTTPConnectionManagerOriginal,
  216. // Enable the fault injection filter in LDS, but override the filter config
  217. // in route.
  218. kRouteOverride,
  219. };
  220. enum BootstrapSource {
  221. kBootstrapFromChannelArg,
  222. kBootstrapFromFile,
  223. kBootstrapFromEnvVar,
  224. };
  225. TestType& set_enable_load_reporting() {
  226. enable_load_reporting_ = true;
  227. return *this;
  228. }
  229. TestType& set_enable_rds_testing() {
  230. enable_rds_testing_ = true;
  231. return *this;
  232. }
  233. TestType& set_use_v2() {
  234. use_v2_ = true;
  235. return *this;
  236. }
  237. TestType& set_use_xds_credentials() {
  238. use_xds_credentials_ = true;
  239. return *this;
  240. }
  241. TestType& set_use_csds_streaming() {
  242. use_csds_streaming_ = true;
  243. return *this;
  244. }
  245. TestType& set_filter_config_setup(FilterConfigSetup setup) {
  246. filter_config_setup_ = setup;
  247. return *this;
  248. }
  249. TestType& set_bootstrap_source(BootstrapSource bootstrap_source) {
  250. bootstrap_source_ = bootstrap_source;
  251. return *this;
  252. }
  253. TestType& set_rbac_action(RBAC_Action action) {
  254. rbac_action_ = action;
  255. return *this;
  256. }
  257. bool enable_load_reporting() const { return enable_load_reporting_; }
  258. bool enable_rds_testing() const { return enable_rds_testing_; }
  259. bool use_v2() const { return use_v2_; }
  260. bool use_xds_credentials() const { return use_xds_credentials_; }
  261. bool use_csds_streaming() const { return use_csds_streaming_; }
  262. FilterConfigSetup filter_config_setup() const { return filter_config_setup_; }
  263. BootstrapSource bootstrap_source() const { return bootstrap_source_; }
  264. RBAC_Action rbac_action() const { return rbac_action_; }
  265. std::string AsString() const {
  266. std::string retval = use_v2_ ? "V2" : "V3";
  267. if (enable_load_reporting_) retval += "WithLoadReporting";
  268. if (enable_rds_testing_) retval += "Rds";
  269. if (use_xds_credentials_) retval += "XdsCreds";
  270. if (use_csds_streaming_) retval += "CsdsStreaming";
  271. if (filter_config_setup_ == kRouteOverride) {
  272. retval += "FilterPerRouteOverride";
  273. }
  274. if (bootstrap_source_ == kBootstrapFromFile) {
  275. retval += "BootstrapFromFile";
  276. } else if (bootstrap_source_ == kBootstrapFromEnvVar) {
  277. retval += "BootstrapFromEnvVar";
  278. }
  279. if (rbac_action_ == RBAC_Action_ALLOW) {
  280. retval += "RbacAllow";
  281. } else if (rbac_action_ == RBAC_Action_DENY) {
  282. retval += "RbacDeny";
  283. }
  284. return retval;
  285. }
  286. private:
  287. bool enable_load_reporting_ = false;
  288. bool enable_rds_testing_ = false;
  289. bool use_v2_ = false;
  290. bool use_xds_credentials_ = false;
  291. bool use_csds_streaming_ = false;
  292. FilterConfigSetup filter_config_setup_ = kHTTPConnectionManagerOriginal;
  293. BootstrapSource bootstrap_source_ = kBootstrapFromChannelArg;
  294. RBAC_Action rbac_action_ = RBAC_Action_LOG;
  295. };
  296. std::string ReadFile(const char* file_path) {
  297. grpc_slice slice;
  298. GPR_ASSERT(
  299. GRPC_LOG_IF_ERROR("load_file", grpc_load_file(file_path, 0, &slice)));
  300. std::string file_contents(grpc_core::StringViewFromSlice(slice));
  301. grpc_slice_unref(slice);
  302. return file_contents;
  303. }
  304. grpc_core::PemKeyCertPairList ReadTlsIdentityPair(const char* key_path,
  305. const char* cert_path) {
  306. return grpc_core::PemKeyCertPairList{
  307. grpc_core::PemKeyCertPair(ReadFile(key_path), ReadFile(cert_path))};
  308. }
  309. // Based on StaticDataCertificateProvider, but provides alternate certificates
  310. // if the certificate name is not empty.
  311. class FakeCertificateProvider final : public grpc_tls_certificate_provider {
  312. public:
  313. struct CertData {
  314. std::string root_certificate;
  315. grpc_core::PemKeyCertPairList identity_key_cert_pairs;
  316. };
  317. using CertDataMap = std::map<std::string /*cert_name */, CertData>;
  318. explicit FakeCertificateProvider(CertDataMap cert_data_map)
  319. : distributor_(
  320. grpc_core::MakeRefCounted<grpc_tls_certificate_distributor>()),
  321. cert_data_map_(std::move(cert_data_map)) {
  322. distributor_->SetWatchStatusCallback([this](std::string cert_name,
  323. bool root_being_watched,
  324. bool identity_being_watched) {
  325. if (!root_being_watched && !identity_being_watched) return;
  326. auto it = cert_data_map_.find(cert_name);
  327. if (it == cert_data_map_.end()) {
  328. grpc_error_handle error =
  329. GRPC_ERROR_CREATE_FROM_CPP_STRING(absl::StrCat(
  330. "No certificates available for cert_name \"", cert_name, "\""));
  331. distributor_->SetErrorForCert(cert_name, GRPC_ERROR_REF(error),
  332. GRPC_ERROR_REF(error));
  333. GRPC_ERROR_UNREF(error);
  334. } else {
  335. absl::optional<std::string> root_certificate;
  336. absl::optional<grpc_core::PemKeyCertPairList> pem_key_cert_pairs;
  337. if (root_being_watched) {
  338. root_certificate = it->second.root_certificate;
  339. }
  340. if (identity_being_watched) {
  341. pem_key_cert_pairs = it->second.identity_key_cert_pairs;
  342. }
  343. distributor_->SetKeyMaterials(cert_name, std::move(root_certificate),
  344. std::move(pem_key_cert_pairs));
  345. }
  346. });
  347. }
  348. ~FakeCertificateProvider() override {
  349. distributor_->SetWatchStatusCallback(nullptr);
  350. }
  351. grpc_core::RefCountedPtr<grpc_tls_certificate_distributor> distributor()
  352. const override {
  353. return distributor_;
  354. }
  355. private:
  356. grpc_core::RefCountedPtr<grpc_tls_certificate_distributor> distributor_;
  357. CertDataMap cert_data_map_;
  358. };
  359. class FakeCertificateProviderFactory
  360. : public grpc_core::CertificateProviderFactory {
  361. public:
  362. class Config : public grpc_core::CertificateProviderFactory::Config {
  363. public:
  364. explicit Config(const char* name) : name_(name) {}
  365. const char* name() const override { return name_; }
  366. std::string ToString() const override { return "{}"; }
  367. private:
  368. const char* name_;
  369. };
  370. FakeCertificateProviderFactory(
  371. const char* name, FakeCertificateProvider::CertDataMap** cert_data_map)
  372. : name_(name), cert_data_map_(cert_data_map) {
  373. GPR_ASSERT(cert_data_map != nullptr);
  374. }
  375. const char* name() const override { return name_; }
  376. grpc_core::RefCountedPtr<grpc_core::CertificateProviderFactory::Config>
  377. CreateCertificateProviderConfig(const grpc_core::Json& /*config_json*/,
  378. grpc_error_handle* /*error*/) override {
  379. return grpc_core::MakeRefCounted<Config>(name_);
  380. }
  381. grpc_core::RefCountedPtr<grpc_tls_certificate_provider>
  382. CreateCertificateProvider(
  383. grpc_core::RefCountedPtr<grpc_core::CertificateProviderFactory::Config>
  384. /*config*/) override {
  385. if (*cert_data_map_ == nullptr) return nullptr;
  386. return grpc_core::MakeRefCounted<FakeCertificateProvider>(**cert_data_map_);
  387. }
  388. private:
  389. const char* name_;
  390. FakeCertificateProvider::CertDataMap** cert_data_map_;
  391. };
  392. // Global variables for each provider.
  393. FakeCertificateProvider::CertDataMap* g_fake1_cert_data_map = nullptr;
  394. FakeCertificateProvider::CertDataMap* g_fake2_cert_data_map = nullptr;
  395. std::shared_ptr<ChannelCredentials> CreateTlsFallbackCredentials() {
  396. IdentityKeyCertPair key_cert_pair;
  397. key_cert_pair.private_key = ReadFile(kServerKeyPath);
  398. key_cert_pair.certificate_chain = ReadFile(kServerCertPath);
  399. std::vector<IdentityKeyCertPair> identity_key_cert_pairs;
  400. identity_key_cert_pairs.emplace_back(key_cert_pair);
  401. auto certificate_provider = std::make_shared<StaticDataCertificateProvider>(
  402. ReadFile(kCaCertPath), identity_key_cert_pairs);
  403. grpc::experimental::TlsChannelCredentialsOptions options;
  404. options.set_certificate_provider(std::move(certificate_provider));
  405. options.watch_root_certs();
  406. options.watch_identity_key_cert_pairs();
  407. auto verifier =
  408. ExternalCertificateVerifier::Create<SyncCertificateVerifier>(true);
  409. options.set_certificate_verifier(std::move(verifier));
  410. options.set_verify_server_certs(true);
  411. options.set_check_call_host(false);
  412. auto channel_creds = grpc::experimental::TlsCredentials(options);
  413. GPR_ASSERT(channel_creds.get() != nullptr);
  414. return channel_creds;
  415. }
  416. // A No-op HTTP filter used for verifying parsing logic.
  417. class NoOpHttpFilter : public grpc_core::XdsHttpFilterImpl {
  418. public:
  419. NoOpHttpFilter(std::string name, bool supported_on_clients,
  420. bool supported_on_servers, bool is_terminal_filter)
  421. : name_(std::move(name)),
  422. supported_on_clients_(supported_on_clients),
  423. supported_on_servers_(supported_on_servers),
  424. is_terminal_filter_(is_terminal_filter) {}
  425. void PopulateSymtab(upb_DefPool* /* symtab */) const override {}
  426. absl::StatusOr<grpc_core::XdsHttpFilterImpl::FilterConfig>
  427. GenerateFilterConfig(upb_StringView /* serialized_filter_config */,
  428. upb_Arena* /* arena */) const override {
  429. return grpc_core::XdsHttpFilterImpl::FilterConfig{name_, grpc_core::Json()};
  430. }
  431. absl::StatusOr<grpc_core::XdsHttpFilterImpl::FilterConfig>
  432. GenerateFilterConfigOverride(upb_StringView /*serialized_filter_config*/,
  433. upb_Arena* /*arena*/) const override {
  434. return grpc_core::XdsHttpFilterImpl::FilterConfig{name_, grpc_core::Json()};
  435. }
  436. const grpc_channel_filter* channel_filter() const override { return nullptr; }
  437. absl::StatusOr<grpc_core::XdsHttpFilterImpl::ServiceConfigJsonEntry>
  438. GenerateServiceConfig(
  439. const FilterConfig& /*hcm_filter_config*/,
  440. const FilterConfig* /*filter_config_override*/) const override {
  441. return grpc_core::XdsHttpFilterImpl::ServiceConfigJsonEntry{name_, ""};
  442. }
  443. bool IsSupportedOnClients() const override { return supported_on_clients_; }
  444. bool IsSupportedOnServers() const override { return supported_on_servers_; }
  445. bool IsTerminalFilter() const override { return is_terminal_filter_; }
  446. private:
  447. const std::string name_;
  448. const bool supported_on_clients_;
  449. const bool supported_on_servers_;
  450. const bool is_terminal_filter_;
  451. };
  452. // There is slight difference between time fetched by GPR and by C++ system
  453. // clock API. It's unclear if they are using the same syscall, but we do know
  454. // GPR round the number at millisecond-level. This creates a 1ms difference,
  455. // which could cause flake.
  456. grpc_core::Timestamp NowFromCycleCounter() {
  457. return grpc_core::Timestamp::FromTimespecRoundDown(
  458. gpr_now(GPR_CLOCK_MONOTONIC));
  459. }
  460. // Returns the number of RPCs needed to pass error_tolerance at 99.99994%
  461. // chance. Rolling dices in drop/fault-injection generates a binomial
  462. // distribution (if our code is not horribly wrong). Let's make "n" the number
  463. // of samples, "p" the probability. If we have np>5 & n(1-p)>5, we can
  464. // approximately treat the binomial distribution as a normal distribution.
  465. //
  466. // For normal distribution, we can easily look up how many standard deviation we
  467. // need to reach 99.995%. Based on Wiki's table
  468. // https://en.wikipedia.org/wiki/68%E2%80%9395%E2%80%9399.7_rule, we need 5.00
  469. // sigma (standard deviation) to cover the probability area of 99.99994%. In
  470. // another word, for a sample with size "n" probability "p" error-tolerance "k",
  471. // we want the error always land within 5.00 sigma. The sigma of binominal
  472. // distribution and be computed as sqrt(np(1-p)). Hence, we have the equation:
  473. //
  474. // kn <= 5.00 * sqrt(np(1-p))
  475. size_t ComputeIdealNumRpcs(double p, double error_tolerance) {
  476. GPR_ASSERT(p >= 0 && p <= 1);
  477. size_t num_rpcs =
  478. ceil(p * (1 - p) * 5.00 * 5.00 / error_tolerance / error_tolerance);
  479. gpr_log(GPR_INFO,
  480. "Sending %" PRIuPTR " RPCs for percentage=%.3f error_tolerance=%.3f",
  481. num_rpcs, p, error_tolerance);
  482. return num_rpcs;
  483. }
  484. // Channel arg pointer vtable for storing xDS channel args in the parent
  485. // channel's channel args.
  486. void* ChannelArgsArgCopy(void* p) {
  487. auto* args = static_cast<grpc_channel_args*>(p);
  488. return grpc_channel_args_copy(args);
  489. }
  490. void ChannelArgsArgDestroy(void* p) {
  491. auto* args = static_cast<grpc_channel_args*>(p);
  492. grpc_channel_args_destroy(args);
  493. }
  494. int ChannelArgsArgCmp(void* a, void* b) {
  495. auto* args_a = static_cast<grpc_channel_args*>(a);
  496. auto* args_b = static_cast<grpc_channel_args*>(b);
  497. return grpc_channel_args_compare(args_a, args_b);
  498. }
  499. const grpc_arg_pointer_vtable kChannelArgsArgVtable = {
  500. ChannelArgsArgCopy, ChannelArgsArgDestroy, ChannelArgsArgCmp};
  501. class XdsEnd2endTest : public ::testing::TestWithParam<TestType> {
  502. protected:
  503. // TODO(roth): In a subsequent PR, move BalancerServerThread definition
  504. // here to avoid the need for this forward declaration.
  505. class BalancerServerThread;
  506. class BootstrapBuilder {
  507. public:
  508. BootstrapBuilder() {}
  509. BootstrapBuilder& SetV2() {
  510. v2_ = true;
  511. return *this;
  512. }
  513. BootstrapBuilder& SetDefaultServer(const std::string& server) {
  514. top_server_ = server;
  515. return *this;
  516. }
  517. BootstrapBuilder& SetClientDefaultListenerResourceNameTemplate(
  518. const std::string& client_default_listener_resource_name_template) {
  519. client_default_listener_resource_name_template_ =
  520. client_default_listener_resource_name_template;
  521. return *this;
  522. }
  523. BootstrapBuilder& AddCertificateProviderPlugin(
  524. const std::string& key, const std::string& name,
  525. const std::string& plugin_config = "") {
  526. plugins_[key] = {name, plugin_config};
  527. return *this;
  528. }
  529. BootstrapBuilder& AddAuthority(
  530. const std::string& authority, const std::string& servers = "",
  531. const std::string& client_listener_resource_name_template = "") {
  532. authorities_[authority] = {servers,
  533. client_listener_resource_name_template};
  534. return *this;
  535. }
  536. BootstrapBuilder& SetServerListenerResourceNameTemplate(
  537. const std::string& server_listener_resource_name_template = "") {
  538. server_listener_resource_name_template_ =
  539. server_listener_resource_name_template;
  540. return *this;
  541. }
  542. std::string Build() {
  543. std::vector<std::string> fields;
  544. fields.push_back(MakeXdsServersText(top_server_));
  545. if (!client_default_listener_resource_name_template_.empty()) {
  546. fields.push_back(absl::StrCat(
  547. " \"client_default_listener_resource_name_template\": \"",
  548. client_default_listener_resource_name_template_, "\""));
  549. }
  550. fields.push_back(MakeNodeText());
  551. if (!server_listener_resource_name_template_.empty()) {
  552. fields.push_back(
  553. absl::StrCat(" \"server_listener_resource_name_template\": \"",
  554. server_listener_resource_name_template_, "\""));
  555. }
  556. fields.push_back(MakeCertificateProviderText());
  557. fields.push_back(MakeAuthorityText());
  558. return absl::StrCat("{", absl::StrJoin(fields, ",\n"), "}");
  559. }
  560. private:
  561. struct PluginInfo {
  562. std::string name;
  563. std::string plugin_config;
  564. };
  565. struct AuthorityInfo {
  566. std::string server;
  567. std::string client_listener_resource_name_template;
  568. };
  569. std::string MakeXdsServersText(absl::string_view server_uri) {
  570. constexpr char kXdsServerTemplate[] =
  571. " \"xds_servers\": [\n"
  572. " {\n"
  573. " \"server_uri\": \"<SERVER_URI>\",\n"
  574. " \"channel_creds\": [\n"
  575. " {\n"
  576. " \"type\": \"fake\"\n"
  577. " }\n"
  578. " ],\n"
  579. " \"server_features\": [<SERVER_FEATURES>]\n"
  580. " }\n"
  581. " ]";
  582. return absl::StrReplaceAll(
  583. kXdsServerTemplate,
  584. {{"<SERVER_URI>", server_uri},
  585. {"<SERVER_FEATURES>", (v2_ ? "" : "\"xds_v3\"")}});
  586. }
  587. std::string MakeNodeText() {
  588. constexpr char kXdsNode[] =
  589. " \"node\": {\n"
  590. " \"id\": \"xds_end2end_test\",\n"
  591. " \"cluster\": \"test\",\n"
  592. " \"metadata\": {\n"
  593. " \"foo\": \"bar\"\n"
  594. " },\n"
  595. " \"locality\": {\n"
  596. " \"region\": \"corp\",\n"
  597. " \"zone\": \"svl\",\n"
  598. " \"sub_zone\": \"mp3\"\n"
  599. " }\n"
  600. " }";
  601. return kXdsNode;
  602. }
  603. std::string MakeCertificateProviderText() {
  604. std::vector<std::string> entries;
  605. for (const auto& p : plugins_) {
  606. const std::string& key = p.first;
  607. const PluginInfo& plugin_info = p.second;
  608. std::vector<std::string> fields;
  609. fields.push_back(absl::StrFormat(" \"%s\": {", key));
  610. if (!plugin_info.plugin_config.empty()) {
  611. fields.push_back(absl::StrFormat(" \"plugin_name\": \"%s\",",
  612. plugin_info.name));
  613. fields.push_back(absl::StrCat(
  614. " \"config\": {\n", plugin_info.plugin_config, "\n }"));
  615. } else {
  616. fields.push_back(absl::StrFormat(" \"plugin_name\": \"%s\"",
  617. plugin_info.name));
  618. }
  619. fields.push_back(" }");
  620. entries.push_back(absl::StrJoin(fields, "\n"));
  621. }
  622. return absl::StrCat(" \"certificate_providers\": {\n",
  623. absl::StrJoin(entries, ",\n"), " \n}");
  624. }
  625. std::string MakeAuthorityText() {
  626. std::vector<std::string> entries;
  627. for (const auto& p : authorities_) {
  628. const std::string& name = p.first;
  629. const AuthorityInfo& authority_info = p.second;
  630. std::vector<std::string> fields = {
  631. MakeXdsServersText(authority_info.server)};
  632. if (!authority_info.client_listener_resource_name_template.empty()) {
  633. fields.push_back(absl::StrCat(
  634. "\"client_listener_resource_name_template\": \"",
  635. authority_info.client_listener_resource_name_template, "\""));
  636. }
  637. entries.push_back(absl::StrCat(absl::StrFormat("\"%s\": {\n ", name),
  638. absl::StrJoin(fields, ",\n"), "\n}"));
  639. }
  640. return absl::StrCat("\"authorities\": {\n", absl::StrJoin(entries, ",\n"),
  641. "\n}");
  642. }
  643. bool v2_ = false;
  644. std::string top_server_;
  645. std::string client_default_listener_resource_name_template_;
  646. std::map<std::string /*key*/, PluginInfo> plugins_;
  647. std::map<std::string /*authority_name*/, AuthorityInfo> authorities_;
  648. std::string server_listener_resource_name_template_ =
  649. "grpc/server?xds.resource.listening_address=%s";
  650. };
  651. // TODO(roth): We currently set the number of backends on a per-test-suite
  652. // basis, not a per-test-case basis. However, not every individual test
  653. // case in a given test suite uses the same number of backends, so we wind
  654. // up having to set the numbers for the test suite to the max number needed
  655. // by any one test case in that test suite. This results in starting more
  656. // servers (and using more ports) than we actually need. When we have
  657. // time, change each test to directly start the number of backends
  658. // that it needs, so that we aren't wasting resources.
  659. explicit XdsEnd2endTest(size_t num_backends,
  660. int client_load_reporting_interval_seconds = 100,
  661. int xds_resource_does_not_exist_timeout_ms = 0,
  662. bool use_xds_enabled_server = false)
  663. : num_backends_(num_backends),
  664. client_load_reporting_interval_seconds_(
  665. client_load_reporting_interval_seconds),
  666. xds_resource_does_not_exist_timeout_ms_(
  667. xds_resource_does_not_exist_timeout_ms),
  668. use_xds_enabled_server_(use_xds_enabled_server) {
  669. bool localhost_resolves_to_ipv4 = false;
  670. bool localhost_resolves_to_ipv6 = false;
  671. grpc_core::LocalhostResolves(&localhost_resolves_to_ipv4,
  672. &localhost_resolves_to_ipv6);
  673. ipv6_only_ = !localhost_resolves_to_ipv4 && localhost_resolves_to_ipv6;
  674. // Initialize default xDS resources.
  675. // Construct LDS resource.
  676. default_listener_.set_name(kServerName);
  677. HttpConnectionManager http_connection_manager;
  678. if (!GetParam().use_v2()) {
  679. auto* filter = http_connection_manager.add_http_filters();
  680. filter->set_name("router");
  681. filter->mutable_typed_config()->PackFrom(
  682. envoy::extensions::filters::http::router::v3::Router());
  683. }
  684. default_listener_.mutable_api_listener()->mutable_api_listener()->PackFrom(
  685. http_connection_manager);
  686. // Construct RDS resource.
  687. default_route_config_.set_name(kDefaultRouteConfigurationName);
  688. auto* virtual_host = default_route_config_.add_virtual_hosts();
  689. virtual_host->add_domains("*");
  690. auto* route = virtual_host->add_routes();
  691. route->mutable_match()->set_prefix("");
  692. route->mutable_route()->set_cluster(kDefaultClusterName);
  693. // Construct CDS resource.
  694. default_cluster_.set_name(kDefaultClusterName);
  695. default_cluster_.set_type(Cluster::EDS);
  696. auto* eds_config = default_cluster_.mutable_eds_cluster_config();
  697. eds_config->mutable_eds_config()->mutable_self();
  698. eds_config->set_service_name(kDefaultEdsServiceName);
  699. default_cluster_.set_lb_policy(Cluster::ROUND_ROBIN);
  700. if (GetParam().enable_load_reporting()) {
  701. default_cluster_.mutable_lrs_server()->mutable_self();
  702. }
  703. // Construct a default server-side RDS resource for tests to use.
  704. default_server_route_config_.set_name(kDefaultServerRouteConfigurationName);
  705. virtual_host = default_server_route_config_.add_virtual_hosts();
  706. virtual_host->add_domains("*");
  707. route = virtual_host->add_routes();
  708. route->mutable_match()->set_prefix("");
  709. route->mutable_non_forwarding_action();
  710. // Construct a default server-side Listener resource
  711. default_server_listener_.mutable_address()
  712. ->mutable_socket_address()
  713. ->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
  714. default_server_listener_.mutable_default_filter_chain()
  715. ->add_filters()
  716. ->mutable_typed_config()
  717. ->PackFrom(http_connection_manager);
  718. }
  719. void CreateClientsAndServers(BootstrapBuilder builder = BootstrapBuilder(),
  720. std::string lb_expected_authority = "") {
  721. // Create the backends but don't start them yet. We need to create the
  722. // backends to allocate the ports, so that the xDS servers know what
  723. // default resources to populate when we create them. However, we can't
  724. // start the backends until after we've started the xDS servers, because
  725. // in the tests that use xDS-enabled servers, the backends will try to
  726. // contact the xDS servers as soon as they start up.
  727. for (size_t i = 0; i < num_backends_; ++i) {
  728. backends_.emplace_back(new BackendServerThread(this));
  729. }
  730. // Start the load balancer.
  731. balancer_ = CreateAndStartBalancer();
  732. // Initialize resources on balancer.
  733. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  734. default_route_config_);
  735. if (use_xds_enabled_server_) {
  736. for (const auto& backend : backends_) {
  737. SetServerListenerNameAndRouteConfiguration(
  738. balancer_.get(), default_server_listener_, backend->port(),
  739. default_server_route_config_);
  740. }
  741. }
  742. balancer_->ads_service()->SetCdsResource(default_cluster_);
  743. // Create fake resolver response generators used by client.
  744. logical_dns_cluster_resolver_response_generator_ =
  745. grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
  746. if (xds_resource_does_not_exist_timeout_ms_ > 0) {
  747. xds_channel_args_to_add_.emplace_back(grpc_channel_arg_integer_create(
  748. const_cast<char*>(GRPC_ARG_XDS_RESOURCE_DOES_NOT_EXIST_TIMEOUT_MS),
  749. xds_resource_does_not_exist_timeout_ms_));
  750. }
  751. if (!lb_expected_authority.empty()) {
  752. constexpr char authority_const[] = "localhost:%d";
  753. if (lb_expected_authority == authority_const) {
  754. lb_expected_authority =
  755. absl::StrFormat(authority_const, balancer_->port());
  756. }
  757. xds_channel_args_to_add_.emplace_back(grpc_channel_arg_string_create(
  758. const_cast<char*>(GRPC_ARG_FAKE_SECURITY_EXPECTED_TARGETS),
  759. const_cast<char*>(lb_expected_authority.c_str())));
  760. }
  761. xds_channel_args_.num_args = xds_channel_args_to_add_.size();
  762. xds_channel_args_.args = xds_channel_args_to_add_.data();
  763. // Initialize XdsClient state.
  764. builder.SetDefaultServer(absl::StrCat("localhost:", balancer_->port()));
  765. if (GetParam().use_v2()) {
  766. builder.SetV2();
  767. }
  768. bootstrap_ = builder.Build();
  769. if (GetParam().bootstrap_source() == TestType::kBootstrapFromEnvVar) {
  770. gpr_setenv("GRPC_XDS_BOOTSTRAP_CONFIG", bootstrap_.c_str());
  771. } else if (GetParam().bootstrap_source() == TestType::kBootstrapFromFile) {
  772. FILE* out = gpr_tmpfile("xds_bootstrap_v3", &bootstrap_file_);
  773. fputs(bootstrap_.c_str(), out);
  774. fclose(out);
  775. gpr_setenv("GRPC_XDS_BOOTSTRAP", bootstrap_file_);
  776. }
  777. if (GetParam().bootstrap_source() != TestType::kBootstrapFromChannelArg) {
  778. // If getting bootstrap from channel arg, we'll pass these args in
  779. // via the parent channel args in CreateChannel() instead.
  780. grpc_core::internal::SetXdsChannelArgsForTest(&xds_channel_args_);
  781. // Make sure each test creates a new XdsClient instance rather than
  782. // reusing the one from the previous test. This avoids spurious failures
  783. // caused when a load reporting test runs after a non-load reporting test
  784. // and the XdsClient is still talking to the old LRS server, which fails
  785. // because it's not expecting the client to connect. It also
  786. // ensures that each test can independently set the global channel
  787. // args for the xDS channel.
  788. grpc_core::internal::UnsetGlobalXdsClientForTest();
  789. }
  790. // Create channel and stub.
  791. ResetStub();
  792. }
  793. void SetUp() override { CreateClientsAndServers(); }
  794. void TearDown() override {
  795. ShutdownAllBackends();
  796. balancer_->Shutdown();
  797. // Clear global xDS channel args, since they will go out of scope
  798. // when this test object is destroyed.
  799. grpc_core::internal::SetXdsChannelArgsForTest(nullptr);
  800. gpr_unsetenv("GRPC_XDS_BOOTSTRAP");
  801. gpr_unsetenv("GRPC_XDS_BOOTSTRAP_CONFIG");
  802. if (bootstrap_file_ != nullptr) {
  803. remove(bootstrap_file_);
  804. gpr_free(bootstrap_file_);
  805. }
  806. }
  807. void StartAllBackends() {
  808. for (auto& backend : backends_) backend->Start();
  809. }
  810. void StartBackend(size_t index) { backends_[index]->Start(); }
  811. void ShutdownAllBackends() {
  812. for (auto& backend : backends_) backend->Shutdown();
  813. }
  814. void ShutdownBackend(size_t index) { backends_[index]->Shutdown(); }
  815. std::unique_ptr<BalancerServerThread> CreateAndStartBalancer() {
  816. std::unique_ptr<BalancerServerThread> balancer =
  817. absl::make_unique<BalancerServerThread>(this);
  818. balancer->Start();
  819. return balancer;
  820. }
  821. void ResetStub(int failover_timeout = 0) {
  822. channel_ = CreateChannel(failover_timeout);
  823. stub_ = grpc::testing::EchoTestService::NewStub(channel_);
  824. stub1_ = grpc::testing::EchoTest1Service::NewStub(channel_);
  825. stub2_ = grpc::testing::EchoTest2Service::NewStub(channel_);
  826. }
  827. std::shared_ptr<Channel> CreateChannel(
  828. int failover_timeout = 0, const char* server_name = kServerName,
  829. const char* xds_authority = "",
  830. grpc_channel_args* xds_channel_args = nullptr) {
  831. ChannelArguments args;
  832. // TODO(roth): Remove this once we enable retries by default internally.
  833. args.SetInt(GRPC_ARG_ENABLE_RETRIES, 1);
  834. if (failover_timeout > 0) {
  835. args.SetInt(GRPC_ARG_PRIORITY_FAILOVER_TIMEOUT_MS, failover_timeout);
  836. }
  837. if (GetParam().bootstrap_source() == TestType::kBootstrapFromChannelArg) {
  838. // We're getting the bootstrap from a channel arg, so we do the
  839. // same thing for the response generator to use for the xDS
  840. // channel and the xDS resource-does-not-exist timeout value.
  841. args.SetString(GRPC_ARG_TEST_ONLY_DO_NOT_USE_IN_PROD_XDS_BOOTSTRAP_CONFIG,
  842. bootstrap_.c_str());
  843. if (xds_channel_args == nullptr) xds_channel_args = &xds_channel_args_;
  844. args.SetPointerWithVtable(
  845. GRPC_ARG_TEST_ONLY_DO_NOT_USE_IN_PROD_XDS_CLIENT_CHANNEL_ARGS,
  846. xds_channel_args, &kChannelArgsArgVtable);
  847. }
  848. args.SetPointerWithVtable(
  849. GRPC_ARG_XDS_LOGICAL_DNS_CLUSTER_FAKE_RESOLVER_RESPONSE_GENERATOR,
  850. logical_dns_cluster_resolver_response_generator_.get(),
  851. &grpc_core::FakeResolverResponseGenerator::kChannelArgPointerVtable);
  852. std::string uri = absl::StrCat("xds://", xds_authority, "/", server_name);
  853. std::shared_ptr<ChannelCredentials> channel_creds =
  854. GetParam().use_xds_credentials()
  855. ? XdsCredentials(CreateTlsFallbackCredentials())
  856. : std::make_shared<SecureChannelCredentials>(
  857. grpc_fake_transport_security_credentials_create());
  858. return grpc::CreateCustomChannel(uri, channel_creds, args);
  859. }
  860. enum RpcService {
  861. SERVICE_ECHO,
  862. SERVICE_ECHO1,
  863. SERVICE_ECHO2,
  864. };
  865. enum RpcMethod {
  866. METHOD_ECHO,
  867. METHOD_ECHO1,
  868. METHOD_ECHO2,
  869. };
  870. struct RpcOptions {
  871. RpcService service = SERVICE_ECHO;
  872. RpcMethod method = METHOD_ECHO;
  873. int timeout_ms = 1000;
  874. bool wait_for_ready = false;
  875. bool server_fail = false;
  876. std::vector<std::pair<std::string, std::string>> metadata;
  877. int server_sleep_us = 0;
  878. int client_cancel_after_us = 0;
  879. bool skip_cancelled_check = false;
  880. StatusCode server_expected_error = StatusCode::OK;
  881. RpcOptions() {}
  882. RpcOptions& set_rpc_service(RpcService rpc_service) {
  883. service = rpc_service;
  884. return *this;
  885. }
  886. RpcOptions& set_rpc_method(RpcMethod rpc_method) {
  887. method = rpc_method;
  888. return *this;
  889. }
  890. RpcOptions& set_timeout_ms(int rpc_timeout_ms) {
  891. timeout_ms = rpc_timeout_ms;
  892. return *this;
  893. }
  894. RpcOptions& set_wait_for_ready(bool rpc_wait_for_ready) {
  895. wait_for_ready = rpc_wait_for_ready;
  896. return *this;
  897. }
  898. RpcOptions& set_server_fail(bool rpc_server_fail) {
  899. server_fail = rpc_server_fail;
  900. return *this;
  901. }
  902. RpcOptions& set_skip_cancelled_check(bool rpc_skip_cancelled_check) {
  903. skip_cancelled_check = rpc_skip_cancelled_check;
  904. return *this;
  905. }
  906. RpcOptions& set_metadata(
  907. std::vector<std::pair<std::string, std::string>> rpc_metadata) {
  908. metadata = std::move(rpc_metadata);
  909. return *this;
  910. }
  911. RpcOptions& set_server_sleep_us(int rpc_server_sleep_us) {
  912. server_sleep_us = rpc_server_sleep_us;
  913. return *this;
  914. }
  915. RpcOptions& set_client_cancel_after_us(int rpc_client_cancel_after_us) {
  916. client_cancel_after_us = rpc_client_cancel_after_us;
  917. return *this;
  918. }
  919. RpcOptions& set_server_expected_error(StatusCode code) {
  920. server_expected_error = code;
  921. return *this;
  922. }
  923. // Populates context and request.
  924. void SetupRpc(ClientContext* context, EchoRequest* request) const {
  925. for (const auto& item : metadata) {
  926. context->AddMetadata(item.first, item.second);
  927. }
  928. if (timeout_ms != 0) {
  929. context->set_deadline(
  930. grpc_timeout_milliseconds_to_deadline(timeout_ms));
  931. }
  932. if (wait_for_ready) context->set_wait_for_ready(true);
  933. request->set_message(kRequestMessage);
  934. if (server_fail) {
  935. request->mutable_param()->mutable_expected_error()->set_code(
  936. GRPC_STATUS_FAILED_PRECONDITION);
  937. }
  938. if (server_sleep_us != 0) {
  939. request->mutable_param()->set_server_sleep_us(server_sleep_us);
  940. }
  941. if (client_cancel_after_us != 0) {
  942. request->mutable_param()->set_client_cancel_after_us(
  943. client_cancel_after_us);
  944. }
  945. if (skip_cancelled_check) {
  946. request->mutable_param()->set_skip_cancelled_check(true);
  947. }
  948. }
  949. };
  950. template <typename Stub>
  951. Status SendRpcMethod(Stub* stub, const RpcOptions& rpc_options,
  952. ClientContext* context, EchoRequest& request,
  953. EchoResponse* response) {
  954. switch (rpc_options.method) {
  955. case METHOD_ECHO:
  956. return stub->Echo(context, request, response);
  957. case METHOD_ECHO1:
  958. return stub->Echo1(context, request, response);
  959. case METHOD_ECHO2:
  960. return stub->Echo2(context, request, response);
  961. }
  962. GPR_UNREACHABLE_CODE();
  963. }
  964. void ResetBackendCounters(size_t start_index = 0, size_t stop_index = 0) {
  965. if (stop_index == 0) stop_index = backends_.size();
  966. for (size_t i = start_index; i < stop_index; ++i) {
  967. backends_[i]->backend_service()->ResetCounters();
  968. backends_[i]->backend_service1()->ResetCounters();
  969. backends_[i]->backend_service2()->ResetCounters();
  970. }
  971. }
  972. bool SeenBackend(size_t backend_idx,
  973. const RpcService rpc_service = SERVICE_ECHO) {
  974. switch (rpc_service) {
  975. case SERVICE_ECHO:
  976. if (backends_[backend_idx]->backend_service()->request_count() == 0) {
  977. return false;
  978. }
  979. break;
  980. case SERVICE_ECHO1:
  981. if (backends_[backend_idx]->backend_service1()->request_count() == 0) {
  982. return false;
  983. }
  984. break;
  985. case SERVICE_ECHO2:
  986. if (backends_[backend_idx]->backend_service2()->request_count() == 0) {
  987. return false;
  988. }
  989. break;
  990. }
  991. return true;
  992. }
  993. bool SeenAllBackends(size_t start_index = 0, size_t stop_index = 0,
  994. const RpcService rpc_service = SERVICE_ECHO) {
  995. if (stop_index == 0) stop_index = backends_.size();
  996. for (size_t i = start_index; i < stop_index; ++i) {
  997. if (!SeenBackend(i, rpc_service)) {
  998. return false;
  999. }
  1000. }
  1001. return true;
  1002. }
  1003. // Sends num_rpcs RPCs, counting how many of them fail with a message
  1004. // matching the specfied drop_error_message_prefix.
  1005. // Any failure with a non-matching message is a test failure.
  1006. size_t SendRpcsAndCountFailuresWithMessage(
  1007. size_t num_rpcs, const char* drop_error_message_prefix,
  1008. const RpcOptions& rpc_options = RpcOptions()) {
  1009. size_t num_failed = 0;
  1010. for (size_t i = 0; i < num_rpcs; ++i) {
  1011. Status status = SendRpc(rpc_options);
  1012. if (!status.ok()) {
  1013. EXPECT_THAT(status.error_message(),
  1014. ::testing::StartsWith(drop_error_message_prefix))
  1015. << "code=" << status.error_code()
  1016. << " message=" << status.error_message();
  1017. ++num_failed;
  1018. }
  1019. }
  1020. return num_failed;
  1021. }
  1022. struct WaitForBackendOptions {
  1023. bool reset_counters = true;
  1024. bool allow_failures = false;
  1025. int timeout_ms = 5000;
  1026. WaitForBackendOptions() {}
  1027. WaitForBackendOptions& set_reset_counters(bool enable) {
  1028. reset_counters = enable;
  1029. return *this;
  1030. }
  1031. WaitForBackendOptions& set_allow_failures(bool enable) {
  1032. allow_failures = enable;
  1033. return *this;
  1034. }
  1035. WaitForBackendOptions& set_timeout_ms(int ms) {
  1036. timeout_ms = ms;
  1037. return *this;
  1038. }
  1039. };
  1040. // Returns the total number of RPCs sent.
  1041. size_t WaitForAllBackends(
  1042. size_t start_index = 0, size_t stop_index = 0,
  1043. const WaitForBackendOptions& wait_options = WaitForBackendOptions(),
  1044. const RpcOptions& rpc_options = RpcOptions()) {
  1045. size_t num_rpcs = 0;
  1046. auto deadline = absl::Now() + (absl::Milliseconds(wait_options.timeout_ms) *
  1047. grpc_test_slowdown_factor());
  1048. gpr_log(GPR_INFO,
  1049. "========= WAITING FOR BACKENDS [%" PRIuPTR ", %" PRIuPTR
  1050. ") ==========",
  1051. start_index, stop_index);
  1052. while (!SeenAllBackends(start_index, stop_index, rpc_options.service)) {
  1053. Status status = SendRpc(rpc_options);
  1054. if (!wait_options.allow_failures) {
  1055. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  1056. << " message=" << status.error_message();
  1057. }
  1058. EXPECT_LE(absl::Now(), deadline);
  1059. if (absl::Now() >= deadline) break;
  1060. ++num_rpcs;
  1061. }
  1062. if (wait_options.reset_counters) ResetBackendCounters();
  1063. gpr_log(GPR_INFO, "Backends up; sent %" PRIuPTR " warm up requests",
  1064. num_rpcs);
  1065. return num_rpcs;
  1066. }
  1067. void WaitForBackend(
  1068. size_t backend_idx,
  1069. const WaitForBackendOptions& wait_options = WaitForBackendOptions(),
  1070. const RpcOptions& rpc_options = RpcOptions()) {
  1071. WaitForAllBackends(backend_idx, backend_idx + 1, wait_options, rpc_options);
  1072. }
  1073. grpc_core::ServerAddressList CreateAddressListFromPortList(
  1074. const std::vector<int>& ports) {
  1075. grpc_core::ServerAddressList addresses;
  1076. for (int port : ports) {
  1077. absl::StatusOr<grpc_core::URI> lb_uri = grpc_core::URI::Parse(
  1078. absl::StrCat(ipv6_only_ ? "ipv6:[::1]:" : "ipv4:127.0.0.1:", port));
  1079. GPR_ASSERT(lb_uri.ok());
  1080. grpc_resolved_address address;
  1081. GPR_ASSERT(grpc_parse_uri(*lb_uri, &address));
  1082. addresses.emplace_back(address.addr, address.len, nullptr);
  1083. }
  1084. return addresses;
  1085. }
  1086. std::string CreateMetadataValueThatHashesToBackendPort(int port) {
  1087. return absl::StrCat(ipv6_only_ ? "[::1]" : "127.0.0.1", ":", port, "_0");
  1088. }
  1089. std::string CreateMetadataValueThatHashesToBackend(int index) {
  1090. return CreateMetadataValueThatHashesToBackendPort(backends_[index]->port());
  1091. }
  1092. std::vector<int> GetBackendPorts(size_t start_index = 0,
  1093. size_t stop_index = 0) const {
  1094. if (stop_index == 0) stop_index = backends_.size();
  1095. std::vector<int> backend_ports;
  1096. for (size_t i = start_index; i < stop_index; ++i) {
  1097. backend_ports.push_back(backends_[i]->port());
  1098. }
  1099. return backend_ports;
  1100. }
  1101. Status SendRpc(const RpcOptions& rpc_options = RpcOptions(),
  1102. EchoResponse* response = nullptr) {
  1103. const bool local_response = (response == nullptr);
  1104. if (local_response) response = new EchoResponse;
  1105. ClientContext context;
  1106. EchoRequest request;
  1107. if (rpc_options.server_expected_error != StatusCode::OK) {
  1108. auto* error = request.mutable_param()->mutable_expected_error();
  1109. error->set_code(rpc_options.server_expected_error);
  1110. }
  1111. rpc_options.SetupRpc(&context, &request);
  1112. Status status;
  1113. switch (rpc_options.service) {
  1114. case SERVICE_ECHO:
  1115. status = SendRpcMethod(stub_.get(), rpc_options, &context, request,
  1116. response);
  1117. break;
  1118. case SERVICE_ECHO1:
  1119. status = SendRpcMethod(stub1_.get(), rpc_options, &context, request,
  1120. response);
  1121. break;
  1122. case SERVICE_ECHO2:
  1123. status = SendRpcMethod(stub2_.get(), rpc_options, &context, request,
  1124. response);
  1125. break;
  1126. }
  1127. if (local_response) delete response;
  1128. return status;
  1129. }
  1130. void CheckRpcSendOk(const size_t times = 1,
  1131. const RpcOptions& rpc_options = RpcOptions()) {
  1132. for (size_t i = 0; i < times; ++i) {
  1133. EchoResponse response;
  1134. const Status status = SendRpc(rpc_options, &response);
  1135. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  1136. << " message=" << status.error_message();
  1137. EXPECT_EQ(response.message(), kRequestMessage);
  1138. }
  1139. }
  1140. struct CheckRpcSendFailureOptions {
  1141. std::function<bool(size_t)> continue_predicate = [](size_t i) {
  1142. return i < 1;
  1143. };
  1144. RpcOptions rpc_options;
  1145. StatusCode expected_error_code = StatusCode::OK;
  1146. CheckRpcSendFailureOptions() {}
  1147. CheckRpcSendFailureOptions& set_times(size_t times) {
  1148. continue_predicate = [times](size_t i) { return i < times; };
  1149. return *this;
  1150. }
  1151. CheckRpcSendFailureOptions& set_continue_predicate(
  1152. std::function<bool(size_t)> pred) {
  1153. continue_predicate = std::move(pred);
  1154. return *this;
  1155. }
  1156. CheckRpcSendFailureOptions& set_rpc_options(const RpcOptions& options) {
  1157. rpc_options = options;
  1158. return *this;
  1159. }
  1160. CheckRpcSendFailureOptions& set_expected_error_code(StatusCode code) {
  1161. expected_error_code = code;
  1162. return *this;
  1163. }
  1164. };
  1165. void CheckRpcSendFailure(const CheckRpcSendFailureOptions& options =
  1166. CheckRpcSendFailureOptions()) {
  1167. for (size_t i = 0; options.continue_predicate(i); ++i) {
  1168. const Status status = SendRpc(options.rpc_options);
  1169. EXPECT_FALSE(status.ok());
  1170. if (options.expected_error_code != StatusCode::OK) {
  1171. EXPECT_EQ(options.expected_error_code, status.error_code())
  1172. << "code=" << status.error_code()
  1173. << " message=" << status.error_message();
  1174. ;
  1175. }
  1176. }
  1177. }
  1178. absl::optional<AdsServiceImpl::ResponseState> WaitForNack(
  1179. std::function<absl::optional<AdsServiceImpl::ResponseState>()> get_state,
  1180. StatusCode expected_status = StatusCode::UNAVAILABLE) {
  1181. absl::optional<AdsServiceImpl::ResponseState> response_state;
  1182. auto deadline = absl::Now() + absl::Seconds(30);
  1183. auto continue_predicate = [&]() {
  1184. if (absl::Now() >= deadline) {
  1185. return false;
  1186. }
  1187. response_state = get_state();
  1188. return !response_state.has_value() ||
  1189. response_state->state != AdsServiceImpl::ResponseState::NACKED;
  1190. };
  1191. do {
  1192. const Status status = SendRpc();
  1193. EXPECT_EQ(expected_status, status.error_code())
  1194. << "code=" << status.error_code()
  1195. << " message=" << status.error_message();
  1196. ;
  1197. } while (continue_predicate());
  1198. return response_state;
  1199. }
  1200. absl::optional<AdsServiceImpl::ResponseState> WaitForLdsNack(
  1201. StatusCode expected_status = StatusCode::UNAVAILABLE) {
  1202. return WaitForNack(
  1203. [&]() { return balancer_->ads_service()->lds_response_state(); },
  1204. expected_status);
  1205. }
  1206. absl::optional<AdsServiceImpl::ResponseState> WaitForRdsNack(
  1207. StatusCode expected_status = StatusCode::UNAVAILABLE) {
  1208. return WaitForNack(
  1209. [&]() { return RouteConfigurationResponseState(balancer_.get()); },
  1210. expected_status);
  1211. }
  1212. absl::optional<AdsServiceImpl::ResponseState> WaitForCdsNack(
  1213. StatusCode expected_status = StatusCode::UNAVAILABLE) {
  1214. return WaitForNack(
  1215. [&]() { return balancer_->ads_service()->cds_response_state(); },
  1216. expected_status);
  1217. }
  1218. absl::optional<AdsServiceImpl::ResponseState> WaitForEdsNack() {
  1219. return WaitForNack(
  1220. [&]() { return balancer_->ads_service()->eds_response_state(); });
  1221. }
  1222. absl::optional<AdsServiceImpl::ResponseState> WaitForRouteConfigNack(
  1223. StatusCode expected_status = StatusCode::UNAVAILABLE) {
  1224. if (GetParam().enable_rds_testing()) {
  1225. return WaitForRdsNack(expected_status);
  1226. }
  1227. return WaitForLdsNack(expected_status);
  1228. }
  1229. absl::optional<AdsServiceImpl::ResponseState> RouteConfigurationResponseState(
  1230. BalancerServerThread* balancer) const {
  1231. AdsServiceImpl* ads_service = balancer->ads_service();
  1232. if (GetParam().enable_rds_testing()) {
  1233. return ads_service->rds_response_state();
  1234. }
  1235. return ads_service->lds_response_state();
  1236. }
  1237. std::string GetServerListenerName(int port) {
  1238. return absl::StrCat("grpc/server?xds.resource.listening_address=",
  1239. ipv6_only_ ? "[::1]:" : "127.0.0.1:", port);
  1240. }
  1241. Listener PopulateServerListenerNameAndPort(const Listener& listener_template,
  1242. int port) {
  1243. Listener listener = listener_template;
  1244. listener.set_name(GetServerListenerName(port));
  1245. listener.mutable_address()->mutable_socket_address()->set_port_value(port);
  1246. return listener;
  1247. }
  1248. // Interface for accessing HttpConnectionManager config in Listener.
  1249. class HcmAccessor {
  1250. public:
  1251. virtual ~HcmAccessor() = default;
  1252. virtual HttpConnectionManager Unpack(const Listener& listener) const = 0;
  1253. virtual void Pack(const HttpConnectionManager& hcm,
  1254. Listener* listener) const = 0;
  1255. };
  1256. // Client-side impl.
  1257. class ClientHcmAccessor : public HcmAccessor {
  1258. public:
  1259. HttpConnectionManager Unpack(const Listener& listener) const override {
  1260. HttpConnectionManager http_connection_manager;
  1261. listener.api_listener().api_listener().UnpackTo(&http_connection_manager);
  1262. return http_connection_manager;
  1263. }
  1264. void Pack(const HttpConnectionManager& hcm,
  1265. Listener* listener) const override {
  1266. auto* api_listener =
  1267. listener->mutable_api_listener()->mutable_api_listener();
  1268. api_listener->PackFrom(hcm);
  1269. }
  1270. };
  1271. // Server-side impl.
  1272. class ServerHcmAccessor : public HcmAccessor {
  1273. public:
  1274. HttpConnectionManager Unpack(const Listener& listener) const override {
  1275. HttpConnectionManager http_connection_manager;
  1276. listener.default_filter_chain().filters().at(0).typed_config().UnpackTo(
  1277. &http_connection_manager);
  1278. return http_connection_manager;
  1279. }
  1280. void Pack(const HttpConnectionManager& hcm,
  1281. Listener* listener) const override {
  1282. listener->mutable_default_filter_chain()
  1283. ->mutable_filters()
  1284. ->at(0)
  1285. .mutable_typed_config()
  1286. ->PackFrom(hcm);
  1287. }
  1288. };
  1289. void SetListenerAndRouteConfiguration(
  1290. BalancerServerThread* balancer, Listener listener,
  1291. const RouteConfiguration& route_config,
  1292. const HcmAccessor& hcm_accessor = ClientHcmAccessor()) {
  1293. HttpConnectionManager http_connection_manager =
  1294. hcm_accessor.Unpack(listener);
  1295. if (GetParam().enable_rds_testing()) {
  1296. auto* rds = http_connection_manager.mutable_rds();
  1297. rds->set_route_config_name(route_config.name());
  1298. rds->mutable_config_source()->mutable_self();
  1299. balancer->ads_service()->SetRdsResource(route_config);
  1300. } else {
  1301. *http_connection_manager.mutable_route_config() = route_config;
  1302. }
  1303. hcm_accessor.Pack(http_connection_manager, &listener);
  1304. balancer->ads_service()->SetLdsResource(listener);
  1305. }
  1306. void SetServerListenerNameAndRouteConfiguration(
  1307. BalancerServerThread* balancer, Listener listener, int port,
  1308. const RouteConfiguration& route_config) {
  1309. SetListenerAndRouteConfiguration(
  1310. balancer, PopulateServerListenerNameAndPort(listener, port),
  1311. route_config, ServerHcmAccessor());
  1312. }
  1313. void SetRouteConfiguration(BalancerServerThread* balancer,
  1314. const RouteConfiguration& route_config,
  1315. const Listener* listener_to_copy = nullptr) {
  1316. if (GetParam().enable_rds_testing()) {
  1317. balancer->ads_service()->SetRdsResource(route_config);
  1318. } else {
  1319. Listener listener(listener_to_copy == nullptr ? default_listener_
  1320. : *listener_to_copy);
  1321. HttpConnectionManager http_connection_manager;
  1322. listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
  1323. &http_connection_manager);
  1324. *(http_connection_manager.mutable_route_config()) = route_config;
  1325. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  1326. http_connection_manager);
  1327. balancer->ads_service()->SetLdsResource(listener);
  1328. }
  1329. }
  1330. struct EdsResourceArgs {
  1331. struct Endpoint {
  1332. explicit Endpoint(int port,
  1333. HealthStatus health_status = HealthStatus::UNKNOWN,
  1334. int lb_weight = 1)
  1335. : port(port), health_status(health_status), lb_weight(lb_weight) {}
  1336. int port;
  1337. HealthStatus health_status;
  1338. int lb_weight;
  1339. };
  1340. struct Locality {
  1341. Locality(std::string sub_zone, std::vector<Endpoint> endpoints,
  1342. int lb_weight = kDefaultLocalityWeight,
  1343. int priority = kDefaultLocalityPriority)
  1344. : sub_zone(std::move(sub_zone)),
  1345. endpoints(std::move(endpoints)),
  1346. lb_weight(lb_weight),
  1347. priority(priority) {}
  1348. const std::string sub_zone;
  1349. std::vector<Endpoint> endpoints;
  1350. int lb_weight;
  1351. int priority;
  1352. };
  1353. EdsResourceArgs() = default;
  1354. explicit EdsResourceArgs(std::vector<Locality> locality_list)
  1355. : locality_list(std::move(locality_list)) {}
  1356. std::vector<Locality> locality_list;
  1357. std::map<std::string, uint32_t> drop_categories;
  1358. FractionalPercent::DenominatorType drop_denominator =
  1359. FractionalPercent::MILLION;
  1360. };
  1361. EdsResourceArgs::Endpoint CreateEndpoint(
  1362. size_t backend_idx, HealthStatus health_status = HealthStatus::UNKNOWN,
  1363. int lb_weight = 1) {
  1364. return EdsResourceArgs::Endpoint(backends_[backend_idx]->port(),
  1365. health_status, lb_weight);
  1366. }
  1367. std::vector<EdsResourceArgs::Endpoint> CreateEndpointsForBackends(
  1368. size_t start_index = 0, size_t stop_index = 0,
  1369. HealthStatus health_status = HealthStatus::UNKNOWN, int lb_weight = 1) {
  1370. if (stop_index == 0) stop_index = backends_.size();
  1371. std::vector<EdsResourceArgs::Endpoint> endpoints;
  1372. for (size_t i = start_index; i < stop_index; ++i) {
  1373. endpoints.emplace_back(CreateEndpoint(i, health_status, lb_weight));
  1374. }
  1375. return endpoints;
  1376. }
  1377. EdsResourceArgs::Endpoint MakeNonExistantEndpoint() {
  1378. return EdsResourceArgs::Endpoint(grpc_pick_unused_port_or_die());
  1379. }
  1380. ClusterLoadAssignment BuildEdsResource(
  1381. const EdsResourceArgs& args,
  1382. const char* eds_service_name = kDefaultEdsServiceName) {
  1383. ClusterLoadAssignment assignment;
  1384. assignment.set_cluster_name(eds_service_name);
  1385. for (const auto& locality : args.locality_list) {
  1386. auto* endpoints = assignment.add_endpoints();
  1387. endpoints->mutable_load_balancing_weight()->set_value(locality.lb_weight);
  1388. endpoints->set_priority(locality.priority);
  1389. endpoints->mutable_locality()->set_region(kDefaultLocalityRegion);
  1390. endpoints->mutable_locality()->set_zone(kDefaultLocalityZone);
  1391. endpoints->mutable_locality()->set_sub_zone(locality.sub_zone);
  1392. for (size_t i = 0; i < locality.endpoints.size(); ++i) {
  1393. const int& port = locality.endpoints[i].port;
  1394. auto* lb_endpoints = endpoints->add_lb_endpoints();
  1395. if (locality.endpoints.size() > i &&
  1396. locality.endpoints[i].health_status != HealthStatus::UNKNOWN) {
  1397. lb_endpoints->set_health_status(locality.endpoints[i].health_status);
  1398. }
  1399. if (locality.endpoints.size() > i &&
  1400. locality.endpoints[i].lb_weight >= 1) {
  1401. lb_endpoints->mutable_load_balancing_weight()->set_value(
  1402. locality.endpoints[i].lb_weight);
  1403. }
  1404. auto* endpoint = lb_endpoints->mutable_endpoint();
  1405. auto* address = endpoint->mutable_address();
  1406. auto* socket_address = address->mutable_socket_address();
  1407. socket_address->set_address(ipv6_only_ ? "::1" : "127.0.0.1");
  1408. socket_address->set_port_value(port);
  1409. }
  1410. }
  1411. if (!args.drop_categories.empty()) {
  1412. auto* policy = assignment.mutable_policy();
  1413. for (const auto& p : args.drop_categories) {
  1414. const std::string& name = p.first;
  1415. const uint32_t parts_per_million = p.second;
  1416. auto* drop_overload = policy->add_drop_overloads();
  1417. drop_overload->set_category(name);
  1418. auto* drop_percentage = drop_overload->mutable_drop_percentage();
  1419. drop_percentage->set_numerator(parts_per_million);
  1420. drop_percentage->set_denominator(args.drop_denominator);
  1421. }
  1422. }
  1423. return assignment;
  1424. }
  1425. public:
  1426. // This method could benefit test subclasses; to make it accessible
  1427. // via bind with a qualified name, it needs to be public.
  1428. void SetEdsResourceWithDelay(BalancerServerThread* balancer,
  1429. const ClusterLoadAssignment& assignment,
  1430. int delay_ms) {
  1431. GPR_ASSERT(delay_ms > 0);
  1432. gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(delay_ms));
  1433. balancer->ads_service()->SetEdsResource(assignment);
  1434. }
  1435. protected:
  1436. class XdsServingStatusNotifier
  1437. : public grpc::experimental::XdsServerServingStatusNotifierInterface {
  1438. public:
  1439. void OnServingStatusUpdate(std::string uri,
  1440. ServingStatusUpdate update) override {
  1441. grpc_core::MutexLock lock(&mu_);
  1442. status_map[uri] = update.status;
  1443. cond_.Signal();
  1444. }
  1445. void WaitOnServingStatusChange(std::string uri,
  1446. grpc::StatusCode expected_status) {
  1447. grpc_core::MutexLock lock(&mu_);
  1448. std::map<std::string, grpc::Status>::iterator it;
  1449. while ((it = status_map.find(uri)) == status_map.end() ||
  1450. it->second.error_code() != expected_status) {
  1451. cond_.Wait(&mu_);
  1452. }
  1453. }
  1454. private:
  1455. grpc_core::Mutex mu_;
  1456. grpc_core::CondVar cond_;
  1457. std::map<std::string, grpc::Status> status_map ABSL_GUARDED_BY(mu_);
  1458. };
  1459. class ServerThread {
  1460. public:
  1461. explicit ServerThread(XdsEnd2endTest* test_obj,
  1462. bool use_xds_enabled_server = false)
  1463. : test_obj_(test_obj),
  1464. port_(grpc_pick_unused_port_or_die()),
  1465. use_xds_enabled_server_(use_xds_enabled_server) {}
  1466. virtual ~ServerThread() { Shutdown(); }
  1467. void Start() {
  1468. gpr_log(GPR_INFO, "starting %s server on port %d", Type(), port_);
  1469. GPR_ASSERT(!running_);
  1470. running_ = true;
  1471. StartAllServices();
  1472. grpc_core::Mutex mu;
  1473. // We need to acquire the lock here in order to prevent the notify_one
  1474. // by ServerThread::Serve from firing before the wait below is hit.
  1475. grpc_core::MutexLock lock(&mu);
  1476. grpc_core::CondVar cond;
  1477. thread_ = absl::make_unique<std::thread>(
  1478. std::bind(&ServerThread::Serve, this, &mu, &cond));
  1479. cond.Wait(&mu);
  1480. gpr_log(GPR_INFO, "%s server startup complete", Type());
  1481. }
  1482. void Serve(grpc_core::Mutex* mu, grpc_core::CondVar* cond) {
  1483. // We need to acquire the lock here in order to prevent the notify_one
  1484. // below from firing before its corresponding wait is executed.
  1485. grpc_core::MutexLock lock(mu);
  1486. std::ostringstream server_address;
  1487. server_address << "localhost:" << port_;
  1488. if (use_xds_enabled_server_) {
  1489. XdsServerBuilder builder;
  1490. if (GetParam().bootstrap_source() ==
  1491. TestType::kBootstrapFromChannelArg) {
  1492. builder.SetOption(
  1493. absl::make_unique<XdsChannelArgsServerBuilderOption>(test_obj_));
  1494. }
  1495. builder.set_status_notifier(&notifier_);
  1496. builder.experimental().set_drain_grace_time(
  1497. test_obj_->xds_drain_grace_time_ms_);
  1498. builder.AddListeningPort(server_address.str(), Credentials());
  1499. RegisterAllServices(&builder);
  1500. server_ = builder.BuildAndStart();
  1501. } else {
  1502. ServerBuilder builder;
  1503. builder.AddListeningPort(server_address.str(), Credentials());
  1504. RegisterAllServices(&builder);
  1505. server_ = builder.BuildAndStart();
  1506. }
  1507. cond->Signal();
  1508. }
  1509. void Shutdown() {
  1510. if (!running_) return;
  1511. gpr_log(GPR_INFO, "%s about to shutdown", Type());
  1512. ShutdownAllServices();
  1513. server_->Shutdown(grpc_timeout_milliseconds_to_deadline(0));
  1514. thread_->join();
  1515. gpr_log(GPR_INFO, "%s shutdown completed", Type());
  1516. running_ = false;
  1517. }
  1518. virtual std::shared_ptr<ServerCredentials> Credentials() {
  1519. return std::make_shared<SecureServerCredentials>(
  1520. grpc_fake_transport_security_server_credentials_create());
  1521. }
  1522. int port() const { return port_; }
  1523. bool use_xds_enabled_server() const { return use_xds_enabled_server_; }
  1524. XdsServingStatusNotifier* notifier() { return &notifier_; }
  1525. private:
  1526. class XdsChannelArgsServerBuilderOption : public grpc::ServerBuilderOption {
  1527. public:
  1528. explicit XdsChannelArgsServerBuilderOption(XdsEnd2endTest* test_obj)
  1529. : test_obj_(test_obj) {}
  1530. void UpdateArguments(grpc::ChannelArguments* args) override {
  1531. args->SetString(
  1532. GRPC_ARG_TEST_ONLY_DO_NOT_USE_IN_PROD_XDS_BOOTSTRAP_CONFIG,
  1533. test_obj_->bootstrap_);
  1534. args->SetPointerWithVtable(
  1535. GRPC_ARG_TEST_ONLY_DO_NOT_USE_IN_PROD_XDS_CLIENT_CHANNEL_ARGS,
  1536. &test_obj_->xds_channel_args_, &kChannelArgsArgVtable);
  1537. }
  1538. void UpdatePlugins(
  1539. std::vector<std::unique_ptr<grpc::ServerBuilderPlugin>>* /*plugins*/)
  1540. override {}
  1541. private:
  1542. XdsEnd2endTest* test_obj_;
  1543. };
  1544. virtual void RegisterAllServices(ServerBuilder* builder) = 0;
  1545. virtual void StartAllServices() = 0;
  1546. virtual void ShutdownAllServices() = 0;
  1547. virtual const char* Type() = 0;
  1548. XdsEnd2endTest* test_obj_;
  1549. const int port_;
  1550. std::unique_ptr<Server> server_;
  1551. XdsServingStatusNotifier notifier_;
  1552. std::unique_ptr<std::thread> thread_;
  1553. bool running_ = false;
  1554. const bool use_xds_enabled_server_;
  1555. };
  1556. class BackendServerThread : public ServerThread {
  1557. public:
  1558. explicit BackendServerThread(XdsEnd2endTest* test_obj)
  1559. : ServerThread(test_obj, test_obj->use_xds_enabled_server_) {}
  1560. BackendServiceImpl<grpc::testing::EchoTestService::Service>*
  1561. backend_service() {
  1562. return &backend_service_;
  1563. }
  1564. BackendServiceImpl<grpc::testing::EchoTest1Service::Service>*
  1565. backend_service1() {
  1566. return &backend_service1_;
  1567. }
  1568. BackendServiceImpl<grpc::testing::EchoTest2Service::Service>*
  1569. backend_service2() {
  1570. return &backend_service2_;
  1571. }
  1572. std::shared_ptr<ServerCredentials> Credentials() override {
  1573. if (GetParam().use_xds_credentials()) {
  1574. if (use_xds_enabled_server()) {
  1575. // We are testing server's use of XdsServerCredentials
  1576. return XdsServerCredentials(InsecureServerCredentials());
  1577. } else {
  1578. // We are testing client's use of XdsCredentials
  1579. std::string root_cert = ReadFile(kCaCertPath);
  1580. std::string identity_cert = ReadFile(kServerCertPath);
  1581. std::string private_key = ReadFile(kServerKeyPath);
  1582. std::vector<experimental::IdentityKeyCertPair>
  1583. identity_key_cert_pairs = {{private_key, identity_cert}};
  1584. auto certificate_provider = std::make_shared<
  1585. grpc::experimental::StaticDataCertificateProvider>(
  1586. root_cert, identity_key_cert_pairs);
  1587. grpc::experimental::TlsServerCredentialsOptions options(
  1588. certificate_provider);
  1589. options.watch_root_certs();
  1590. options.watch_identity_key_cert_pairs();
  1591. options.set_cert_request_type(
  1592. GRPC_SSL_REQUEST_CLIENT_CERTIFICATE_AND_VERIFY);
  1593. return grpc::experimental::TlsServerCredentials(options);
  1594. }
  1595. }
  1596. return ServerThread::Credentials();
  1597. }
  1598. private:
  1599. void RegisterAllServices(ServerBuilder* builder) override {
  1600. builder->RegisterService(&backend_service_);
  1601. builder->RegisterService(&backend_service1_);
  1602. builder->RegisterService(&backend_service2_);
  1603. }
  1604. void StartAllServices() override {
  1605. backend_service_.Start();
  1606. backend_service1_.Start();
  1607. backend_service2_.Start();
  1608. }
  1609. void ShutdownAllServices() override {
  1610. backend_service_.Shutdown();
  1611. backend_service1_.Shutdown();
  1612. backend_service2_.Shutdown();
  1613. }
  1614. const char* Type() override { return "Backend"; }
  1615. BackendServiceImpl<grpc::testing::EchoTestService::Service>
  1616. backend_service_;
  1617. BackendServiceImpl<grpc::testing::EchoTest1Service::Service>
  1618. backend_service1_;
  1619. BackendServiceImpl<grpc::testing::EchoTest2Service::Service>
  1620. backend_service2_;
  1621. };
  1622. class BalancerServerThread : public ServerThread {
  1623. public:
  1624. explicit BalancerServerThread(XdsEnd2endTest* test_obj)
  1625. : ServerThread(test_obj, /*use_xds_enabled_server=*/false),
  1626. ads_service_(new AdsServiceImpl()),
  1627. lrs_service_(new LrsServiceImpl(
  1628. (GetParam().enable_load_reporting()
  1629. ? test_obj->client_load_reporting_interval_seconds_
  1630. : 0),
  1631. {kDefaultClusterName})) {}
  1632. AdsServiceImpl* ads_service() { return ads_service_.get(); }
  1633. LrsServiceImpl* lrs_service() { return lrs_service_.get(); }
  1634. private:
  1635. void RegisterAllServices(ServerBuilder* builder) override {
  1636. builder->RegisterService(ads_service_->v2_rpc_service());
  1637. builder->RegisterService(ads_service_->v3_rpc_service());
  1638. builder->RegisterService(lrs_service_->v2_rpc_service());
  1639. builder->RegisterService(lrs_service_->v3_rpc_service());
  1640. }
  1641. void StartAllServices() override {
  1642. ads_service_->Start();
  1643. lrs_service_->Start();
  1644. }
  1645. void ShutdownAllServices() override {
  1646. ads_service_->Shutdown();
  1647. lrs_service_->Shutdown();
  1648. }
  1649. const char* Type() override { return "Balancer"; }
  1650. std::shared_ptr<AdsServiceImpl> ads_service_;
  1651. std::shared_ptr<LrsServiceImpl> lrs_service_;
  1652. };
  1653. #ifndef DISABLED_XDS_PROTO_IN_CC
  1654. class AdminServerThread : public ServerThread {
  1655. public:
  1656. explicit AdminServerThread(XdsEnd2endTest* test_obj)
  1657. : ServerThread(test_obj) {}
  1658. private:
  1659. void RegisterAllServices(ServerBuilder* builder) override {
  1660. builder->RegisterService(&csds_service_);
  1661. }
  1662. void StartAllServices() override {}
  1663. void ShutdownAllServices() override {}
  1664. const char* Type() override { return "Admin"; }
  1665. grpc::xds::experimental::ClientStatusDiscoveryService csds_service_;
  1666. };
  1667. #endif // DISABLED_XDS_PROTO_IN_CC
  1668. class LongRunningRpc {
  1669. public:
  1670. void StartRpc(grpc::testing::EchoTestService::Stub* stub,
  1671. const RpcOptions& rpc_options =
  1672. RpcOptions().set_timeout_ms(0).set_client_cancel_after_us(
  1673. 1 * 1000 * 1000)) {
  1674. sender_thread_ = std::thread([this, stub, rpc_options]() {
  1675. EchoRequest request;
  1676. EchoResponse response;
  1677. rpc_options.SetupRpc(&context_, &request);
  1678. status_ = stub->Echo(&context_, request, &response);
  1679. });
  1680. }
  1681. void CancelRpc() {
  1682. context_.TryCancel();
  1683. if (sender_thread_.joinable()) sender_thread_.join();
  1684. }
  1685. Status GetStatus() {
  1686. if (sender_thread_.joinable()) sender_thread_.join();
  1687. return status_;
  1688. }
  1689. private:
  1690. std::thread sender_thread_;
  1691. ClientContext context_;
  1692. Status status_;
  1693. };
  1694. struct ConcurrentRpc {
  1695. ClientContext context;
  1696. Status status;
  1697. grpc_core::Duration elapsed_time;
  1698. EchoResponse response;
  1699. };
  1700. std::vector<ConcurrentRpc> SendConcurrentRpcs(
  1701. grpc::testing::EchoTestService::Stub* stub, size_t num_rpcs,
  1702. const RpcOptions& rpc_options) {
  1703. // Variables for RPCs.
  1704. std::vector<ConcurrentRpc> rpcs(num_rpcs);
  1705. EchoRequest request;
  1706. // Variables for synchronization
  1707. absl::Mutex mu;
  1708. absl::CondVar cv;
  1709. size_t completed = 0;
  1710. // Set-off callback RPCs
  1711. for (size_t i = 0; i < num_rpcs; i++) {
  1712. ConcurrentRpc* rpc = &rpcs[i];
  1713. rpc_options.SetupRpc(&rpc->context, &request);
  1714. grpc_core::Timestamp t0 = NowFromCycleCounter();
  1715. stub->async()->Echo(&rpc->context, &request, &rpc->response,
  1716. [rpc, &mu, &completed, &cv, num_rpcs, t0](Status s) {
  1717. rpc->status = s;
  1718. rpc->elapsed_time = NowFromCycleCounter() - t0;
  1719. bool done;
  1720. {
  1721. absl::MutexLock lock(&mu);
  1722. done = (++completed) == num_rpcs;
  1723. }
  1724. if (done) cv.Signal();
  1725. });
  1726. }
  1727. {
  1728. absl::MutexLock lock(&mu);
  1729. cv.Wait(&mu);
  1730. }
  1731. EXPECT_EQ(completed, num_rpcs);
  1732. return rpcs;
  1733. }
  1734. const size_t num_backends_;
  1735. const int client_load_reporting_interval_seconds_;
  1736. bool ipv6_only_ = false;
  1737. std::shared_ptr<Channel> channel_;
  1738. std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
  1739. std::unique_ptr<grpc::testing::EchoTest1Service::Stub> stub1_;
  1740. std::unique_ptr<grpc::testing::EchoTest2Service::Stub> stub2_;
  1741. std::vector<std::unique_ptr<BackendServerThread>> backends_;
  1742. std::unique_ptr<BalancerServerThread> balancer_;
  1743. grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
  1744. logical_dns_cluster_resolver_response_generator_;
  1745. int xds_resource_does_not_exist_timeout_ms_ = 0;
  1746. absl::InlinedVector<grpc_arg, 3> xds_channel_args_to_add_;
  1747. grpc_channel_args xds_channel_args_;
  1748. Listener default_listener_;
  1749. RouteConfiguration default_route_config_;
  1750. Listener default_server_listener_;
  1751. RouteConfiguration default_server_route_config_;
  1752. Cluster default_cluster_;
  1753. bool use_xds_enabled_server_;
  1754. int xds_drain_grace_time_ms_ = 10 * 60 * 1000; // 10 mins
  1755. bool bootstrap_contents_from_env_var_;
  1756. std::string bootstrap_;
  1757. char* bootstrap_file_ = nullptr;
  1758. };
  1759. class BasicTest : public XdsEnd2endTest {
  1760. public:
  1761. BasicTest() : XdsEnd2endTest(4) {}
  1762. void SetUp() override {
  1763. XdsEnd2endTest::SetUp();
  1764. StartAllBackends();
  1765. }
  1766. };
  1767. // Tests that the balancer sends the correct response to the client, and the
  1768. // client sends RPCs to the backends using the default child policy.
  1769. TEST_P(BasicTest, Vanilla) {
  1770. const size_t kNumRpcsPerAddress = 100;
  1771. EdsResourceArgs args({
  1772. {"locality0", CreateEndpointsForBackends()},
  1773. });
  1774. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  1775. // Make sure that trying to connect works without a call.
  1776. channel_->GetState(true /* try_to_connect */);
  1777. // We need to wait for all backends to come online.
  1778. WaitForAllBackends();
  1779. // Send kNumRpcsPerAddress RPCs per server.
  1780. CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
  1781. // Each backend should have gotten 100 requests.
  1782. for (size_t i = 0; i < backends_.size(); ++i) {
  1783. EXPECT_EQ(kNumRpcsPerAddress,
  1784. backends_[i]->backend_service()->request_count());
  1785. }
  1786. // Check LB policy name for the channel.
  1787. EXPECT_EQ("xds_cluster_manager_experimental",
  1788. channel_->GetLoadBalancingPolicyName());
  1789. }
  1790. TEST_P(BasicTest, IgnoresUnhealthyEndpoints) {
  1791. const size_t kNumRpcsPerAddress = 100;
  1792. auto endpoints = CreateEndpointsForBackends();
  1793. endpoints[0].health_status = HealthStatus::DRAINING;
  1794. EdsResourceArgs args({
  1795. {"locality0", std::move(endpoints), kDefaultLocalityWeight,
  1796. kDefaultLocalityPriority},
  1797. });
  1798. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  1799. // Make sure that trying to connect works without a call.
  1800. channel_->GetState(true /* try_to_connect */);
  1801. // We need to wait for all backends to come online.
  1802. WaitForAllBackends(/*start_index=*/1);
  1803. // Send kNumRpcsPerAddress RPCs per server.
  1804. CheckRpcSendOk(kNumRpcsPerAddress * (num_backends_ - 1));
  1805. // Each backend should have gotten 100 requests.
  1806. for (size_t i = 1; i < backends_.size(); ++i) {
  1807. EXPECT_EQ(kNumRpcsPerAddress,
  1808. backends_[i]->backend_service()->request_count());
  1809. }
  1810. }
  1811. // Tests that subchannel sharing works when the same backend is listed
  1812. // multiple times.
  1813. TEST_P(BasicTest, SameBackendListedMultipleTimes) {
  1814. // Same backend listed twice.
  1815. auto endpoints = CreateEndpointsForBackends(0, 1);
  1816. endpoints.push_back(endpoints.front());
  1817. EdsResourceArgs args({
  1818. {"locality0", endpoints},
  1819. });
  1820. const size_t kNumRpcsPerAddress = 10;
  1821. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  1822. // We need to wait for the backend to come online.
  1823. WaitForBackend(0);
  1824. // Send kNumRpcsPerAddress RPCs per server.
  1825. CheckRpcSendOk(kNumRpcsPerAddress * endpoints.size());
  1826. // Backend should have gotten 20 requests.
  1827. EXPECT_EQ(kNumRpcsPerAddress * endpoints.size(),
  1828. backends_[0]->backend_service()->request_count());
  1829. // And they should have come from a single client port, because of
  1830. // subchannel sharing.
  1831. EXPECT_EQ(1UL, backends_[0]->backend_service()->clients().size());
  1832. }
  1833. // Tests that RPCs will be blocked until a non-empty serverlist is received.
  1834. TEST_P(BasicTest, InitiallyEmptyServerlist) {
  1835. const int kServerlistDelayMs = 500 * grpc_test_slowdown_factor();
  1836. const int kCallDeadlineMs = kServerlistDelayMs * 2;
  1837. // First response is an empty serverlist, sent right away.
  1838. EdsResourceArgs::Locality empty_locality("locality0", {});
  1839. EdsResourceArgs args({
  1840. empty_locality,
  1841. });
  1842. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  1843. // Send non-empty serverlist only after kServerlistDelayMs.
  1844. args = EdsResourceArgs({
  1845. {"locality0", CreateEndpointsForBackends()},
  1846. });
  1847. std::thread delayed_resource_setter(
  1848. std::bind(&BasicTest::SetEdsResourceWithDelay, this, balancer_.get(),
  1849. BuildEdsResource(args), kServerlistDelayMs));
  1850. const auto t0 = system_clock::now();
  1851. // Client will block: LB will initially send empty serverlist.
  1852. CheckRpcSendOk(
  1853. 1, RpcOptions().set_timeout_ms(kCallDeadlineMs).set_wait_for_ready(true));
  1854. const auto ellapsed_ms =
  1855. std::chrono::duration_cast<std::chrono::milliseconds>(
  1856. system_clock::now() - t0);
  1857. // but eventually, the LB sends a serverlist update that allows the call to
  1858. // proceed. The call delay must be larger than the delay in sending the
  1859. // populated serverlist but under the call's deadline (which is enforced by
  1860. // the call's deadline).
  1861. EXPECT_GT(ellapsed_ms.count(), kServerlistDelayMs);
  1862. delayed_resource_setter.join();
  1863. }
  1864. // Tests that RPCs will fail with UNAVAILABLE instead of DEADLINE_EXCEEDED if
  1865. // all the servers are unreachable.
  1866. TEST_P(BasicTest, AllServersUnreachableFailFast) {
  1867. // Set Rpc timeout to 5 seconds to ensure there is enough time
  1868. // for communication with the xDS server to take place upon test start up.
  1869. const uint32_t kRpcTimeoutMs = 5000;
  1870. const size_t kNumUnreachableServers = 5;
  1871. std::vector<EdsResourceArgs::Endpoint> endpoints;
  1872. for (size_t i = 0; i < kNumUnreachableServers; ++i) {
  1873. endpoints.emplace_back(grpc_pick_unused_port_or_die());
  1874. }
  1875. EdsResourceArgs args({
  1876. {"locality0", endpoints},
  1877. });
  1878. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  1879. const Status status = SendRpc(RpcOptions().set_timeout_ms(kRpcTimeoutMs));
  1880. // The error shouldn't be DEADLINE_EXCEEDED because timeout is set to 5
  1881. // seconds, and we should disocver in that time that the target backend is
  1882. // down.
  1883. EXPECT_EQ(StatusCode::UNAVAILABLE, status.error_code());
  1884. }
  1885. // Tests that RPCs fail when the backends are down, and will succeed again
  1886. // after the backends are restarted.
  1887. TEST_P(BasicTest, BackendsRestart) {
  1888. EdsResourceArgs args({
  1889. {"locality0", CreateEndpointsForBackends()},
  1890. });
  1891. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  1892. WaitForAllBackends();
  1893. // Stop backends. RPCs should fail.
  1894. ShutdownAllBackends();
  1895. // Sending multiple failed requests instead of just one to ensure that the
  1896. // client notices that all backends are down before we restart them. If we
  1897. // didn't do this, then a single RPC could fail here due to the race
  1898. // condition between the LB pick and the GOAWAY from the chosen backend
  1899. // being shut down, which would not actually prove that the client noticed
  1900. // that all of the backends are down. Then, when we send another request
  1901. // below (which we expect to succeed), if the callbacks happen in the wrong
  1902. // order, the same race condition could happen again due to the client not
  1903. // yet having noticed that the backends were all down.
  1904. CheckRpcSendFailure(CheckRpcSendFailureOptions().set_times(num_backends_));
  1905. // Restart all backends. RPCs should start succeeding again.
  1906. StartAllBackends();
  1907. CheckRpcSendOk(1, RpcOptions().set_timeout_ms(2000).set_wait_for_ready(true));
  1908. }
  1909. TEST_P(BasicTest, IgnoresDuplicateUpdates) {
  1910. const size_t kNumRpcsPerAddress = 100;
  1911. EdsResourceArgs args({
  1912. {"locality0", CreateEndpointsForBackends()},
  1913. });
  1914. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  1915. // Wait for all backends to come online.
  1916. WaitForAllBackends();
  1917. // Send kNumRpcsPerAddress RPCs per server, but send an EDS update in
  1918. // between. If the update is not ignored, this will cause the
  1919. // round_robin policy to see an update, which will randomly reset its
  1920. // position in the address list.
  1921. for (size_t i = 0; i < kNumRpcsPerAddress; ++i) {
  1922. CheckRpcSendOk(2);
  1923. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  1924. CheckRpcSendOk(2);
  1925. }
  1926. // Each backend should have gotten the right number of requests.
  1927. for (size_t i = 1; i < backends_.size(); ++i) {
  1928. EXPECT_EQ(kNumRpcsPerAddress,
  1929. backends_[i]->backend_service()->request_count());
  1930. }
  1931. }
  1932. using XdsResolverOnlyTest = BasicTest;
  1933. TEST_P(XdsResolverOnlyTest, ResourceTypeVersionPersistsAcrossStreamRestarts) {
  1934. EdsResourceArgs args({
  1935. {"locality0", CreateEndpointsForBackends(0, 1)},
  1936. });
  1937. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  1938. // Wait for backends to come online.
  1939. WaitForAllBackends(0, 1);
  1940. // Stop balancer.
  1941. balancer_->Shutdown();
  1942. // Tell balancer to require minimum version 1 for all resource types.
  1943. balancer_->ads_service()->SetResourceMinVersion(kLdsTypeUrl, 1);
  1944. balancer_->ads_service()->SetResourceMinVersion(kRdsTypeUrl, 1);
  1945. balancer_->ads_service()->SetResourceMinVersion(kCdsTypeUrl, 1);
  1946. balancer_->ads_service()->SetResourceMinVersion(kEdsTypeUrl, 1);
  1947. // Update backend, just so we can be sure that the client has
  1948. // reconnected to the balancer.
  1949. EdsResourceArgs args2({
  1950. {"locality0", CreateEndpointsForBackends(1, 2)},
  1951. });
  1952. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args2));
  1953. // Restart balancer.
  1954. balancer_->Start();
  1955. // Make sure client has reconnected.
  1956. WaitForAllBackends(1, 2);
  1957. }
  1958. // Tests switching over from one cluster to another.
  1959. TEST_P(XdsResolverOnlyTest, ChangeClusters) {
  1960. const char* kNewClusterName = "new_cluster_name";
  1961. const char* kNewEdsServiceName = "new_eds_service_name";
  1962. EdsResourceArgs args({
  1963. {"locality0", CreateEndpointsForBackends(0, 2)},
  1964. });
  1965. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  1966. // We need to wait for all backends to come online.
  1967. WaitForAllBackends(0, 2);
  1968. // Populate new EDS resource.
  1969. EdsResourceArgs args2({
  1970. {"locality0", CreateEndpointsForBackends(2, 4)},
  1971. });
  1972. balancer_->ads_service()->SetEdsResource(
  1973. BuildEdsResource(args2, kNewEdsServiceName));
  1974. // Populate new CDS resource.
  1975. Cluster new_cluster = default_cluster_;
  1976. new_cluster.set_name(kNewClusterName);
  1977. new_cluster.mutable_eds_cluster_config()->set_service_name(
  1978. kNewEdsServiceName);
  1979. balancer_->ads_service()->SetCdsResource(new_cluster);
  1980. // Change RDS resource to point to new cluster.
  1981. RouteConfiguration new_route_config = default_route_config_;
  1982. new_route_config.mutable_virtual_hosts(0)
  1983. ->mutable_routes(0)
  1984. ->mutable_route()
  1985. ->set_cluster(kNewClusterName);
  1986. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  1987. new_route_config);
  1988. // Wait for all new backends to be used.
  1989. WaitForAllBackends(2, 4);
  1990. }
  1991. // Tests that we go into TRANSIENT_FAILURE if the Cluster disappears.
  1992. TEST_P(XdsResolverOnlyTest, ClusterRemoved) {
  1993. EdsResourceArgs args({
  1994. {"locality0", CreateEndpointsForBackends()},
  1995. });
  1996. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  1997. // We need to wait for all backends to come online.
  1998. WaitForAllBackends();
  1999. // Unset CDS resource.
  2000. balancer_->ads_service()->UnsetResource(kCdsTypeUrl, kDefaultClusterName);
  2001. // Wait for RPCs to start failing.
  2002. do {
  2003. } while (SendRpc(RpcOptions(), nullptr).ok());
  2004. // Make sure RPCs are still failing.
  2005. CheckRpcSendFailure(CheckRpcSendFailureOptions().set_times(1000));
  2006. // Make sure we ACK'ed the update.
  2007. auto response_state = balancer_->ads_service()->cds_response_state();
  2008. ASSERT_TRUE(response_state.has_value());
  2009. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  2010. }
  2011. // Tests that we restart all xDS requests when we reestablish the ADS call.
  2012. TEST_P(XdsResolverOnlyTest, RestartsRequestsUponReconnection) {
  2013. // Manually configure use of RDS.
  2014. auto listener = default_listener_;
  2015. HttpConnectionManager http_connection_manager;
  2016. listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
  2017. &http_connection_manager);
  2018. auto* rds = http_connection_manager.mutable_rds();
  2019. rds->set_route_config_name(kDefaultRouteConfigurationName);
  2020. rds->mutable_config_source()->mutable_self();
  2021. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  2022. http_connection_manager);
  2023. balancer_->ads_service()->SetLdsResource(listener);
  2024. balancer_->ads_service()->SetRdsResource(default_route_config_);
  2025. const char* kNewClusterName = "new_cluster_name";
  2026. const char* kNewEdsServiceName = "new_eds_service_name";
  2027. EdsResourceArgs args({
  2028. {"locality0", CreateEndpointsForBackends(0, 2)},
  2029. });
  2030. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  2031. // We need to wait for all backends to come online.
  2032. WaitForAllBackends(0, 2);
  2033. // Now shut down and restart the balancer. When the client
  2034. // reconnects, it should automatically restart the requests for all
  2035. // resource types.
  2036. balancer_->Shutdown();
  2037. balancer_->Start();
  2038. // Make sure things are still working.
  2039. CheckRpcSendOk(100);
  2040. // Populate new EDS resource.
  2041. EdsResourceArgs args2({
  2042. {"locality0", CreateEndpointsForBackends(2, 4)},
  2043. });
  2044. balancer_->ads_service()->SetEdsResource(
  2045. BuildEdsResource(args2, kNewEdsServiceName));
  2046. // Populate new CDS resource.
  2047. Cluster new_cluster = default_cluster_;
  2048. new_cluster.set_name(kNewClusterName);
  2049. new_cluster.mutable_eds_cluster_config()->set_service_name(
  2050. kNewEdsServiceName);
  2051. balancer_->ads_service()->SetCdsResource(new_cluster);
  2052. // Change RDS resource to point to new cluster.
  2053. RouteConfiguration new_route_config = default_route_config_;
  2054. new_route_config.mutable_virtual_hosts(0)
  2055. ->mutable_routes(0)
  2056. ->mutable_route()
  2057. ->set_cluster(kNewClusterName);
  2058. balancer_->ads_service()->SetRdsResource(new_route_config);
  2059. // Wait for all new backends to be used.
  2060. WaitForAllBackends(2, 4);
  2061. }
  2062. TEST_P(XdsResolverOnlyTest, DefaultRouteSpecifiesSlashPrefix) {
  2063. RouteConfiguration route_config = default_route_config_;
  2064. route_config.mutable_virtual_hosts(0)
  2065. ->mutable_routes(0)
  2066. ->mutable_match()
  2067. ->set_prefix("/");
  2068. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  2069. route_config);
  2070. EdsResourceArgs args({
  2071. {"locality0", CreateEndpointsForBackends()},
  2072. });
  2073. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  2074. // We need to wait for all backends to come online.
  2075. WaitForAllBackends();
  2076. }
  2077. TEST_P(XdsResolverOnlyTest, CircuitBreaking) {
  2078. constexpr size_t kMaxConcurrentRequests = 10;
  2079. // Populate new EDS resources.
  2080. EdsResourceArgs args({
  2081. {"locality0", CreateEndpointsForBackends(0, 1)},
  2082. });
  2083. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  2084. // Update CDS resource to set max concurrent request.
  2085. CircuitBreakers circuit_breaks;
  2086. Cluster cluster = default_cluster_;
  2087. auto* threshold = cluster.mutable_circuit_breakers()->add_thresholds();
  2088. threshold->set_priority(RoutingPriority::DEFAULT);
  2089. threshold->mutable_max_requests()->set_value(kMaxConcurrentRequests);
  2090. balancer_->ads_service()->SetCdsResource(cluster);
  2091. // Send exactly max_concurrent_requests long RPCs.
  2092. LongRunningRpc rpcs[kMaxConcurrentRequests];
  2093. for (size_t i = 0; i < kMaxConcurrentRequests; ++i) {
  2094. rpcs[i].StartRpc(stub_.get());
  2095. }
  2096. // Wait for all RPCs to be in flight.
  2097. while (backends_[0]->backend_service()->RpcsWaitingForClientCancel() <
  2098. kMaxConcurrentRequests) {
  2099. gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
  2100. gpr_time_from_micros(1 * 1000, GPR_TIMESPAN)));
  2101. }
  2102. // Sending a RPC now should fail, the error message should tell us
  2103. // we hit the max concurrent requests limit and got dropped.
  2104. Status status = SendRpc();
  2105. EXPECT_FALSE(status.ok());
  2106. EXPECT_EQ(status.error_message(), "circuit breaker drop");
  2107. // Cancel one RPC to allow another one through
  2108. rpcs[0].CancelRpc();
  2109. status = SendRpc();
  2110. EXPECT_TRUE(status.ok());
  2111. for (size_t i = 1; i < kMaxConcurrentRequests; ++i) {
  2112. rpcs[i].CancelRpc();
  2113. }
  2114. // Make sure RPCs go to the correct backend:
  2115. EXPECT_EQ(kMaxConcurrentRequests + 1,
  2116. backends_[0]->backend_service()->request_count());
  2117. }
  2118. TEST_P(XdsResolverOnlyTest, CircuitBreakingMultipleChannelsShareCallCounter) {
  2119. constexpr size_t kMaxConcurrentRequests = 10;
  2120. // Populate new EDS resources.
  2121. EdsResourceArgs args({
  2122. {"locality0", CreateEndpointsForBackends(0, 1)},
  2123. });
  2124. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  2125. // Update CDS resource to set max concurrent request.
  2126. CircuitBreakers circuit_breaks;
  2127. Cluster cluster = default_cluster_;
  2128. auto* threshold = cluster.mutable_circuit_breakers()->add_thresholds();
  2129. threshold->set_priority(RoutingPriority::DEFAULT);
  2130. threshold->mutable_max_requests()->set_value(kMaxConcurrentRequests);
  2131. balancer_->ads_service()->SetCdsResource(cluster);
  2132. auto channel2 = CreateChannel();
  2133. auto stub2 = grpc::testing::EchoTestService::NewStub(channel2);
  2134. // Send exactly max_concurrent_requests long RPCs, alternating between
  2135. // the two channels.
  2136. LongRunningRpc rpcs[kMaxConcurrentRequests];
  2137. for (size_t i = 0; i < kMaxConcurrentRequests; ++i) {
  2138. rpcs[i].StartRpc(i % 2 == 0 ? stub_.get() : stub2.get());
  2139. }
  2140. // Wait for all RPCs to be in flight.
  2141. while (backends_[0]->backend_service()->RpcsWaitingForClientCancel() <
  2142. kMaxConcurrentRequests) {
  2143. gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
  2144. gpr_time_from_micros(1 * 1000, GPR_TIMESPAN)));
  2145. }
  2146. // Sending a RPC now should fail, the error message should tell us
  2147. // we hit the max concurrent requests limit and got dropped.
  2148. Status status = SendRpc();
  2149. EXPECT_FALSE(status.ok());
  2150. EXPECT_EQ(status.error_message(), "circuit breaker drop");
  2151. // Cancel one RPC to allow another one through
  2152. rpcs[0].CancelRpc();
  2153. status = SendRpc();
  2154. EXPECT_TRUE(status.ok());
  2155. for (size_t i = 1; i < kMaxConcurrentRequests; ++i) {
  2156. rpcs[i].CancelRpc();
  2157. }
  2158. // Make sure RPCs go to the correct backend:
  2159. EXPECT_EQ(kMaxConcurrentRequests + 1,
  2160. backends_[0]->backend_service()->request_count());
  2161. }
  2162. TEST_P(XdsResolverOnlyTest, ClusterChangeAfterAdsCallFails) {
  2163. const char* kNewEdsResourceName = "new_eds_resource_name";
  2164. // Populate EDS resources.
  2165. EdsResourceArgs args({
  2166. {"locality0", CreateEndpointsForBackends(0, 1)},
  2167. });
  2168. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  2169. // Check that the channel is working.
  2170. CheckRpcSendOk();
  2171. // Stop and restart the balancer.
  2172. balancer_->Shutdown();
  2173. balancer_->Start();
  2174. // Create new EDS resource.
  2175. EdsResourceArgs args2({
  2176. {"locality0", CreateEndpointsForBackends(1, 2)},
  2177. });
  2178. balancer_->ads_service()->SetEdsResource(
  2179. BuildEdsResource(args2, kNewEdsResourceName));
  2180. // Change CDS resource to point to new EDS resource.
  2181. auto cluster = default_cluster_;
  2182. cluster.mutable_eds_cluster_config()->set_service_name(kNewEdsResourceName);
  2183. balancer_->ads_service()->SetCdsResource(cluster);
  2184. // Make sure client sees the change.
  2185. // TODO(roth): This should not be allowing errors. The errors are
  2186. // being caused by a bug that triggers in the following situation:
  2187. //
  2188. // 1. xDS call fails.
  2189. // 2. When xDS call is restarted, the server sends the updated CDS
  2190. // resource that points to the new EDS resource name.
  2191. // 3. When the client receives the CDS update, it does two things:
  2192. // - Sends the update to the CDS LB policy, which creates a new
  2193. // xds_cluster_resolver policy using the new EDS service name.
  2194. // - Notices that the CDS update no longer refers to the old EDS
  2195. // service name, so removes that resource, notifying the old
  2196. // xds_cluster_resolver policy that the resource no longer exists.
  2197. //
  2198. // Need to figure out a way to fix this bug, and then change this to
  2199. // not allow failures.
  2200. WaitForBackend(1, WaitForBackendOptions().set_allow_failures(true));
  2201. }
  2202. // Tests that if the balancer is down, the RPCs will still be sent to the
  2203. // backends according to the last balancer response, until a new balancer is
  2204. // reachable.
  2205. TEST_P(XdsResolverOnlyTest, KeepUsingLastDataIfBalancerGoesDown) {
  2206. // Set up EDS resource pointing to backend 0.
  2207. EdsResourceArgs args({{"locality0", CreateEndpointsForBackends(0, 1)}});
  2208. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  2209. // Start the client and make sure it sees the backend.
  2210. WaitForBackend(0);
  2211. // Stop the balancer, and verify that RPCs continue to flow to backend 0.
  2212. balancer_->Shutdown();
  2213. auto deadline = grpc_timeout_seconds_to_deadline(5);
  2214. do {
  2215. CheckRpcSendOk();
  2216. } while (gpr_time_cmp(gpr_now(GPR_CLOCK_MONOTONIC), deadline) < 0);
  2217. // Check the EDS resource to point to backend 1 and bring the balancer
  2218. // back up.
  2219. args = EdsResourceArgs({{"locality0", CreateEndpointsForBackends(1, 2)}});
  2220. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  2221. balancer_->Start();
  2222. // Wait for client to see backend 1.
  2223. WaitForBackend(1);
  2224. }
  2225. TEST_P(XdsResolverOnlyTest, XdsStreamErrorPropagation) {
  2226. const std::string kErrorMessage = "test forced ADS stream failure";
  2227. balancer_->ads_service()->ForceADSFailure(
  2228. Status(StatusCode::RESOURCE_EXHAUSTED, kErrorMessage));
  2229. auto status = SendRpc();
  2230. gpr_log(GPR_INFO,
  2231. "XdsStreamErrorPropagation test: RPC got error: code=%d message=%s",
  2232. status.error_code(), status.error_message().c_str());
  2233. EXPECT_THAT(status.error_code(), StatusCode::UNAVAILABLE);
  2234. EXPECT_THAT(status.error_message(), ::testing::HasSubstr(kErrorMessage));
  2235. }
  2236. using GlobalXdsClientTest = BasicTest;
  2237. TEST_P(GlobalXdsClientTest, MultipleChannelsShareXdsClient) {
  2238. const char* kNewServerName = "new-server.example.com";
  2239. Listener listener = default_listener_;
  2240. listener.set_name(kNewServerName);
  2241. SetListenerAndRouteConfiguration(balancer_.get(), listener,
  2242. default_route_config_);
  2243. EdsResourceArgs args({
  2244. {"locality0", CreateEndpointsForBackends()},
  2245. });
  2246. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  2247. WaitForAllBackends();
  2248. // Create second channel and tell it to connect to kNewServerName.
  2249. auto channel2 = CreateChannel(/*failover_timeout=*/0, kNewServerName);
  2250. channel2->GetState(/*try_to_connect=*/true);
  2251. ASSERT_TRUE(
  2252. channel2->WaitForConnected(grpc_timeout_milliseconds_to_deadline(100)));
  2253. // Make sure there's only one client connected.
  2254. EXPECT_EQ(1UL, balancer_->ads_service()->clients().size());
  2255. }
  2256. TEST_P(
  2257. GlobalXdsClientTest,
  2258. MultipleChannelsShareXdsClientWithResourceUpdateAfterOneChannelGoesAway) {
  2259. // Test for https://github.com/grpc/grpc/issues/28468. Makes sure that the
  2260. // XdsClient properly handles the case where there are multiple watchers on
  2261. // the same resource and one of them unsubscribes.
  2262. const char* kNewServerName = "new-server.example.com";
  2263. Listener listener = default_listener_;
  2264. listener.set_name(kNewServerName);
  2265. SetListenerAndRouteConfiguration(balancer_.get(), listener,
  2266. default_route_config_);
  2267. balancer_->ads_service()->SetEdsResource(BuildEdsResource(EdsResourceArgs({
  2268. {"locality0", CreateEndpointsForBackends(0, 1)},
  2269. })));
  2270. WaitForBackend(0);
  2271. // Create second channel and tell it to connect to kNewServerName.
  2272. auto channel2 = CreateChannel(/*failover_timeout=*/0, kNewServerName);
  2273. channel2->GetState(/*try_to_connect=*/true);
  2274. ASSERT_TRUE(
  2275. channel2->WaitForConnected(grpc_timeout_milliseconds_to_deadline(100)));
  2276. // Now, destroy the new channel, send an EDS update to use a different backend
  2277. // and test that the channel switches to that backend.
  2278. channel2.reset();
  2279. // This sleep is needed to be able to reproduce the bug and to give time for
  2280. // the buggy unsubscription to take place.
  2281. // TODO(yashykt): Figure out a way to do this without the sleep.
  2282. gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(10));
  2283. balancer_->ads_service()->SetEdsResource(BuildEdsResource(EdsResourceArgs({
  2284. {"locality0", CreateEndpointsForBackends(1, 2)},
  2285. })));
  2286. WaitForBackend(1);
  2287. }
  2288. // Tests that the NACK for multiple bad LDS resources includes both errors.
  2289. TEST_P(GlobalXdsClientTest, MultipleBadResources) {
  2290. constexpr char kServerName2[] = "server.other.com";
  2291. constexpr char kServerName3[] = "server.another.com";
  2292. auto listener = default_listener_;
  2293. listener.clear_api_listener();
  2294. balancer_->ads_service()->SetLdsResource(listener);
  2295. listener.set_name(kServerName2);
  2296. balancer_->ads_service()->SetLdsResource(listener);
  2297. listener = default_listener_;
  2298. listener.set_name(kServerName3);
  2299. SetListenerAndRouteConfiguration(balancer_.get(), listener,
  2300. default_route_config_);
  2301. EdsResourceArgs args({
  2302. {"locality0", CreateEndpointsForBackends(0, 1)},
  2303. });
  2304. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  2305. const auto response_state = WaitForLdsNack();
  2306. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  2307. EXPECT_THAT(response_state->error_message,
  2308. ::testing::ContainsRegex(absl::StrCat(
  2309. kServerName,
  2310. ": validation error.*"
  2311. "Listener has neither address nor ApiListener.*")));
  2312. // Need to create a second channel to subscribe to a second LDS resource.
  2313. auto channel2 = CreateChannel(0, kServerName2);
  2314. auto stub2 = grpc::testing::EchoTestService::NewStub(channel2);
  2315. {
  2316. ClientContext context;
  2317. EchoRequest request;
  2318. request.set_message(kRequestMessage);
  2319. EchoResponse response;
  2320. grpc::Status status = stub2->Echo(&context, request, &response);
  2321. EXPECT_FALSE(status.ok());
  2322. // Wait for second NACK to be reported to xDS server.
  2323. const auto response_state = WaitForLdsNack();
  2324. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  2325. EXPECT_THAT(response_state->error_message,
  2326. ::testing::ContainsRegex(absl::StrCat(
  2327. kServerName,
  2328. ": validation error.*"
  2329. "Listener has neither address nor ApiListener.*")));
  2330. EXPECT_THAT(response_state->error_message,
  2331. ::testing::ContainsRegex(absl::StrCat(
  2332. kServerName2,
  2333. ": validation error.*"
  2334. "Listener has neither address nor ApiListener.*")));
  2335. }
  2336. // Now start a new channel with a third server name, this one with a
  2337. // valid resource.
  2338. auto channel3 = CreateChannel(0, kServerName3);
  2339. auto stub3 = grpc::testing::EchoTestService::NewStub(channel3);
  2340. {
  2341. ClientContext context;
  2342. EchoRequest request;
  2343. request.set_message(kRequestMessage);
  2344. EchoResponse response;
  2345. grpc::Status status = stub3->Echo(&context, request, &response);
  2346. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  2347. << " message=" << status.error_message();
  2348. }
  2349. }
  2350. // Tests that we don't trigger does-not-exist callbacks for a resource
  2351. // that was previously valid but is updated to be invalid.
  2352. TEST_P(GlobalXdsClientTest, InvalidListenerStillExistsIfPreviouslyCached) {
  2353. // Set up valid resources and check that the channel works.
  2354. EdsResourceArgs args({
  2355. {"locality0", CreateEndpointsForBackends(0, 1)},
  2356. });
  2357. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  2358. CheckRpcSendOk();
  2359. // Now send an update changing the Listener to be invalid.
  2360. auto listener = default_listener_;
  2361. listener.clear_api_listener();
  2362. balancer_->ads_service()->SetLdsResource(listener);
  2363. const auto response_state = WaitForLdsNack(StatusCode::OK);
  2364. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  2365. EXPECT_THAT(response_state->error_message,
  2366. ::testing::ContainsRegex(absl::StrCat(
  2367. kServerName,
  2368. ": validation error.*"
  2369. "Listener has neither address nor ApiListener")));
  2370. }
  2371. class XdsFederationTest : public XdsEnd2endTest {
  2372. protected:
  2373. XdsFederationTest() : XdsEnd2endTest(2, 3, 0, true) {
  2374. authority_balancer_ = CreateAndStartBalancer();
  2375. }
  2376. void SetUp() override {
  2377. // Each test will use a slightly different bootstrapfile,
  2378. // so SetUp() is intentionally empty here and the real
  2379. // setup: calling of CreateClientAndServers(builder)
  2380. // is moved into each test.
  2381. }
  2382. void TearDown() override {
  2383. authority_balancer_->Shutdown();
  2384. XdsEnd2endTest::TearDown();
  2385. }
  2386. std::unique_ptr<BalancerServerThread> authority_balancer_;
  2387. };
  2388. // Channel is created with URI "xds:server.example.com".
  2389. // Bootstrap config default client listener template uses new-style name with
  2390. // authority "xds.example.com".
  2391. TEST_P(XdsFederationTest, FederationTargetNoAuthorityWithResourceTemplate) {
  2392. gpr_setenv("GRPC_EXPERIMENTAL_XDS_FEDERATION", "true");
  2393. const char* kAuthority = "xds.example.com";
  2394. const char* kNewListenerTemplate =
  2395. "xdstp://xds.example.com/envoy.config.listener.v3.Listener/"
  2396. "client/%s?psm_project_id=1234";
  2397. const char* kNewListenerName =
  2398. "xdstp://xds.example.com/envoy.config.listener.v3.Listener/"
  2399. "client/server.example.com?psm_project_id=1234";
  2400. const char* kNewRouteConfigName =
  2401. "xdstp://xds.example.com/envoy.config.route.v3.RouteConfiguration/"
  2402. "new_route_config_name";
  2403. const char* kNewEdsServiceName =
  2404. "xdstp://xds.example.com/envoy.config.endpoint.v3.ClusterLoadAssignment/"
  2405. "new_edsservice_name";
  2406. const char* kNewClusterName =
  2407. "xdstp://xds.example.com/envoy.config.cluster.v3.Cluster/"
  2408. "new_cluster_name";
  2409. BootstrapBuilder builder = BootstrapBuilder();
  2410. builder.SetClientDefaultListenerResourceNameTemplate(kNewListenerTemplate);
  2411. builder.AddAuthority(
  2412. kAuthority, absl::StrCat("localhost:", authority_balancer_->port()),
  2413. // Note we will not use the client_listener_resource_name_template field
  2414. // in the authority.
  2415. "xdstp://xds.example.com/envoy.config.listener.v3.Listener"
  2416. "client/%s?client_listener_resource_name_template_not_in_use");
  2417. CreateClientsAndServers(builder);
  2418. StartAllBackends();
  2419. // Eds for the new authority balancer.
  2420. EdsResourceArgs args =
  2421. EdsResourceArgs({{"locality0", CreateEndpointsForBackends()}});
  2422. authority_balancer_->ads_service()->SetEdsResource(
  2423. BuildEdsResource(args, kNewEdsServiceName));
  2424. // New cluster
  2425. Cluster new_cluster = default_cluster_;
  2426. new_cluster.set_name(kNewClusterName);
  2427. new_cluster.mutable_eds_cluster_config()->set_service_name(
  2428. kNewEdsServiceName);
  2429. authority_balancer_->ads_service()->SetCdsResource(new_cluster);
  2430. // New Route
  2431. RouteConfiguration new_route_config = default_route_config_;
  2432. new_route_config.set_name(kNewRouteConfigName);
  2433. new_route_config.mutable_virtual_hosts(0)
  2434. ->mutable_routes(0)
  2435. ->mutable_route()
  2436. ->set_cluster(kNewClusterName);
  2437. // New Listener
  2438. Listener listener = default_listener_;
  2439. listener.set_name(kNewListenerName);
  2440. SetListenerAndRouteConfiguration(authority_balancer_.get(), listener,
  2441. new_route_config);
  2442. WaitForAllBackends();
  2443. gpr_unsetenv("GRPC_EXPERIMENTAL_XDS_FEDERATION");
  2444. }
  2445. // Channel is created with URI "xds://xds.example.com/server.example.com".
  2446. // In bootstrap config, authority has no client listener template, so we use the
  2447. // default.
  2448. TEST_P(XdsFederationTest, FederationTargetAuthorityDefaultResourceTemplate) {
  2449. gpr_setenv("GRPC_EXPERIMENTAL_XDS_FEDERATION", "true");
  2450. const char* kAuthority = "xds.example.com";
  2451. const char* kNewServerName = "whee%/server.example.com";
  2452. const char* kNewListenerName =
  2453. "xdstp://xds.example.com/envoy.config.listener.v3.Listener/"
  2454. "whee%25/server.example.com";
  2455. const char* kNewRouteConfigName =
  2456. "xdstp://xds.example.com/envoy.config.route.v3.RouteConfiguration/"
  2457. "new_route_config_name";
  2458. const char* kNewEdsServiceName =
  2459. "xdstp://xds.example.com/envoy.config.endpoint.v3.ClusterLoadAssignment/"
  2460. "edsservice_name";
  2461. const char* kNewClusterName =
  2462. "xdstp://xds.example.com/envoy.config.cluster.v3.Cluster/"
  2463. "cluster_name";
  2464. BootstrapBuilder builder = BootstrapBuilder();
  2465. builder.AddAuthority(kAuthority,
  2466. absl::StrCat("localhost:", authority_balancer_->port()));
  2467. CreateClientsAndServers(builder);
  2468. StartAllBackends();
  2469. // Eds for 2 balancers to ensure RPCs sent using current stub go to backend 0
  2470. // and RPCs sent using the new stub go to backend 1.
  2471. EdsResourceArgs args({{"locality0", CreateEndpointsForBackends(0, 1)}});
  2472. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  2473. args = EdsResourceArgs({{"locality0", CreateEndpointsForBackends(1, 2)}});
  2474. authority_balancer_->ads_service()->SetEdsResource(
  2475. BuildEdsResource(args, kNewEdsServiceName));
  2476. // New cluster
  2477. Cluster new_cluster = default_cluster_;
  2478. new_cluster.set_name(kNewClusterName);
  2479. new_cluster.mutable_eds_cluster_config()->set_service_name(
  2480. kNewEdsServiceName);
  2481. authority_balancer_->ads_service()->SetCdsResource(new_cluster);
  2482. // New Route
  2483. RouteConfiguration new_route_config = default_route_config_;
  2484. new_route_config.set_name(kNewRouteConfigName);
  2485. new_route_config.mutable_virtual_hosts(0)
  2486. ->mutable_routes(0)
  2487. ->mutable_route()
  2488. ->set_cluster(kNewClusterName);
  2489. // New Listener
  2490. Listener listener = default_listener_;
  2491. listener.set_name(kNewListenerName);
  2492. SetListenerAndRouteConfiguration(authority_balancer_.get(), listener,
  2493. new_route_config);
  2494. // Ensure update has reached and send 10 RPCs to the current stub.
  2495. WaitForAllBackends(0, 1);
  2496. // Create second channel to new target uri and send 1 RPC .
  2497. auto channel2 =
  2498. CreateChannel(/*failover_timeout=*/0, kNewServerName, kAuthority);
  2499. channel2->GetState(/*try_to_connect=*/true);
  2500. ASSERT_TRUE(
  2501. channel2->WaitForConnected(grpc_timeout_milliseconds_to_deadline(100)));
  2502. auto stub2 = grpc::testing::EchoTestService::NewStub(channel2);
  2503. ClientContext context;
  2504. EchoRequest request;
  2505. request.set_message(kRequestMessage);
  2506. EchoResponse response;
  2507. grpc::Status status = stub2->Echo(&context, request, &response);
  2508. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  2509. << " message=" << status.error_message();
  2510. // We should be reaching backend 1, not 0, as balanced by the authority xds
  2511. // server.
  2512. EXPECT_EQ(0U, backends_[0]->backend_service()->request_count());
  2513. EXPECT_EQ(1U, backends_[1]->backend_service()->request_count());
  2514. gpr_unsetenv("GRPC_EXPERIMENTAL_XDS_FEDERATION");
  2515. }
  2516. // Channel is created with URI "xds://xds.example.com/server.example.com".
  2517. // Bootstrap entry for that authority specifies a client listener name template.
  2518. TEST_P(XdsFederationTest, FederationTargetAuthorityWithResourceTemplate) {
  2519. gpr_setenv("GRPC_EXPERIMENTAL_XDS_FEDERATION", "true");
  2520. const char* kAuthority = "xds.example.com";
  2521. const char* kNewServerName = "whee%/server.example.com";
  2522. const char* kNewListenerTemplate =
  2523. "xdstp://xds.example.com/envoy.config.listener.v3.Listener/"
  2524. "client/%s?psm_project_id=1234";
  2525. const char* kNewListenerName =
  2526. "xdstp://xds.example.com/envoy.config.listener.v3.Listener/"
  2527. "client/whee%25/server.example.com?psm_project_id=1234";
  2528. const char* kNewRouteConfigName =
  2529. "xdstp://xds.example.com/envoy.config.route.v3.RouteConfiguration/"
  2530. "new_route_config_name";
  2531. const char* kNewEdsServiceName =
  2532. "xdstp://xds.example.com/envoy.config.endpoint.v3.ClusterLoadAssignment/"
  2533. "edsservice_name";
  2534. const char* kNewClusterName =
  2535. "xdstp://xds.example.com/envoy.config.cluster.v3.Cluster/"
  2536. "cluster_name";
  2537. BootstrapBuilder builder = BootstrapBuilder();
  2538. builder.AddAuthority(kAuthority,
  2539. absl::StrCat("localhost:", authority_balancer_->port()),
  2540. kNewListenerTemplate);
  2541. CreateClientsAndServers(builder);
  2542. StartAllBackends();
  2543. // Eds for 2 balancers to ensure RPCs sent using current stub go to backend 0
  2544. // and RPCs sent using the new stub go to backend 1.
  2545. EdsResourceArgs args({{"locality0", CreateEndpointsForBackends(0, 1)}});
  2546. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  2547. args = EdsResourceArgs({{"locality0", CreateEndpointsForBackends(1, 2)}});
  2548. authority_balancer_->ads_service()->SetEdsResource(
  2549. BuildEdsResource(args, kNewEdsServiceName));
  2550. // New cluster
  2551. Cluster new_cluster = default_cluster_;
  2552. new_cluster.set_name(kNewClusterName);
  2553. new_cluster.mutable_eds_cluster_config()->set_service_name(
  2554. kNewEdsServiceName);
  2555. authority_balancer_->ads_service()->SetCdsResource(new_cluster);
  2556. // New Route
  2557. RouteConfiguration new_route_config = default_route_config_;
  2558. new_route_config.set_name(kNewRouteConfigName);
  2559. new_route_config.mutable_virtual_hosts(0)
  2560. ->mutable_routes(0)
  2561. ->mutable_route()
  2562. ->set_cluster(kNewClusterName);
  2563. // New Listener
  2564. Listener listener = default_listener_;
  2565. listener.set_name(kNewListenerName);
  2566. SetListenerAndRouteConfiguration(authority_balancer_.get(), listener,
  2567. new_route_config);
  2568. // Ensure update has reached and send 10 RPCs to the current stub.
  2569. WaitForAllBackends(0, 1);
  2570. // Create second channel to new target uri and send 1 RPC .
  2571. auto channel2 =
  2572. CreateChannel(/*failover_timeout=*/0, kNewServerName, kAuthority);
  2573. channel2->GetState(/*try_to_connect=*/true);
  2574. ASSERT_TRUE(
  2575. channel2->WaitForConnected(grpc_timeout_milliseconds_to_deadline(100)));
  2576. auto stub2 = grpc::testing::EchoTestService::NewStub(channel2);
  2577. ClientContext context;
  2578. EchoRequest request;
  2579. request.set_message(kRequestMessage);
  2580. EchoResponse response;
  2581. grpc::Status status = stub2->Echo(&context, request, &response);
  2582. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  2583. << " message=" << status.error_message();
  2584. // We should be reaching backend 1, not 0, as balanced by the authority xds
  2585. // server.
  2586. EXPECT_EQ(0U, backends_[0]->backend_service()->request_count());
  2587. EXPECT_EQ(1U, backends_[1]->backend_service()->request_count());
  2588. gpr_unsetenv("GRPC_EXPERIMENTAL_XDS_FEDERATION");
  2589. }
  2590. // Setting server_listener_resource_name_template to start with "xdstp:" and
  2591. // look up xds server under an authority map.
  2592. TEST_P(XdsFederationTest, FederationServer) {
  2593. gpr_setenv("GRPC_EXPERIMENTAL_XDS_FEDERATION", "true");
  2594. const char* kAuthority = "xds.example.com";
  2595. const char* kNewListenerTemplate =
  2596. "xdstp://xds.example.com/envoy.config.listener.v3.Listener/"
  2597. "client/%s?psm_project_id=1234";
  2598. const char* kNewServerListenerTemplate =
  2599. "xdstp://xds.example.com/envoy.config.listener.v3.Listener/"
  2600. "server/%s?psm_project_id=1234";
  2601. const char* kNewListenerName =
  2602. "xdstp://xds.example.com/envoy.config.listener.v3.Listener/"
  2603. "client/server.example.com?psm_project_id=1234";
  2604. const char* kNewRouteConfigName =
  2605. "xdstp://xds.example.com/envoy.config.route.v3.RouteConfiguration/"
  2606. "new_route_config_name";
  2607. const char* kNewEdsServiceName =
  2608. "xdstp://xds.example.com/envoy.config.endpoint.v3.ClusterLoadAssignment/"
  2609. "new_edsservice_name";
  2610. const char* kNewClusterName =
  2611. "xdstp://xds.example.com/envoy.config.cluster.v3.Cluster/"
  2612. "new_cluster_name";
  2613. BootstrapBuilder builder = BootstrapBuilder();
  2614. builder.SetClientDefaultListenerResourceNameTemplate(kNewListenerTemplate);
  2615. builder.SetServerListenerResourceNameTemplate(kNewServerListenerTemplate);
  2616. builder.AddAuthority(
  2617. kAuthority, absl::StrCat("localhost:", authority_balancer_->port()),
  2618. // Note we will not use the client_listener_resource_name_template field
  2619. // in the authority.
  2620. "xdstp://xds.example.com/envoy.config.listener.v3.Listener"
  2621. "client/%s?client_listener_resource_name_template_not_in_use");
  2622. CreateClientsAndServers(builder);
  2623. StartAllBackends();
  2624. // Eds for new authority balancer.
  2625. EdsResourceArgs args =
  2626. EdsResourceArgs({{"locality0", CreateEndpointsForBackends()}});
  2627. authority_balancer_->ads_service()->SetEdsResource(
  2628. BuildEdsResource(args, kNewEdsServiceName));
  2629. // New cluster
  2630. Cluster new_cluster = default_cluster_;
  2631. new_cluster.set_name(kNewClusterName);
  2632. new_cluster.mutable_eds_cluster_config()->set_service_name(
  2633. kNewEdsServiceName);
  2634. authority_balancer_->ads_service()->SetCdsResource(new_cluster);
  2635. // New Route
  2636. RouteConfiguration new_route_config = default_route_config_;
  2637. new_route_config.set_name(kNewRouteConfigName);
  2638. new_route_config.mutable_virtual_hosts(0)
  2639. ->mutable_routes(0)
  2640. ->mutable_route()
  2641. ->set_cluster(kNewClusterName);
  2642. // New Listener
  2643. Listener listener = default_listener_;
  2644. listener.set_name(kNewListenerName);
  2645. SetListenerAndRouteConfiguration(authority_balancer_.get(), listener,
  2646. new_route_config);
  2647. // New Server Listeners
  2648. for (int port : GetBackendPorts()) {
  2649. Listener server_listener = default_server_listener_;
  2650. server_listener.set_name(absl::StrCat(
  2651. "xdstp://xds.example.com/envoy.config.listener.v3.Listener/server/",
  2652. ipv6_only_ ? "%5B::1%5D:" : "127.0.0.1:", port,
  2653. "?psm_project_id=1234"));
  2654. server_listener.mutable_address()->mutable_socket_address()->set_port_value(
  2655. port);
  2656. authority_balancer_->ads_service()->SetLdsResource(server_listener);
  2657. }
  2658. WaitForAllBackends();
  2659. gpr_unsetenv("GRPC_EXPERIMENTAL_XDS_FEDERATION");
  2660. }
  2661. using XdsFederationLoadReportingTest = XdsFederationTest;
  2662. // Channel is created with URI "xds://xds.example.com/server.example.com".
  2663. // Bootstrap entry for that authority specifies a client listener name template.
  2664. // Sending traffic to both default balancer and authority balancer and checking
  2665. // load reporting with each one.
  2666. TEST_P(XdsFederationLoadReportingTest, FederationMultipleLoadReportingTest) {
  2667. gpr_setenv("GRPC_EXPERIMENTAL_XDS_FEDERATION", "true");
  2668. const char* kAuthority = "xds.example.com";
  2669. const char* kNewServerName = "whee%/server.example.com";
  2670. const char* kNewListenerTemplate =
  2671. "xdstp://xds.example.com/envoy.config.listener.v3.Listener/"
  2672. "client/%s?psm_project_id=1234";
  2673. const char* kNewListenerName =
  2674. "xdstp://xds.example.com/envoy.config.listener.v3.Listener/"
  2675. "client/whee%25/server.example.com?psm_project_id=1234";
  2676. const char* kNewRouteConfigName =
  2677. "xdstp://xds.example.com/envoy.config.route.v3.RouteConfiguration/"
  2678. "new_route_config_name";
  2679. const char* kNewEdsServiceName =
  2680. "xdstp://xds.example.com/envoy.config.endpoint.v3.ClusterLoadAssignment/"
  2681. "edsservice_name";
  2682. const char* kNewClusterName =
  2683. "xdstp://xds.example.com/envoy.config.cluster.v3.Cluster/"
  2684. "cluster_name";
  2685. const size_t kNumRpcsToDefaultBalancer = 5;
  2686. const size_t kNumRpcsToAuthorityBalancer = 10;
  2687. BootstrapBuilder builder = BootstrapBuilder();
  2688. builder.AddAuthority(kAuthority,
  2689. absl::StrCat("localhost:", authority_balancer_->port()),
  2690. kNewListenerTemplate);
  2691. CreateClientsAndServers(builder);
  2692. StartAllBackends();
  2693. // Eds for 2 balancers to ensure RPCs sent using current stub go to backend 0
  2694. // and RPCs sent using the new stub go to backend 1.
  2695. EdsResourceArgs args({{"locality0", CreateEndpointsForBackends(0, 1)}});
  2696. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  2697. args = EdsResourceArgs({{"locality0", CreateEndpointsForBackends(1, 2)}});
  2698. authority_balancer_->ads_service()->SetEdsResource(
  2699. BuildEdsResource(args, kNewEdsServiceName));
  2700. authority_balancer_->lrs_service()->set_cluster_names({kNewClusterName});
  2701. // New cluster
  2702. Cluster new_cluster = default_cluster_;
  2703. new_cluster.set_name(kNewClusterName);
  2704. new_cluster.mutable_lrs_server()->mutable_self();
  2705. new_cluster.mutable_eds_cluster_config()->set_service_name(
  2706. kNewEdsServiceName);
  2707. authority_balancer_->ads_service()->SetCdsResource(new_cluster);
  2708. // New Route
  2709. RouteConfiguration new_route_config = default_route_config_;
  2710. new_route_config.set_name(kNewRouteConfigName);
  2711. new_route_config.mutable_virtual_hosts(0)
  2712. ->mutable_routes(0)
  2713. ->mutable_route()
  2714. ->set_cluster(kNewClusterName);
  2715. // New Listener
  2716. Listener listener = default_listener_;
  2717. listener.set_name(kNewListenerName);
  2718. SetListenerAndRouteConfiguration(authority_balancer_.get(), listener,
  2719. new_route_config);
  2720. // Ensure update has reached and send 10 RPCs to the current stub.
  2721. CheckRpcSendOk(kNumRpcsToDefaultBalancer);
  2722. // Create second channel to new target uri and send 1 RPC .
  2723. auto channel2 =
  2724. CreateChannel(/*failover_timeout=*/0, kNewServerName, kAuthority);
  2725. channel2->GetState(/*try_to_connect=*/true);
  2726. ASSERT_TRUE(
  2727. channel2->WaitForConnected(grpc_timeout_milliseconds_to_deadline(100)));
  2728. auto stub2 = grpc::testing::EchoTestService::NewStub(channel2);
  2729. for (size_t i = 0; i < kNumRpcsToAuthorityBalancer; ++i) {
  2730. ClientContext context;
  2731. EchoRequest request;
  2732. request.set_message(kRequestMessage);
  2733. EchoResponse response;
  2734. grpc::Status status = stub2->Echo(&context, request, &response);
  2735. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  2736. << " message=" << status.error_message();
  2737. }
  2738. // Each backend should have received the expected number of RPCs,
  2739. // and the load report also reflect the correct numbers.
  2740. EXPECT_EQ(kNumRpcsToAuthorityBalancer,
  2741. backends_[1]->backend_service()->request_count());
  2742. EXPECT_EQ(kNumRpcsToDefaultBalancer,
  2743. backends_[0]->backend_service()->request_count());
  2744. // Load report for authority LRS.
  2745. std::vector<ClientStats> authority_load_report =
  2746. authority_balancer_->lrs_service()->WaitForLoadReport();
  2747. ASSERT_EQ(authority_load_report.size(), 1UL);
  2748. ClientStats& authority_client_stats = authority_load_report.front();
  2749. EXPECT_EQ(kNumRpcsToAuthorityBalancer,
  2750. authority_client_stats.total_successful_requests());
  2751. EXPECT_EQ(0U, authority_client_stats.total_requests_in_progress());
  2752. EXPECT_EQ(kNumRpcsToAuthorityBalancer,
  2753. authority_client_stats.total_issued_requests());
  2754. EXPECT_EQ(0U, authority_client_stats.total_error_requests());
  2755. EXPECT_EQ(0U, authority_client_stats.total_dropped_requests());
  2756. EXPECT_EQ(1U, authority_balancer_->lrs_service()->request_count());
  2757. EXPECT_EQ(1U, authority_balancer_->lrs_service()->response_count());
  2758. // Load report for default LRS.
  2759. std::vector<ClientStats> default_load_report =
  2760. balancer_->lrs_service()->WaitForLoadReport();
  2761. ASSERT_EQ(default_load_report.size(), 1UL);
  2762. ClientStats& default_client_stats = default_load_report.front();
  2763. EXPECT_EQ(kNumRpcsToDefaultBalancer,
  2764. default_client_stats.total_successful_requests());
  2765. EXPECT_EQ(0U, default_client_stats.total_requests_in_progress());
  2766. EXPECT_EQ(kNumRpcsToDefaultBalancer,
  2767. default_client_stats.total_issued_requests());
  2768. EXPECT_EQ(0U, default_client_stats.total_error_requests());
  2769. EXPECT_EQ(0U, default_client_stats.total_dropped_requests());
  2770. EXPECT_EQ(1U, balancer_->lrs_service()->request_count());
  2771. EXPECT_EQ(1U, balancer_->lrs_service()->response_count());
  2772. gpr_unsetenv("GRPC_EXPERIMENTAL_XDS_FEDERATION");
  2773. }
  2774. class SecureNamingTest : public XdsEnd2endTest {
  2775. public:
  2776. SecureNamingTest()
  2777. : XdsEnd2endTest(/*num_backends=*/4,
  2778. /*client_load_reporting_interval_seconds=*/100,
  2779. /*xds_resource_does_not_exist_timeout_ms=*/0,
  2780. /*use_xds_enabled_server=*/false) {}
  2781. void SetUp() override {}
  2782. };
  2783. // Tests that secure naming check passes if target name is expected.
  2784. TEST_P(SecureNamingTest, TargetNameIsExpected) {
  2785. CreateClientsAndServers(BootstrapBuilder(),
  2786. /*lb_expected_authority=*/"localhost:%d");
  2787. StartAllBackends();
  2788. EdsResourceArgs args({
  2789. {"locality0", CreateEndpointsForBackends()},
  2790. });
  2791. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  2792. CheckRpcSendOk();
  2793. }
  2794. // Tests that secure naming check fails if target name is unexpected.
  2795. TEST_P(SecureNamingTest, TargetNameIsUnexpected) {
  2796. GTEST_FLAG_SET(death_test_style, "threadsafe");
  2797. CreateClientsAndServers(BootstrapBuilder(),
  2798. /*lb_expected_authority=*/"incorrect_server_name");
  2799. StartAllBackends();
  2800. EdsResourceArgs args({
  2801. {"locality0", CreateEndpointsForBackends()},
  2802. });
  2803. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  2804. // Make sure that we blow up (via abort() from the security connector) when
  2805. // the name from the balancer doesn't match expectations.
  2806. ASSERT_DEATH_IF_SUPPORTED({ CheckRpcSendOk(); }, "");
  2807. }
  2808. using LdsTest = BasicTest;
  2809. // Tests that LDS client should send a NACK if there is no API listener in the
  2810. // Listener in the LDS response.
  2811. TEST_P(LdsTest, NoApiListener) {
  2812. auto listener = default_listener_;
  2813. listener.clear_api_listener();
  2814. balancer_->ads_service()->SetLdsResource(listener);
  2815. const auto response_state = WaitForLdsNack();
  2816. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  2817. EXPECT_THAT(
  2818. response_state->error_message,
  2819. ::testing::HasSubstr("Listener has neither address nor ApiListener"));
  2820. }
  2821. // Tests that LDS client should send a NACK if the route_specifier in the
  2822. // http_connection_manager is neither inlined route_config nor RDS.
  2823. TEST_P(LdsTest, WrongRouteSpecifier) {
  2824. auto listener = default_listener_;
  2825. HttpConnectionManager http_connection_manager;
  2826. listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
  2827. &http_connection_manager);
  2828. http_connection_manager.mutable_scoped_routes();
  2829. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  2830. http_connection_manager);
  2831. balancer_->ads_service()->SetLdsResource(listener);
  2832. const auto response_state = WaitForLdsNack();
  2833. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  2834. EXPECT_THAT(
  2835. response_state->error_message,
  2836. ::testing::HasSubstr(
  2837. "HttpConnectionManager neither has inlined route_config nor RDS."));
  2838. }
  2839. // Tests that LDS client should send a NACK if the rds message in the
  2840. // http_connection_manager is missing the config_source field.
  2841. TEST_P(LdsTest, RdsMissingConfigSource) {
  2842. auto listener = default_listener_;
  2843. HttpConnectionManager http_connection_manager;
  2844. listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
  2845. &http_connection_manager);
  2846. http_connection_manager.mutable_rds()->set_route_config_name(
  2847. kDefaultRouteConfigurationName);
  2848. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  2849. http_connection_manager);
  2850. balancer_->ads_service()->SetLdsResource(listener);
  2851. const auto response_state = WaitForLdsNack();
  2852. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  2853. EXPECT_THAT(response_state->error_message,
  2854. ::testing::HasSubstr(
  2855. "HttpConnectionManager missing config_source for RDS."));
  2856. }
  2857. // Tests that LDS client should send a NACK if the rds message in the
  2858. // http_connection_manager has a config_source field that does not specify
  2859. // ADS or SELF.
  2860. TEST_P(LdsTest, RdsConfigSourceDoesNotSpecifyAdsOrSelf) {
  2861. auto listener = default_listener_;
  2862. HttpConnectionManager http_connection_manager;
  2863. listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
  2864. &http_connection_manager);
  2865. auto* rds = http_connection_manager.mutable_rds();
  2866. rds->set_route_config_name(kDefaultRouteConfigurationName);
  2867. rds->mutable_config_source()->set_path("/foo/bar");
  2868. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  2869. http_connection_manager);
  2870. balancer_->ads_service()->SetLdsResource(listener);
  2871. const auto response_state = WaitForLdsNack();
  2872. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  2873. EXPECT_THAT(response_state->error_message,
  2874. ::testing::HasSubstr("HttpConnectionManager ConfigSource for "
  2875. "RDS does not specify ADS or SELF."));
  2876. }
  2877. // Tests that LDS client accepts the rds message in the
  2878. // http_connection_manager with a config_source field that specifies ADS.
  2879. TEST_P(LdsTest, AcceptsRdsConfigSourceOfTypeAds) {
  2880. auto listener = default_listener_;
  2881. HttpConnectionManager http_connection_manager;
  2882. listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
  2883. &http_connection_manager);
  2884. auto* rds = http_connection_manager.mutable_rds();
  2885. rds->set_route_config_name(kDefaultRouteConfigurationName);
  2886. rds->mutable_config_source()->mutable_ads();
  2887. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  2888. http_connection_manager);
  2889. SetListenerAndRouteConfiguration(balancer_.get(), listener,
  2890. default_route_config_);
  2891. EdsResourceArgs args({{"locality0", CreateEndpointsForBackends()}});
  2892. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  2893. WaitForAllBackends();
  2894. auto response_state = balancer_->ads_service()->lds_response_state();
  2895. ASSERT_TRUE(response_state.has_value());
  2896. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  2897. }
  2898. // Tests that we NACK non-terminal filters at the end of the list.
  2899. TEST_P(LdsTest, NacksNonTerminalHttpFilterAtEndOfList) {
  2900. auto listener = default_listener_;
  2901. HttpConnectionManager http_connection_manager;
  2902. listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
  2903. &http_connection_manager);
  2904. auto* filter = http_connection_manager.mutable_http_filters(0);
  2905. filter->set_name("unknown");
  2906. filter->mutable_typed_config()->set_type_url(
  2907. "grpc.testing.client_only_http_filter");
  2908. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  2909. http_connection_manager);
  2910. SetListenerAndRouteConfiguration(balancer_.get(), listener,
  2911. default_route_config_);
  2912. const auto response_state = WaitForLdsNack();
  2913. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  2914. EXPECT_THAT(response_state->error_message,
  2915. ::testing::HasSubstr(
  2916. "non-terminal filter for config type grpc.testing"
  2917. ".client_only_http_filter is the last filter in the chain"));
  2918. }
  2919. // Test that we NACK terminal filters that are not at the end of the list.
  2920. TEST_P(LdsTest, NacksTerminalFilterBeforeEndOfList) {
  2921. auto listener = default_listener_;
  2922. HttpConnectionManager http_connection_manager;
  2923. listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
  2924. &http_connection_manager);
  2925. // The default_listener_ has a terminal router filter by default. Add an
  2926. // additional filter.
  2927. auto* filter = http_connection_manager.add_http_filters();
  2928. filter->set_name("grpc.testing.terminal_http_filter");
  2929. filter->mutable_typed_config()->set_type_url(
  2930. "grpc.testing.terminal_http_filter");
  2931. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  2932. http_connection_manager);
  2933. SetListenerAndRouteConfiguration(balancer_.get(), listener,
  2934. default_route_config_);
  2935. const auto response_state = WaitForLdsNack();
  2936. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  2937. EXPECT_THAT(
  2938. response_state->error_message,
  2939. ::testing::HasSubstr(
  2940. "terminal filter for config type envoy.extensions.filters.http"
  2941. ".router.v3.Router must be the last filter in the chain"));
  2942. }
  2943. // Test that we NACK empty filter names.
  2944. TEST_P(LdsTest, RejectsEmptyHttpFilterName) {
  2945. auto listener = default_listener_;
  2946. HttpConnectionManager http_connection_manager;
  2947. listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
  2948. &http_connection_manager);
  2949. *http_connection_manager.add_http_filters() =
  2950. http_connection_manager.http_filters(0);
  2951. auto* filter = http_connection_manager.mutable_http_filters(0);
  2952. filter->Clear();
  2953. filter->mutable_typed_config()->PackFrom(Listener());
  2954. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  2955. http_connection_manager);
  2956. SetListenerAndRouteConfiguration(balancer_.get(), listener,
  2957. default_route_config_);
  2958. const auto response_state = WaitForLdsNack();
  2959. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  2960. EXPECT_THAT(response_state->error_message,
  2961. ::testing::HasSubstr("empty filter name at index 0"));
  2962. }
  2963. // Test that we NACK duplicate HTTP filter names.
  2964. TEST_P(LdsTest, RejectsDuplicateHttpFilterName) {
  2965. auto listener = default_listener_;
  2966. HttpConnectionManager http_connection_manager;
  2967. listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
  2968. &http_connection_manager);
  2969. *http_connection_manager.add_http_filters() =
  2970. http_connection_manager.http_filters(0);
  2971. http_connection_manager.mutable_http_filters(0)
  2972. ->mutable_typed_config()
  2973. ->PackFrom(HTTPFault());
  2974. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  2975. http_connection_manager);
  2976. SetListenerAndRouteConfiguration(balancer_.get(), listener,
  2977. default_route_config_);
  2978. const auto response_state = WaitForLdsNack();
  2979. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  2980. EXPECT_THAT(response_state->error_message,
  2981. ::testing::HasSubstr("duplicate HTTP filter name: router"));
  2982. }
  2983. // Test that we NACK unknown filter types.
  2984. TEST_P(LdsTest, RejectsUnknownHttpFilterType) {
  2985. auto listener = default_listener_;
  2986. HttpConnectionManager http_connection_manager;
  2987. listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
  2988. &http_connection_manager);
  2989. *http_connection_manager.add_http_filters() =
  2990. http_connection_manager.http_filters(0);
  2991. auto* filter = http_connection_manager.mutable_http_filters(0);
  2992. filter->set_name("unknown");
  2993. filter->mutable_typed_config()->PackFrom(Listener());
  2994. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  2995. http_connection_manager);
  2996. SetListenerAndRouteConfiguration(balancer_.get(), listener,
  2997. default_route_config_);
  2998. const auto response_state = WaitForLdsNack();
  2999. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  3000. EXPECT_THAT(response_state->error_message,
  3001. ::testing::HasSubstr("no filter registered for config type "
  3002. "envoy.config.listener.v3.Listener"));
  3003. }
  3004. // Test that we ignore optional unknown filter types.
  3005. TEST_P(LdsTest, IgnoresOptionalUnknownHttpFilterType) {
  3006. auto listener = default_listener_;
  3007. HttpConnectionManager http_connection_manager;
  3008. listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
  3009. &http_connection_manager);
  3010. *http_connection_manager.add_http_filters() =
  3011. http_connection_manager.http_filters(0);
  3012. auto* filter = http_connection_manager.mutable_http_filters(0);
  3013. filter->set_name("unknown");
  3014. filter->mutable_typed_config()->PackFrom(Listener());
  3015. filter->set_is_optional(true);
  3016. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  3017. http_connection_manager);
  3018. SetListenerAndRouteConfiguration(balancer_.get(), listener,
  3019. default_route_config_);
  3020. EdsResourceArgs args({
  3021. {"locality0", CreateEndpointsForBackends()},
  3022. });
  3023. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  3024. WaitForAllBackends();
  3025. auto response_state = balancer_->ads_service()->lds_response_state();
  3026. ASSERT_TRUE(response_state.has_value());
  3027. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  3028. }
  3029. // Test that we NACK filters without configs.
  3030. TEST_P(LdsTest, RejectsHttpFilterWithoutConfig) {
  3031. auto listener = default_listener_;
  3032. HttpConnectionManager http_connection_manager;
  3033. listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
  3034. &http_connection_manager);
  3035. *http_connection_manager.add_http_filters() =
  3036. http_connection_manager.http_filters(0);
  3037. auto* filter = http_connection_manager.mutable_http_filters(0);
  3038. filter->Clear();
  3039. filter->set_name("unknown");
  3040. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  3041. http_connection_manager);
  3042. SetListenerAndRouteConfiguration(balancer_.get(), listener,
  3043. default_route_config_);
  3044. const auto response_state = WaitForLdsNack();
  3045. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  3046. EXPECT_THAT(response_state->error_message,
  3047. ::testing::HasSubstr(
  3048. "no filter config specified for filter name unknown"));
  3049. }
  3050. // Test that we ignore optional filters without configs.
  3051. TEST_P(LdsTest, IgnoresOptionalHttpFilterWithoutConfig) {
  3052. auto listener = default_listener_;
  3053. HttpConnectionManager http_connection_manager;
  3054. listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
  3055. &http_connection_manager);
  3056. *http_connection_manager.add_http_filters() =
  3057. http_connection_manager.http_filters(0);
  3058. auto* filter = http_connection_manager.mutable_http_filters(0);
  3059. filter->Clear();
  3060. filter->set_name("unknown");
  3061. filter->set_is_optional(true);
  3062. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  3063. http_connection_manager);
  3064. SetListenerAndRouteConfiguration(balancer_.get(), listener,
  3065. default_route_config_);
  3066. EdsResourceArgs args({
  3067. {"locality0", CreateEndpointsForBackends()},
  3068. });
  3069. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  3070. WaitForAllBackends();
  3071. auto response_state = balancer_->ads_service()->lds_response_state();
  3072. ASSERT_TRUE(response_state.has_value());
  3073. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  3074. }
  3075. // Test that we NACK unparseable filter configs.
  3076. TEST_P(LdsTest, RejectsUnparseableHttpFilterType) {
  3077. auto listener = default_listener_;
  3078. HttpConnectionManager http_connection_manager;
  3079. listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
  3080. &http_connection_manager);
  3081. *http_connection_manager.add_http_filters() =
  3082. http_connection_manager.http_filters(0);
  3083. auto* filter = http_connection_manager.mutable_http_filters(0);
  3084. filter->set_name("unknown");
  3085. filter->mutable_typed_config()->PackFrom(listener);
  3086. filter->mutable_typed_config()->set_type_url(
  3087. "type.googleapis.com/envoy.extensions.filters.http.fault.v3.HTTPFault");
  3088. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  3089. http_connection_manager);
  3090. SetListenerAndRouteConfiguration(balancer_.get(), listener,
  3091. default_route_config_);
  3092. const auto response_state = WaitForLdsNack();
  3093. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  3094. EXPECT_THAT(
  3095. response_state->error_message,
  3096. ::testing::HasSubstr(
  3097. "filter config for type "
  3098. "envoy.extensions.filters.http.fault.v3.HTTPFault failed to parse"));
  3099. }
  3100. // Test that we NACK HTTP filters unsupported on client-side.
  3101. TEST_P(LdsTest, RejectsHttpFiltersNotSupportedOnClients) {
  3102. auto listener = default_listener_;
  3103. HttpConnectionManager http_connection_manager;
  3104. listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
  3105. &http_connection_manager);
  3106. *http_connection_manager.add_http_filters() =
  3107. http_connection_manager.http_filters(0);
  3108. auto* filter = http_connection_manager.mutable_http_filters(0);
  3109. filter->set_name("grpc.testing.server_only_http_filter");
  3110. filter->mutable_typed_config()->set_type_url(
  3111. "grpc.testing.server_only_http_filter");
  3112. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  3113. http_connection_manager);
  3114. SetListenerAndRouteConfiguration(balancer_.get(), listener,
  3115. default_route_config_);
  3116. const auto response_state = WaitForLdsNack();
  3117. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  3118. EXPECT_THAT(
  3119. response_state->error_message,
  3120. ::testing::HasSubstr("Filter grpc.testing.server_only_http_filter is not "
  3121. "supported on clients"));
  3122. }
  3123. // Test that we ignore optional HTTP filters unsupported on client-side.
  3124. TEST_P(LdsTest, IgnoresOptionalHttpFiltersNotSupportedOnClients) {
  3125. auto listener = default_listener_;
  3126. HttpConnectionManager http_connection_manager;
  3127. listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
  3128. &http_connection_manager);
  3129. *http_connection_manager.add_http_filters() =
  3130. http_connection_manager.http_filters(0);
  3131. auto* filter = http_connection_manager.mutable_http_filters(0);
  3132. filter->set_name("grpc.testing.server_only_http_filter");
  3133. filter->mutable_typed_config()->set_type_url(
  3134. "grpc.testing.server_only_http_filter");
  3135. filter->set_is_optional(true);
  3136. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  3137. http_connection_manager);
  3138. SetListenerAndRouteConfiguration(balancer_.get(), listener,
  3139. default_route_config_);
  3140. EdsResourceArgs args({
  3141. {"locality0", CreateEndpointsForBackends(0, 1)},
  3142. });
  3143. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  3144. WaitForBackend(0);
  3145. auto response_state = balancer_->ads_service()->lds_response_state();
  3146. ASSERT_TRUE(response_state.has_value());
  3147. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  3148. }
  3149. // Test that we NACK non-zero xff_num_trusted_hops
  3150. TEST_P(LdsTest, RejectsNonZeroXffNumTrusterHops) {
  3151. auto listener = default_listener_;
  3152. HttpConnectionManager http_connection_manager;
  3153. listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
  3154. &http_connection_manager);
  3155. http_connection_manager.set_xff_num_trusted_hops(1);
  3156. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  3157. http_connection_manager);
  3158. SetListenerAndRouteConfiguration(balancer_.get(), listener,
  3159. default_route_config_);
  3160. const auto response_state = WaitForLdsNack();
  3161. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  3162. EXPECT_THAT(response_state->error_message,
  3163. ::testing::HasSubstr("'xff_num_trusted_hops' must be zero"));
  3164. }
  3165. // Test that we NACK non-empty original_ip_detection_extensions
  3166. TEST_P(LdsTest, RejectsNonEmptyOriginalIpDetectionExtensions) {
  3167. auto listener = default_listener_;
  3168. HttpConnectionManager http_connection_manager;
  3169. listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
  3170. &http_connection_manager);
  3171. http_connection_manager.add_original_ip_detection_extensions();
  3172. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  3173. http_connection_manager);
  3174. SetListenerAndRouteConfiguration(balancer_.get(), listener,
  3175. default_route_config_);
  3176. const auto response_state = WaitForLdsNack();
  3177. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  3178. EXPECT_THAT(
  3179. response_state->error_message,
  3180. ::testing::HasSubstr("'original_ip_detection_extensions' must be empty"));
  3181. }
  3182. using LdsV2Test = LdsTest;
  3183. // Tests that we ignore the HTTP filter list in v2.
  3184. // TODO(roth): The test framework is not set up to allow us to test
  3185. // the server sending v2 resources when the client requests v3, so this
  3186. // just tests a pure v2 setup. When we have time, fix this.
  3187. TEST_P(LdsV2Test, IgnoresHttpFilters) {
  3188. auto listener = default_listener_;
  3189. HttpConnectionManager http_connection_manager;
  3190. listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
  3191. &http_connection_manager);
  3192. auto* filter = http_connection_manager.add_http_filters();
  3193. filter->set_name("unknown");
  3194. filter->mutable_typed_config()->PackFrom(Listener());
  3195. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  3196. http_connection_manager);
  3197. SetListenerAndRouteConfiguration(balancer_.get(), listener,
  3198. default_route_config_);
  3199. EdsResourceArgs args({
  3200. {"locality0", CreateEndpointsForBackends(0, 1)},
  3201. });
  3202. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  3203. CheckRpcSendOk();
  3204. }
  3205. using LdsRdsTest = BasicTest;
  3206. MATCHER_P2(AdjustedClockInRange, t1, t2, "equals time") {
  3207. gpr_cycle_counter cycle_now = gpr_get_cycle_counter();
  3208. grpc_core::Timestamp cycle_time =
  3209. grpc_core::Timestamp::FromCycleCounterRoundDown(cycle_now);
  3210. grpc_core::Timestamp time_spec =
  3211. grpc_core::Timestamp::FromTimespecRoundDown(gpr_now(GPR_CLOCK_MONOTONIC));
  3212. grpc_core::Timestamp now = arg + (time_spec - cycle_time);
  3213. bool ok = true;
  3214. ok &= ::testing::ExplainMatchResult(::testing::Ge(t1), now, result_listener);
  3215. ok &= ::testing::ExplainMatchResult(::testing::Lt(t2), now, result_listener);
  3216. return ok;
  3217. }
  3218. // Tests that LDS client should send an ACK upon correct LDS response (with
  3219. // inlined RDS result).
  3220. TEST_P(LdsRdsTest, Vanilla) {
  3221. (void)SendRpc();
  3222. auto response_state = RouteConfigurationResponseState(balancer_.get());
  3223. ASSERT_TRUE(response_state.has_value());
  3224. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  3225. // Make sure we actually used the RPC service for the right version of xDS.
  3226. EXPECT_EQ(balancer_->ads_service()->seen_v2_client(), GetParam().use_v2());
  3227. EXPECT_NE(balancer_->ads_service()->seen_v3_client(), GetParam().use_v2());
  3228. }
  3229. // Tests that we go into TRANSIENT_FAILURE if the Listener is removed.
  3230. TEST_P(LdsRdsTest, ListenerRemoved) {
  3231. EdsResourceArgs args({
  3232. {"locality0", CreateEndpointsForBackends()},
  3233. });
  3234. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  3235. // We need to wait for all backends to come online.
  3236. WaitForAllBackends();
  3237. // Unset LDS resource.
  3238. balancer_->ads_service()->UnsetResource(kLdsTypeUrl, kServerName);
  3239. // Wait for RPCs to start failing.
  3240. do {
  3241. } while (SendRpc(RpcOptions(), nullptr).ok());
  3242. // Make sure RPCs are still failing.
  3243. CheckRpcSendFailure(CheckRpcSendFailureOptions().set_times(1000));
  3244. // Make sure we ACK'ed the update.
  3245. auto response_state = balancer_->ads_service()->lds_response_state();
  3246. ASSERT_TRUE(response_state.has_value());
  3247. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  3248. }
  3249. // Tests that LDS client ACKs but fails if matching domain can't be found in
  3250. // the LDS response.
  3251. TEST_P(LdsRdsTest, NoMatchedDomain) {
  3252. RouteConfiguration route_config = default_route_config_;
  3253. route_config.mutable_virtual_hosts(0)->clear_domains();
  3254. route_config.mutable_virtual_hosts(0)->add_domains("unmatched_domain");
  3255. SetRouteConfiguration(balancer_.get(), route_config);
  3256. CheckRpcSendFailure();
  3257. // Do a bit of polling, to allow the ACK to get to the ADS server.
  3258. channel_->WaitForConnected(grpc_timeout_milliseconds_to_deadline(100));
  3259. auto response_state = RouteConfigurationResponseState(balancer_.get());
  3260. ASSERT_TRUE(response_state.has_value());
  3261. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  3262. }
  3263. // Tests that LDS client should choose the virtual host with matching domain
  3264. // if multiple virtual hosts exist in the LDS response.
  3265. TEST_P(LdsRdsTest, ChooseMatchedDomain) {
  3266. RouteConfiguration route_config = default_route_config_;
  3267. *(route_config.add_virtual_hosts()) = route_config.virtual_hosts(0);
  3268. route_config.mutable_virtual_hosts(0)->clear_domains();
  3269. route_config.mutable_virtual_hosts(0)->add_domains("unmatched_domain");
  3270. SetRouteConfiguration(balancer_.get(), route_config);
  3271. (void)SendRpc();
  3272. auto response_state = RouteConfigurationResponseState(balancer_.get());
  3273. ASSERT_TRUE(response_state.has_value());
  3274. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  3275. }
  3276. // Tests that LDS client should choose the last route in the virtual host if
  3277. // multiple routes exist in the LDS response.
  3278. TEST_P(LdsRdsTest, ChooseLastRoute) {
  3279. RouteConfiguration route_config = default_route_config_;
  3280. *(route_config.mutable_virtual_hosts(0)->add_routes()) =
  3281. route_config.virtual_hosts(0).routes(0);
  3282. route_config.mutable_virtual_hosts(0)
  3283. ->mutable_routes(0)
  3284. ->mutable_route()
  3285. ->mutable_cluster_header();
  3286. SetRouteConfiguration(balancer_.get(), route_config);
  3287. (void)SendRpc();
  3288. auto response_state = RouteConfigurationResponseState(balancer_.get());
  3289. ASSERT_TRUE(response_state.has_value());
  3290. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  3291. }
  3292. // Tests that LDS client should ignore route which has query_parameters.
  3293. TEST_P(LdsRdsTest, RouteMatchHasQueryParameters) {
  3294. RouteConfiguration route_config = default_route_config_;
  3295. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3296. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3297. route1->mutable_match()->add_query_parameters();
  3298. SetRouteConfiguration(balancer_.get(), route_config);
  3299. const auto response_state = WaitForRdsNack();
  3300. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  3301. EXPECT_THAT(response_state->error_message,
  3302. ::testing::HasSubstr("No valid routes specified."));
  3303. }
  3304. // Tests that LDS client should send a ACK if route match has a prefix
  3305. // that is either empty or a single slash
  3306. TEST_P(LdsRdsTest, RouteMatchHasValidPrefixEmptyOrSingleSlash) {
  3307. RouteConfiguration route_config = default_route_config_;
  3308. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3309. route1->mutable_match()->set_prefix("");
  3310. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  3311. default_route->mutable_match()->set_prefix("/");
  3312. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3313. SetRouteConfiguration(balancer_.get(), route_config);
  3314. (void)SendRpc();
  3315. const auto response_state = RouteConfigurationResponseState(balancer_.get());
  3316. ASSERT_TRUE(response_state.has_value());
  3317. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  3318. }
  3319. // Tests that LDS client should ignore route which has a path
  3320. // prefix string does not start with "/".
  3321. TEST_P(LdsRdsTest, RouteMatchHasInvalidPrefixNoLeadingSlash) {
  3322. RouteConfiguration route_config = default_route_config_;
  3323. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3324. route1->mutable_match()->set_prefix("grpc.testing.EchoTest1Service/");
  3325. SetRouteConfiguration(balancer_.get(), route_config);
  3326. const auto response_state = WaitForRdsNack();
  3327. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  3328. EXPECT_THAT(response_state->error_message,
  3329. ::testing::HasSubstr("No valid routes specified."));
  3330. }
  3331. // Tests that LDS client should ignore route which has a prefix
  3332. // string with more than 2 slashes.
  3333. TEST_P(LdsRdsTest, RouteMatchHasInvalidPrefixExtraContent) {
  3334. RouteConfiguration route_config = default_route_config_;
  3335. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3336. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/Echo1/");
  3337. SetRouteConfiguration(balancer_.get(), route_config);
  3338. const auto response_state = WaitForRdsNack();
  3339. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  3340. EXPECT_THAT(response_state->error_message,
  3341. ::testing::HasSubstr("No valid routes specified."));
  3342. }
  3343. // Tests that LDS client should ignore route which has a prefix
  3344. // string "//".
  3345. TEST_P(LdsRdsTest, RouteMatchHasInvalidPrefixDoubleSlash) {
  3346. RouteConfiguration route_config = default_route_config_;
  3347. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3348. route1->mutable_match()->set_prefix("//");
  3349. SetRouteConfiguration(balancer_.get(), route_config);
  3350. const auto response_state = WaitForRdsNack();
  3351. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  3352. EXPECT_THAT(response_state->error_message,
  3353. ::testing::HasSubstr("No valid routes specified."));
  3354. }
  3355. // Tests that LDS client should ignore route which has path
  3356. // but it's empty.
  3357. TEST_P(LdsRdsTest, RouteMatchHasInvalidPathEmptyPath) {
  3358. RouteConfiguration route_config = default_route_config_;
  3359. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3360. route1->mutable_match()->set_path("");
  3361. SetRouteConfiguration(balancer_.get(), route_config);
  3362. const auto response_state = WaitForRdsNack();
  3363. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  3364. EXPECT_THAT(response_state->error_message,
  3365. ::testing::HasSubstr("No valid routes specified."));
  3366. }
  3367. // Tests that LDS client should ignore route which has path
  3368. // string does not start with "/".
  3369. TEST_P(LdsRdsTest, RouteMatchHasInvalidPathNoLeadingSlash) {
  3370. RouteConfiguration route_config = default_route_config_;
  3371. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3372. route1->mutable_match()->set_path("grpc.testing.EchoTest1Service/Echo1");
  3373. SetRouteConfiguration(balancer_.get(), route_config);
  3374. const auto response_state = WaitForRdsNack();
  3375. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  3376. EXPECT_THAT(response_state->error_message,
  3377. ::testing::HasSubstr("No valid routes specified."));
  3378. }
  3379. // Tests that LDS client should ignore route which has path
  3380. // string that has too many slashes; for example, ends with "/".
  3381. TEST_P(LdsRdsTest, RouteMatchHasInvalidPathTooManySlashes) {
  3382. RouteConfiguration route_config = default_route_config_;
  3383. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3384. route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service/Echo1/");
  3385. SetRouteConfiguration(balancer_.get(), route_config);
  3386. const auto response_state = WaitForRdsNack();
  3387. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  3388. EXPECT_THAT(response_state->error_message,
  3389. ::testing::HasSubstr("No valid routes specified."));
  3390. }
  3391. // Tests that LDS client should ignore route which has path
  3392. // string that has only 1 slash: missing "/" between service and method.
  3393. TEST_P(LdsRdsTest, RouteMatchHasInvalidPathOnlyOneSlash) {
  3394. RouteConfiguration route_config = default_route_config_;
  3395. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3396. route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service.Echo1");
  3397. SetRouteConfiguration(balancer_.get(), route_config);
  3398. const auto response_state = WaitForRdsNack();
  3399. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  3400. EXPECT_THAT(response_state->error_message,
  3401. ::testing::HasSubstr("No valid routes specified."));
  3402. }
  3403. // Tests that LDS client should ignore route which has path
  3404. // string that is missing service.
  3405. TEST_P(LdsRdsTest, RouteMatchHasInvalidPathMissingService) {
  3406. RouteConfiguration route_config = default_route_config_;
  3407. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3408. route1->mutable_match()->set_path("//Echo1");
  3409. SetRouteConfiguration(balancer_.get(), route_config);
  3410. const auto response_state = WaitForRdsNack();
  3411. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  3412. EXPECT_THAT(response_state->error_message,
  3413. ::testing::HasSubstr("No valid routes specified."));
  3414. }
  3415. // Tests that LDS client should ignore route which has path
  3416. // string that is missing method.
  3417. TEST_P(LdsRdsTest, RouteMatchHasInvalidPathMissingMethod) {
  3418. RouteConfiguration route_config = default_route_config_;
  3419. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3420. route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service/");
  3421. SetRouteConfiguration(balancer_.get(), route_config);
  3422. const auto response_state = WaitForRdsNack();
  3423. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  3424. EXPECT_THAT(response_state->error_message,
  3425. ::testing::HasSubstr("No valid routes specified."));
  3426. }
  3427. // Test that LDS client should reject route which has invalid path regex.
  3428. TEST_P(LdsRdsTest, RouteMatchHasInvalidPathRegex) {
  3429. const char* kNewCluster1Name = "new_cluster_1";
  3430. RouteConfiguration route_config = default_route_config_;
  3431. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3432. route1->mutable_match()->mutable_safe_regex()->set_regex("a[z-a]");
  3433. route1->mutable_route()->set_cluster(kNewCluster1Name);
  3434. SetRouteConfiguration(balancer_.get(), route_config);
  3435. const auto response_state = WaitForRdsNack();
  3436. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  3437. EXPECT_THAT(response_state->error_message,
  3438. ::testing::HasSubstr(
  3439. "path matcher: Invalid regex string specified in matcher."));
  3440. }
  3441. // Tests that LDS client should fail RPCs with UNAVAILABLE status code if the
  3442. // matching route has an action other than RouteAction.
  3443. TEST_P(LdsRdsTest, MatchingRouteHasNoRouteAction) {
  3444. RouteConfiguration route_config = default_route_config_;
  3445. // Set a route with an inappropriate route action
  3446. auto* vhost = route_config.mutable_virtual_hosts(0);
  3447. vhost->mutable_routes(0)->mutable_redirect();
  3448. // Add another route to make sure that the resolver code actually tries to
  3449. // match to a route instead of using a shorthand logic to error out.
  3450. auto* route = vhost->add_routes();
  3451. route->mutable_match()->set_prefix("");
  3452. route->mutable_route()->set_cluster(kDefaultClusterName);
  3453. SetRouteConfiguration(balancer_.get(), route_config);
  3454. CheckRpcSendFailure(CheckRpcSendFailureOptions().set_expected_error_code(
  3455. StatusCode::UNAVAILABLE));
  3456. }
  3457. TEST_P(LdsRdsTest, RouteActionClusterHasEmptyClusterName) {
  3458. RouteConfiguration route_config = default_route_config_;
  3459. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3460. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3461. route1->mutable_route()->set_cluster("");
  3462. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  3463. default_route->mutable_match()->set_prefix("");
  3464. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3465. SetRouteConfiguration(balancer_.get(), route_config);
  3466. const auto response_state = WaitForRdsNack();
  3467. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  3468. EXPECT_THAT(
  3469. response_state->error_message,
  3470. ::testing::HasSubstr("RouteAction cluster contains empty cluster name."));
  3471. }
  3472. TEST_P(LdsRdsTest, RouteActionWeightedTargetHasIncorrectTotalWeightSet) {
  3473. const size_t kWeight75 = 75;
  3474. const char* kNewCluster1Name = "new_cluster_1";
  3475. RouteConfiguration route_config = default_route_config_;
  3476. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3477. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3478. auto* weighted_cluster1 =
  3479. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3480. weighted_cluster1->set_name(kNewCluster1Name);
  3481. weighted_cluster1->mutable_weight()->set_value(kWeight75);
  3482. route1->mutable_route()
  3483. ->mutable_weighted_clusters()
  3484. ->mutable_total_weight()
  3485. ->set_value(kWeight75 + 1);
  3486. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  3487. default_route->mutable_match()->set_prefix("");
  3488. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3489. SetRouteConfiguration(balancer_.get(), route_config);
  3490. const auto response_state = WaitForRdsNack();
  3491. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  3492. EXPECT_THAT(response_state->error_message,
  3493. ::testing::HasSubstr(
  3494. "RouteAction weighted_cluster has incorrect total weight"));
  3495. }
  3496. TEST_P(LdsRdsTest, RouteActionWeightedClusterHasZeroTotalWeight) {
  3497. const char* kNewCluster1Name = "new_cluster_1";
  3498. RouteConfiguration route_config = default_route_config_;
  3499. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3500. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3501. auto* weighted_cluster1 =
  3502. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3503. weighted_cluster1->set_name(kNewCluster1Name);
  3504. weighted_cluster1->mutable_weight()->set_value(0);
  3505. route1->mutable_route()
  3506. ->mutable_weighted_clusters()
  3507. ->mutable_total_weight()
  3508. ->set_value(0);
  3509. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  3510. default_route->mutable_match()->set_prefix("");
  3511. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3512. SetRouteConfiguration(balancer_.get(), route_config);
  3513. const auto response_state = WaitForRdsNack();
  3514. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  3515. EXPECT_THAT(
  3516. response_state->error_message,
  3517. ::testing::HasSubstr(
  3518. "RouteAction weighted_cluster has no valid clusters specified."));
  3519. }
  3520. TEST_P(LdsRdsTest, RouteActionWeightedTargetClusterHasEmptyClusterName) {
  3521. const size_t kWeight75 = 75;
  3522. RouteConfiguration route_config = default_route_config_;
  3523. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3524. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3525. auto* weighted_cluster1 =
  3526. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3527. weighted_cluster1->set_name("");
  3528. weighted_cluster1->mutable_weight()->set_value(kWeight75);
  3529. route1->mutable_route()
  3530. ->mutable_weighted_clusters()
  3531. ->mutable_total_weight()
  3532. ->set_value(kWeight75);
  3533. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  3534. default_route->mutable_match()->set_prefix("");
  3535. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3536. SetRouteConfiguration(balancer_.get(), route_config);
  3537. const auto response_state = WaitForRdsNack();
  3538. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  3539. EXPECT_THAT(response_state->error_message,
  3540. ::testing::HasSubstr("RouteAction weighted_cluster cluster "
  3541. "contains empty cluster name."));
  3542. }
  3543. TEST_P(LdsRdsTest, RouteActionWeightedTargetClusterHasNoWeight) {
  3544. const size_t kWeight75 = 75;
  3545. const char* kNewCluster1Name = "new_cluster_1";
  3546. RouteConfiguration route_config = default_route_config_;
  3547. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3548. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3549. auto* weighted_cluster1 =
  3550. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3551. weighted_cluster1->set_name(kNewCluster1Name);
  3552. route1->mutable_route()
  3553. ->mutable_weighted_clusters()
  3554. ->mutable_total_weight()
  3555. ->set_value(kWeight75);
  3556. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  3557. default_route->mutable_match()->set_prefix("");
  3558. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3559. SetRouteConfiguration(balancer_.get(), route_config);
  3560. const auto response_state = WaitForRdsNack();
  3561. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  3562. EXPECT_THAT(response_state->error_message,
  3563. ::testing::HasSubstr(
  3564. "RouteAction weighted_cluster cluster missing weight"));
  3565. }
  3566. TEST_P(LdsRdsTest, RouteHeaderMatchInvalidRegex) {
  3567. const char* kNewCluster1Name = "new_cluster_1";
  3568. RouteConfiguration route_config = default_route_config_;
  3569. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3570. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3571. auto* header_matcher1 = route1->mutable_match()->add_headers();
  3572. header_matcher1->set_name("header1");
  3573. header_matcher1->mutable_safe_regex_match()->set_regex("a[z-a]");
  3574. route1->mutable_route()->set_cluster(kNewCluster1Name);
  3575. SetRouteConfiguration(balancer_.get(), route_config);
  3576. const auto response_state = WaitForRdsNack();
  3577. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  3578. EXPECT_THAT(
  3579. response_state->error_message,
  3580. ::testing::HasSubstr(
  3581. "header matcher: Invalid regex string specified in matcher."));
  3582. }
  3583. TEST_P(LdsRdsTest, RouteHeaderMatchInvalidRange) {
  3584. const char* kNewCluster1Name = "new_cluster_1";
  3585. RouteConfiguration route_config = default_route_config_;
  3586. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3587. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3588. auto* header_matcher1 = route1->mutable_match()->add_headers();
  3589. header_matcher1->set_name("header1");
  3590. header_matcher1->mutable_range_match()->set_start(1001);
  3591. header_matcher1->mutable_range_match()->set_end(1000);
  3592. route1->mutable_route()->set_cluster(kNewCluster1Name);
  3593. SetRouteConfiguration(balancer_.get(), route_config);
  3594. const auto response_state = WaitForRdsNack();
  3595. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  3596. EXPECT_THAT(
  3597. response_state->error_message,
  3598. ::testing::HasSubstr(
  3599. "header matcher: Invalid range specifier specified: end cannot be "
  3600. "smaller than start."));
  3601. }
  3602. // Tests that LDS client should choose the default route (with no matching
  3603. // specified) after unable to find a match with previous routes.
  3604. TEST_P(LdsRdsTest, XdsRoutingPathMatching) {
  3605. const char* kNewCluster1Name = "new_cluster_1";
  3606. const char* kNewEdsService1Name = "new_eds_service_name_1";
  3607. const char* kNewCluster2Name = "new_cluster_2";
  3608. const char* kNewEdsService2Name = "new_eds_service_name_2";
  3609. const size_t kNumEcho1Rpcs = 10;
  3610. const size_t kNumEcho2Rpcs = 20;
  3611. const size_t kNumEchoRpcs = 30;
  3612. // Populate new EDS resources.
  3613. EdsResourceArgs args({
  3614. {"locality0", CreateEndpointsForBackends(0, 2)},
  3615. });
  3616. EdsResourceArgs args1({
  3617. {"locality0", CreateEndpointsForBackends(2, 3)},
  3618. });
  3619. EdsResourceArgs args2({
  3620. {"locality0", CreateEndpointsForBackends(3, 4)},
  3621. });
  3622. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  3623. balancer_->ads_service()->SetEdsResource(
  3624. BuildEdsResource(args1, kNewEdsService1Name));
  3625. balancer_->ads_service()->SetEdsResource(
  3626. BuildEdsResource(args2, kNewEdsService2Name));
  3627. // Populate new CDS resources.
  3628. Cluster new_cluster1 = default_cluster_;
  3629. new_cluster1.set_name(kNewCluster1Name);
  3630. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  3631. kNewEdsService1Name);
  3632. balancer_->ads_service()->SetCdsResource(new_cluster1);
  3633. Cluster new_cluster2 = default_cluster_;
  3634. new_cluster2.set_name(kNewCluster2Name);
  3635. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  3636. kNewEdsService2Name);
  3637. balancer_->ads_service()->SetCdsResource(new_cluster2);
  3638. // Populating Route Configurations for LDS.
  3639. RouteConfiguration new_route_config = default_route_config_;
  3640. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3641. route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service/Echo1");
  3642. route1->mutable_route()->set_cluster(kNewCluster1Name);
  3643. auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3644. route2->mutable_match()->set_path("/grpc.testing.EchoTest2Service/Echo2");
  3645. route2->mutable_route()->set_cluster(kNewCluster2Name);
  3646. auto* route3 = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3647. route3->mutable_match()->set_path("/grpc.testing.EchoTest3Service/Echo3");
  3648. route3->mutable_route()->set_cluster(kDefaultClusterName);
  3649. auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3650. default_route->mutable_match()->set_prefix("");
  3651. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3652. SetRouteConfiguration(balancer_.get(), new_route_config);
  3653. WaitForAllBackends(0, 2);
  3654. CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
  3655. CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions()
  3656. .set_rpc_service(SERVICE_ECHO1)
  3657. .set_rpc_method(METHOD_ECHO1)
  3658. .set_wait_for_ready(true));
  3659. CheckRpcSendOk(kNumEcho2Rpcs, RpcOptions()
  3660. .set_rpc_service(SERVICE_ECHO2)
  3661. .set_rpc_method(METHOD_ECHO2)
  3662. .set_wait_for_ready(true));
  3663. // Make sure RPCs all go to the correct backend.
  3664. for (size_t i = 0; i < 2; ++i) {
  3665. EXPECT_EQ(kNumEchoRpcs / 2,
  3666. backends_[i]->backend_service()->request_count());
  3667. EXPECT_EQ(0, backends_[i]->backend_service1()->request_count());
  3668. EXPECT_EQ(0, backends_[i]->backend_service2()->request_count());
  3669. }
  3670. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  3671. EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
  3672. EXPECT_EQ(0, backends_[2]->backend_service2()->request_count());
  3673. EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
  3674. EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
  3675. EXPECT_EQ(kNumEcho2Rpcs, backends_[3]->backend_service2()->request_count());
  3676. }
  3677. TEST_P(LdsRdsTest, XdsRoutingPathMatchingCaseInsensitive) {
  3678. const char* kNewCluster1Name = "new_cluster_1";
  3679. const char* kNewEdsService1Name = "new_eds_service_name_1";
  3680. const char* kNewCluster2Name = "new_cluster_2";
  3681. const char* kNewEdsService2Name = "new_eds_service_name_2";
  3682. const size_t kNumEcho1Rpcs = 10;
  3683. const size_t kNumEchoRpcs = 30;
  3684. // Populate new EDS resources.
  3685. EdsResourceArgs args({
  3686. {"locality0", CreateEndpointsForBackends(0, 1)},
  3687. });
  3688. EdsResourceArgs args1({
  3689. {"locality0", CreateEndpointsForBackends(1, 2)},
  3690. });
  3691. EdsResourceArgs args2({
  3692. {"locality0", CreateEndpointsForBackends(2, 3)},
  3693. });
  3694. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  3695. balancer_->ads_service()->SetEdsResource(
  3696. BuildEdsResource(args1, kNewEdsService1Name));
  3697. balancer_->ads_service()->SetEdsResource(
  3698. BuildEdsResource(args2, kNewEdsService2Name));
  3699. // Populate new CDS resources.
  3700. Cluster new_cluster1 = default_cluster_;
  3701. new_cluster1.set_name(kNewCluster1Name);
  3702. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  3703. kNewEdsService1Name);
  3704. balancer_->ads_service()->SetCdsResource(new_cluster1);
  3705. Cluster new_cluster2 = default_cluster_;
  3706. new_cluster2.set_name(kNewCluster2Name);
  3707. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  3708. kNewEdsService2Name);
  3709. balancer_->ads_service()->SetCdsResource(new_cluster2);
  3710. // Populating Route Configurations for LDS.
  3711. RouteConfiguration new_route_config = default_route_config_;
  3712. // First route will not match, since it's case-sensitive.
  3713. // Second route will match with same path.
  3714. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3715. route1->mutable_match()->set_path("/GrPc.TeStInG.EcHoTeSt1SErViCe/EcHo1");
  3716. route1->mutable_route()->set_cluster(kNewCluster1Name);
  3717. auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3718. route2->mutable_match()->set_path("/GrPc.TeStInG.EcHoTeSt1SErViCe/EcHo1");
  3719. route2->mutable_match()->mutable_case_sensitive()->set_value(false);
  3720. route2->mutable_route()->set_cluster(kNewCluster2Name);
  3721. auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3722. default_route->mutable_match()->set_prefix("");
  3723. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3724. SetRouteConfiguration(balancer_.get(), new_route_config);
  3725. CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
  3726. CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions()
  3727. .set_rpc_service(SERVICE_ECHO1)
  3728. .set_rpc_method(METHOD_ECHO1)
  3729. .set_wait_for_ready(true));
  3730. // Make sure RPCs all go to the correct backend.
  3731. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  3732. EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
  3733. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  3734. EXPECT_EQ(0, backends_[1]->backend_service1()->request_count());
  3735. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  3736. EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
  3737. }
  3738. TEST_P(LdsRdsTest, XdsRoutingPrefixMatching) {
  3739. const char* kNewCluster1Name = "new_cluster_1";
  3740. const char* kNewEdsService1Name = "new_eds_service_name_1";
  3741. const char* kNewCluster2Name = "new_cluster_2";
  3742. const char* kNewEdsService2Name = "new_eds_service_name_2";
  3743. const size_t kNumEcho1Rpcs = 10;
  3744. const size_t kNumEcho2Rpcs = 20;
  3745. const size_t kNumEchoRpcs = 30;
  3746. // Populate new EDS resources.
  3747. EdsResourceArgs args({
  3748. {"locality0", CreateEndpointsForBackends(0, 2)},
  3749. });
  3750. EdsResourceArgs args1({
  3751. {"locality0", CreateEndpointsForBackends(2, 3)},
  3752. });
  3753. EdsResourceArgs args2({
  3754. {"locality0", CreateEndpointsForBackends(3, 4)},
  3755. });
  3756. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  3757. balancer_->ads_service()->SetEdsResource(
  3758. BuildEdsResource(args1, kNewEdsService1Name));
  3759. balancer_->ads_service()->SetEdsResource(
  3760. BuildEdsResource(args2, kNewEdsService2Name));
  3761. // Populate new CDS resources.
  3762. Cluster new_cluster1 = default_cluster_;
  3763. new_cluster1.set_name(kNewCluster1Name);
  3764. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  3765. kNewEdsService1Name);
  3766. balancer_->ads_service()->SetCdsResource(new_cluster1);
  3767. Cluster new_cluster2 = default_cluster_;
  3768. new_cluster2.set_name(kNewCluster2Name);
  3769. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  3770. kNewEdsService2Name);
  3771. balancer_->ads_service()->SetCdsResource(new_cluster2);
  3772. // Populating Route Configurations for LDS.
  3773. RouteConfiguration new_route_config = default_route_config_;
  3774. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3775. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3776. route1->mutable_route()->set_cluster(kNewCluster1Name);
  3777. auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3778. route2->mutable_match()->set_prefix("/grpc.testing.EchoTest2Service/");
  3779. route2->mutable_route()->set_cluster(kNewCluster2Name);
  3780. auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3781. default_route->mutable_match()->set_prefix("");
  3782. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3783. SetRouteConfiguration(balancer_.get(), new_route_config);
  3784. WaitForAllBackends(0, 2);
  3785. CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
  3786. CheckRpcSendOk(
  3787. kNumEcho1Rpcs,
  3788. RpcOptions().set_rpc_service(SERVICE_ECHO1).set_wait_for_ready(true));
  3789. CheckRpcSendOk(
  3790. kNumEcho2Rpcs,
  3791. RpcOptions().set_rpc_service(SERVICE_ECHO2).set_wait_for_ready(true));
  3792. // Make sure RPCs all go to the correct backend.
  3793. for (size_t i = 0; i < 2; ++i) {
  3794. EXPECT_EQ(kNumEchoRpcs / 2,
  3795. backends_[i]->backend_service()->request_count());
  3796. EXPECT_EQ(0, backends_[i]->backend_service1()->request_count());
  3797. EXPECT_EQ(0, backends_[i]->backend_service2()->request_count());
  3798. }
  3799. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  3800. EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
  3801. EXPECT_EQ(0, backends_[2]->backend_service2()->request_count());
  3802. EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
  3803. EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
  3804. EXPECT_EQ(kNumEcho2Rpcs, backends_[3]->backend_service2()->request_count());
  3805. }
  3806. TEST_P(LdsRdsTest, XdsRoutingPrefixMatchingCaseInsensitive) {
  3807. const char* kNewCluster1Name = "new_cluster_1";
  3808. const char* kNewEdsService1Name = "new_eds_service_name_1";
  3809. const char* kNewCluster2Name = "new_cluster_2";
  3810. const char* kNewEdsService2Name = "new_eds_service_name_2";
  3811. const size_t kNumEcho1Rpcs = 10;
  3812. const size_t kNumEchoRpcs = 30;
  3813. // Populate new EDS resources.
  3814. EdsResourceArgs args({
  3815. {"locality0", CreateEndpointsForBackends(0, 1)},
  3816. });
  3817. EdsResourceArgs args1({
  3818. {"locality0", CreateEndpointsForBackends(1, 2)},
  3819. });
  3820. EdsResourceArgs args2({
  3821. {"locality0", CreateEndpointsForBackends(2, 3)},
  3822. });
  3823. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  3824. balancer_->ads_service()->SetEdsResource(
  3825. BuildEdsResource(args1, kNewEdsService1Name));
  3826. balancer_->ads_service()->SetEdsResource(
  3827. BuildEdsResource(args2, kNewEdsService2Name));
  3828. // Populate new CDS resources.
  3829. Cluster new_cluster1 = default_cluster_;
  3830. new_cluster1.set_name(kNewCluster1Name);
  3831. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  3832. kNewEdsService1Name);
  3833. balancer_->ads_service()->SetCdsResource(new_cluster1);
  3834. Cluster new_cluster2 = default_cluster_;
  3835. new_cluster2.set_name(kNewCluster2Name);
  3836. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  3837. kNewEdsService2Name);
  3838. balancer_->ads_service()->SetCdsResource(new_cluster2);
  3839. // Populating Route Configurations for LDS.
  3840. RouteConfiguration new_route_config = default_route_config_;
  3841. // First route will not match, since it's case-sensitive.
  3842. // Second route will match with same path.
  3843. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3844. route1->mutable_match()->set_prefix("/GrPc.TeStInG.EcHoTeSt1SErViCe");
  3845. route1->mutable_route()->set_cluster(kNewCluster1Name);
  3846. auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3847. route2->mutable_match()->set_prefix("/GrPc.TeStInG.EcHoTeSt1SErViCe");
  3848. route2->mutable_match()->mutable_case_sensitive()->set_value(false);
  3849. route2->mutable_route()->set_cluster(kNewCluster2Name);
  3850. auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3851. default_route->mutable_match()->set_prefix("");
  3852. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3853. SetRouteConfiguration(balancer_.get(), new_route_config);
  3854. CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
  3855. CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions()
  3856. .set_rpc_service(SERVICE_ECHO1)
  3857. .set_rpc_method(METHOD_ECHO1)
  3858. .set_wait_for_ready(true));
  3859. // Make sure RPCs all go to the correct backend.
  3860. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  3861. EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
  3862. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  3863. EXPECT_EQ(0, backends_[1]->backend_service1()->request_count());
  3864. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  3865. EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
  3866. }
  3867. TEST_P(LdsRdsTest, XdsRoutingPathRegexMatching) {
  3868. const char* kNewCluster1Name = "new_cluster_1";
  3869. const char* kNewEdsService1Name = "new_eds_service_name_1";
  3870. const char* kNewCluster2Name = "new_cluster_2";
  3871. const char* kNewEdsService2Name = "new_eds_service_name_2";
  3872. const size_t kNumEcho1Rpcs = 10;
  3873. const size_t kNumEcho2Rpcs = 20;
  3874. const size_t kNumEchoRpcs = 30;
  3875. // Populate new EDS resources.
  3876. EdsResourceArgs args({
  3877. {"locality0", CreateEndpointsForBackends(0, 2)},
  3878. });
  3879. EdsResourceArgs args1({
  3880. {"locality0", CreateEndpointsForBackends(2, 3)},
  3881. });
  3882. EdsResourceArgs args2({
  3883. {"locality0", CreateEndpointsForBackends(3, 4)},
  3884. });
  3885. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  3886. balancer_->ads_service()->SetEdsResource(
  3887. BuildEdsResource(args1, kNewEdsService1Name));
  3888. balancer_->ads_service()->SetEdsResource(
  3889. BuildEdsResource(args2, kNewEdsService2Name));
  3890. // Populate new CDS resources.
  3891. Cluster new_cluster1 = default_cluster_;
  3892. new_cluster1.set_name(kNewCluster1Name);
  3893. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  3894. kNewEdsService1Name);
  3895. balancer_->ads_service()->SetCdsResource(new_cluster1);
  3896. Cluster new_cluster2 = default_cluster_;
  3897. new_cluster2.set_name(kNewCluster2Name);
  3898. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  3899. kNewEdsService2Name);
  3900. balancer_->ads_service()->SetCdsResource(new_cluster2);
  3901. // Populating Route Configurations for LDS.
  3902. RouteConfiguration new_route_config = default_route_config_;
  3903. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3904. // Will match "/grpc.testing.EchoTest1Service/"
  3905. route1->mutable_match()->mutable_safe_regex()->set_regex(".*1.*");
  3906. route1->mutable_route()->set_cluster(kNewCluster1Name);
  3907. auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3908. // Will match "/grpc.testing.EchoTest2Service/"
  3909. route2->mutable_match()->mutable_safe_regex()->set_regex(".*2.*");
  3910. route2->mutable_route()->set_cluster(kNewCluster2Name);
  3911. auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3912. default_route->mutable_match()->set_prefix("");
  3913. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  3914. SetRouteConfiguration(balancer_.get(), new_route_config);
  3915. WaitForAllBackends(0, 2);
  3916. CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_wait_for_ready(true));
  3917. CheckRpcSendOk(
  3918. kNumEcho1Rpcs,
  3919. RpcOptions().set_rpc_service(SERVICE_ECHO1).set_wait_for_ready(true));
  3920. CheckRpcSendOk(
  3921. kNumEcho2Rpcs,
  3922. RpcOptions().set_rpc_service(SERVICE_ECHO2).set_wait_for_ready(true));
  3923. // Make sure RPCs all go to the correct backend.
  3924. for (size_t i = 0; i < 2; ++i) {
  3925. EXPECT_EQ(kNumEchoRpcs / 2,
  3926. backends_[i]->backend_service()->request_count());
  3927. EXPECT_EQ(0, backends_[i]->backend_service1()->request_count());
  3928. EXPECT_EQ(0, backends_[i]->backend_service2()->request_count());
  3929. }
  3930. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  3931. EXPECT_EQ(kNumEcho1Rpcs, backends_[2]->backend_service1()->request_count());
  3932. EXPECT_EQ(0, backends_[2]->backend_service2()->request_count());
  3933. EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
  3934. EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
  3935. EXPECT_EQ(kNumEcho2Rpcs, backends_[3]->backend_service2()->request_count());
  3936. }
  3937. TEST_P(LdsRdsTest, XdsRoutingWeightedCluster) {
  3938. const char* kNewCluster1Name = "new_cluster_1";
  3939. const char* kNewEdsService1Name = "new_eds_service_name_1";
  3940. const char* kNewCluster2Name = "new_cluster_2";
  3941. const char* kNewEdsService2Name = "new_eds_service_name_2";
  3942. const char* kNotUsedClusterName = "not_used_cluster";
  3943. const size_t kNumEchoRpcs = 10; // RPCs that will go to a fixed backend.
  3944. const size_t kWeight75 = 75;
  3945. const size_t kWeight25 = 25;
  3946. const double kErrorTolerance = 0.05;
  3947. const double kWeight75Percent = static_cast<double>(kWeight75) / 100;
  3948. const double kWeight25Percent = static_cast<double>(kWeight25) / 100;
  3949. const size_t kNumEcho1Rpcs =
  3950. ComputeIdealNumRpcs(kWeight75Percent, kErrorTolerance);
  3951. // Populate new EDS resources.
  3952. EdsResourceArgs args({
  3953. {"locality0", CreateEndpointsForBackends(0, 1)},
  3954. });
  3955. EdsResourceArgs args1({
  3956. {"locality0", CreateEndpointsForBackends(1, 2)},
  3957. });
  3958. EdsResourceArgs args2({
  3959. {"locality0", CreateEndpointsForBackends(2, 3)},
  3960. });
  3961. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  3962. balancer_->ads_service()->SetEdsResource(
  3963. BuildEdsResource(args1, kNewEdsService1Name));
  3964. balancer_->ads_service()->SetEdsResource(
  3965. BuildEdsResource(args2, kNewEdsService2Name));
  3966. // Populate new CDS resources.
  3967. Cluster new_cluster1 = default_cluster_;
  3968. new_cluster1.set_name(kNewCluster1Name);
  3969. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  3970. kNewEdsService1Name);
  3971. balancer_->ads_service()->SetCdsResource(new_cluster1);
  3972. Cluster new_cluster2 = default_cluster_;
  3973. new_cluster2.set_name(kNewCluster2Name);
  3974. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  3975. kNewEdsService2Name);
  3976. balancer_->ads_service()->SetCdsResource(new_cluster2);
  3977. // Populating Route Configurations for LDS.
  3978. RouteConfiguration new_route_config = default_route_config_;
  3979. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  3980. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  3981. auto* weighted_cluster1 =
  3982. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3983. weighted_cluster1->set_name(kNewCluster1Name);
  3984. weighted_cluster1->mutable_weight()->set_value(kWeight75);
  3985. auto* weighted_cluster2 =
  3986. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3987. weighted_cluster2->set_name(kNewCluster2Name);
  3988. weighted_cluster2->mutable_weight()->set_value(kWeight25);
  3989. // Cluster with weight 0 will not be used.
  3990. auto* weighted_cluster3 =
  3991. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  3992. weighted_cluster3->set_name(kNotUsedClusterName);
  3993. weighted_cluster3->mutable_weight()->set_value(0);
  3994. route1->mutable_route()
  3995. ->mutable_weighted_clusters()
  3996. ->mutable_total_weight()
  3997. ->set_value(kWeight75 + kWeight25);
  3998. auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
  3999. default_route->mutable_match()->set_prefix("");
  4000. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  4001. SetRouteConfiguration(balancer_.get(), new_route_config);
  4002. WaitForAllBackends(0, 1);
  4003. WaitForAllBackends(1, 3, WaitForBackendOptions(),
  4004. RpcOptions().set_rpc_service(SERVICE_ECHO1));
  4005. CheckRpcSendOk(kNumEchoRpcs);
  4006. CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions().set_rpc_service(SERVICE_ECHO1));
  4007. // Make sure RPCs all go to the correct backend.
  4008. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  4009. EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
  4010. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  4011. const int weight_75_request_count =
  4012. backends_[1]->backend_service1()->request_count();
  4013. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  4014. const int weight_25_request_count =
  4015. backends_[2]->backend_service1()->request_count();
  4016. gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
  4017. weight_75_request_count, weight_25_request_count);
  4018. EXPECT_THAT(static_cast<double>(weight_75_request_count) / kNumEcho1Rpcs,
  4019. ::testing::DoubleNear(kWeight75Percent, kErrorTolerance));
  4020. EXPECT_THAT(static_cast<double>(weight_25_request_count) / kNumEcho1Rpcs,
  4021. ::testing::DoubleNear(kWeight25Percent, kErrorTolerance));
  4022. }
  4023. TEST_P(LdsRdsTest, RouteActionWeightedTargetDefaultRoute) {
  4024. const char* kNewCluster1Name = "new_cluster_1";
  4025. const char* kNewEdsService1Name = "new_eds_service_name_1";
  4026. const char* kNewCluster2Name = "new_cluster_2";
  4027. const char* kNewEdsService2Name = "new_eds_service_name_2";
  4028. const size_t kWeight75 = 75;
  4029. const size_t kWeight25 = 25;
  4030. const double kErrorTolerance = 0.05;
  4031. const double kWeight75Percent = static_cast<double>(kWeight75) / 100;
  4032. const double kWeight25Percent = static_cast<double>(kWeight25) / 100;
  4033. const size_t kNumEchoRpcs =
  4034. ComputeIdealNumRpcs(kWeight75Percent, kErrorTolerance);
  4035. // Populate new EDS resources.
  4036. EdsResourceArgs args({
  4037. {"locality0", CreateEndpointsForBackends(0, 1)},
  4038. });
  4039. EdsResourceArgs args1({
  4040. {"locality0", CreateEndpointsForBackends(1, 2)},
  4041. });
  4042. EdsResourceArgs args2({
  4043. {"locality0", CreateEndpointsForBackends(2, 3)},
  4044. });
  4045. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  4046. balancer_->ads_service()->SetEdsResource(
  4047. BuildEdsResource(args1, kNewEdsService1Name));
  4048. balancer_->ads_service()->SetEdsResource(
  4049. BuildEdsResource(args2, kNewEdsService2Name));
  4050. // Populate new CDS resources.
  4051. Cluster new_cluster1 = default_cluster_;
  4052. new_cluster1.set_name(kNewCluster1Name);
  4053. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  4054. kNewEdsService1Name);
  4055. balancer_->ads_service()->SetCdsResource(new_cluster1);
  4056. Cluster new_cluster2 = default_cluster_;
  4057. new_cluster2.set_name(kNewCluster2Name);
  4058. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  4059. kNewEdsService2Name);
  4060. balancer_->ads_service()->SetCdsResource(new_cluster2);
  4061. // Populating Route Configurations for LDS.
  4062. RouteConfiguration new_route_config = default_route_config_;
  4063. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  4064. route1->mutable_match()->set_prefix("");
  4065. auto* weighted_cluster1 =
  4066. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  4067. weighted_cluster1->set_name(kNewCluster1Name);
  4068. weighted_cluster1->mutable_weight()->set_value(kWeight75);
  4069. auto* weighted_cluster2 =
  4070. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  4071. weighted_cluster2->set_name(kNewCluster2Name);
  4072. weighted_cluster2->mutable_weight()->set_value(kWeight25);
  4073. route1->mutable_route()
  4074. ->mutable_weighted_clusters()
  4075. ->mutable_total_weight()
  4076. ->set_value(kWeight75 + kWeight25);
  4077. SetRouteConfiguration(balancer_.get(), new_route_config);
  4078. WaitForAllBackends(1, 3);
  4079. CheckRpcSendOk(kNumEchoRpcs);
  4080. // Make sure RPCs all go to the correct backend.
  4081. EXPECT_EQ(0, backends_[0]->backend_service()->request_count());
  4082. const int weight_75_request_count =
  4083. backends_[1]->backend_service()->request_count();
  4084. const int weight_25_request_count =
  4085. backends_[2]->backend_service()->request_count();
  4086. gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
  4087. weight_75_request_count, weight_25_request_count);
  4088. EXPECT_THAT(static_cast<double>(weight_75_request_count) / kNumEchoRpcs,
  4089. ::testing::DoubleNear(kWeight75Percent, kErrorTolerance));
  4090. EXPECT_THAT(static_cast<double>(weight_25_request_count) / kNumEchoRpcs,
  4091. ::testing::DoubleNear(kWeight25Percent, kErrorTolerance));
  4092. }
  4093. TEST_P(LdsRdsTest, XdsRoutingWeightedClusterUpdateWeights) {
  4094. const char* kNewCluster1Name = "new_cluster_1";
  4095. const char* kNewEdsService1Name = "new_eds_service_name_1";
  4096. const char* kNewCluster2Name = "new_cluster_2";
  4097. const char* kNewEdsService2Name = "new_eds_service_name_2";
  4098. const char* kNewCluster3Name = "new_cluster_3";
  4099. const char* kNewEdsService3Name = "new_eds_service_name_3";
  4100. const size_t kNumEchoRpcs = 10;
  4101. const size_t kWeight75 = 75;
  4102. const size_t kWeight25 = 25;
  4103. const size_t kWeight50 = 50;
  4104. const double kErrorTolerance = 0.05;
  4105. const double kWeight75Percent = static_cast<double>(kWeight75) / 100;
  4106. const double kWeight25Percent = static_cast<double>(kWeight25) / 100;
  4107. const double kWeight50Percent = static_cast<double>(kWeight50) / 100;
  4108. const size_t kNumEcho1Rpcs7525 =
  4109. ComputeIdealNumRpcs(kWeight75Percent, kErrorTolerance);
  4110. const size_t kNumEcho1Rpcs5050 =
  4111. ComputeIdealNumRpcs(kWeight50Percent, kErrorTolerance);
  4112. // Populate new EDS resources.
  4113. EdsResourceArgs args({
  4114. {"locality0", CreateEndpointsForBackends(0, 1)},
  4115. });
  4116. EdsResourceArgs args1({
  4117. {"locality0", CreateEndpointsForBackends(1, 2)},
  4118. });
  4119. EdsResourceArgs args2({
  4120. {"locality0", CreateEndpointsForBackends(2, 3)},
  4121. });
  4122. EdsResourceArgs args3({
  4123. {"locality0", CreateEndpointsForBackends(3, 4)},
  4124. });
  4125. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  4126. balancer_->ads_service()->SetEdsResource(
  4127. BuildEdsResource(args1, kNewEdsService1Name));
  4128. balancer_->ads_service()->SetEdsResource(
  4129. BuildEdsResource(args2, kNewEdsService2Name));
  4130. balancer_->ads_service()->SetEdsResource(
  4131. BuildEdsResource(args3, kNewEdsService3Name));
  4132. // Populate new CDS resources.
  4133. Cluster new_cluster1 = default_cluster_;
  4134. new_cluster1.set_name(kNewCluster1Name);
  4135. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  4136. kNewEdsService1Name);
  4137. balancer_->ads_service()->SetCdsResource(new_cluster1);
  4138. Cluster new_cluster2 = default_cluster_;
  4139. new_cluster2.set_name(kNewCluster2Name);
  4140. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  4141. kNewEdsService2Name);
  4142. balancer_->ads_service()->SetCdsResource(new_cluster2);
  4143. Cluster new_cluster3 = default_cluster_;
  4144. new_cluster3.set_name(kNewCluster3Name);
  4145. new_cluster3.mutable_eds_cluster_config()->set_service_name(
  4146. kNewEdsService3Name);
  4147. balancer_->ads_service()->SetCdsResource(new_cluster3);
  4148. // Populating Route Configurations.
  4149. RouteConfiguration new_route_config = default_route_config_;
  4150. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  4151. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  4152. auto* weighted_cluster1 =
  4153. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  4154. weighted_cluster1->set_name(kNewCluster1Name);
  4155. weighted_cluster1->mutable_weight()->set_value(kWeight75);
  4156. auto* weighted_cluster2 =
  4157. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  4158. weighted_cluster2->set_name(kNewCluster2Name);
  4159. weighted_cluster2->mutable_weight()->set_value(kWeight25);
  4160. route1->mutable_route()
  4161. ->mutable_weighted_clusters()
  4162. ->mutable_total_weight()
  4163. ->set_value(kWeight75 + kWeight25);
  4164. auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
  4165. default_route->mutable_match()->set_prefix("");
  4166. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  4167. SetRouteConfiguration(balancer_.get(), new_route_config);
  4168. WaitForAllBackends(0, 1);
  4169. WaitForAllBackends(1, 3, WaitForBackendOptions(),
  4170. RpcOptions().set_rpc_service(SERVICE_ECHO1));
  4171. CheckRpcSendOk(kNumEchoRpcs);
  4172. CheckRpcSendOk(kNumEcho1Rpcs7525,
  4173. RpcOptions().set_rpc_service(SERVICE_ECHO1));
  4174. // Make sure RPCs all go to the correct backend.
  4175. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  4176. EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
  4177. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  4178. const int weight_75_request_count =
  4179. backends_[1]->backend_service1()->request_count();
  4180. EXPECT_EQ(0, backends_[1]->backend_service2()->request_count());
  4181. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  4182. const int weight_25_request_count =
  4183. backends_[2]->backend_service1()->request_count();
  4184. EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
  4185. EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
  4186. gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
  4187. weight_75_request_count, weight_25_request_count);
  4188. EXPECT_THAT(static_cast<double>(weight_75_request_count) / kNumEcho1Rpcs7525,
  4189. ::testing::DoubleNear(kWeight75Percent, kErrorTolerance));
  4190. EXPECT_THAT(static_cast<double>(weight_25_request_count) / kNumEcho1Rpcs7525,
  4191. ::testing::DoubleNear(kWeight25Percent, kErrorTolerance));
  4192. // Change Route Configurations: same clusters different weights.
  4193. weighted_cluster1->mutable_weight()->set_value(kWeight50);
  4194. weighted_cluster2->mutable_weight()->set_value(kWeight50);
  4195. // Change default route to a new cluster to help to identify when new
  4196. // polices are seen by the client.
  4197. default_route->mutable_route()->set_cluster(kNewCluster3Name);
  4198. SetRouteConfiguration(balancer_.get(), new_route_config);
  4199. ResetBackendCounters();
  4200. WaitForAllBackends(3, 4);
  4201. CheckRpcSendOk(kNumEchoRpcs);
  4202. CheckRpcSendOk(kNumEcho1Rpcs5050,
  4203. RpcOptions().set_rpc_service(SERVICE_ECHO1));
  4204. // Make sure RPCs all go to the correct backend.
  4205. EXPECT_EQ(0, backends_[0]->backend_service()->request_count());
  4206. EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
  4207. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  4208. const int weight_50_request_count_1 =
  4209. backends_[1]->backend_service1()->request_count();
  4210. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  4211. const int weight_50_request_count_2 =
  4212. backends_[2]->backend_service1()->request_count();
  4213. EXPECT_EQ(kNumEchoRpcs, backends_[3]->backend_service()->request_count());
  4214. EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
  4215. EXPECT_THAT(
  4216. static_cast<double>(weight_50_request_count_1) / kNumEcho1Rpcs5050,
  4217. ::testing::DoubleNear(kWeight50Percent, kErrorTolerance));
  4218. EXPECT_THAT(
  4219. static_cast<double>(weight_50_request_count_2) / kNumEcho1Rpcs5050,
  4220. ::testing::DoubleNear(kWeight50Percent, kErrorTolerance));
  4221. }
  4222. TEST_P(LdsRdsTest, XdsRoutingWeightedClusterUpdateClusters) {
  4223. const char* kNewCluster1Name = "new_cluster_1";
  4224. const char* kNewEdsService1Name = "new_eds_service_name_1";
  4225. const char* kNewCluster2Name = "new_cluster_2";
  4226. const char* kNewEdsService2Name = "new_eds_service_name_2";
  4227. const char* kNewCluster3Name = "new_cluster_3";
  4228. const char* kNewEdsService3Name = "new_eds_service_name_3";
  4229. const size_t kNumEchoRpcs = 10;
  4230. const size_t kWeight75 = 75;
  4231. const size_t kWeight25 = 25;
  4232. const size_t kWeight50 = 50;
  4233. const double kErrorTolerance = 0.05;
  4234. const double kWeight75Percent = static_cast<double>(kWeight75) / 100;
  4235. const double kWeight25Percent = static_cast<double>(kWeight25) / 100;
  4236. const double kWeight50Percent = static_cast<double>(kWeight50) / 100;
  4237. const size_t kNumEcho1Rpcs7525 =
  4238. ComputeIdealNumRpcs(kWeight75Percent, kErrorTolerance);
  4239. const size_t kNumEcho1Rpcs5050 =
  4240. ComputeIdealNumRpcs(kWeight50Percent, kErrorTolerance);
  4241. // Populate new EDS resources.
  4242. EdsResourceArgs args({
  4243. {"locality0", CreateEndpointsForBackends(0, 1)},
  4244. });
  4245. EdsResourceArgs args1({
  4246. {"locality0", CreateEndpointsForBackends(1, 2)},
  4247. });
  4248. EdsResourceArgs args2({
  4249. {"locality0", CreateEndpointsForBackends(2, 3)},
  4250. });
  4251. EdsResourceArgs args3({
  4252. {"locality0", CreateEndpointsForBackends(3, 4)},
  4253. });
  4254. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  4255. balancer_->ads_service()->SetEdsResource(
  4256. BuildEdsResource(args1, kNewEdsService1Name));
  4257. balancer_->ads_service()->SetEdsResource(
  4258. BuildEdsResource(args2, kNewEdsService2Name));
  4259. balancer_->ads_service()->SetEdsResource(
  4260. BuildEdsResource(args3, kNewEdsService3Name));
  4261. // Populate new CDS resources.
  4262. Cluster new_cluster1 = default_cluster_;
  4263. new_cluster1.set_name(kNewCluster1Name);
  4264. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  4265. kNewEdsService1Name);
  4266. balancer_->ads_service()->SetCdsResource(new_cluster1);
  4267. Cluster new_cluster2 = default_cluster_;
  4268. new_cluster2.set_name(kNewCluster2Name);
  4269. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  4270. kNewEdsService2Name);
  4271. balancer_->ads_service()->SetCdsResource(new_cluster2);
  4272. Cluster new_cluster3 = default_cluster_;
  4273. new_cluster3.set_name(kNewCluster3Name);
  4274. new_cluster3.mutable_eds_cluster_config()->set_service_name(
  4275. kNewEdsService3Name);
  4276. balancer_->ads_service()->SetCdsResource(new_cluster3);
  4277. // Populating Route Configurations.
  4278. RouteConfiguration new_route_config = default_route_config_;
  4279. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  4280. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  4281. auto* weighted_cluster1 =
  4282. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  4283. weighted_cluster1->set_name(kNewCluster1Name);
  4284. weighted_cluster1->mutable_weight()->set_value(kWeight75);
  4285. auto* weighted_cluster2 =
  4286. route1->mutable_route()->mutable_weighted_clusters()->add_clusters();
  4287. weighted_cluster2->set_name(kDefaultClusterName);
  4288. weighted_cluster2->mutable_weight()->set_value(kWeight25);
  4289. route1->mutable_route()
  4290. ->mutable_weighted_clusters()
  4291. ->mutable_total_weight()
  4292. ->set_value(kWeight75 + kWeight25);
  4293. auto* default_route = new_route_config.mutable_virtual_hosts(0)->add_routes();
  4294. default_route->mutable_match()->set_prefix("");
  4295. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  4296. SetRouteConfiguration(balancer_.get(), new_route_config);
  4297. WaitForBackend(0);
  4298. WaitForBackend(1, WaitForBackendOptions(),
  4299. RpcOptions().set_rpc_service(SERVICE_ECHO1));
  4300. CheckRpcSendOk(kNumEchoRpcs);
  4301. CheckRpcSendOk(kNumEcho1Rpcs7525,
  4302. RpcOptions().set_rpc_service(SERVICE_ECHO1));
  4303. // Make sure RPCs all go to the correct backend.
  4304. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  4305. int weight_25_request_count =
  4306. backends_[0]->backend_service1()->request_count();
  4307. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  4308. int weight_75_request_count =
  4309. backends_[1]->backend_service1()->request_count();
  4310. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  4311. EXPECT_EQ(0, backends_[2]->backend_service1()->request_count());
  4312. EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
  4313. EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
  4314. gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
  4315. weight_75_request_count, weight_25_request_count);
  4316. EXPECT_THAT(static_cast<double>(weight_75_request_count) / kNumEcho1Rpcs7525,
  4317. ::testing::DoubleNear(kWeight75Percent, kErrorTolerance));
  4318. EXPECT_THAT(static_cast<double>(weight_25_request_count) / kNumEcho1Rpcs7525,
  4319. ::testing::DoubleNear(kWeight25Percent, kErrorTolerance));
  4320. // Change Route Configurations: new set of clusters with different weights.
  4321. weighted_cluster1->mutable_weight()->set_value(kWeight50);
  4322. weighted_cluster2->set_name(kNewCluster2Name);
  4323. weighted_cluster2->mutable_weight()->set_value(kWeight50);
  4324. SetRouteConfiguration(balancer_.get(), new_route_config);
  4325. ResetBackendCounters();
  4326. WaitForBackend(2, WaitForBackendOptions(),
  4327. RpcOptions().set_rpc_service(SERVICE_ECHO1));
  4328. CheckRpcSendOk(kNumEchoRpcs);
  4329. CheckRpcSendOk(kNumEcho1Rpcs5050,
  4330. RpcOptions().set_rpc_service(SERVICE_ECHO1));
  4331. // Make sure RPCs all go to the correct backend.
  4332. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  4333. EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
  4334. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  4335. const int weight_50_request_count_1 =
  4336. backends_[1]->backend_service1()->request_count();
  4337. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  4338. const int weight_50_request_count_2 =
  4339. backends_[2]->backend_service1()->request_count();
  4340. EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
  4341. EXPECT_EQ(0, backends_[3]->backend_service1()->request_count());
  4342. EXPECT_THAT(
  4343. static_cast<double>(weight_50_request_count_1) / kNumEcho1Rpcs5050,
  4344. ::testing::DoubleNear(kWeight50Percent, kErrorTolerance));
  4345. EXPECT_THAT(
  4346. static_cast<double>(weight_50_request_count_2) / kNumEcho1Rpcs5050,
  4347. ::testing::DoubleNear(kWeight50Percent, kErrorTolerance));
  4348. // Change Route Configurations.
  4349. weighted_cluster1->mutable_weight()->set_value(kWeight75);
  4350. weighted_cluster2->set_name(kNewCluster3Name);
  4351. weighted_cluster2->mutable_weight()->set_value(kWeight25);
  4352. SetRouteConfiguration(balancer_.get(), new_route_config);
  4353. ResetBackendCounters();
  4354. WaitForBackend(3, WaitForBackendOptions(),
  4355. RpcOptions().set_rpc_service(SERVICE_ECHO1));
  4356. CheckRpcSendOk(kNumEchoRpcs);
  4357. CheckRpcSendOk(kNumEcho1Rpcs7525,
  4358. RpcOptions().set_rpc_service(SERVICE_ECHO1));
  4359. // Make sure RPCs all go to the correct backend.
  4360. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  4361. EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
  4362. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  4363. weight_75_request_count = backends_[1]->backend_service1()->request_count();
  4364. EXPECT_EQ(0, backends_[2]->backend_service()->request_count());
  4365. EXPECT_EQ(0, backends_[2]->backend_service1()->request_count());
  4366. EXPECT_EQ(0, backends_[3]->backend_service()->request_count());
  4367. weight_25_request_count = backends_[3]->backend_service1()->request_count();
  4368. gpr_log(GPR_INFO, "target_75 received %d rpcs and target_25 received %d rpcs",
  4369. weight_75_request_count, weight_25_request_count);
  4370. EXPECT_THAT(static_cast<double>(weight_75_request_count) / kNumEcho1Rpcs7525,
  4371. ::testing::DoubleNear(kWeight75Percent, kErrorTolerance));
  4372. EXPECT_THAT(static_cast<double>(weight_25_request_count) / kNumEcho1Rpcs7525,
  4373. ::testing::DoubleNear(kWeight25Percent, kErrorTolerance));
  4374. }
  4375. TEST_P(LdsRdsTest, XdsRoutingClusterUpdateClusters) {
  4376. const char* kNewClusterName = "new_cluster";
  4377. const char* kNewEdsServiceName = "new_eds_service_name";
  4378. const size_t kNumEchoRpcs = 5;
  4379. // Populate new EDS resources.
  4380. EdsResourceArgs args({
  4381. {"locality0", CreateEndpointsForBackends(0, 1)},
  4382. });
  4383. EdsResourceArgs args1({
  4384. {"locality0", CreateEndpointsForBackends(1, 2)},
  4385. });
  4386. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  4387. balancer_->ads_service()->SetEdsResource(
  4388. BuildEdsResource(args1, kNewEdsServiceName));
  4389. // Populate new CDS resources.
  4390. Cluster new_cluster = default_cluster_;
  4391. new_cluster.set_name(kNewClusterName);
  4392. new_cluster.mutable_eds_cluster_config()->set_service_name(
  4393. kNewEdsServiceName);
  4394. balancer_->ads_service()->SetCdsResource(new_cluster);
  4395. // Send Route Configuration.
  4396. RouteConfiguration new_route_config = default_route_config_;
  4397. SetRouteConfiguration(balancer_.get(), new_route_config);
  4398. WaitForAllBackends(0, 1);
  4399. CheckRpcSendOk(kNumEchoRpcs);
  4400. // Make sure RPCs all go to the correct backend.
  4401. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  4402. // Change Route Configurations: new default cluster.
  4403. auto* default_route =
  4404. new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  4405. default_route->mutable_route()->set_cluster(kNewClusterName);
  4406. SetRouteConfiguration(balancer_.get(), new_route_config);
  4407. WaitForAllBackends(1, 2);
  4408. CheckRpcSendOk(kNumEchoRpcs);
  4409. // Make sure RPCs all go to the correct backend.
  4410. EXPECT_EQ(kNumEchoRpcs, backends_[1]->backend_service()->request_count());
  4411. }
  4412. TEST_P(LdsRdsTest, XdsRoutingClusterUpdateClustersWithPickingDelays) {
  4413. const char* kNewClusterName = "new_cluster";
  4414. const char* kNewEdsServiceName = "new_eds_service_name";
  4415. // Populate new EDS resources.
  4416. EdsResourceArgs args({
  4417. {"locality0", CreateEndpointsForBackends(0, 1)},
  4418. });
  4419. EdsResourceArgs args1({
  4420. {"locality0", CreateEndpointsForBackends(1, 2)},
  4421. });
  4422. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  4423. balancer_->ads_service()->SetEdsResource(
  4424. BuildEdsResource(args1, kNewEdsServiceName));
  4425. // Populate new CDS resources.
  4426. Cluster new_cluster = default_cluster_;
  4427. new_cluster.set_name(kNewClusterName);
  4428. new_cluster.mutable_eds_cluster_config()->set_service_name(
  4429. kNewEdsServiceName);
  4430. balancer_->ads_service()->SetCdsResource(new_cluster);
  4431. // Bring down the current backend: 0, this will delay route picking time,
  4432. // resulting in un-committed RPCs.
  4433. ShutdownBackend(0);
  4434. // Send a RouteConfiguration with a default route that points to
  4435. // backend 0.
  4436. RouteConfiguration new_route_config = default_route_config_;
  4437. SetRouteConfiguration(balancer_.get(), new_route_config);
  4438. // Send exactly one RPC with no deadline and with wait_for_ready=true.
  4439. // This RPC will not complete until after backend 0 is started.
  4440. std::thread sending_rpc([this]() {
  4441. CheckRpcSendOk(1, RpcOptions().set_wait_for_ready(true).set_timeout_ms(0));
  4442. });
  4443. // Send a non-wait_for_ready RPC which should fail, this will tell us
  4444. // that the client has received the update and attempted to connect.
  4445. const Status status = SendRpc(RpcOptions().set_timeout_ms(0));
  4446. EXPECT_FALSE(status.ok());
  4447. // Send a update RouteConfiguration to use backend 1.
  4448. auto* default_route =
  4449. new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  4450. default_route->mutable_route()->set_cluster(kNewClusterName);
  4451. SetRouteConfiguration(balancer_.get(), new_route_config);
  4452. // Wait for RPCs to go to the new backend: 1, this ensures that the client
  4453. // has processed the update.
  4454. WaitForBackend(
  4455. 1, WaitForBackendOptions().set_reset_counters(false).set_allow_failures(
  4456. true));
  4457. // Bring up the previous backend: 0, this will allow the delayed RPC to
  4458. // finally call on_call_committed upon completion.
  4459. StartBackend(0);
  4460. sending_rpc.join();
  4461. // Make sure RPCs go to the correct backend:
  4462. EXPECT_EQ(1, backends_[0]->backend_service()->request_count());
  4463. EXPECT_EQ(1, backends_[1]->backend_service()->request_count());
  4464. }
  4465. TEST_P(LdsRdsTest, XdsRoutingApplyXdsTimeout) {
  4466. const int64_t kTimeoutMillis = 500;
  4467. const int64_t kTimeoutNano = kTimeoutMillis * 1000000;
  4468. const int64_t kTimeoutGrpcTimeoutHeaderMaxSecond = 1;
  4469. const int64_t kTimeoutMaxStreamDurationSecond = 2;
  4470. const int64_t kTimeoutHttpMaxStreamDurationSecond = 3;
  4471. const int64_t kTimeoutApplicationSecond = 4;
  4472. const char* kNewCluster1Name = "new_cluster_1";
  4473. const char* kNewEdsService1Name = "new_eds_service_name_1";
  4474. const char* kNewCluster2Name = "new_cluster_2";
  4475. const char* kNewEdsService2Name = "new_eds_service_name_2";
  4476. const char* kNewCluster3Name = "new_cluster_3";
  4477. const char* kNewEdsService3Name = "new_eds_service_name_3";
  4478. // Populate new EDS resources.
  4479. EdsResourceArgs args({{"locality0", {MakeNonExistantEndpoint()}}});
  4480. EdsResourceArgs args1({{"locality0", {MakeNonExistantEndpoint()}}});
  4481. EdsResourceArgs args2({{"locality0", {MakeNonExistantEndpoint()}}});
  4482. EdsResourceArgs args3({{"locality0", {MakeNonExistantEndpoint()}}});
  4483. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  4484. balancer_->ads_service()->SetEdsResource(
  4485. BuildEdsResource(args1, kNewEdsService1Name));
  4486. balancer_->ads_service()->SetEdsResource(
  4487. BuildEdsResource(args2, kNewEdsService2Name));
  4488. balancer_->ads_service()->SetEdsResource(
  4489. BuildEdsResource(args3, kNewEdsService3Name));
  4490. // Populate new CDS resources.
  4491. Cluster new_cluster1 = default_cluster_;
  4492. new_cluster1.set_name(kNewCluster1Name);
  4493. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  4494. kNewEdsService1Name);
  4495. balancer_->ads_service()->SetCdsResource(new_cluster1);
  4496. Cluster new_cluster2 = default_cluster_;
  4497. new_cluster2.set_name(kNewCluster2Name);
  4498. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  4499. kNewEdsService2Name);
  4500. balancer_->ads_service()->SetCdsResource(new_cluster2);
  4501. Cluster new_cluster3 = default_cluster_;
  4502. new_cluster3.set_name(kNewCluster3Name);
  4503. new_cluster3.mutable_eds_cluster_config()->set_service_name(
  4504. kNewEdsService3Name);
  4505. balancer_->ads_service()->SetCdsResource(new_cluster3);
  4506. // Construct listener.
  4507. auto listener = default_listener_;
  4508. HttpConnectionManager http_connection_manager;
  4509. listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
  4510. &http_connection_manager);
  4511. // Set up HTTP max_stream_duration of 3.5 seconds
  4512. auto* duration =
  4513. http_connection_manager.mutable_common_http_protocol_options()
  4514. ->mutable_max_stream_duration();
  4515. duration->set_seconds(kTimeoutHttpMaxStreamDurationSecond);
  4516. duration->set_nanos(kTimeoutNano);
  4517. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  4518. http_connection_manager);
  4519. // Construct route config.
  4520. RouteConfiguration new_route_config = default_route_config_;
  4521. // route 1: Set max_stream_duration of 2.5 seconds, Set
  4522. // grpc_timeout_header_max of 1.5
  4523. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  4524. route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service/Echo1");
  4525. route1->mutable_route()->set_cluster(kNewCluster1Name);
  4526. auto* max_stream_duration =
  4527. route1->mutable_route()->mutable_max_stream_duration();
  4528. duration = max_stream_duration->mutable_max_stream_duration();
  4529. duration->set_seconds(kTimeoutMaxStreamDurationSecond);
  4530. duration->set_nanos(kTimeoutNano);
  4531. duration = max_stream_duration->mutable_grpc_timeout_header_max();
  4532. duration->set_seconds(kTimeoutGrpcTimeoutHeaderMaxSecond);
  4533. duration->set_nanos(kTimeoutNano);
  4534. // route 2: Set max_stream_duration of 2.5 seconds
  4535. auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
  4536. route2->mutable_match()->set_path("/grpc.testing.EchoTest2Service/Echo2");
  4537. route2->mutable_route()->set_cluster(kNewCluster2Name);
  4538. max_stream_duration = route2->mutable_route()->mutable_max_stream_duration();
  4539. duration = max_stream_duration->mutable_max_stream_duration();
  4540. duration->set_seconds(kTimeoutMaxStreamDurationSecond);
  4541. duration->set_nanos(kTimeoutNano);
  4542. // route 3: No timeout values in route configuration
  4543. auto* route3 = new_route_config.mutable_virtual_hosts(0)->add_routes();
  4544. route3->mutable_match()->set_path("/grpc.testing.EchoTestService/Echo");
  4545. route3->mutable_route()->set_cluster(kNewCluster3Name);
  4546. // Set listener and route config.
  4547. SetListenerAndRouteConfiguration(balancer_.get(), std::move(listener),
  4548. new_route_config);
  4549. // Test grpc_timeout_header_max of 1.5 seconds applied
  4550. grpc_core::Timestamp t0 = NowFromCycleCounter();
  4551. grpc_core::Timestamp t1 =
  4552. t0 + grpc_core::Duration::Seconds(kTimeoutGrpcTimeoutHeaderMaxSecond) +
  4553. grpc_core::Duration::Milliseconds(kTimeoutMillis);
  4554. grpc_core::Timestamp t2 =
  4555. t0 + grpc_core::Duration::Seconds(kTimeoutMaxStreamDurationSecond) +
  4556. grpc_core::Duration::Milliseconds(kTimeoutMillis);
  4557. CheckRpcSendFailure(
  4558. CheckRpcSendFailureOptions()
  4559. .set_rpc_options(RpcOptions()
  4560. .set_rpc_service(SERVICE_ECHO1)
  4561. .set_rpc_method(METHOD_ECHO1)
  4562. .set_wait_for_ready(true)
  4563. .set_timeout_ms(grpc_core::Duration::Seconds(
  4564. kTimeoutApplicationSecond)
  4565. .millis()))
  4566. .set_expected_error_code(StatusCode::DEADLINE_EXCEEDED));
  4567. EXPECT_THAT(NowFromCycleCounter(), AdjustedClockInRange(t1, t2));
  4568. // Test max_stream_duration of 2.5 seconds applied
  4569. t0 = NowFromCycleCounter();
  4570. t1 = t0 + grpc_core::Duration::Seconds(kTimeoutMaxStreamDurationSecond) +
  4571. grpc_core::Duration::Milliseconds(kTimeoutMillis);
  4572. t2 = t0 + grpc_core::Duration::Seconds(kTimeoutHttpMaxStreamDurationSecond) +
  4573. grpc_core::Duration::Milliseconds(kTimeoutMillis);
  4574. CheckRpcSendFailure(
  4575. CheckRpcSendFailureOptions()
  4576. .set_rpc_options(RpcOptions()
  4577. .set_rpc_service(SERVICE_ECHO2)
  4578. .set_rpc_method(METHOD_ECHO2)
  4579. .set_wait_for_ready(true)
  4580. .set_timeout_ms(grpc_core::Duration::Seconds(
  4581. kTimeoutApplicationSecond)
  4582. .millis()))
  4583. .set_expected_error_code(StatusCode::DEADLINE_EXCEEDED));
  4584. EXPECT_THAT(NowFromCycleCounter(), AdjustedClockInRange(t1, t2));
  4585. // Test http_stream_duration of 3.5 seconds applied
  4586. t0 = NowFromCycleCounter();
  4587. t1 = t0 + grpc_core::Duration::Seconds(kTimeoutHttpMaxStreamDurationSecond) +
  4588. grpc_core::Duration::Milliseconds(kTimeoutMillis);
  4589. t2 = t0 + grpc_core::Duration::Seconds(kTimeoutApplicationSecond) +
  4590. grpc_core::Duration::Milliseconds(kTimeoutMillis);
  4591. CheckRpcSendFailure(
  4592. CheckRpcSendFailureOptions()
  4593. .set_rpc_options(RpcOptions().set_wait_for_ready(true).set_timeout_ms(
  4594. grpc_core::Duration::Seconds(kTimeoutApplicationSecond).millis()))
  4595. .set_expected_error_code(StatusCode::DEADLINE_EXCEEDED));
  4596. EXPECT_THAT(NowFromCycleCounter(), AdjustedClockInRange(t1, t2));
  4597. }
  4598. TEST_P(LdsRdsTest, XdsRoutingApplyApplicationTimeoutWhenXdsTimeoutExplicit0) {
  4599. const int64_t kTimeoutNano = 500000000;
  4600. const int64_t kTimeoutMaxStreamDurationSecond = 2;
  4601. const int64_t kTimeoutHttpMaxStreamDurationSecond = 3;
  4602. const int64_t kTimeoutApplicationSecond = 4;
  4603. const char* kNewCluster1Name = "new_cluster_1";
  4604. const char* kNewEdsService1Name = "new_eds_service_name_1";
  4605. const char* kNewCluster2Name = "new_cluster_2";
  4606. const char* kNewEdsService2Name = "new_eds_service_name_2";
  4607. // Populate new EDS resources.
  4608. EdsResourceArgs args({{"locality0", {MakeNonExistantEndpoint()}}});
  4609. EdsResourceArgs args1({{"locality0", {MakeNonExistantEndpoint()}}});
  4610. EdsResourceArgs args2({{"locality0", {MakeNonExistantEndpoint()}}});
  4611. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  4612. balancer_->ads_service()->SetEdsResource(
  4613. BuildEdsResource(args1, kNewEdsService1Name));
  4614. balancer_->ads_service()->SetEdsResource(
  4615. BuildEdsResource(args2, kNewEdsService2Name));
  4616. // Populate new CDS resources.
  4617. Cluster new_cluster1 = default_cluster_;
  4618. new_cluster1.set_name(kNewCluster1Name);
  4619. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  4620. kNewEdsService1Name);
  4621. balancer_->ads_service()->SetCdsResource(new_cluster1);
  4622. Cluster new_cluster2 = default_cluster_;
  4623. new_cluster2.set_name(kNewCluster2Name);
  4624. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  4625. kNewEdsService2Name);
  4626. balancer_->ads_service()->SetCdsResource(new_cluster2);
  4627. // Construct listener.
  4628. auto listener = default_listener_;
  4629. HttpConnectionManager http_connection_manager;
  4630. listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
  4631. &http_connection_manager);
  4632. // Set up HTTP max_stream_duration of 3.5 seconds
  4633. auto* duration =
  4634. http_connection_manager.mutable_common_http_protocol_options()
  4635. ->mutable_max_stream_duration();
  4636. duration->set_seconds(kTimeoutHttpMaxStreamDurationSecond);
  4637. duration->set_nanos(kTimeoutNano);
  4638. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  4639. http_connection_manager);
  4640. // Construct route config.
  4641. RouteConfiguration new_route_config = default_route_config_;
  4642. // route 1: Set max_stream_duration of 2.5 seconds, Set
  4643. // grpc_timeout_header_max of 0
  4644. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  4645. route1->mutable_match()->set_path("/grpc.testing.EchoTest1Service/Echo1");
  4646. route1->mutable_route()->set_cluster(kNewCluster1Name);
  4647. auto* max_stream_duration =
  4648. route1->mutable_route()->mutable_max_stream_duration();
  4649. duration = max_stream_duration->mutable_max_stream_duration();
  4650. duration->set_seconds(kTimeoutMaxStreamDurationSecond);
  4651. duration->set_nanos(kTimeoutNano);
  4652. duration = max_stream_duration->mutable_grpc_timeout_header_max();
  4653. duration->set_seconds(0);
  4654. duration->set_nanos(0);
  4655. // route 2: Set max_stream_duration to 0
  4656. auto* route2 = new_route_config.mutable_virtual_hosts(0)->add_routes();
  4657. route2->mutable_match()->set_path("/grpc.testing.EchoTest2Service/Echo2");
  4658. route2->mutable_route()->set_cluster(kNewCluster2Name);
  4659. max_stream_duration = route2->mutable_route()->mutable_max_stream_duration();
  4660. duration = max_stream_duration->mutable_max_stream_duration();
  4661. duration->set_seconds(0);
  4662. duration->set_nanos(0);
  4663. // Set listener and route config.
  4664. SetListenerAndRouteConfiguration(balancer_.get(), std::move(listener),
  4665. new_route_config);
  4666. // Test application timeout is applied for route 1
  4667. auto t0 = system_clock::now();
  4668. CheckRpcSendFailure(
  4669. CheckRpcSendFailureOptions()
  4670. .set_rpc_options(
  4671. RpcOptions()
  4672. .set_rpc_service(SERVICE_ECHO1)
  4673. .set_rpc_method(METHOD_ECHO1)
  4674. .set_wait_for_ready(true)
  4675. .set_timeout_ms(kTimeoutApplicationSecond * 1000))
  4676. .set_expected_error_code(StatusCode::DEADLINE_EXCEEDED));
  4677. auto ellapsed_nano_seconds =
  4678. std::chrono::duration_cast<std::chrono::nanoseconds>(system_clock::now() -
  4679. t0);
  4680. EXPECT_GT(ellapsed_nano_seconds.count(),
  4681. kTimeoutApplicationSecond * 1000000000);
  4682. // Test application timeout is applied for route 2
  4683. t0 = system_clock::now();
  4684. CheckRpcSendFailure(
  4685. CheckRpcSendFailureOptions()
  4686. .set_rpc_options(
  4687. RpcOptions()
  4688. .set_rpc_service(SERVICE_ECHO2)
  4689. .set_rpc_method(METHOD_ECHO2)
  4690. .set_wait_for_ready(true)
  4691. .set_timeout_ms(kTimeoutApplicationSecond * 1000))
  4692. .set_expected_error_code(StatusCode::DEADLINE_EXCEEDED));
  4693. ellapsed_nano_seconds = std::chrono::duration_cast<std::chrono::nanoseconds>(
  4694. system_clock::now() - t0);
  4695. EXPECT_GT(ellapsed_nano_seconds.count(),
  4696. kTimeoutApplicationSecond * 1000000000);
  4697. }
  4698. TEST_P(LdsRdsTest, XdsRoutingApplyApplicationTimeoutWhenHttpTimeoutExplicit0) {
  4699. const int64_t kTimeoutApplicationSecond = 4;
  4700. // Populate new EDS resources.
  4701. EdsResourceArgs args({{"locality0", {MakeNonExistantEndpoint()}}});
  4702. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  4703. auto listener = default_listener_;
  4704. HttpConnectionManager http_connection_manager;
  4705. listener.mutable_api_listener()->mutable_api_listener()->UnpackTo(
  4706. &http_connection_manager);
  4707. // Set up HTTP max_stream_duration to be explicit 0
  4708. auto* duration =
  4709. http_connection_manager.mutable_common_http_protocol_options()
  4710. ->mutable_max_stream_duration();
  4711. duration->set_seconds(0);
  4712. duration->set_nanos(0);
  4713. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  4714. http_connection_manager);
  4715. // Set listener and route config.
  4716. SetListenerAndRouteConfiguration(balancer_.get(), std::move(listener),
  4717. default_route_config_);
  4718. // Test application timeout is applied for route 1
  4719. auto t0 = system_clock::now();
  4720. CheckRpcSendFailure(
  4721. CheckRpcSendFailureOptions()
  4722. .set_rpc_options(RpcOptions().set_wait_for_ready(true).set_timeout_ms(
  4723. grpc_core::Duration::Seconds(kTimeoutApplicationSecond).millis()))
  4724. .set_expected_error_code(StatusCode::DEADLINE_EXCEEDED));
  4725. auto ellapsed_nano_seconds =
  4726. std::chrono::duration_cast<std::chrono::nanoseconds>(system_clock::now() -
  4727. t0);
  4728. EXPECT_GT(ellapsed_nano_seconds.count(),
  4729. kTimeoutApplicationSecond * 1000000000);
  4730. }
  4731. // Test to ensure application-specified deadline won't be affected when
  4732. // the xDS config does not specify a timeout.
  4733. TEST_P(LdsRdsTest, XdsRoutingWithOnlyApplicationTimeout) {
  4734. const int64_t kTimeoutApplicationSecond = 4;
  4735. // Populate new EDS resources.
  4736. EdsResourceArgs args({{"locality0", {MakeNonExistantEndpoint()}}});
  4737. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  4738. auto t0 = system_clock::now();
  4739. CheckRpcSendFailure(
  4740. CheckRpcSendFailureOptions()
  4741. .set_rpc_options(RpcOptions().set_wait_for_ready(true).set_timeout_ms(
  4742. grpc_core::Duration::Seconds(kTimeoutApplicationSecond).millis()))
  4743. .set_expected_error_code(StatusCode::DEADLINE_EXCEEDED));
  4744. auto ellapsed_nano_seconds =
  4745. std::chrono::duration_cast<std::chrono::nanoseconds>(system_clock::now() -
  4746. t0);
  4747. EXPECT_GT(ellapsed_nano_seconds.count(),
  4748. kTimeoutApplicationSecond * 1000000000);
  4749. }
  4750. TEST_P(LdsRdsTest, XdsRetryPolicyNumRetries) {
  4751. const size_t kNumRetries = 3;
  4752. // Populate new EDS resources.
  4753. EdsResourceArgs args({
  4754. {"locality0", CreateEndpointsForBackends(0, 1)},
  4755. });
  4756. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  4757. // Construct route config to set retry policy.
  4758. RouteConfiguration new_route_config = default_route_config_;
  4759. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  4760. auto* retry_policy = route1->mutable_route()->mutable_retry_policy();
  4761. retry_policy->set_retry_on(
  4762. "5xx,cancelled,deadline-exceeded,internal,resource-exhausted,"
  4763. "unavailable");
  4764. retry_policy->mutable_num_retries()->set_value(kNumRetries);
  4765. SetRouteConfiguration(balancer_.get(), new_route_config);
  4766. // Ensure we retried the correct number of times on all supported status.
  4767. CheckRpcSendFailure(
  4768. CheckRpcSendFailureOptions()
  4769. .set_rpc_options(
  4770. RpcOptions().set_server_expected_error(StatusCode::CANCELLED))
  4771. .set_expected_error_code(StatusCode::CANCELLED));
  4772. EXPECT_EQ(kNumRetries + 1, backends_[0]->backend_service()->request_count());
  4773. ResetBackendCounters();
  4774. CheckRpcSendFailure(
  4775. CheckRpcSendFailureOptions()
  4776. .set_rpc_options(RpcOptions().set_server_expected_error(
  4777. StatusCode::DEADLINE_EXCEEDED))
  4778. .set_expected_error_code(StatusCode::DEADLINE_EXCEEDED));
  4779. EXPECT_EQ(kNumRetries + 1, backends_[0]->backend_service()->request_count());
  4780. ResetBackendCounters();
  4781. CheckRpcSendFailure(
  4782. CheckRpcSendFailureOptions()
  4783. .set_rpc_options(
  4784. RpcOptions().set_server_expected_error(StatusCode::INTERNAL))
  4785. .set_expected_error_code(StatusCode::INTERNAL));
  4786. EXPECT_EQ(kNumRetries + 1, backends_[0]->backend_service()->request_count());
  4787. ResetBackendCounters();
  4788. CheckRpcSendFailure(
  4789. CheckRpcSendFailureOptions()
  4790. .set_rpc_options(RpcOptions().set_server_expected_error(
  4791. StatusCode::RESOURCE_EXHAUSTED))
  4792. .set_expected_error_code(StatusCode::RESOURCE_EXHAUSTED));
  4793. EXPECT_EQ(kNumRetries + 1, backends_[0]->backend_service()->request_count());
  4794. ResetBackendCounters();
  4795. CheckRpcSendFailure(
  4796. CheckRpcSendFailureOptions()
  4797. .set_rpc_options(
  4798. RpcOptions().set_server_expected_error(StatusCode::UNAVAILABLE))
  4799. .set_expected_error_code(StatusCode::UNAVAILABLE));
  4800. EXPECT_EQ(kNumRetries + 1, backends_[0]->backend_service()->request_count());
  4801. ResetBackendCounters();
  4802. // Ensure we don't retry on an unsupported status.
  4803. CheckRpcSendFailure(
  4804. CheckRpcSendFailureOptions()
  4805. .set_rpc_options(RpcOptions().set_server_expected_error(
  4806. StatusCode::UNAUTHENTICATED))
  4807. .set_expected_error_code(StatusCode::UNAUTHENTICATED));
  4808. EXPECT_EQ(1, backends_[0]->backend_service()->request_count());
  4809. }
  4810. TEST_P(LdsRdsTest, XdsRetryPolicyAtVirtualHostLevel) {
  4811. const size_t kNumRetries = 3;
  4812. // Populate new EDS resources.
  4813. EdsResourceArgs args({
  4814. {"locality0", CreateEndpointsForBackends(0, 1)},
  4815. });
  4816. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  4817. // Construct route config to set retry policy.
  4818. RouteConfiguration new_route_config = default_route_config_;
  4819. auto* retry_policy =
  4820. new_route_config.mutable_virtual_hosts(0)->mutable_retry_policy();
  4821. retry_policy->set_retry_on(
  4822. "cancelled,deadline-exceeded,internal,resource-exhausted,unavailable");
  4823. retry_policy->mutable_num_retries()->set_value(kNumRetries);
  4824. SetRouteConfiguration(balancer_.get(), new_route_config);
  4825. // Ensure we retried the correct number of times on a supported status.
  4826. CheckRpcSendFailure(
  4827. CheckRpcSendFailureOptions()
  4828. .set_rpc_options(RpcOptions().set_server_expected_error(
  4829. StatusCode::DEADLINE_EXCEEDED))
  4830. .set_expected_error_code(StatusCode::DEADLINE_EXCEEDED));
  4831. EXPECT_EQ(kNumRetries + 1, backends_[0]->backend_service()->request_count());
  4832. }
  4833. TEST_P(LdsRdsTest, XdsRetryPolicyLongBackOff) {
  4834. // Set num retries to 3, but due to longer back off, we expect only 1 retry
  4835. // will take place.
  4836. const size_t kNumRetries = 3;
  4837. // Populate new EDS resources.
  4838. EdsResourceArgs args({
  4839. {"locality0", CreateEndpointsForBackends(0, 1)},
  4840. });
  4841. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  4842. // Construct route config to set retry policy.
  4843. RouteConfiguration new_route_config = default_route_config_;
  4844. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  4845. auto* retry_policy = route1->mutable_route()->mutable_retry_policy();
  4846. retry_policy->set_retry_on(
  4847. "5xx,cancelled,deadline-exceeded,internal,resource-exhausted,"
  4848. "unavailable");
  4849. retry_policy->mutable_num_retries()->set_value(kNumRetries);
  4850. auto base_interval =
  4851. retry_policy->mutable_retry_back_off()->mutable_base_interval();
  4852. // Set backoff to 1 second, 1/2 of rpc timeout of 2 second.
  4853. base_interval->set_seconds(1 * grpc_test_slowdown_factor());
  4854. base_interval->set_nanos(0);
  4855. SetRouteConfiguration(balancer_.get(), new_route_config);
  4856. // No need to set max interval and just let it be the default of 10x of base.
  4857. // We expect 1 retry before the RPC times out with DEADLINE_EXCEEDED.
  4858. CheckRpcSendFailure(
  4859. CheckRpcSendFailureOptions()
  4860. .set_rpc_options(
  4861. RpcOptions().set_timeout_ms(2500).set_server_expected_error(
  4862. StatusCode::CANCELLED))
  4863. .set_expected_error_code(StatusCode::DEADLINE_EXCEEDED));
  4864. EXPECT_EQ(1 + 1, backends_[0]->backend_service()->request_count());
  4865. }
  4866. TEST_P(LdsRdsTest, XdsRetryPolicyMaxBackOff) {
  4867. // Set num retries to 3, but due to longer back off, we expect only 2 retry
  4868. // will take place, while the 2nd one will obey the max backoff.
  4869. const size_t kNumRetries = 3;
  4870. // Populate new EDS resources.
  4871. EdsResourceArgs args({
  4872. {"locality0", CreateEndpointsForBackends(0, 1)},
  4873. });
  4874. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  4875. // Construct route config to set retry policy.
  4876. RouteConfiguration new_route_config = default_route_config_;
  4877. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  4878. auto* retry_policy = route1->mutable_route()->mutable_retry_policy();
  4879. retry_policy->set_retry_on(
  4880. "5xx,cancelled,deadline-exceeded,internal,resource-exhausted,"
  4881. "unavailable");
  4882. retry_policy->mutable_num_retries()->set_value(kNumRetries);
  4883. auto base_interval =
  4884. retry_policy->mutable_retry_back_off()->mutable_base_interval();
  4885. // Set backoff to 1 second.
  4886. base_interval->set_seconds(1 * grpc_test_slowdown_factor());
  4887. base_interval->set_nanos(0);
  4888. auto max_interval =
  4889. retry_policy->mutable_retry_back_off()->mutable_max_interval();
  4890. // Set max interval to be the same as base, so 2 retries will take 2 seconds
  4891. // and both retries will take place before the 2.5 seconds rpc timeout.
  4892. // Tested to ensure if max is not set, this test will be the same as
  4893. // XdsRetryPolicyLongBackOff and we will only see 1 retry in that case.
  4894. max_interval->set_seconds(1 * grpc_test_slowdown_factor());
  4895. max_interval->set_nanos(0);
  4896. SetRouteConfiguration(balancer_.get(), new_route_config);
  4897. // We expect 2 retry before the RPC times out with DEADLINE_EXCEEDED.
  4898. CheckRpcSendFailure(
  4899. CheckRpcSendFailureOptions()
  4900. .set_rpc_options(
  4901. RpcOptions().set_timeout_ms(2500).set_server_expected_error(
  4902. StatusCode::CANCELLED))
  4903. .set_expected_error_code(StatusCode::DEADLINE_EXCEEDED));
  4904. EXPECT_EQ(2 + 1, backends_[0]->backend_service()->request_count());
  4905. }
  4906. TEST_P(LdsRdsTest, XdsRetryPolicyUnsupportedStatusCode) {
  4907. const size_t kNumRetries = 3;
  4908. // Populate new EDS resources.
  4909. EdsResourceArgs args({
  4910. {"locality0", CreateEndpointsForBackends(0, 1)},
  4911. });
  4912. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  4913. // Construct route config to set retry policy.
  4914. RouteConfiguration new_route_config = default_route_config_;
  4915. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  4916. auto* retry_policy = route1->mutable_route()->mutable_retry_policy();
  4917. retry_policy->set_retry_on("5xx");
  4918. retry_policy->mutable_num_retries()->set_value(kNumRetries);
  4919. SetRouteConfiguration(balancer_.get(), new_route_config);
  4920. // We expect no retry.
  4921. CheckRpcSendFailure(
  4922. CheckRpcSendFailureOptions()
  4923. .set_rpc_options(RpcOptions().set_server_expected_error(
  4924. StatusCode::DEADLINE_EXCEEDED))
  4925. .set_expected_error_code(StatusCode::DEADLINE_EXCEEDED));
  4926. EXPECT_EQ(1, backends_[0]->backend_service()->request_count());
  4927. }
  4928. TEST_P(LdsRdsTest,
  4929. XdsRetryPolicyUnsupportedStatusCodeWithVirtualHostLevelRetry) {
  4930. const size_t kNumRetries = 3;
  4931. // Populate new EDS resources.
  4932. EdsResourceArgs args({
  4933. {"locality0", CreateEndpointsForBackends(0, 1)},
  4934. });
  4935. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  4936. // Construct route config to set retry policy with no supported retry_on
  4937. // statuses.
  4938. RouteConfiguration new_route_config = default_route_config_;
  4939. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  4940. auto* retry_policy = route1->mutable_route()->mutable_retry_policy();
  4941. retry_policy->set_retry_on("5xx");
  4942. retry_policy->mutable_num_retries()->set_value(kNumRetries);
  4943. // Construct a virtual host level retry policy with supported statuses.
  4944. auto* virtual_host_retry_policy =
  4945. new_route_config.mutable_virtual_hosts(0)->mutable_retry_policy();
  4946. virtual_host_retry_policy->set_retry_on(
  4947. "cancelled,deadline-exceeded,internal,resource-exhausted,unavailable");
  4948. virtual_host_retry_policy->mutable_num_retries()->set_value(kNumRetries);
  4949. SetRouteConfiguration(balancer_.get(), new_route_config);
  4950. // We expect no retry.
  4951. CheckRpcSendFailure(
  4952. CheckRpcSendFailureOptions()
  4953. .set_rpc_options(RpcOptions().set_server_expected_error(
  4954. StatusCode::DEADLINE_EXCEEDED))
  4955. .set_expected_error_code(StatusCode::DEADLINE_EXCEEDED));
  4956. EXPECT_EQ(1, backends_[0]->backend_service()->request_count());
  4957. }
  4958. TEST_P(LdsRdsTest, XdsRetryPolicyInvalidNumRetriesZero) {
  4959. // Populate new EDS resources.
  4960. EdsResourceArgs args({
  4961. {"locality0", CreateEndpointsForBackends(0, 1)},
  4962. });
  4963. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  4964. // Construct route config to set retry policy.
  4965. RouteConfiguration new_route_config = default_route_config_;
  4966. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  4967. auto* retry_policy = route1->mutable_route()->mutable_retry_policy();
  4968. retry_policy->set_retry_on("deadline-exceeded");
  4969. // Setting num_retries to zero is not valid.
  4970. retry_policy->mutable_num_retries()->set_value(0);
  4971. SetRouteConfiguration(balancer_.get(), new_route_config);
  4972. const auto response_state = WaitForRdsNack();
  4973. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  4974. EXPECT_THAT(
  4975. response_state->error_message,
  4976. ::testing::HasSubstr(
  4977. "RouteAction RetryPolicy num_retries set to invalid value 0."));
  4978. }
  4979. TEST_P(LdsRdsTest, XdsRetryPolicyRetryBackOffMissingBaseInterval) {
  4980. // Populate new EDS resources.
  4981. EdsResourceArgs args({
  4982. {"locality0", CreateEndpointsForBackends(0, 1)},
  4983. });
  4984. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  4985. // Construct route config to set retry policy.
  4986. RouteConfiguration new_route_config = default_route_config_;
  4987. auto* route1 = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  4988. auto* retry_policy = route1->mutable_route()->mutable_retry_policy();
  4989. retry_policy->set_retry_on("deadline-exceeded");
  4990. retry_policy->mutable_num_retries()->set_value(1);
  4991. // RetryBackoff is there but base interval is missing.
  4992. auto max_interval =
  4993. retry_policy->mutable_retry_back_off()->mutable_max_interval();
  4994. max_interval->set_seconds(0);
  4995. max_interval->set_nanos(250000000);
  4996. SetRouteConfiguration(balancer_.get(), new_route_config);
  4997. const auto response_state = WaitForRdsNack();
  4998. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  4999. EXPECT_THAT(
  5000. response_state->error_message,
  5001. ::testing::HasSubstr(
  5002. "RouteAction RetryPolicy RetryBackoff missing base interval."));
  5003. }
  5004. TEST_P(LdsRdsTest, XdsRoutingHeadersMatching) {
  5005. const char* kNewClusterName = "new_cluster";
  5006. const char* kNewEdsServiceName = "new_eds_service_name";
  5007. const size_t kNumEcho1Rpcs = 100;
  5008. const size_t kNumEchoRpcs = 5;
  5009. // Populate new EDS resources.
  5010. EdsResourceArgs args({
  5011. {"locality0", CreateEndpointsForBackends(0, 1)},
  5012. });
  5013. EdsResourceArgs args1({
  5014. {"locality0", CreateEndpointsForBackends(1, 2)},
  5015. });
  5016. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  5017. balancer_->ads_service()->SetEdsResource(
  5018. BuildEdsResource(args1, kNewEdsServiceName));
  5019. // Populate new CDS resources.
  5020. Cluster new_cluster = default_cluster_;
  5021. new_cluster.set_name(kNewClusterName);
  5022. new_cluster.mutable_eds_cluster_config()->set_service_name(
  5023. kNewEdsServiceName);
  5024. balancer_->ads_service()->SetCdsResource(new_cluster);
  5025. // Populating Route Configurations for LDS.
  5026. RouteConfiguration route_config = default_route_config_;
  5027. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  5028. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  5029. auto* header_matcher1 = route1->mutable_match()->add_headers();
  5030. header_matcher1->set_name("header1");
  5031. header_matcher1->set_exact_match("POST,PUT,GET");
  5032. auto* header_matcher2 = route1->mutable_match()->add_headers();
  5033. header_matcher2->set_name("header2");
  5034. header_matcher2->mutable_safe_regex_match()->set_regex("[a-z]*");
  5035. auto* header_matcher3 = route1->mutable_match()->add_headers();
  5036. header_matcher3->set_name("header3");
  5037. header_matcher3->mutable_range_match()->set_start(1);
  5038. header_matcher3->mutable_range_match()->set_end(1000);
  5039. auto* header_matcher4 = route1->mutable_match()->add_headers();
  5040. header_matcher4->set_name("header4");
  5041. header_matcher4->set_present_match(false);
  5042. auto* header_matcher5 = route1->mutable_match()->add_headers();
  5043. header_matcher5->set_name("header5");
  5044. header_matcher5->set_present_match(true);
  5045. auto* header_matcher6 = route1->mutable_match()->add_headers();
  5046. header_matcher6->set_name("header6");
  5047. header_matcher6->set_prefix_match("/grpc");
  5048. auto* header_matcher7 = route1->mutable_match()->add_headers();
  5049. header_matcher7->set_name("header7");
  5050. header_matcher7->set_suffix_match(".cc");
  5051. header_matcher7->set_invert_match(true);
  5052. route1->mutable_route()->set_cluster(kNewClusterName);
  5053. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  5054. default_route->mutable_match()->set_prefix("");
  5055. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  5056. SetRouteConfiguration(balancer_.get(), route_config);
  5057. std::vector<std::pair<std::string, std::string>> metadata = {
  5058. {"header1", "POST"},
  5059. {"header2", "blah"},
  5060. {"header3", "1"},
  5061. {"header5", "anything"},
  5062. {"header6", "/grpc.testing.EchoTest1Service/"},
  5063. {"header1", "PUT"},
  5064. {"header7", "grpc.java"},
  5065. {"header1", "GET"},
  5066. };
  5067. const auto header_match_rpc_options = RpcOptions()
  5068. .set_rpc_service(SERVICE_ECHO1)
  5069. .set_rpc_method(METHOD_ECHO1)
  5070. .set_metadata(std::move(metadata));
  5071. // Make sure all backends are up.
  5072. WaitForBackend(0);
  5073. WaitForBackend(1, WaitForBackendOptions(), header_match_rpc_options);
  5074. // Send RPCs.
  5075. CheckRpcSendOk(kNumEchoRpcs);
  5076. CheckRpcSendOk(kNumEcho1Rpcs, header_match_rpc_options);
  5077. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  5078. EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
  5079. EXPECT_EQ(0, backends_[0]->backend_service2()->request_count());
  5080. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  5081. EXPECT_EQ(kNumEcho1Rpcs, backends_[1]->backend_service1()->request_count());
  5082. EXPECT_EQ(0, backends_[1]->backend_service2()->request_count());
  5083. auto response_state = RouteConfigurationResponseState(balancer_.get());
  5084. ASSERT_TRUE(response_state.has_value());
  5085. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  5086. }
  5087. TEST_P(LdsRdsTest, XdsRoutingHeadersMatchingSpecialHeaderContentType) {
  5088. const char* kNewClusterName = "new_cluster";
  5089. const char* kNewEdsServiceName = "new_eds_service_name";
  5090. const size_t kNumEchoRpcs = 100;
  5091. // Populate new EDS resources.
  5092. EdsResourceArgs args({
  5093. {"locality0", CreateEndpointsForBackends(0, 1)},
  5094. });
  5095. EdsResourceArgs args1({
  5096. {"locality0", CreateEndpointsForBackends(1, 2)},
  5097. });
  5098. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  5099. balancer_->ads_service()->SetEdsResource(
  5100. BuildEdsResource(args1, kNewEdsServiceName));
  5101. // Populate new CDS resources.
  5102. Cluster new_cluster = default_cluster_;
  5103. new_cluster.set_name(kNewClusterName);
  5104. new_cluster.mutable_eds_cluster_config()->set_service_name(
  5105. kNewEdsServiceName);
  5106. balancer_->ads_service()->SetCdsResource(new_cluster);
  5107. // Populating Route Configurations for LDS.
  5108. RouteConfiguration route_config = default_route_config_;
  5109. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  5110. route1->mutable_match()->set_prefix("");
  5111. auto* header_matcher1 = route1->mutable_match()->add_headers();
  5112. header_matcher1->set_name("content-type");
  5113. header_matcher1->set_exact_match("notapplication/grpc");
  5114. route1->mutable_route()->set_cluster(kNewClusterName);
  5115. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  5116. default_route->mutable_match()->set_prefix("");
  5117. auto* header_matcher2 = default_route->mutable_match()->add_headers();
  5118. header_matcher2->set_name("content-type");
  5119. header_matcher2->set_exact_match("application/grpc");
  5120. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  5121. SetRouteConfiguration(balancer_.get(), route_config);
  5122. // Make sure the backend is up.
  5123. WaitForAllBackends(0, 1);
  5124. // Send RPCs.
  5125. CheckRpcSendOk(kNumEchoRpcs);
  5126. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  5127. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  5128. auto response_state = RouteConfigurationResponseState(balancer_.get());
  5129. ASSERT_TRUE(response_state.has_value());
  5130. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  5131. }
  5132. TEST_P(LdsRdsTest, XdsRoutingHeadersMatchingSpecialCasesToIgnore) {
  5133. const char* kNewCluster1Name = "new_cluster_1";
  5134. const char* kNewEdsService1Name = "new_eds_service_name_1";
  5135. const size_t kNumEchoRpcs = 100;
  5136. // Populate new EDS resources.
  5137. EdsResourceArgs args({
  5138. {"locality0", CreateEndpointsForBackends(0, 1)},
  5139. });
  5140. EdsResourceArgs args1({
  5141. {"locality0", CreateEndpointsForBackends(1, 2)},
  5142. });
  5143. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  5144. balancer_->ads_service()->SetEdsResource(
  5145. BuildEdsResource(args1, kNewEdsService1Name));
  5146. // Populate new CDS resources.
  5147. Cluster new_cluster1 = default_cluster_;
  5148. new_cluster1.set_name(kNewCluster1Name);
  5149. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  5150. kNewEdsService1Name);
  5151. balancer_->ads_service()->SetCdsResource(new_cluster1);
  5152. // Populating Route Configurations for LDS.
  5153. RouteConfiguration route_config = default_route_config_;
  5154. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  5155. route1->mutable_match()->set_prefix("");
  5156. auto* header_matcher1 = route1->mutable_match()->add_headers();
  5157. header_matcher1->set_name("grpc-foo-bin");
  5158. header_matcher1->set_present_match(true);
  5159. route1->mutable_route()->set_cluster(kNewCluster1Name);
  5160. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  5161. default_route->mutable_match()->set_prefix("");
  5162. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  5163. SetRouteConfiguration(balancer_.get(), route_config);
  5164. // Send headers which will mismatch each route
  5165. std::vector<std::pair<std::string, std::string>> metadata = {
  5166. {"grpc-foo-bin", "grpc-foo-bin"},
  5167. };
  5168. WaitForAllBackends(0, 1);
  5169. CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_metadata(metadata));
  5170. // Verify that only the default backend got RPCs since all previous routes
  5171. // were mismatched.
  5172. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  5173. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  5174. auto response_state = RouteConfigurationResponseState(balancer_.get());
  5175. ASSERT_TRUE(response_state.has_value());
  5176. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  5177. }
  5178. TEST_P(LdsRdsTest, XdsRoutingRuntimeFractionMatching) {
  5179. const char* kNewClusterName = "new_cluster";
  5180. const char* kNewEdsServiceName = "new_eds_service_name";
  5181. const double kErrorTolerance = 0.05;
  5182. const size_t kRouteMatchNumerator = 25;
  5183. const double kRouteMatchPercent =
  5184. static_cast<double>(kRouteMatchNumerator) / 100;
  5185. const size_t kNumRpcs =
  5186. ComputeIdealNumRpcs(kRouteMatchPercent, kErrorTolerance);
  5187. // Populate new EDS resources.
  5188. EdsResourceArgs args({
  5189. {"locality0", CreateEndpointsForBackends(0, 1)},
  5190. });
  5191. EdsResourceArgs args1({
  5192. {"locality0", CreateEndpointsForBackends(1, 2)},
  5193. });
  5194. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  5195. balancer_->ads_service()->SetEdsResource(
  5196. BuildEdsResource(args1, kNewEdsServiceName));
  5197. // Populate new CDS resources.
  5198. Cluster new_cluster = default_cluster_;
  5199. new_cluster.set_name(kNewClusterName);
  5200. new_cluster.mutable_eds_cluster_config()->set_service_name(
  5201. kNewEdsServiceName);
  5202. balancer_->ads_service()->SetCdsResource(new_cluster);
  5203. // Populating Route Configurations for LDS.
  5204. RouteConfiguration route_config = default_route_config_;
  5205. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  5206. route1->mutable_match()
  5207. ->mutable_runtime_fraction()
  5208. ->mutable_default_value()
  5209. ->set_numerator(kRouteMatchNumerator);
  5210. route1->mutable_route()->set_cluster(kNewClusterName);
  5211. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  5212. default_route->mutable_match()->set_prefix("");
  5213. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  5214. SetRouteConfiguration(balancer_.get(), route_config);
  5215. WaitForAllBackends(0, 2);
  5216. CheckRpcSendOk(kNumRpcs);
  5217. const int default_backend_count =
  5218. backends_[0]->backend_service()->request_count();
  5219. const int matched_backend_count =
  5220. backends_[1]->backend_service()->request_count();
  5221. EXPECT_THAT(static_cast<double>(default_backend_count) / kNumRpcs,
  5222. ::testing::DoubleNear(1 - kRouteMatchPercent, kErrorTolerance));
  5223. EXPECT_THAT(static_cast<double>(matched_backend_count) / kNumRpcs,
  5224. ::testing::DoubleNear(kRouteMatchPercent, kErrorTolerance));
  5225. auto response_state = RouteConfigurationResponseState(balancer_.get());
  5226. ASSERT_TRUE(response_state.has_value());
  5227. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  5228. }
  5229. TEST_P(LdsRdsTest, XdsRoutingHeadersMatchingUnmatchCases) {
  5230. const char* kNewCluster1Name = "new_cluster_1";
  5231. const char* kNewEdsService1Name = "new_eds_service_name_1";
  5232. const char* kNewCluster2Name = "new_cluster_2";
  5233. const char* kNewEdsService2Name = "new_eds_service_name_2";
  5234. const char* kNewCluster3Name = "new_cluster_3";
  5235. const char* kNewEdsService3Name = "new_eds_service_name_3";
  5236. const size_t kNumEcho1Rpcs = 100;
  5237. const size_t kNumEchoRpcs = 5;
  5238. // Populate new EDS resources.
  5239. EdsResourceArgs args({
  5240. {"locality0", CreateEndpointsForBackends(0, 1)},
  5241. });
  5242. EdsResourceArgs args1({
  5243. {"locality0", CreateEndpointsForBackends(1, 2)},
  5244. });
  5245. EdsResourceArgs args2({
  5246. {"locality0", CreateEndpointsForBackends(2, 3)},
  5247. });
  5248. EdsResourceArgs args3({
  5249. {"locality0", CreateEndpointsForBackends(3, 4)},
  5250. });
  5251. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  5252. balancer_->ads_service()->SetEdsResource(
  5253. BuildEdsResource(args1, kNewEdsService1Name));
  5254. balancer_->ads_service()->SetEdsResource(
  5255. BuildEdsResource(args2, kNewEdsService2Name));
  5256. balancer_->ads_service()->SetEdsResource(
  5257. BuildEdsResource(args3, kNewEdsService3Name));
  5258. // Populate new CDS resources.
  5259. Cluster new_cluster1 = default_cluster_;
  5260. new_cluster1.set_name(kNewCluster1Name);
  5261. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  5262. kNewEdsService1Name);
  5263. balancer_->ads_service()->SetCdsResource(new_cluster1);
  5264. Cluster new_cluster2 = default_cluster_;
  5265. new_cluster2.set_name(kNewCluster2Name);
  5266. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  5267. kNewEdsService2Name);
  5268. balancer_->ads_service()->SetCdsResource(new_cluster2);
  5269. Cluster new_cluster3 = default_cluster_;
  5270. new_cluster3.set_name(kNewCluster3Name);
  5271. new_cluster3.mutable_eds_cluster_config()->set_service_name(
  5272. kNewEdsService3Name);
  5273. balancer_->ads_service()->SetCdsResource(new_cluster3);
  5274. // Populating Route Configurations for LDS.
  5275. RouteConfiguration route_config = default_route_config_;
  5276. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  5277. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  5278. auto* header_matcher1 = route1->mutable_match()->add_headers();
  5279. header_matcher1->set_name("header1");
  5280. header_matcher1->set_exact_match("POST");
  5281. route1->mutable_route()->set_cluster(kNewCluster1Name);
  5282. auto route2 = route_config.mutable_virtual_hosts(0)->add_routes();
  5283. route2->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  5284. auto* header_matcher2 = route2->mutable_match()->add_headers();
  5285. header_matcher2->set_name("header2");
  5286. header_matcher2->mutable_range_match()->set_start(1);
  5287. header_matcher2->mutable_range_match()->set_end(1000);
  5288. route2->mutable_route()->set_cluster(kNewCluster2Name);
  5289. auto route3 = route_config.mutable_virtual_hosts(0)->add_routes();
  5290. route3->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  5291. auto* header_matcher3 = route3->mutable_match()->add_headers();
  5292. header_matcher3->set_name("header3");
  5293. header_matcher3->mutable_safe_regex_match()->set_regex("[a-z]*");
  5294. route3->mutable_route()->set_cluster(kNewCluster3Name);
  5295. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  5296. default_route->mutable_match()->set_prefix("");
  5297. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  5298. SetRouteConfiguration(balancer_.get(), route_config);
  5299. // Send headers which will mismatch each route
  5300. std::vector<std::pair<std::string, std::string>> metadata = {
  5301. {"header1", "POST"},
  5302. {"header2", "1000"},
  5303. {"header3", "123"},
  5304. {"header1", "GET"},
  5305. };
  5306. WaitForAllBackends(0, 1);
  5307. CheckRpcSendOk(kNumEchoRpcs, RpcOptions().set_metadata(metadata));
  5308. CheckRpcSendOk(kNumEcho1Rpcs, RpcOptions()
  5309. .set_rpc_service(SERVICE_ECHO1)
  5310. .set_rpc_method(METHOD_ECHO1)
  5311. .set_metadata(metadata));
  5312. // Verify that only the default backend got RPCs since all previous routes
  5313. // were mismatched.
  5314. for (size_t i = 1; i < 4; ++i) {
  5315. EXPECT_EQ(0, backends_[i]->backend_service()->request_count());
  5316. EXPECT_EQ(0, backends_[i]->backend_service1()->request_count());
  5317. EXPECT_EQ(0, backends_[i]->backend_service2()->request_count());
  5318. }
  5319. EXPECT_EQ(kNumEchoRpcs, backends_[0]->backend_service()->request_count());
  5320. EXPECT_EQ(kNumEcho1Rpcs, backends_[0]->backend_service1()->request_count());
  5321. EXPECT_EQ(0, backends_[0]->backend_service2()->request_count());
  5322. auto response_state = RouteConfigurationResponseState(balancer_.get());
  5323. ASSERT_TRUE(response_state.has_value());
  5324. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  5325. }
  5326. TEST_P(LdsRdsTest, XdsRoutingChangeRoutesWithoutChangingClusters) {
  5327. const char* kNewClusterName = "new_cluster";
  5328. const char* kNewEdsServiceName = "new_eds_service_name";
  5329. // Populate new EDS resources.
  5330. EdsResourceArgs args({
  5331. {"locality0", CreateEndpointsForBackends(0, 1)},
  5332. });
  5333. EdsResourceArgs args1({
  5334. {"locality0", CreateEndpointsForBackends(1, 2)},
  5335. });
  5336. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  5337. balancer_->ads_service()->SetEdsResource(
  5338. BuildEdsResource(args1, kNewEdsServiceName));
  5339. // Populate new CDS resources.
  5340. Cluster new_cluster = default_cluster_;
  5341. new_cluster.set_name(kNewClusterName);
  5342. new_cluster.mutable_eds_cluster_config()->set_service_name(
  5343. kNewEdsServiceName);
  5344. balancer_->ads_service()->SetCdsResource(new_cluster);
  5345. // Populating Route Configurations for LDS.
  5346. RouteConfiguration route_config = default_route_config_;
  5347. auto* route1 = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  5348. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest1Service/");
  5349. route1->mutable_route()->set_cluster(kNewClusterName);
  5350. auto* default_route = route_config.mutable_virtual_hosts(0)->add_routes();
  5351. default_route->mutable_match()->set_prefix("");
  5352. default_route->mutable_route()->set_cluster(kDefaultClusterName);
  5353. SetRouteConfiguration(balancer_.get(), route_config);
  5354. // Make sure all backends are up and that requests for each RPC
  5355. // service go to the right backends.
  5356. WaitForBackend(0, WaitForBackendOptions().set_reset_counters(false));
  5357. WaitForBackend(1, WaitForBackendOptions().set_reset_counters(false),
  5358. RpcOptions().set_rpc_service(SERVICE_ECHO1));
  5359. WaitForBackend(0, WaitForBackendOptions().set_reset_counters(false),
  5360. RpcOptions().set_rpc_service(SERVICE_ECHO2));
  5361. // Requests for services Echo and Echo2 should have gone to backend 0.
  5362. EXPECT_EQ(1, backends_[0]->backend_service()->request_count());
  5363. EXPECT_EQ(0, backends_[0]->backend_service1()->request_count());
  5364. EXPECT_EQ(1, backends_[0]->backend_service2()->request_count());
  5365. // Requests for service Echo1 should have gone to backend 1.
  5366. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  5367. EXPECT_EQ(1, backends_[1]->backend_service1()->request_count());
  5368. EXPECT_EQ(0, backends_[1]->backend_service2()->request_count());
  5369. // Now send an update that changes the first route to match a
  5370. // different RPC service, and wait for the client to make the change.
  5371. route1->mutable_match()->set_prefix("/grpc.testing.EchoTest2Service/");
  5372. SetRouteConfiguration(balancer_.get(), route_config);
  5373. WaitForBackend(1, WaitForBackendOptions(),
  5374. RpcOptions().set_rpc_service(SERVICE_ECHO2));
  5375. // Now repeat the earlier test, making sure all traffic goes to the
  5376. // right place.
  5377. WaitForBackend(0, WaitForBackendOptions().set_reset_counters(false));
  5378. WaitForBackend(0, WaitForBackendOptions().set_reset_counters(false),
  5379. RpcOptions().set_rpc_service(SERVICE_ECHO1));
  5380. WaitForBackend(1, WaitForBackendOptions().set_reset_counters(false),
  5381. RpcOptions().set_rpc_service(SERVICE_ECHO2));
  5382. // Requests for services Echo and Echo1 should have gone to backend 0.
  5383. EXPECT_EQ(1, backends_[0]->backend_service()->request_count());
  5384. EXPECT_EQ(1, backends_[0]->backend_service1()->request_count());
  5385. EXPECT_EQ(0, backends_[0]->backend_service2()->request_count());
  5386. // Requests for service Echo2 should have gone to backend 1.
  5387. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  5388. EXPECT_EQ(0, backends_[1]->backend_service1()->request_count());
  5389. EXPECT_EQ(1, backends_[1]->backend_service2()->request_count());
  5390. }
  5391. // Test that we NACK unknown filter types in VirtualHost.
  5392. TEST_P(LdsRdsTest, RejectsUnknownHttpFilterTypeInVirtualHost) {
  5393. if (GetParam().use_v2()) return; // Filters supported in v3 only.
  5394. RouteConfiguration route_config = default_route_config_;
  5395. auto* per_filter_config =
  5396. route_config.mutable_virtual_hosts(0)->mutable_typed_per_filter_config();
  5397. (*per_filter_config)["unknown"].PackFrom(Listener());
  5398. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  5399. route_config);
  5400. const auto response_state = WaitForRdsNack();
  5401. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  5402. EXPECT_THAT(response_state->error_message,
  5403. ::testing::HasSubstr("no filter registered for config type "
  5404. "envoy.config.listener.v3.Listener"));
  5405. }
  5406. // Test that we ignore optional unknown filter types in VirtualHost.
  5407. TEST_P(LdsRdsTest, IgnoresOptionalUnknownHttpFilterTypeInVirtualHost) {
  5408. if (GetParam().use_v2()) return; // Filters supported in v3 only.
  5409. RouteConfiguration route_config = default_route_config_;
  5410. auto* per_filter_config =
  5411. route_config.mutable_virtual_hosts(0)->mutable_typed_per_filter_config();
  5412. ::envoy::config::route::v3::FilterConfig filter_config;
  5413. filter_config.mutable_config()->PackFrom(Listener());
  5414. filter_config.set_is_optional(true);
  5415. (*per_filter_config)["unknown"].PackFrom(filter_config);
  5416. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  5417. route_config);
  5418. EdsResourceArgs args({
  5419. {"locality0", CreateEndpointsForBackends()},
  5420. });
  5421. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  5422. WaitForAllBackends();
  5423. auto response_state = RouteConfigurationResponseState(balancer_.get());
  5424. ASSERT_TRUE(response_state.has_value());
  5425. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  5426. }
  5427. // Test that we NACK filters without configs in VirtualHost.
  5428. TEST_P(LdsRdsTest, RejectsHttpFilterWithoutConfigInVirtualHost) {
  5429. if (GetParam().use_v2()) return; // Filters supported in v3 only.
  5430. RouteConfiguration route_config = default_route_config_;
  5431. auto* per_filter_config =
  5432. route_config.mutable_virtual_hosts(0)->mutable_typed_per_filter_config();
  5433. (*per_filter_config)["unknown"];
  5434. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  5435. route_config);
  5436. const auto response_state = WaitForRdsNack();
  5437. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  5438. EXPECT_THAT(response_state->error_message,
  5439. ::testing::HasSubstr(
  5440. "no filter config specified for filter name unknown"));
  5441. }
  5442. // Test that we NACK filters without configs in FilterConfig in VirtualHost.
  5443. TEST_P(LdsRdsTest, RejectsHttpFilterWithoutConfigInFilterConfigInVirtualHost) {
  5444. if (GetParam().use_v2()) return; // Filters supported in v3 only.
  5445. RouteConfiguration route_config = default_route_config_;
  5446. auto* per_filter_config =
  5447. route_config.mutable_virtual_hosts(0)->mutable_typed_per_filter_config();
  5448. (*per_filter_config)["unknown"].PackFrom(
  5449. ::envoy::config::route::v3::FilterConfig());
  5450. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  5451. route_config);
  5452. const auto response_state = WaitForRdsNack();
  5453. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  5454. EXPECT_THAT(response_state->error_message,
  5455. ::testing::HasSubstr(
  5456. "no filter config specified for filter name unknown"));
  5457. }
  5458. // Test that we ignore optional filters without configs in VirtualHost.
  5459. TEST_P(LdsRdsTest, IgnoresOptionalHttpFilterWithoutConfigInVirtualHost) {
  5460. if (GetParam().use_v2()) return; // Filters supported in v3 only.
  5461. RouteConfiguration route_config = default_route_config_;
  5462. auto* per_filter_config =
  5463. route_config.mutable_virtual_hosts(0)->mutable_typed_per_filter_config();
  5464. ::envoy::config::route::v3::FilterConfig filter_config;
  5465. filter_config.set_is_optional(true);
  5466. (*per_filter_config)["unknown"].PackFrom(filter_config);
  5467. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  5468. route_config);
  5469. EdsResourceArgs args({
  5470. {"locality0", CreateEndpointsForBackends()},
  5471. });
  5472. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  5473. WaitForAllBackends();
  5474. auto response_state = RouteConfigurationResponseState(balancer_.get());
  5475. ASSERT_TRUE(response_state.has_value());
  5476. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  5477. }
  5478. // Test that we NACK unparseable filter types in VirtualHost.
  5479. TEST_P(LdsRdsTest, RejectsUnparseableHttpFilterTypeInVirtualHost) {
  5480. if (GetParam().use_v2()) return; // Filters supported in v3 only.
  5481. RouteConfiguration route_config = default_route_config_;
  5482. auto* per_filter_config =
  5483. route_config.mutable_virtual_hosts(0)->mutable_typed_per_filter_config();
  5484. (*per_filter_config)["unknown"].PackFrom(
  5485. envoy::extensions::filters::http::router::v3::Router());
  5486. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  5487. route_config);
  5488. const auto response_state = WaitForRdsNack();
  5489. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  5490. EXPECT_THAT(
  5491. response_state->error_message,
  5492. ::testing::HasSubstr("router filter does not support config override"));
  5493. }
  5494. // Test that we NACK unknown filter types in Route.
  5495. TEST_P(LdsRdsTest, RejectsUnknownHttpFilterTypeInRoute) {
  5496. if (GetParam().use_v2()) return; // Filters supported in v3 only.
  5497. RouteConfiguration route_config = default_route_config_;
  5498. auto* per_filter_config = route_config.mutable_virtual_hosts(0)
  5499. ->mutable_routes(0)
  5500. ->mutable_typed_per_filter_config();
  5501. (*per_filter_config)["unknown"].PackFrom(Listener());
  5502. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  5503. route_config);
  5504. const auto response_state = WaitForRdsNack();
  5505. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  5506. EXPECT_THAT(response_state->error_message,
  5507. ::testing::HasSubstr("no filter registered for config type "
  5508. "envoy.config.listener.v3.Listener"));
  5509. }
  5510. // Test that we ignore optional unknown filter types in Route.
  5511. TEST_P(LdsRdsTest, IgnoresOptionalUnknownHttpFilterTypeInRoute) {
  5512. if (GetParam().use_v2()) return; // Filters supported in v3 only.
  5513. RouteConfiguration route_config = default_route_config_;
  5514. auto* per_filter_config = route_config.mutable_virtual_hosts(0)
  5515. ->mutable_routes(0)
  5516. ->mutable_typed_per_filter_config();
  5517. ::envoy::config::route::v3::FilterConfig filter_config;
  5518. filter_config.mutable_config()->PackFrom(Listener());
  5519. filter_config.set_is_optional(true);
  5520. (*per_filter_config)["unknown"].PackFrom(filter_config);
  5521. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  5522. route_config);
  5523. EdsResourceArgs args({
  5524. {"locality0", CreateEndpointsForBackends()},
  5525. });
  5526. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  5527. WaitForAllBackends();
  5528. auto response_state = RouteConfigurationResponseState(balancer_.get());
  5529. ASSERT_TRUE(response_state.has_value());
  5530. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  5531. }
  5532. // Test that we NACK filters without configs in Route.
  5533. TEST_P(LdsRdsTest, RejectsHttpFilterWithoutConfigInRoute) {
  5534. if (GetParam().use_v2()) return; // Filters supported in v3 only.
  5535. RouteConfiguration route_config = default_route_config_;
  5536. auto* per_filter_config = route_config.mutable_virtual_hosts(0)
  5537. ->mutable_routes(0)
  5538. ->mutable_typed_per_filter_config();
  5539. (*per_filter_config)["unknown"];
  5540. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  5541. route_config);
  5542. const auto response_state = WaitForRdsNack();
  5543. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  5544. EXPECT_THAT(response_state->error_message,
  5545. ::testing::HasSubstr(
  5546. "no filter config specified for filter name unknown"));
  5547. }
  5548. // Test that we NACK filters without configs in FilterConfig in Route.
  5549. TEST_P(LdsRdsTest, RejectsHttpFilterWithoutConfigInFilterConfigInRoute) {
  5550. if (GetParam().use_v2()) return; // Filters supported in v3 only.
  5551. RouteConfiguration route_config = default_route_config_;
  5552. auto* per_filter_config = route_config.mutable_virtual_hosts(0)
  5553. ->mutable_routes(0)
  5554. ->mutable_typed_per_filter_config();
  5555. (*per_filter_config)["unknown"].PackFrom(
  5556. ::envoy::config::route::v3::FilterConfig());
  5557. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  5558. route_config);
  5559. const auto response_state = WaitForRdsNack();
  5560. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  5561. EXPECT_THAT(response_state->error_message,
  5562. ::testing::HasSubstr(
  5563. "no filter config specified for filter name unknown"));
  5564. }
  5565. // Test that we ignore optional filters without configs in Route.
  5566. TEST_P(LdsRdsTest, IgnoresOptionalHttpFilterWithoutConfigInRoute) {
  5567. if (GetParam().use_v2()) return; // Filters supported in v3 only.
  5568. RouteConfiguration route_config = default_route_config_;
  5569. auto* per_filter_config = route_config.mutable_virtual_hosts(0)
  5570. ->mutable_routes(0)
  5571. ->mutable_typed_per_filter_config();
  5572. ::envoy::config::route::v3::FilterConfig filter_config;
  5573. filter_config.set_is_optional(true);
  5574. (*per_filter_config)["unknown"].PackFrom(filter_config);
  5575. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  5576. route_config);
  5577. EdsResourceArgs args({
  5578. {"locality0", CreateEndpointsForBackends()},
  5579. });
  5580. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  5581. WaitForAllBackends();
  5582. auto response_state = RouteConfigurationResponseState(balancer_.get());
  5583. ASSERT_TRUE(response_state.has_value());
  5584. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  5585. }
  5586. // Test that we NACK unparseable filter types in Route.
  5587. TEST_P(LdsRdsTest, RejectsUnparseableHttpFilterTypeInRoute) {
  5588. if (GetParam().use_v2()) return; // Filters supported in v3 only.
  5589. RouteConfiguration route_config = default_route_config_;
  5590. auto* per_filter_config = route_config.mutable_virtual_hosts(0)
  5591. ->mutable_routes(0)
  5592. ->mutable_typed_per_filter_config();
  5593. (*per_filter_config)["unknown"].PackFrom(
  5594. envoy::extensions::filters::http::router::v3::Router());
  5595. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  5596. route_config);
  5597. const auto response_state = WaitForRdsNack();
  5598. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  5599. EXPECT_THAT(
  5600. response_state->error_message,
  5601. ::testing::HasSubstr("router filter does not support config override"));
  5602. }
  5603. // Test that we NACK unknown filter types in ClusterWeight.
  5604. TEST_P(LdsRdsTest, RejectsUnknownHttpFilterTypeInClusterWeight) {
  5605. if (GetParam().use_v2()) return; // Filters supported in v3 only.
  5606. RouteConfiguration route_config = default_route_config_;
  5607. auto* cluster_weight = route_config.mutable_virtual_hosts(0)
  5608. ->mutable_routes(0)
  5609. ->mutable_route()
  5610. ->mutable_weighted_clusters()
  5611. ->add_clusters();
  5612. cluster_weight->set_name(kDefaultClusterName);
  5613. cluster_weight->mutable_weight()->set_value(100);
  5614. auto* per_filter_config = cluster_weight->mutable_typed_per_filter_config();
  5615. (*per_filter_config)["unknown"].PackFrom(Listener());
  5616. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  5617. route_config);
  5618. const auto response_state = WaitForRdsNack();
  5619. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  5620. EXPECT_THAT(response_state->error_message,
  5621. ::testing::HasSubstr("no filter registered for config type "
  5622. "envoy.config.listener.v3.Listener"));
  5623. }
  5624. // Test that we ignore optional unknown filter types in ClusterWeight.
  5625. TEST_P(LdsRdsTest, IgnoresOptionalUnknownHttpFilterTypeInClusterWeight) {
  5626. if (GetParam().use_v2()) return; // Filters supported in v3 only.
  5627. RouteConfiguration route_config = default_route_config_;
  5628. auto* cluster_weight = route_config.mutable_virtual_hosts(0)
  5629. ->mutable_routes(0)
  5630. ->mutable_route()
  5631. ->mutable_weighted_clusters()
  5632. ->add_clusters();
  5633. cluster_weight->set_name(kDefaultClusterName);
  5634. cluster_weight->mutable_weight()->set_value(100);
  5635. auto* per_filter_config = cluster_weight->mutable_typed_per_filter_config();
  5636. ::envoy::config::route::v3::FilterConfig filter_config;
  5637. filter_config.mutable_config()->PackFrom(Listener());
  5638. filter_config.set_is_optional(true);
  5639. (*per_filter_config)["unknown"].PackFrom(filter_config);
  5640. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  5641. route_config);
  5642. EdsResourceArgs args({
  5643. {"locality0", CreateEndpointsForBackends()},
  5644. });
  5645. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  5646. WaitForAllBackends();
  5647. auto response_state = RouteConfigurationResponseState(balancer_.get());
  5648. ASSERT_TRUE(response_state.has_value());
  5649. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  5650. }
  5651. // Test that we NACK filters without configs in ClusterWeight.
  5652. TEST_P(LdsRdsTest, RejectsHttpFilterWithoutConfigInClusterWeight) {
  5653. if (GetParam().use_v2()) return; // Filters supported in v3 only.
  5654. RouteConfiguration route_config = default_route_config_;
  5655. auto* cluster_weight = route_config.mutable_virtual_hosts(0)
  5656. ->mutable_routes(0)
  5657. ->mutable_route()
  5658. ->mutable_weighted_clusters()
  5659. ->add_clusters();
  5660. cluster_weight->set_name(kDefaultClusterName);
  5661. cluster_weight->mutable_weight()->set_value(100);
  5662. auto* per_filter_config = cluster_weight->mutable_typed_per_filter_config();
  5663. (*per_filter_config)["unknown"];
  5664. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  5665. route_config);
  5666. const auto response_state = WaitForRdsNack();
  5667. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  5668. EXPECT_THAT(response_state->error_message,
  5669. ::testing::HasSubstr(
  5670. "no filter config specified for filter name unknown"));
  5671. }
  5672. // Test that we NACK filters without configs in FilterConfig in ClusterWeight.
  5673. TEST_P(LdsRdsTest,
  5674. RejectsHttpFilterWithoutConfigInFilterConfigInClusterWeight) {
  5675. if (GetParam().use_v2()) return; // Filters supported in v3 only.
  5676. RouteConfiguration route_config = default_route_config_;
  5677. auto* cluster_weight = route_config.mutable_virtual_hosts(0)
  5678. ->mutable_routes(0)
  5679. ->mutable_route()
  5680. ->mutable_weighted_clusters()
  5681. ->add_clusters();
  5682. cluster_weight->set_name(kDefaultClusterName);
  5683. cluster_weight->mutable_weight()->set_value(100);
  5684. auto* per_filter_config = cluster_weight->mutable_typed_per_filter_config();
  5685. (*per_filter_config)["unknown"].PackFrom(
  5686. ::envoy::config::route::v3::FilterConfig());
  5687. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  5688. route_config);
  5689. const auto response_state = WaitForRdsNack();
  5690. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  5691. EXPECT_THAT(response_state->error_message,
  5692. ::testing::HasSubstr(
  5693. "no filter config specified for filter name unknown"));
  5694. }
  5695. // Test that we ignore optional filters without configs in ClusterWeight.
  5696. TEST_P(LdsRdsTest, IgnoresOptionalHttpFilterWithoutConfigInClusterWeight) {
  5697. if (GetParam().use_v2()) return; // Filters supported in v3 only.
  5698. RouteConfiguration route_config = default_route_config_;
  5699. auto* cluster_weight = route_config.mutable_virtual_hosts(0)
  5700. ->mutable_routes(0)
  5701. ->mutable_route()
  5702. ->mutable_weighted_clusters()
  5703. ->add_clusters();
  5704. cluster_weight->set_name(kDefaultClusterName);
  5705. cluster_weight->mutable_weight()->set_value(100);
  5706. auto* per_filter_config = cluster_weight->mutable_typed_per_filter_config();
  5707. ::envoy::config::route::v3::FilterConfig filter_config;
  5708. filter_config.set_is_optional(true);
  5709. (*per_filter_config)["unknown"].PackFrom(filter_config);
  5710. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  5711. route_config);
  5712. EdsResourceArgs args({
  5713. {"locality0", CreateEndpointsForBackends()},
  5714. });
  5715. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  5716. WaitForAllBackends();
  5717. auto response_state = RouteConfigurationResponseState(balancer_.get());
  5718. ASSERT_TRUE(response_state.has_value());
  5719. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  5720. }
  5721. // Test that we NACK unparseable filter types in ClusterWeight.
  5722. TEST_P(LdsRdsTest, RejectsUnparseableHttpFilterTypeInClusterWeight) {
  5723. if (GetParam().use_v2()) return; // Filters supported in v3 only.
  5724. RouteConfiguration route_config = default_route_config_;
  5725. auto* cluster_weight = route_config.mutable_virtual_hosts(0)
  5726. ->mutable_routes(0)
  5727. ->mutable_route()
  5728. ->mutable_weighted_clusters()
  5729. ->add_clusters();
  5730. cluster_weight->set_name(kDefaultClusterName);
  5731. cluster_weight->mutable_weight()->set_value(100);
  5732. auto* per_filter_config = cluster_weight->mutable_typed_per_filter_config();
  5733. (*per_filter_config)["unknown"].PackFrom(
  5734. envoy::extensions::filters::http::router::v3::Router());
  5735. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  5736. route_config);
  5737. const auto response_state = WaitForRdsNack();
  5738. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  5739. EXPECT_THAT(
  5740. response_state->error_message,
  5741. ::testing::HasSubstr("router filter does not support config override"));
  5742. }
  5743. using CdsTest = BasicTest;
  5744. // Tests that CDS client should send an ACK upon correct CDS response.
  5745. TEST_P(CdsTest, Vanilla) {
  5746. (void)SendRpc();
  5747. auto response_state = balancer_->ads_service()->cds_response_state();
  5748. ASSERT_TRUE(response_state.has_value());
  5749. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  5750. }
  5751. TEST_P(CdsTest, LogicalDNSClusterType) {
  5752. gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER",
  5753. "true");
  5754. // Create Logical DNS Cluster
  5755. auto cluster = default_cluster_;
  5756. cluster.set_type(Cluster::LOGICAL_DNS);
  5757. auto* address = cluster.mutable_load_assignment()
  5758. ->add_endpoints()
  5759. ->add_lb_endpoints()
  5760. ->mutable_endpoint()
  5761. ->mutable_address()
  5762. ->mutable_socket_address();
  5763. address->set_address(kServerName);
  5764. address->set_port_value(443);
  5765. balancer_->ads_service()->SetCdsResource(cluster);
  5766. // Set Logical DNS result
  5767. {
  5768. grpc_core::ExecCtx exec_ctx;
  5769. grpc_core::Resolver::Result result;
  5770. result.addresses = CreateAddressListFromPortList(GetBackendPorts(1, 2));
  5771. logical_dns_cluster_resolver_response_generator_->SetResponse(
  5772. std::move(result));
  5773. }
  5774. // Wait for traffic to go to backend 1.
  5775. WaitForBackend(1);
  5776. gpr_unsetenv(
  5777. "GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER");
  5778. }
  5779. TEST_P(CdsTest, LogicalDNSClusterTypeMissingLoadAssignment) {
  5780. gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER",
  5781. "true");
  5782. // Create Logical DNS Cluster
  5783. auto cluster = default_cluster_;
  5784. cluster.set_type(Cluster::LOGICAL_DNS);
  5785. balancer_->ads_service()->SetCdsResource(cluster);
  5786. const auto response_state = WaitForCdsNack();
  5787. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  5788. EXPECT_THAT(response_state->error_message,
  5789. ::testing::HasSubstr(
  5790. "load_assignment not present for LOGICAL_DNS cluster"));
  5791. gpr_unsetenv(
  5792. "GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER");
  5793. }
  5794. TEST_P(CdsTest, LogicalDNSClusterTypeMissingLocalities) {
  5795. gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER",
  5796. "true");
  5797. // Create Logical DNS Cluster
  5798. auto cluster = default_cluster_;
  5799. cluster.set_type(Cluster::LOGICAL_DNS);
  5800. cluster.mutable_load_assignment();
  5801. balancer_->ads_service()->SetCdsResource(cluster);
  5802. const auto response_state = WaitForCdsNack();
  5803. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  5804. EXPECT_THAT(
  5805. response_state->error_message,
  5806. ::testing::HasSubstr("load_assignment for LOGICAL_DNS cluster must have "
  5807. "exactly one locality, found 0"));
  5808. gpr_unsetenv(
  5809. "GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER");
  5810. }
  5811. TEST_P(CdsTest, LogicalDNSClusterTypeMultipleLocalities) {
  5812. gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER",
  5813. "true");
  5814. // Create Logical DNS Cluster
  5815. auto cluster = default_cluster_;
  5816. cluster.set_type(Cluster::LOGICAL_DNS);
  5817. auto* load_assignment = cluster.mutable_load_assignment();
  5818. load_assignment->add_endpoints();
  5819. load_assignment->add_endpoints();
  5820. balancer_->ads_service()->SetCdsResource(cluster);
  5821. const auto response_state = WaitForCdsNack();
  5822. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  5823. EXPECT_THAT(
  5824. response_state->error_message,
  5825. ::testing::HasSubstr("load_assignment for LOGICAL_DNS cluster must have "
  5826. "exactly one locality, found 2"));
  5827. gpr_unsetenv(
  5828. "GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER");
  5829. }
  5830. TEST_P(CdsTest, LogicalDNSClusterTypeMissingEndpoints) {
  5831. gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER",
  5832. "true");
  5833. // Create Logical DNS Cluster
  5834. auto cluster = default_cluster_;
  5835. cluster.set_type(Cluster::LOGICAL_DNS);
  5836. cluster.mutable_load_assignment()->add_endpoints();
  5837. balancer_->ads_service()->SetCdsResource(cluster);
  5838. const auto response_state = WaitForCdsNack();
  5839. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  5840. EXPECT_THAT(response_state->error_message,
  5841. ::testing::HasSubstr(
  5842. "locality for LOGICAL_DNS cluster must have exactly one "
  5843. "endpoint, found 0"));
  5844. gpr_unsetenv(
  5845. "GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER");
  5846. }
  5847. TEST_P(CdsTest, LogicalDNSClusterTypeMultipleEndpoints) {
  5848. gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER",
  5849. "true");
  5850. // Create Logical DNS Cluster
  5851. auto cluster = default_cluster_;
  5852. cluster.set_type(Cluster::LOGICAL_DNS);
  5853. auto* locality = cluster.mutable_load_assignment()->add_endpoints();
  5854. locality->add_lb_endpoints();
  5855. locality->add_lb_endpoints();
  5856. balancer_->ads_service()->SetCdsResource(cluster);
  5857. const auto response_state = WaitForCdsNack();
  5858. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  5859. EXPECT_THAT(response_state->error_message,
  5860. ::testing::HasSubstr(
  5861. "locality for LOGICAL_DNS cluster must have exactly one "
  5862. "endpoint, found 2"));
  5863. gpr_unsetenv(
  5864. "GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER");
  5865. }
  5866. TEST_P(CdsTest, LogicalDNSClusterTypeEmptyEndpoint) {
  5867. gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER",
  5868. "true");
  5869. // Create Logical DNS Cluster
  5870. auto cluster = default_cluster_;
  5871. cluster.set_type(Cluster::LOGICAL_DNS);
  5872. cluster.mutable_load_assignment()->add_endpoints()->add_lb_endpoints();
  5873. balancer_->ads_service()->SetCdsResource(cluster);
  5874. const auto response_state = WaitForCdsNack();
  5875. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  5876. EXPECT_THAT(response_state->error_message,
  5877. ::testing::HasSubstr("LbEndpoint endpoint field not set"));
  5878. gpr_unsetenv(
  5879. "GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER");
  5880. }
  5881. TEST_P(CdsTest, LogicalDNSClusterTypeEndpointMissingAddress) {
  5882. gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER",
  5883. "true");
  5884. // Create Logical DNS Cluster
  5885. auto cluster = default_cluster_;
  5886. cluster.set_type(Cluster::LOGICAL_DNS);
  5887. cluster.mutable_load_assignment()
  5888. ->add_endpoints()
  5889. ->add_lb_endpoints()
  5890. ->mutable_endpoint();
  5891. balancer_->ads_service()->SetCdsResource(cluster);
  5892. const auto response_state = WaitForCdsNack();
  5893. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  5894. EXPECT_THAT(response_state->error_message,
  5895. ::testing::HasSubstr("Endpoint address field not set"));
  5896. gpr_unsetenv(
  5897. "GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER");
  5898. }
  5899. TEST_P(CdsTest, LogicalDNSClusterTypeAddressMissingSocketAddress) {
  5900. gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER",
  5901. "true");
  5902. // Create Logical DNS Cluster
  5903. auto cluster = default_cluster_;
  5904. cluster.set_type(Cluster::LOGICAL_DNS);
  5905. cluster.mutable_load_assignment()
  5906. ->add_endpoints()
  5907. ->add_lb_endpoints()
  5908. ->mutable_endpoint()
  5909. ->mutable_address();
  5910. balancer_->ads_service()->SetCdsResource(cluster);
  5911. const auto response_state = WaitForCdsNack();
  5912. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  5913. EXPECT_THAT(response_state->error_message,
  5914. ::testing::HasSubstr("Address socket_address field not set"));
  5915. gpr_unsetenv(
  5916. "GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER");
  5917. }
  5918. TEST_P(CdsTest, LogicalDNSClusterTypeSocketAddressHasResolverName) {
  5919. gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER",
  5920. "true");
  5921. // Create Logical DNS Cluster
  5922. auto cluster = default_cluster_;
  5923. cluster.set_type(Cluster::LOGICAL_DNS);
  5924. cluster.mutable_load_assignment()
  5925. ->add_endpoints()
  5926. ->add_lb_endpoints()
  5927. ->mutable_endpoint()
  5928. ->mutable_address()
  5929. ->mutable_socket_address()
  5930. ->set_resolver_name("foo");
  5931. balancer_->ads_service()->SetCdsResource(cluster);
  5932. const auto response_state = WaitForCdsNack();
  5933. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  5934. EXPECT_THAT(response_state->error_message,
  5935. ::testing::HasSubstr("LOGICAL_DNS clusters must NOT have a "
  5936. "custom resolver name set"));
  5937. gpr_unsetenv(
  5938. "GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER");
  5939. }
  5940. TEST_P(CdsTest, LogicalDNSClusterTypeSocketAddressMissingAddress) {
  5941. gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER",
  5942. "true");
  5943. // Create Logical DNS Cluster
  5944. auto cluster = default_cluster_;
  5945. cluster.set_type(Cluster::LOGICAL_DNS);
  5946. cluster.mutable_load_assignment()
  5947. ->add_endpoints()
  5948. ->add_lb_endpoints()
  5949. ->mutable_endpoint()
  5950. ->mutable_address()
  5951. ->mutable_socket_address();
  5952. balancer_->ads_service()->SetCdsResource(cluster);
  5953. const auto response_state = WaitForCdsNack();
  5954. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  5955. EXPECT_THAT(response_state->error_message,
  5956. ::testing::HasSubstr("SocketAddress address field not set"));
  5957. gpr_unsetenv(
  5958. "GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER");
  5959. }
  5960. TEST_P(CdsTest, LogicalDNSClusterTypeSocketAddressMissingPort) {
  5961. gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER",
  5962. "true");
  5963. // Create Logical DNS Cluster
  5964. auto cluster = default_cluster_;
  5965. cluster.set_type(Cluster::LOGICAL_DNS);
  5966. cluster.mutable_load_assignment()
  5967. ->add_endpoints()
  5968. ->add_lb_endpoints()
  5969. ->mutable_endpoint()
  5970. ->mutable_address()
  5971. ->mutable_socket_address()
  5972. ->set_address(kServerName);
  5973. balancer_->ads_service()->SetCdsResource(cluster);
  5974. const auto response_state = WaitForCdsNack();
  5975. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  5976. EXPECT_THAT(response_state->error_message,
  5977. ::testing::HasSubstr("SocketAddress port_value field not set"));
  5978. gpr_unsetenv(
  5979. "GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER");
  5980. }
  5981. TEST_P(CdsTest, AggregateClusterType) {
  5982. gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER",
  5983. "true");
  5984. const char* kNewCluster1Name = "new_cluster_1";
  5985. const char* kNewEdsService1Name = "new_eds_service_name_1";
  5986. const char* kNewCluster2Name = "new_cluster_2";
  5987. const char* kNewEdsService2Name = "new_eds_service_name_2";
  5988. // Populate new EDS resources.
  5989. EdsResourceArgs args1({
  5990. {"locality0", CreateEndpointsForBackends(1, 2)},
  5991. });
  5992. EdsResourceArgs args2({
  5993. {"locality0", CreateEndpointsForBackends(2, 3)},
  5994. });
  5995. balancer_->ads_service()->SetEdsResource(
  5996. BuildEdsResource(args1, kNewEdsService1Name));
  5997. balancer_->ads_service()->SetEdsResource(
  5998. BuildEdsResource(args2, kNewEdsService2Name));
  5999. // Populate new CDS resources.
  6000. Cluster new_cluster1 = default_cluster_;
  6001. new_cluster1.set_name(kNewCluster1Name);
  6002. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  6003. kNewEdsService1Name);
  6004. balancer_->ads_service()->SetCdsResource(new_cluster1);
  6005. Cluster new_cluster2 = default_cluster_;
  6006. new_cluster2.set_name(kNewCluster2Name);
  6007. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  6008. kNewEdsService2Name);
  6009. balancer_->ads_service()->SetCdsResource(new_cluster2);
  6010. // Create Aggregate Cluster
  6011. auto cluster = default_cluster_;
  6012. CustomClusterType* custom_cluster = cluster.mutable_cluster_type();
  6013. custom_cluster->set_name("envoy.clusters.aggregate");
  6014. ClusterConfig cluster_config;
  6015. cluster_config.add_clusters(kNewCluster1Name);
  6016. cluster_config.add_clusters(kNewCluster2Name);
  6017. custom_cluster->mutable_typed_config()->PackFrom(cluster_config);
  6018. balancer_->ads_service()->SetCdsResource(cluster);
  6019. // Wait for traffic to go to backend 1.
  6020. WaitForBackend(1);
  6021. // Shutdown backend 1 and wait for all traffic to go to backend 2.
  6022. ShutdownBackend(1);
  6023. WaitForBackend(2, WaitForBackendOptions().set_allow_failures(true));
  6024. auto response_state = balancer_->ads_service()->cds_response_state();
  6025. ASSERT_TRUE(response_state.has_value());
  6026. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  6027. // Bring backend 1 back and ensure all traffic go back to it.
  6028. StartBackend(1);
  6029. WaitForBackend(1);
  6030. gpr_unsetenv(
  6031. "GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER");
  6032. }
  6033. TEST_P(CdsTest, AggregateClusterFallBackFromRingHashAtStartup) {
  6034. gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER",
  6035. "true");
  6036. const char* kNewCluster1Name = "new_cluster_1";
  6037. const char* kNewEdsService1Name = "new_eds_service_name_1";
  6038. const char* kNewCluster2Name = "new_cluster_2";
  6039. const char* kNewEdsService2Name = "new_eds_service_name_2";
  6040. // Populate new EDS resources.
  6041. EdsResourceArgs args1({
  6042. {"locality0", {MakeNonExistantEndpoint(), MakeNonExistantEndpoint()}},
  6043. });
  6044. EdsResourceArgs args2({
  6045. {"locality0", CreateEndpointsForBackends()},
  6046. });
  6047. balancer_->ads_service()->SetEdsResource(
  6048. BuildEdsResource(args1, kNewEdsService1Name));
  6049. balancer_->ads_service()->SetEdsResource(
  6050. BuildEdsResource(args2, kNewEdsService2Name));
  6051. // Populate new CDS resources.
  6052. Cluster new_cluster1 = default_cluster_;
  6053. new_cluster1.set_name(kNewCluster1Name);
  6054. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  6055. kNewEdsService1Name);
  6056. balancer_->ads_service()->SetCdsResource(new_cluster1);
  6057. Cluster new_cluster2 = default_cluster_;
  6058. new_cluster2.set_name(kNewCluster2Name);
  6059. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  6060. kNewEdsService2Name);
  6061. balancer_->ads_service()->SetCdsResource(new_cluster2);
  6062. // Create Aggregate Cluster
  6063. auto cluster = default_cluster_;
  6064. cluster.set_lb_policy(Cluster::RING_HASH);
  6065. CustomClusterType* custom_cluster = cluster.mutable_cluster_type();
  6066. custom_cluster->set_name("envoy.clusters.aggregate");
  6067. ClusterConfig cluster_config;
  6068. cluster_config.add_clusters(kNewCluster1Name);
  6069. cluster_config.add_clusters(kNewCluster2Name);
  6070. custom_cluster->mutable_typed_config()->PackFrom(cluster_config);
  6071. balancer_->ads_service()->SetCdsResource(cluster);
  6072. // Set up route with channel id hashing
  6073. auto new_route_config = default_route_config_;
  6074. auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  6075. auto* hash_policy = route->mutable_route()->add_hash_policy();
  6076. hash_policy->mutable_filter_state()->set_key("io.grpc.channel_id");
  6077. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  6078. new_route_config);
  6079. // Verifying that we are using ring hash as only 1 endpoint is receiving all
  6080. // the traffic.
  6081. CheckRpcSendOk(100);
  6082. bool found = false;
  6083. for (size_t i = 0; i < backends_.size(); ++i) {
  6084. if (backends_[i]->backend_service()->request_count() > 0) {
  6085. EXPECT_EQ(backends_[i]->backend_service()->request_count(), 100)
  6086. << "backend " << i;
  6087. EXPECT_FALSE(found) << "backend " << i;
  6088. found = true;
  6089. }
  6090. }
  6091. EXPECT_TRUE(found);
  6092. gpr_unsetenv(
  6093. "GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER");
  6094. }
  6095. TEST_P(CdsTest, AggregateClusterEdsToLogicalDns) {
  6096. gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER",
  6097. "true");
  6098. const char* kNewCluster1Name = "new_cluster_1";
  6099. const char* kNewEdsService1Name = "new_eds_service_name_1";
  6100. const char* kLogicalDNSClusterName = "logical_dns_cluster";
  6101. // Populate new EDS resources.
  6102. EdsResourceArgs args1({
  6103. {"locality0", CreateEndpointsForBackends(1, 2)},
  6104. });
  6105. balancer_->ads_service()->SetEdsResource(
  6106. BuildEdsResource(args1, kNewEdsService1Name));
  6107. // Populate new CDS resources.
  6108. Cluster new_cluster1 = default_cluster_;
  6109. new_cluster1.set_name(kNewCluster1Name);
  6110. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  6111. kNewEdsService1Name);
  6112. balancer_->ads_service()->SetCdsResource(new_cluster1);
  6113. // Create Logical DNS Cluster
  6114. auto logical_dns_cluster = default_cluster_;
  6115. logical_dns_cluster.set_name(kLogicalDNSClusterName);
  6116. logical_dns_cluster.set_type(Cluster::LOGICAL_DNS);
  6117. auto* address = logical_dns_cluster.mutable_load_assignment()
  6118. ->add_endpoints()
  6119. ->add_lb_endpoints()
  6120. ->mutable_endpoint()
  6121. ->mutable_address()
  6122. ->mutable_socket_address();
  6123. address->set_address(kServerName);
  6124. address->set_port_value(443);
  6125. balancer_->ads_service()->SetCdsResource(logical_dns_cluster);
  6126. // Create Aggregate Cluster
  6127. auto cluster = default_cluster_;
  6128. CustomClusterType* custom_cluster = cluster.mutable_cluster_type();
  6129. custom_cluster->set_name("envoy.clusters.aggregate");
  6130. ClusterConfig cluster_config;
  6131. cluster_config.add_clusters(kNewCluster1Name);
  6132. cluster_config.add_clusters(kLogicalDNSClusterName);
  6133. custom_cluster->mutable_typed_config()->PackFrom(cluster_config);
  6134. balancer_->ads_service()->SetCdsResource(cluster);
  6135. // Set Logical DNS result
  6136. {
  6137. grpc_core::ExecCtx exec_ctx;
  6138. grpc_core::Resolver::Result result;
  6139. result.addresses = CreateAddressListFromPortList(GetBackendPorts(2, 3));
  6140. logical_dns_cluster_resolver_response_generator_->SetResponse(
  6141. std::move(result));
  6142. }
  6143. // Wait for traffic to go to backend 1.
  6144. WaitForBackend(1);
  6145. // Shutdown backend 1 and wait for all traffic to go to backend 2.
  6146. ShutdownBackend(1);
  6147. WaitForBackend(2, WaitForBackendOptions().set_allow_failures(true));
  6148. auto response_state = balancer_->ads_service()->cds_response_state();
  6149. ASSERT_TRUE(response_state.has_value());
  6150. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  6151. // Bring backend 1 back and ensure all traffic go back to it.
  6152. StartBackend(1);
  6153. WaitForBackend(1);
  6154. gpr_unsetenv(
  6155. "GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER");
  6156. }
  6157. TEST_P(CdsTest, AggregateClusterLogicalDnsToEds) {
  6158. gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER",
  6159. "true");
  6160. const char* kNewCluster2Name = "new_cluster_2";
  6161. const char* kNewEdsService2Name = "new_eds_service_name_2";
  6162. const char* kLogicalDNSClusterName = "logical_dns_cluster";
  6163. // Populate new EDS resources.
  6164. EdsResourceArgs args2({
  6165. {"locality0", CreateEndpointsForBackends(2, 3)},
  6166. });
  6167. balancer_->ads_service()->SetEdsResource(
  6168. BuildEdsResource(args2, kNewEdsService2Name));
  6169. // Populate new CDS resources.
  6170. Cluster new_cluster2 = default_cluster_;
  6171. new_cluster2.set_name(kNewCluster2Name);
  6172. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  6173. kNewEdsService2Name);
  6174. balancer_->ads_service()->SetCdsResource(new_cluster2);
  6175. // Create Logical DNS Cluster
  6176. auto logical_dns_cluster = default_cluster_;
  6177. logical_dns_cluster.set_name(kLogicalDNSClusterName);
  6178. logical_dns_cluster.set_type(Cluster::LOGICAL_DNS);
  6179. auto* address = logical_dns_cluster.mutable_load_assignment()
  6180. ->add_endpoints()
  6181. ->add_lb_endpoints()
  6182. ->mutable_endpoint()
  6183. ->mutable_address()
  6184. ->mutable_socket_address();
  6185. address->set_address(kServerName);
  6186. address->set_port_value(443);
  6187. balancer_->ads_service()->SetCdsResource(logical_dns_cluster);
  6188. // Create Aggregate Cluster
  6189. auto cluster = default_cluster_;
  6190. CustomClusterType* custom_cluster = cluster.mutable_cluster_type();
  6191. custom_cluster->set_name("envoy.clusters.aggregate");
  6192. ClusterConfig cluster_config;
  6193. cluster_config.add_clusters(kLogicalDNSClusterName);
  6194. cluster_config.add_clusters(kNewCluster2Name);
  6195. custom_cluster->mutable_typed_config()->PackFrom(cluster_config);
  6196. balancer_->ads_service()->SetCdsResource(cluster);
  6197. // Set Logical DNS result
  6198. {
  6199. grpc_core::ExecCtx exec_ctx;
  6200. grpc_core::Resolver::Result result;
  6201. result.addresses = CreateAddressListFromPortList(GetBackendPorts(1, 2));
  6202. logical_dns_cluster_resolver_response_generator_->SetResponse(
  6203. std::move(result));
  6204. }
  6205. // Wait for traffic to go to backend 1.
  6206. WaitForBackend(1);
  6207. // Shutdown backend 1 and wait for all traffic to go to backend 2.
  6208. ShutdownBackend(1);
  6209. WaitForBackend(2, WaitForBackendOptions().set_allow_failures(true));
  6210. auto response_state = balancer_->ads_service()->cds_response_state();
  6211. ASSERT_TRUE(response_state.has_value());
  6212. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  6213. // Bring backend 1 back and ensure all traffic go back to it.
  6214. StartBackend(1);
  6215. WaitForBackend(1);
  6216. gpr_unsetenv(
  6217. "GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER");
  6218. }
  6219. // This test covers a bug seen in the wild where the
  6220. // xds_cluster_resolver policy's code to reuse child policy names did
  6221. // not correctly handle the case where the LOGICAL_DNS priority failed,
  6222. // thus returning a priority with no localities. This caused the child
  6223. // name to be reused incorrectly, which triggered an assertion failure
  6224. // in the xds_cluster_impl policy caused by changing its cluster name.
  6225. TEST_P(CdsTest, AggregateClusterReconfigEdsWhileLogicalDnsChildFails) {
  6226. gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER",
  6227. "true");
  6228. const char* kNewCluster1Name = "new_cluster_1";
  6229. const char* kNewEdsService1Name = "new_eds_service_name_1";
  6230. const char* kLogicalDNSClusterName = "logical_dns_cluster";
  6231. // Populate EDS resource with all unreachable endpoints.
  6232. // - Priority 0: locality0
  6233. // - Priority 1: locality1, locality2
  6234. EdsResourceArgs args1({
  6235. {"locality0", {MakeNonExistantEndpoint()}, kDefaultLocalityWeight, 0},
  6236. {"locality1", {MakeNonExistantEndpoint()}, kDefaultLocalityWeight, 1},
  6237. {"locality2", {MakeNonExistantEndpoint()}, kDefaultLocalityWeight, 1},
  6238. });
  6239. balancer_->ads_service()->SetEdsResource(
  6240. BuildEdsResource(args1, kNewEdsService1Name));
  6241. // Populate new CDS resources.
  6242. Cluster new_cluster1 = default_cluster_;
  6243. new_cluster1.set_name(kNewCluster1Name);
  6244. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  6245. kNewEdsService1Name);
  6246. balancer_->ads_service()->SetCdsResource(new_cluster1);
  6247. // Create Logical DNS Cluster
  6248. auto logical_dns_cluster = default_cluster_;
  6249. logical_dns_cluster.set_name(kLogicalDNSClusterName);
  6250. logical_dns_cluster.set_type(Cluster::LOGICAL_DNS);
  6251. auto* address = logical_dns_cluster.mutable_load_assignment()
  6252. ->add_endpoints()
  6253. ->add_lb_endpoints()
  6254. ->mutable_endpoint()
  6255. ->mutable_address()
  6256. ->mutable_socket_address();
  6257. address->set_address(kServerName);
  6258. address->set_port_value(443);
  6259. balancer_->ads_service()->SetCdsResource(logical_dns_cluster);
  6260. // Create Aggregate Cluster
  6261. auto cluster = default_cluster_;
  6262. CustomClusterType* custom_cluster = cluster.mutable_cluster_type();
  6263. custom_cluster->set_name("envoy.clusters.aggregate");
  6264. ClusterConfig cluster_config;
  6265. cluster_config.add_clusters(kNewCluster1Name);
  6266. cluster_config.add_clusters(kLogicalDNSClusterName);
  6267. custom_cluster->mutable_typed_config()->PackFrom(cluster_config);
  6268. balancer_->ads_service()->SetCdsResource(cluster);
  6269. // Set Logical DNS result
  6270. {
  6271. grpc_core::ExecCtx exec_ctx;
  6272. grpc_core::Resolver::Result result;
  6273. result.addresses = absl::UnavailableError("injected error");
  6274. logical_dns_cluster_resolver_response_generator_->SetResponse(
  6275. std::move(result));
  6276. }
  6277. // When an RPC fails, we know the channel has seen the update.
  6278. CheckRpcSendFailure();
  6279. // Send an EDS update that moves locality1 to priority 0.
  6280. args1 = EdsResourceArgs({
  6281. {"locality1", CreateEndpointsForBackends(0, 1), kDefaultLocalityWeight,
  6282. 0},
  6283. {"locality2", CreateEndpointsForBackends(1, 2), kDefaultLocalityWeight,
  6284. 1},
  6285. });
  6286. balancer_->ads_service()->SetEdsResource(
  6287. BuildEdsResource(args1, kNewEdsService1Name));
  6288. WaitForBackend(0, WaitForBackendOptions().set_allow_failures(true));
  6289. gpr_unsetenv(
  6290. "GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER");
  6291. }
  6292. TEST_P(CdsTest, AggregateClusterMultipleClustersWithSameLocalities) {
  6293. gpr_setenv("GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER",
  6294. "true");
  6295. const char* kNewClusterName1 = "new_cluster_1";
  6296. const char* kNewEdsServiceName1 = "new_eds_service_name_1";
  6297. const char* kNewClusterName2 = "new_cluster_2";
  6298. const char* kNewEdsServiceName2 = "new_eds_service_name_2";
  6299. // Populate EDS resource for cluster 1 with unreachable endpoint.
  6300. EdsResourceArgs args1({{"locality0", {MakeNonExistantEndpoint()}}});
  6301. balancer_->ads_service()->SetEdsResource(
  6302. BuildEdsResource(args1, kNewEdsServiceName1));
  6303. // Populate CDS resource for cluster 1.
  6304. Cluster new_cluster1 = default_cluster_;
  6305. new_cluster1.set_name(kNewClusterName1);
  6306. new_cluster1.mutable_eds_cluster_config()->set_service_name(
  6307. kNewEdsServiceName1);
  6308. balancer_->ads_service()->SetCdsResource(new_cluster1);
  6309. // Populate EDS resource for cluster 2.
  6310. args1 = EdsResourceArgs({{"locality1", CreateEndpointsForBackends(0, 1)}});
  6311. balancer_->ads_service()->SetEdsResource(
  6312. BuildEdsResource(args1, kNewEdsServiceName2));
  6313. // Populate CDS resource for cluster 2.
  6314. Cluster new_cluster2 = default_cluster_;
  6315. new_cluster2.set_name(kNewClusterName2);
  6316. new_cluster2.mutable_eds_cluster_config()->set_service_name(
  6317. kNewEdsServiceName2);
  6318. balancer_->ads_service()->SetCdsResource(new_cluster2);
  6319. // Create Aggregate Cluster
  6320. auto cluster = default_cluster_;
  6321. CustomClusterType* custom_cluster = cluster.mutable_cluster_type();
  6322. custom_cluster->set_name("envoy.clusters.aggregate");
  6323. ClusterConfig cluster_config;
  6324. cluster_config.add_clusters(kNewClusterName1);
  6325. cluster_config.add_clusters(kNewClusterName2);
  6326. custom_cluster->mutable_typed_config()->PackFrom(cluster_config);
  6327. balancer_->ads_service()->SetCdsResource(cluster);
  6328. // Wait for channel to get the resources and get connected.
  6329. WaitForBackend(0);
  6330. // Send an EDS update for cluster 1 that reuses the locality name from
  6331. // cluster 1 and points traffic to backend 1.
  6332. args1 = EdsResourceArgs({{"locality1", CreateEndpointsForBackends(1, 2)}});
  6333. balancer_->ads_service()->SetEdsResource(
  6334. BuildEdsResource(args1, kNewEdsServiceName1));
  6335. WaitForBackend(1);
  6336. gpr_unsetenv(
  6337. "GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER");
  6338. }
  6339. // Test that CDS client should send a NACK if cluster type is Logical DNS but
  6340. // the feature is not yet supported.
  6341. TEST_P(CdsTest, LogicalDNSClusterTypeDisabled) {
  6342. auto cluster = default_cluster_;
  6343. cluster.set_type(Cluster::LOGICAL_DNS);
  6344. balancer_->ads_service()->SetCdsResource(cluster);
  6345. const auto response_state = WaitForCdsNack();
  6346. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  6347. EXPECT_THAT(response_state->error_message,
  6348. ::testing::HasSubstr("DiscoveryType is not valid."));
  6349. }
  6350. // Test that CDS client should send a NACK if cluster type is AGGREGATE but
  6351. // the feature is not yet supported.
  6352. TEST_P(CdsTest, AggregateClusterTypeDisabled) {
  6353. auto cluster = default_cluster_;
  6354. CustomClusterType* custom_cluster = cluster.mutable_cluster_type();
  6355. custom_cluster->set_name("envoy.clusters.aggregate");
  6356. ClusterConfig cluster_config;
  6357. cluster_config.add_clusters("cluster1");
  6358. cluster_config.add_clusters("cluster2");
  6359. custom_cluster->mutable_typed_config()->PackFrom(cluster_config);
  6360. cluster.set_type(Cluster::LOGICAL_DNS);
  6361. balancer_->ads_service()->SetCdsResource(cluster);
  6362. const auto response_state = WaitForCdsNack();
  6363. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  6364. EXPECT_THAT(response_state->error_message,
  6365. ::testing::HasSubstr("DiscoveryType is not valid."));
  6366. }
  6367. // Tests that CDS client should send a NACK if the cluster type in CDS
  6368. // response is unsupported.
  6369. TEST_P(CdsTest, UnsupportedClusterType) {
  6370. auto cluster = default_cluster_;
  6371. cluster.set_type(Cluster::STATIC);
  6372. balancer_->ads_service()->SetCdsResource(cluster);
  6373. const auto response_state = WaitForCdsNack();
  6374. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  6375. EXPECT_THAT(response_state->error_message,
  6376. ::testing::HasSubstr("DiscoveryType is not valid."));
  6377. }
  6378. // Tests that the NACK for multiple bad resources includes both errors.
  6379. TEST_P(CdsTest, MultipleBadResources) {
  6380. constexpr char kClusterName2[] = "cluster_name_2";
  6381. constexpr char kClusterName3[] = "cluster_name_3";
  6382. // Add cluster with unsupported type.
  6383. auto cluster = default_cluster_;
  6384. cluster.set_name(kClusterName2);
  6385. cluster.set_type(Cluster::STATIC);
  6386. balancer_->ads_service()->SetCdsResource(cluster);
  6387. // Add second cluster with the same error.
  6388. cluster.set_name(kClusterName3);
  6389. balancer_->ads_service()->SetCdsResource(cluster);
  6390. // Change RouteConfig to point to all clusters.
  6391. RouteConfiguration route_config = default_route_config_;
  6392. route_config.mutable_virtual_hosts(0)->clear_routes();
  6393. // First route: default cluster, selected based on header.
  6394. auto* route = route_config.mutable_virtual_hosts(0)->add_routes();
  6395. route->mutable_match()->set_prefix("");
  6396. auto* header_matcher = route->mutable_match()->add_headers();
  6397. header_matcher->set_name("cluster");
  6398. header_matcher->set_exact_match(kDefaultClusterName);
  6399. route->mutable_route()->set_cluster(kDefaultClusterName);
  6400. // Second route: cluster 2, selected based on header.
  6401. route = route_config.mutable_virtual_hosts(0)->add_routes();
  6402. route->mutable_match()->set_prefix("");
  6403. header_matcher = route->mutable_match()->add_headers();
  6404. header_matcher->set_name("cluster");
  6405. header_matcher->set_exact_match(kClusterName2);
  6406. route->mutable_route()->set_cluster(kClusterName2);
  6407. // Third route: cluster 3, used by default.
  6408. route = route_config.mutable_virtual_hosts(0)->add_routes();
  6409. route->mutable_match()->set_prefix("");
  6410. route->mutable_route()->set_cluster(kClusterName3);
  6411. SetRouteConfiguration(balancer_.get(), route_config);
  6412. // Add EDS resource.
  6413. EdsResourceArgs args({
  6414. {"locality0", CreateEndpointsForBackends(0, 1)},
  6415. });
  6416. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  6417. // Send RPC.
  6418. const auto response_state = WaitForCdsNack();
  6419. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  6420. EXPECT_THAT(
  6421. response_state->error_message,
  6422. ::testing::ContainsRegex(absl::StrCat(kClusterName2,
  6423. ": validation error.*"
  6424. "DiscoveryType is not valid.*",
  6425. kClusterName3,
  6426. ": validation error.*"
  6427. "DiscoveryType is not valid")));
  6428. // RPCs for default cluster should succeed.
  6429. std::vector<std::pair<std::string, std::string>> metadata_default_cluster = {
  6430. {"cluster", kDefaultClusterName},
  6431. };
  6432. CheckRpcSendOk(
  6433. 1, RpcOptions().set_metadata(std::move(metadata_default_cluster)));
  6434. // RPCs for cluster 2 should fail.
  6435. std::vector<std::pair<std::string, std::string>> metadata_cluster_2 = {
  6436. {"cluster", kClusterName2},
  6437. };
  6438. CheckRpcSendFailure(CheckRpcSendFailureOptions().set_rpc_options(
  6439. RpcOptions().set_metadata(std::move(metadata_cluster_2))));
  6440. }
  6441. // Tests that we don't trigger does-not-exist callbacks for a resource
  6442. // that was previously valid but is updated to be invalid.
  6443. TEST_P(CdsTest, InvalidClusterStillExistsIfPreviouslyCached) {
  6444. EdsResourceArgs args({
  6445. {"locality0", CreateEndpointsForBackends(0, 1)},
  6446. });
  6447. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  6448. // Check that everything works.
  6449. CheckRpcSendOk();
  6450. // Now send an update changing the Cluster to be invalid.
  6451. auto cluster = default_cluster_;
  6452. cluster.set_type(Cluster::STATIC);
  6453. balancer_->ads_service()->SetCdsResource(cluster);
  6454. const auto response_state = WaitForCdsNack(StatusCode::OK);
  6455. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  6456. EXPECT_THAT(response_state->error_message,
  6457. ::testing::ContainsRegex(absl::StrCat(
  6458. kDefaultClusterName,
  6459. ": validation error.*DiscoveryType is not valid")));
  6460. }
  6461. // Tests that CDS client should send a NACK if the eds_config in CDS response
  6462. // is other than ADS or SELF.
  6463. TEST_P(CdsTest, EdsConfigSourceDoesNotSpecifyAdsOrSelf) {
  6464. auto cluster = default_cluster_;
  6465. cluster.mutable_eds_cluster_config()->mutable_eds_config()->set_path(
  6466. "/foo/bar");
  6467. balancer_->ads_service()->SetCdsResource(cluster);
  6468. const auto response_state = WaitForCdsNack();
  6469. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  6470. EXPECT_THAT(response_state->error_message,
  6471. ::testing::HasSubstr("EDS ConfigSource is not ADS or SELF."));
  6472. }
  6473. // Tests that CDS client accepts an eds_config of type ADS.
  6474. TEST_P(CdsTest, AcceptsEdsConfigSourceOfTypeAds) {
  6475. auto cluster = default_cluster_;
  6476. cluster.mutable_eds_cluster_config()->mutable_eds_config()->mutable_ads();
  6477. balancer_->ads_service()->SetCdsResource(cluster);
  6478. EdsResourceArgs args({{"locality0", CreateEndpointsForBackends()}});
  6479. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  6480. WaitForAllBackends();
  6481. auto response_state = balancer_->ads_service()->cds_response_state();
  6482. ASSERT_TRUE(response_state.has_value());
  6483. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  6484. }
  6485. // Tests that CDS client should send a NACK if the lb_policy in CDS response
  6486. // is other than ROUND_ROBIN.
  6487. TEST_P(CdsTest, WrongLbPolicy) {
  6488. auto cluster = default_cluster_;
  6489. cluster.set_lb_policy(Cluster::LEAST_REQUEST);
  6490. balancer_->ads_service()->SetCdsResource(cluster);
  6491. const auto response_state = WaitForCdsNack();
  6492. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  6493. EXPECT_THAT(response_state->error_message,
  6494. ::testing::HasSubstr("LB policy is not supported."));
  6495. }
  6496. // Tests that CDS client should send a NACK if the lrs_server in CDS response
  6497. // is other than SELF.
  6498. TEST_P(CdsTest, WrongLrsServer) {
  6499. auto cluster = default_cluster_;
  6500. cluster.mutable_lrs_server()->mutable_ads();
  6501. balancer_->ads_service()->SetCdsResource(cluster);
  6502. const auto response_state = WaitForCdsNack();
  6503. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  6504. EXPECT_THAT(response_state->error_message,
  6505. ::testing::HasSubstr("LRS ConfigSource is not self."));
  6506. }
  6507. // Tests that ring hash policy that hashes using channel id ensures all RPCs
  6508. // to go 1 particular backend.
  6509. TEST_P(CdsTest, RingHashChannelIdHashing) {
  6510. auto cluster = default_cluster_;
  6511. cluster.set_lb_policy(Cluster::RING_HASH);
  6512. balancer_->ads_service()->SetCdsResource(cluster);
  6513. auto new_route_config = default_route_config_;
  6514. auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  6515. auto* hash_policy = route->mutable_route()->add_hash_policy();
  6516. hash_policy->mutable_filter_state()->set_key("io.grpc.channel_id");
  6517. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  6518. new_route_config);
  6519. EdsResourceArgs args({
  6520. {"locality0", CreateEndpointsForBackends()},
  6521. });
  6522. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  6523. CheckRpcSendOk(100);
  6524. bool found = false;
  6525. for (size_t i = 0; i < backends_.size(); ++i) {
  6526. if (backends_[i]->backend_service()->request_count() > 0) {
  6527. EXPECT_EQ(backends_[i]->backend_service()->request_count(), 100)
  6528. << "backend " << i;
  6529. EXPECT_FALSE(found) << "backend " << i;
  6530. found = true;
  6531. }
  6532. }
  6533. EXPECT_TRUE(found);
  6534. }
  6535. // Tests that ring hash policy that hashes using a header value can spread
  6536. // RPCs across all the backends.
  6537. TEST_P(CdsTest, RingHashHeaderHashing) {
  6538. auto cluster = default_cluster_;
  6539. cluster.set_lb_policy(Cluster::RING_HASH);
  6540. balancer_->ads_service()->SetCdsResource(cluster);
  6541. auto new_route_config = default_route_config_;
  6542. auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  6543. auto* hash_policy = route->mutable_route()->add_hash_policy();
  6544. hash_policy->mutable_header()->set_header_name("address_hash");
  6545. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  6546. new_route_config);
  6547. EdsResourceArgs args({
  6548. {"locality0", CreateEndpointsForBackends()},
  6549. });
  6550. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  6551. // Note each type of RPC will contains a header value that will always be
  6552. // hashed to a specific backend as the header value matches the value used
  6553. // to create the entry in the ring.
  6554. std::vector<std::pair<std::string, std::string>> metadata = {
  6555. {"address_hash", CreateMetadataValueThatHashesToBackend(0)}};
  6556. std::vector<std::pair<std::string, std::string>> metadata1 = {
  6557. {"address_hash", CreateMetadataValueThatHashesToBackend(1)}};
  6558. std::vector<std::pair<std::string, std::string>> metadata2 = {
  6559. {"address_hash", CreateMetadataValueThatHashesToBackend(2)}};
  6560. std::vector<std::pair<std::string, std::string>> metadata3 = {
  6561. {"address_hash", CreateMetadataValueThatHashesToBackend(3)}};
  6562. const auto rpc_options = RpcOptions().set_metadata(std::move(metadata));
  6563. const auto rpc_options1 = RpcOptions().set_metadata(std::move(metadata1));
  6564. const auto rpc_options2 = RpcOptions().set_metadata(std::move(metadata2));
  6565. const auto rpc_options3 = RpcOptions().set_metadata(std::move(metadata3));
  6566. WaitForBackend(0, WaitForBackendOptions(), rpc_options);
  6567. WaitForBackend(1, WaitForBackendOptions(), rpc_options1);
  6568. WaitForBackend(2, WaitForBackendOptions(), rpc_options2);
  6569. WaitForBackend(3, WaitForBackendOptions(), rpc_options3);
  6570. CheckRpcSendOk(100, rpc_options);
  6571. CheckRpcSendOk(100, rpc_options1);
  6572. CheckRpcSendOk(100, rpc_options2);
  6573. CheckRpcSendOk(100, rpc_options3);
  6574. for (size_t i = 0; i < backends_.size(); ++i) {
  6575. EXPECT_EQ(100, backends_[i]->backend_service()->request_count());
  6576. }
  6577. }
  6578. // Tests that ring hash policy that hashes using a header value and regex
  6579. // rewrite to aggregate RPCs to 1 backend.
  6580. TEST_P(CdsTest, RingHashHeaderHashingWithRegexRewrite) {
  6581. auto cluster = default_cluster_;
  6582. cluster.set_lb_policy(Cluster::RING_HASH);
  6583. balancer_->ads_service()->SetCdsResource(cluster);
  6584. auto new_route_config = default_route_config_;
  6585. auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  6586. auto* hash_policy = route->mutable_route()->add_hash_policy();
  6587. hash_policy->mutable_header()->set_header_name("address_hash");
  6588. hash_policy->mutable_header()
  6589. ->mutable_regex_rewrite()
  6590. ->mutable_pattern()
  6591. ->set_regex("[0-9]+");
  6592. hash_policy->mutable_header()->mutable_regex_rewrite()->set_substitution(
  6593. "foo");
  6594. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  6595. new_route_config);
  6596. EdsResourceArgs args({
  6597. {"locality0", CreateEndpointsForBackends()},
  6598. });
  6599. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  6600. std::vector<std::pair<std::string, std::string>> metadata = {
  6601. {"address_hash", CreateMetadataValueThatHashesToBackend(0)}};
  6602. std::vector<std::pair<std::string, std::string>> metadata1 = {
  6603. {"address_hash", CreateMetadataValueThatHashesToBackend(1)}};
  6604. std::vector<std::pair<std::string, std::string>> metadata2 = {
  6605. {"address_hash", CreateMetadataValueThatHashesToBackend(2)}};
  6606. std::vector<std::pair<std::string, std::string>> metadata3 = {
  6607. {"address_hash", CreateMetadataValueThatHashesToBackend(3)}};
  6608. const auto rpc_options = RpcOptions().set_metadata(std::move(metadata));
  6609. const auto rpc_options1 = RpcOptions().set_metadata(std::move(metadata1));
  6610. const auto rpc_options2 = RpcOptions().set_metadata(std::move(metadata2));
  6611. const auto rpc_options3 = RpcOptions().set_metadata(std::move(metadata3));
  6612. CheckRpcSendOk(100, rpc_options);
  6613. CheckRpcSendOk(100, rpc_options1);
  6614. CheckRpcSendOk(100, rpc_options2);
  6615. CheckRpcSendOk(100, rpc_options3);
  6616. bool found = false;
  6617. for (size_t i = 0; i < backends_.size(); ++i) {
  6618. if (backends_[i]->backend_service()->request_count() > 0) {
  6619. EXPECT_EQ(backends_[i]->backend_service()->request_count(), 400)
  6620. << "backend " << i;
  6621. EXPECT_FALSE(found) << "backend " << i;
  6622. found = true;
  6623. }
  6624. }
  6625. EXPECT_TRUE(found);
  6626. }
  6627. // Tests that ring hash policy that hashes using a random value.
  6628. TEST_P(CdsTest, RingHashNoHashPolicy) {
  6629. const double kDistribution50Percent = 0.5;
  6630. const double kErrorTolerance = 0.05;
  6631. const uint32_t kRpcTimeoutMs = 10000;
  6632. const size_t kNumRpcs =
  6633. ComputeIdealNumRpcs(kDistribution50Percent, kErrorTolerance);
  6634. auto cluster = default_cluster_;
  6635. // Increasing min ring size for random distribution.
  6636. cluster.mutable_ring_hash_lb_config()->mutable_minimum_ring_size()->set_value(
  6637. 100000);
  6638. cluster.set_lb_policy(Cluster::RING_HASH);
  6639. balancer_->ads_service()->SetCdsResource(cluster);
  6640. EdsResourceArgs args({{"locality0", CreateEndpointsForBackends(0, 2)}});
  6641. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  6642. // TODO(donnadionne): remove extended timeout after ring creation
  6643. // optimization.
  6644. WaitForAllBackends(0, 2, WaitForBackendOptions(),
  6645. RpcOptions().set_timeout_ms(kRpcTimeoutMs));
  6646. CheckRpcSendOk(kNumRpcs);
  6647. const int request_count_1 = backends_[0]->backend_service()->request_count();
  6648. const int request_count_2 = backends_[1]->backend_service()->request_count();
  6649. EXPECT_THAT(static_cast<double>(request_count_1) / kNumRpcs,
  6650. ::testing::DoubleNear(kDistribution50Percent, kErrorTolerance));
  6651. EXPECT_THAT(static_cast<double>(request_count_2) / kNumRpcs,
  6652. ::testing::DoubleNear(kDistribution50Percent, kErrorTolerance));
  6653. }
  6654. // Test that ring hash policy evaluation will continue past the terminal
  6655. // policy if no results are produced yet.
  6656. TEST_P(CdsTest, RingHashContinuesPastTerminalPolicyThatDoesNotProduceResult) {
  6657. auto cluster = default_cluster_;
  6658. cluster.set_lb_policy(Cluster::RING_HASH);
  6659. balancer_->ads_service()->SetCdsResource(cluster);
  6660. auto new_route_config = default_route_config_;
  6661. auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  6662. auto* hash_policy = route->mutable_route()->add_hash_policy();
  6663. hash_policy->mutable_header()->set_header_name("header_not_present");
  6664. hash_policy->set_terminal(true);
  6665. auto* hash_policy2 = route->mutable_route()->add_hash_policy();
  6666. hash_policy2->mutable_header()->set_header_name("address_hash");
  6667. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  6668. new_route_config);
  6669. EdsResourceArgs args({{"locality0", CreateEndpointsForBackends(0, 2)}});
  6670. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  6671. std::vector<std::pair<std::string, std::string>> metadata = {
  6672. {"address_hash", CreateMetadataValueThatHashesToBackend(0)}};
  6673. const auto rpc_options = RpcOptions().set_metadata(std::move(metadata));
  6674. CheckRpcSendOk(100, rpc_options);
  6675. EXPECT_EQ(backends_[0]->backend_service()->request_count(), 100);
  6676. EXPECT_EQ(backends_[1]->backend_service()->request_count(), 0);
  6677. }
  6678. // Test random hash is used when header hashing specified a header field that
  6679. // the RPC did not have.
  6680. TEST_P(CdsTest, RingHashOnHeaderThatIsNotPresent) {
  6681. const double kDistribution50Percent = 0.5;
  6682. const double kErrorTolerance = 0.05;
  6683. const uint32_t kRpcTimeoutMs = 10000;
  6684. const size_t kNumRpcs =
  6685. ComputeIdealNumRpcs(kDistribution50Percent, kErrorTolerance);
  6686. auto cluster = default_cluster_;
  6687. // Increasing min ring size for random distribution.
  6688. cluster.mutable_ring_hash_lb_config()->mutable_minimum_ring_size()->set_value(
  6689. 100000);
  6690. cluster.set_lb_policy(Cluster::RING_HASH);
  6691. balancer_->ads_service()->SetCdsResource(cluster);
  6692. auto new_route_config = default_route_config_;
  6693. auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  6694. auto* hash_policy = route->mutable_route()->add_hash_policy();
  6695. hash_policy->mutable_header()->set_header_name("header_not_present");
  6696. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  6697. new_route_config);
  6698. EdsResourceArgs args({{"locality0", CreateEndpointsForBackends(0, 2)}});
  6699. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  6700. std::vector<std::pair<std::string, std::string>> metadata = {
  6701. {"unmatched_header", absl::StrFormat("%" PRIu32, rand())},
  6702. };
  6703. const auto rpc_options = RpcOptions().set_metadata(std::move(metadata));
  6704. // TODO(donnadionne): remove extended timeout after ring creation
  6705. // optimization.
  6706. WaitForAllBackends(0, 2, WaitForBackendOptions(),
  6707. RpcOptions().set_timeout_ms(kRpcTimeoutMs));
  6708. CheckRpcSendOk(kNumRpcs, rpc_options);
  6709. const int request_count_1 = backends_[0]->backend_service()->request_count();
  6710. const int request_count_2 = backends_[1]->backend_service()->request_count();
  6711. EXPECT_THAT(static_cast<double>(request_count_1) / kNumRpcs,
  6712. ::testing::DoubleNear(kDistribution50Percent, kErrorTolerance));
  6713. EXPECT_THAT(static_cast<double>(request_count_2) / kNumRpcs,
  6714. ::testing::DoubleNear(kDistribution50Percent, kErrorTolerance));
  6715. }
  6716. // Test random hash is used when only unsupported hash policies are
  6717. // configured.
  6718. TEST_P(CdsTest, RingHashUnsupportedHashPolicyDefaultToRandomHashing) {
  6719. const double kDistribution50Percent = 0.5;
  6720. const double kErrorTolerance = 0.05;
  6721. const uint32_t kRpcTimeoutMs = 10000;
  6722. const size_t kNumRpcs =
  6723. ComputeIdealNumRpcs(kDistribution50Percent, kErrorTolerance);
  6724. auto cluster = default_cluster_;
  6725. // Increasing min ring size for random distribution.
  6726. cluster.mutable_ring_hash_lb_config()->mutable_minimum_ring_size()->set_value(
  6727. 100000);
  6728. cluster.set_lb_policy(Cluster::RING_HASH);
  6729. balancer_->ads_service()->SetCdsResource(cluster);
  6730. auto new_route_config = default_route_config_;
  6731. auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  6732. auto* hash_policy_unsupported_1 = route->mutable_route()->add_hash_policy();
  6733. hash_policy_unsupported_1->mutable_cookie()->set_name("cookie");
  6734. auto* hash_policy_unsupported_2 = route->mutable_route()->add_hash_policy();
  6735. hash_policy_unsupported_2->mutable_connection_properties()->set_source_ip(
  6736. true);
  6737. auto* hash_policy_unsupported_3 = route->mutable_route()->add_hash_policy();
  6738. hash_policy_unsupported_3->mutable_query_parameter()->set_name(
  6739. "query_parameter");
  6740. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  6741. new_route_config);
  6742. EdsResourceArgs args({{"locality0", CreateEndpointsForBackends(0, 2)}});
  6743. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  6744. // TODO(donnadionne): remove extended timeout after ring creation
  6745. // optimization.
  6746. WaitForAllBackends(0, 2, WaitForBackendOptions(),
  6747. RpcOptions().set_timeout_ms(kRpcTimeoutMs));
  6748. CheckRpcSendOk(kNumRpcs);
  6749. const int request_count_1 = backends_[0]->backend_service()->request_count();
  6750. const int request_count_2 = backends_[1]->backend_service()->request_count();
  6751. EXPECT_THAT(static_cast<double>(request_count_1) / kNumRpcs,
  6752. ::testing::DoubleNear(kDistribution50Percent, kErrorTolerance));
  6753. EXPECT_THAT(static_cast<double>(request_count_2) / kNumRpcs,
  6754. ::testing::DoubleNear(kDistribution50Percent, kErrorTolerance));
  6755. }
  6756. // Tests that ring hash policy that hashes using a random value can spread
  6757. // RPCs across all the backends according to locality weight.
  6758. TEST_P(CdsTest, RingHashRandomHashingDistributionAccordingToEndpointWeight) {
  6759. const size_t kWeight1 = 1;
  6760. const size_t kWeight2 = 2;
  6761. const size_t kWeightTotal = kWeight1 + kWeight2;
  6762. const double kWeight33Percent = static_cast<double>(kWeight1) / kWeightTotal;
  6763. const double kWeight66Percent = static_cast<double>(kWeight2) / kWeightTotal;
  6764. const double kErrorTolerance = 0.05;
  6765. const uint32_t kRpcTimeoutMs = 10000;
  6766. const size_t kNumRpcs =
  6767. ComputeIdealNumRpcs(kWeight33Percent, kErrorTolerance);
  6768. auto cluster = default_cluster_;
  6769. // Increasing min ring size for random distribution.
  6770. cluster.mutable_ring_hash_lb_config()->mutable_minimum_ring_size()->set_value(
  6771. 100000);
  6772. cluster.set_lb_policy(Cluster::RING_HASH);
  6773. balancer_->ads_service()->SetCdsResource(cluster);
  6774. EdsResourceArgs args({{"locality0",
  6775. {CreateEndpoint(0, HealthStatus::UNKNOWN, 1),
  6776. CreateEndpoint(1, HealthStatus::UNKNOWN, 2)}}});
  6777. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  6778. // TODO(donnadionne): remove extended timeout after ring creation
  6779. // optimization.
  6780. WaitForAllBackends(0, 2, WaitForBackendOptions(),
  6781. RpcOptions().set_timeout_ms(kRpcTimeoutMs));
  6782. CheckRpcSendOk(kNumRpcs);
  6783. const int weight_33_request_count =
  6784. backends_[0]->backend_service()->request_count();
  6785. const int weight_66_request_count =
  6786. backends_[1]->backend_service()->request_count();
  6787. EXPECT_THAT(static_cast<double>(weight_33_request_count) / kNumRpcs,
  6788. ::testing::DoubleNear(kWeight33Percent, kErrorTolerance));
  6789. EXPECT_THAT(static_cast<double>(weight_66_request_count) / kNumRpcs,
  6790. ::testing::DoubleNear(kWeight66Percent, kErrorTolerance));
  6791. }
  6792. // Tests that ring hash policy that hashes using a random value can spread
  6793. // RPCs across all the backends according to locality weight.
  6794. TEST_P(CdsTest,
  6795. RingHashRandomHashingDistributionAccordingToLocalityAndEndpointWeight) {
  6796. const size_t kWeight1 = 1 * 1;
  6797. const size_t kWeight2 = 2 * 2;
  6798. const size_t kWeightTotal = kWeight1 + kWeight2;
  6799. const double kWeight20Percent = static_cast<double>(kWeight1) / kWeightTotal;
  6800. const double kWeight80Percent = static_cast<double>(kWeight2) / kWeightTotal;
  6801. const double kErrorTolerance = 0.05;
  6802. const uint32_t kRpcTimeoutMs = 10000;
  6803. const size_t kNumRpcs =
  6804. ComputeIdealNumRpcs(kWeight20Percent, kErrorTolerance);
  6805. auto cluster = default_cluster_;
  6806. // Increasing min ring size for random distribution.
  6807. cluster.mutable_ring_hash_lb_config()->mutable_minimum_ring_size()->set_value(
  6808. 100000);
  6809. cluster.set_lb_policy(Cluster::RING_HASH);
  6810. balancer_->ads_service()->SetCdsResource(cluster);
  6811. EdsResourceArgs args(
  6812. {{"locality0", {CreateEndpoint(0, HealthStatus::UNKNOWN, 1)}, 1},
  6813. {"locality1", {CreateEndpoint(1, HealthStatus::UNKNOWN, 2)}, 2}});
  6814. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  6815. // TODO(donnadionne): remove extended timeout after ring creation
  6816. // optimization.
  6817. WaitForAllBackends(0, 2, WaitForBackendOptions(),
  6818. RpcOptions().set_timeout_ms(kRpcTimeoutMs));
  6819. CheckRpcSendOk(kNumRpcs);
  6820. const int weight_20_request_count =
  6821. backends_[0]->backend_service()->request_count();
  6822. const int weight_80_request_count =
  6823. backends_[1]->backend_service()->request_count();
  6824. EXPECT_THAT(static_cast<double>(weight_20_request_count) / kNumRpcs,
  6825. ::testing::DoubleNear(kWeight20Percent, kErrorTolerance));
  6826. EXPECT_THAT(static_cast<double>(weight_80_request_count) / kNumRpcs,
  6827. ::testing::DoubleNear(kWeight80Percent, kErrorTolerance));
  6828. }
  6829. // Tests round robin is not implacted by the endpoint weight, and that the
  6830. // localities in a locality map are picked according to their weights.
  6831. TEST_P(CdsTest, RingHashEndpointWeightDoesNotImpactWeightedRoundRobin) {
  6832. const int kLocalityWeight0 = 2;
  6833. const int kLocalityWeight1 = 8;
  6834. const int kTotalLocalityWeight = kLocalityWeight0 + kLocalityWeight1;
  6835. const double kLocalityWeightRate0 =
  6836. static_cast<double>(kLocalityWeight0) / kTotalLocalityWeight;
  6837. const double kLocalityWeightRate1 =
  6838. static_cast<double>(kLocalityWeight1) / kTotalLocalityWeight;
  6839. const double kErrorTolerance = 0.05;
  6840. const size_t kNumRpcs =
  6841. ComputeIdealNumRpcs(kLocalityWeightRate0, kErrorTolerance);
  6842. // ADS response contains 2 localities, each of which contains 1 backend.
  6843. EdsResourceArgs args({
  6844. {"locality0",
  6845. {CreateEndpoint(0, HealthStatus::UNKNOWN, 8)},
  6846. kLocalityWeight0},
  6847. {"locality1",
  6848. {CreateEndpoint(1, HealthStatus::UNKNOWN, 2)},
  6849. kLocalityWeight1},
  6850. });
  6851. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  6852. // Wait for both backends to be ready.
  6853. WaitForAllBackends(0, 2);
  6854. // Send kNumRpcs RPCs.
  6855. CheckRpcSendOk(kNumRpcs);
  6856. // The locality picking rates should be roughly equal to the expectation.
  6857. const double locality_picked_rate_0 =
  6858. static_cast<double>(backends_[0]->backend_service()->request_count()) /
  6859. kNumRpcs;
  6860. const double locality_picked_rate_1 =
  6861. static_cast<double>(backends_[1]->backend_service()->request_count()) /
  6862. kNumRpcs;
  6863. EXPECT_THAT(locality_picked_rate_0,
  6864. ::testing::DoubleNear(kLocalityWeightRate0, kErrorTolerance));
  6865. EXPECT_THAT(locality_picked_rate_1,
  6866. ::testing::DoubleNear(kLocalityWeightRate1, kErrorTolerance));
  6867. }
  6868. // Tests that ring hash policy that hashes using a fixed string ensures all
  6869. // RPCs to go 1 particular backend; and that subsequent hashing policies are
  6870. // ignored due to the setting of terminal.
  6871. TEST_P(CdsTest, RingHashFixedHashingTerminalPolicy) {
  6872. auto cluster = default_cluster_;
  6873. cluster.set_lb_policy(Cluster::RING_HASH);
  6874. balancer_->ads_service()->SetCdsResource(cluster);
  6875. auto new_route_config = default_route_config_;
  6876. auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  6877. auto* hash_policy = route->mutable_route()->add_hash_policy();
  6878. hash_policy->mutable_header()->set_header_name("fixed_string");
  6879. hash_policy->set_terminal(true);
  6880. auto* hash_policy_to_be_ignored = route->mutable_route()->add_hash_policy();
  6881. hash_policy_to_be_ignored->mutable_header()->set_header_name("random_string");
  6882. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  6883. new_route_config);
  6884. EdsResourceArgs args({
  6885. {"locality0", CreateEndpointsForBackends()},
  6886. });
  6887. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  6888. std::vector<std::pair<std::string, std::string>> metadata = {
  6889. {"fixed_string", "fixed_value"},
  6890. {"random_string", absl::StrFormat("%" PRIu32, rand())},
  6891. };
  6892. const auto rpc_options = RpcOptions().set_metadata(std::move(metadata));
  6893. CheckRpcSendOk(100, rpc_options);
  6894. bool found = false;
  6895. for (size_t i = 0; i < backends_.size(); ++i) {
  6896. if (backends_[i]->backend_service()->request_count() > 0) {
  6897. EXPECT_EQ(backends_[i]->backend_service()->request_count(), 100)
  6898. << "backend " << i;
  6899. EXPECT_FALSE(found) << "backend " << i;
  6900. found = true;
  6901. }
  6902. }
  6903. EXPECT_TRUE(found);
  6904. }
  6905. // Test that the channel will go from idle to ready via connecting;
  6906. // (tho it is not possible to catch the connecting state before moving to
  6907. // ready)
  6908. TEST_P(CdsTest, RingHashIdleToReady) {
  6909. auto cluster = default_cluster_;
  6910. cluster.set_lb_policy(Cluster::RING_HASH);
  6911. balancer_->ads_service()->SetCdsResource(cluster);
  6912. auto new_route_config = default_route_config_;
  6913. auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  6914. auto* hash_policy = route->mutable_route()->add_hash_policy();
  6915. hash_policy->mutable_filter_state()->set_key("io.grpc.channel_id");
  6916. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  6917. new_route_config);
  6918. EdsResourceArgs args({
  6919. {"locality0", CreateEndpointsForBackends()},
  6920. });
  6921. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  6922. EXPECT_EQ(GRPC_CHANNEL_IDLE, channel_->GetState(false));
  6923. CheckRpcSendOk();
  6924. EXPECT_EQ(GRPC_CHANNEL_READY, channel_->GetState(false));
  6925. }
  6926. // Test that when the first pick is down leading to a transient failure, we
  6927. // will move on to the next ring hash entry.
  6928. TEST_P(CdsTest, RingHashTransientFailureCheckNextOne) {
  6929. auto cluster = default_cluster_;
  6930. cluster.set_lb_policy(Cluster::RING_HASH);
  6931. balancer_->ads_service()->SetCdsResource(cluster);
  6932. auto new_route_config = default_route_config_;
  6933. auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  6934. auto* hash_policy = route->mutable_route()->add_hash_policy();
  6935. hash_policy->mutable_header()->set_header_name("address_hash");
  6936. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  6937. new_route_config);
  6938. std::vector<EdsResourceArgs::Endpoint> endpoints;
  6939. const int unused_port = grpc_pick_unused_port_or_die();
  6940. endpoints.emplace_back(unused_port);
  6941. endpoints.emplace_back(backends_[1]->port());
  6942. EdsResourceArgs args({
  6943. {"locality0", std::move(endpoints)},
  6944. });
  6945. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  6946. std::vector<std::pair<std::string, std::string>> metadata = {
  6947. {"address_hash",
  6948. CreateMetadataValueThatHashesToBackendPort(unused_port)}};
  6949. const auto rpc_options = RpcOptions().set_metadata(std::move(metadata));
  6950. WaitForBackend(1, WaitForBackendOptions(), rpc_options);
  6951. CheckRpcSendOk(100, rpc_options);
  6952. EXPECT_EQ(0, backends_[0]->backend_service()->request_count());
  6953. EXPECT_EQ(100, backends_[1]->backend_service()->request_count());
  6954. }
  6955. // Test that when a backend goes down, we will move on to the next subchannel
  6956. // (with a lower priority). When the backend comes back up, traffic will move
  6957. // back.
  6958. TEST_P(CdsTest, RingHashSwitchToLowerPrioirtyAndThenBack) {
  6959. auto cluster = default_cluster_;
  6960. cluster.set_lb_policy(Cluster::RING_HASH);
  6961. balancer_->ads_service()->SetCdsResource(cluster);
  6962. auto new_route_config = default_route_config_;
  6963. auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  6964. auto* hash_policy = route->mutable_route()->add_hash_policy();
  6965. hash_policy->mutable_header()->set_header_name("address_hash");
  6966. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  6967. new_route_config);
  6968. EdsResourceArgs args({
  6969. {"locality0", CreateEndpointsForBackends(0, 1), kDefaultLocalityWeight,
  6970. 0},
  6971. {"locality1", CreateEndpointsForBackends(1, 2), kDefaultLocalityWeight,
  6972. 1},
  6973. });
  6974. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  6975. std::vector<std::pair<std::string, std::string>> metadata = {
  6976. {"address_hash", CreateMetadataValueThatHashesToBackend(0)}};
  6977. const auto rpc_options = RpcOptions().set_metadata(std::move(metadata));
  6978. WaitForBackend(0, WaitForBackendOptions(), rpc_options);
  6979. ShutdownBackend(0);
  6980. WaitForBackend(1, WaitForBackendOptions().set_allow_failures(true),
  6981. rpc_options);
  6982. StartBackend(0);
  6983. WaitForBackend(0, WaitForBackendOptions(), rpc_options);
  6984. CheckRpcSendOk(100, rpc_options);
  6985. EXPECT_EQ(100, backends_[0]->backend_service()->request_count());
  6986. EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
  6987. }
  6988. // Test that when all backends are down, we will keep reattempting.
  6989. TEST_P(CdsTest, RingHashAllFailReattempt) {
  6990. const uint32_t kConnectionTimeoutMilliseconds = 5000;
  6991. auto cluster = default_cluster_;
  6992. cluster.set_lb_policy(Cluster::RING_HASH);
  6993. balancer_->ads_service()->SetCdsResource(cluster);
  6994. auto new_route_config = default_route_config_;
  6995. auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  6996. auto* hash_policy = route->mutable_route()->add_hash_policy();
  6997. hash_policy->mutable_header()->set_header_name("address_hash");
  6998. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  6999. new_route_config);
  7000. std::vector<EdsResourceArgs::Endpoint> endpoints;
  7001. endpoints.emplace_back(grpc_pick_unused_port_or_die());
  7002. endpoints.emplace_back(backends_[1]->port());
  7003. EdsResourceArgs args({
  7004. {"locality0", std::move(endpoints)},
  7005. });
  7006. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  7007. std::vector<std::pair<std::string, std::string>> metadata = {
  7008. {"address_hash", CreateMetadataValueThatHashesToBackend(0)}};
  7009. EXPECT_EQ(GRPC_CHANNEL_IDLE, channel_->GetState(false));
  7010. ShutdownBackend(1);
  7011. CheckRpcSendFailure(CheckRpcSendFailureOptions().set_rpc_options(
  7012. RpcOptions().set_metadata(std::move(metadata))));
  7013. StartBackend(1);
  7014. // Ensure we are actively connecting without any traffic.
  7015. EXPECT_TRUE(channel_->WaitForConnected(
  7016. grpc_timeout_milliseconds_to_deadline(kConnectionTimeoutMilliseconds)));
  7017. }
  7018. // Test that when all backends are down and then up, we may pick a TF backend
  7019. // and we will then jump to ready backend.
  7020. TEST_P(CdsTest, RingHashTransientFailureSkipToAvailableReady) {
  7021. const uint32_t kConnectionTimeoutMilliseconds = 5000;
  7022. auto cluster = default_cluster_;
  7023. cluster.set_lb_policy(Cluster::RING_HASH);
  7024. balancer_->ads_service()->SetCdsResource(cluster);
  7025. auto new_route_config = default_route_config_;
  7026. auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  7027. auto* hash_policy = route->mutable_route()->add_hash_policy();
  7028. hash_policy->mutable_header()->set_header_name("address_hash");
  7029. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  7030. new_route_config);
  7031. std::vector<EdsResourceArgs::Endpoint> endpoints;
  7032. // Make sure we include some unused ports to fill the ring.
  7033. endpoints.emplace_back(backends_[0]->port());
  7034. endpoints.emplace_back(backends_[1]->port());
  7035. endpoints.emplace_back(grpc_pick_unused_port_or_die());
  7036. endpoints.emplace_back(grpc_pick_unused_port_or_die());
  7037. EdsResourceArgs args({
  7038. {"locality0", std::move(endpoints)},
  7039. });
  7040. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  7041. std::vector<std::pair<std::string, std::string>> metadata = {
  7042. {"address_hash", CreateMetadataValueThatHashesToBackend(0)}};
  7043. const auto rpc_options = RpcOptions().set_metadata(std::move(metadata));
  7044. EXPECT_EQ(GRPC_CHANNEL_IDLE, channel_->GetState(false));
  7045. ShutdownBackend(0);
  7046. ShutdownBackend(1);
  7047. CheckRpcSendFailure(
  7048. CheckRpcSendFailureOptions().set_rpc_options(rpc_options));
  7049. EXPECT_EQ(GRPC_CHANNEL_TRANSIENT_FAILURE, channel_->GetState(false));
  7050. // Bring up 0, should be picked as the RPC is hashed to it.
  7051. StartBackend(0);
  7052. EXPECT_TRUE(channel_->WaitForConnected(
  7053. grpc_timeout_milliseconds_to_deadline(kConnectionTimeoutMilliseconds)));
  7054. WaitForBackend(0, WaitForBackendOptions(), rpc_options);
  7055. // Bring down 0 and bring up 1.
  7056. // Note the RPC contains a header value that will always be hashed to
  7057. // backend 0. So by purposely bring down backend 0 and bring up another
  7058. // backend, this will ensure Picker's first choice of backend 0 will fail
  7059. // and it will
  7060. // 1. reattempt backend 0 and
  7061. // 2. go through the remaining subchannels to find one in READY.
  7062. // Since the the entries in the ring is pretty distributed and we have
  7063. // unused ports to fill the ring, it is almost guaranteed that the Picker
  7064. // will go through some non-READY entries and skip them as per design.
  7065. ShutdownBackend(0);
  7066. CheckRpcSendFailure(
  7067. CheckRpcSendFailureOptions().set_rpc_options(rpc_options));
  7068. StartBackend(1);
  7069. EXPECT_TRUE(channel_->WaitForConnected(
  7070. grpc_timeout_milliseconds_to_deadline(kConnectionTimeoutMilliseconds)));
  7071. WaitForBackend(1, WaitForBackendOptions(), rpc_options);
  7072. }
  7073. // Test unspported hash policy types are all ignored before a supported
  7074. // policy.
  7075. TEST_P(CdsTest, RingHashUnsupportedHashPolicyUntilChannelIdHashing) {
  7076. auto cluster = default_cluster_;
  7077. cluster.set_lb_policy(Cluster::RING_HASH);
  7078. balancer_->ads_service()->SetCdsResource(cluster);
  7079. auto new_route_config = default_route_config_;
  7080. auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  7081. auto* hash_policy_unsupported_1 = route->mutable_route()->add_hash_policy();
  7082. hash_policy_unsupported_1->mutable_cookie()->set_name("cookie");
  7083. auto* hash_policy_unsupported_2 = route->mutable_route()->add_hash_policy();
  7084. hash_policy_unsupported_2->mutable_connection_properties()->set_source_ip(
  7085. true);
  7086. auto* hash_policy_unsupported_3 = route->mutable_route()->add_hash_policy();
  7087. hash_policy_unsupported_3->mutable_query_parameter()->set_name(
  7088. "query_parameter");
  7089. auto* hash_policy = route->mutable_route()->add_hash_policy();
  7090. hash_policy->mutable_filter_state()->set_key("io.grpc.channel_id");
  7091. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  7092. new_route_config);
  7093. EdsResourceArgs args({
  7094. {"locality0", CreateEndpointsForBackends()},
  7095. });
  7096. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  7097. CheckRpcSendOk(100);
  7098. bool found = false;
  7099. for (size_t i = 0; i < backends_.size(); ++i) {
  7100. if (backends_[i]->backend_service()->request_count() > 0) {
  7101. EXPECT_EQ(backends_[i]->backend_service()->request_count(), 100)
  7102. << "backend " << i;
  7103. EXPECT_FALSE(found) << "backend " << i;
  7104. found = true;
  7105. }
  7106. }
  7107. EXPECT_TRUE(found);
  7108. }
  7109. // Test we nack when ring hash policy has invalid hash function (something
  7110. // other than XX_HASH.
  7111. TEST_P(CdsTest, RingHashPolicyHasInvalidHashFunction) {
  7112. auto cluster = default_cluster_;
  7113. cluster.set_lb_policy(Cluster::RING_HASH);
  7114. cluster.mutable_ring_hash_lb_config()->set_hash_function(
  7115. Cluster::RingHashLbConfig::MURMUR_HASH_2);
  7116. balancer_->ads_service()->SetCdsResource(cluster);
  7117. auto new_route_config = default_route_config_;
  7118. auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  7119. auto* hash_policy = route->mutable_route()->add_hash_policy();
  7120. hash_policy->mutable_filter_state()->set_key("io.grpc.channel_id");
  7121. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  7122. new_route_config);
  7123. EdsResourceArgs args({
  7124. {"locality0", CreateEndpointsForBackends()},
  7125. });
  7126. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  7127. const auto response_state = WaitForCdsNack();
  7128. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  7129. EXPECT_THAT(
  7130. response_state->error_message,
  7131. ::testing::HasSubstr("ring hash lb config has invalid hash function."));
  7132. }
  7133. // Test we nack when ring hash policy has invalid ring size.
  7134. TEST_P(CdsTest, RingHashPolicyHasInvalidMinimumRingSize) {
  7135. auto cluster = default_cluster_;
  7136. cluster.set_lb_policy(Cluster::RING_HASH);
  7137. cluster.mutable_ring_hash_lb_config()->mutable_minimum_ring_size()->set_value(
  7138. 0);
  7139. balancer_->ads_service()->SetCdsResource(cluster);
  7140. auto new_route_config = default_route_config_;
  7141. auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  7142. auto* hash_policy = route->mutable_route()->add_hash_policy();
  7143. hash_policy->mutable_filter_state()->set_key("io.grpc.channel_id");
  7144. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  7145. new_route_config);
  7146. EdsResourceArgs args({
  7147. {"locality0", CreateEndpointsForBackends()},
  7148. });
  7149. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  7150. const auto response_state = WaitForCdsNack();
  7151. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  7152. EXPECT_THAT(response_state->error_message,
  7153. ::testing::HasSubstr(
  7154. "min_ring_size is not in the range of 1 to 8388608."));
  7155. }
  7156. // Test we nack when ring hash policy has invalid ring size.
  7157. TEST_P(CdsTest, RingHashPolicyHasInvalidMaxmumRingSize) {
  7158. auto cluster = default_cluster_;
  7159. cluster.set_lb_policy(Cluster::RING_HASH);
  7160. cluster.mutable_ring_hash_lb_config()->mutable_maximum_ring_size()->set_value(
  7161. 8388609);
  7162. balancer_->ads_service()->SetCdsResource(cluster);
  7163. auto new_route_config = default_route_config_;
  7164. auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  7165. auto* hash_policy = route->mutable_route()->add_hash_policy();
  7166. hash_policy->mutable_filter_state()->set_key("io.grpc.channel_id");
  7167. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  7168. new_route_config);
  7169. EdsResourceArgs args({
  7170. {"locality0", CreateEndpointsForBackends()},
  7171. });
  7172. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  7173. const auto response_state = WaitForCdsNack();
  7174. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  7175. EXPECT_THAT(response_state->error_message,
  7176. ::testing::HasSubstr(
  7177. "max_ring_size is not in the range of 1 to 8388608."));
  7178. }
  7179. // Test we nack when ring hash policy has invalid ring size.
  7180. TEST_P(CdsTest, RingHashPolicyHasInvalidRingSizeMinGreaterThanMax) {
  7181. auto cluster = default_cluster_;
  7182. cluster.set_lb_policy(Cluster::RING_HASH);
  7183. cluster.mutable_ring_hash_lb_config()->mutable_maximum_ring_size()->set_value(
  7184. 5000);
  7185. cluster.mutable_ring_hash_lb_config()->mutable_minimum_ring_size()->set_value(
  7186. 5001);
  7187. balancer_->ads_service()->SetCdsResource(cluster);
  7188. auto new_route_config = default_route_config_;
  7189. auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  7190. auto* hash_policy = route->mutable_route()->add_hash_policy();
  7191. hash_policy->mutable_filter_state()->set_key("io.grpc.channel_id");
  7192. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  7193. new_route_config);
  7194. EdsResourceArgs args({
  7195. {"locality0", CreateEndpointsForBackends()},
  7196. });
  7197. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  7198. const auto response_state = WaitForCdsNack();
  7199. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  7200. EXPECT_THAT(response_state->error_message,
  7201. ::testing::HasSubstr(
  7202. "min_ring_size cannot be greater than max_ring_size."));
  7203. }
  7204. class XdsSecurityTest : public BasicTest {
  7205. protected:
  7206. void SetUp() override {
  7207. BootstrapBuilder builder = BootstrapBuilder();
  7208. builder.AddCertificateProviderPlugin("fake_plugin1", "fake1");
  7209. builder.AddCertificateProviderPlugin("fake_plugin2", "fake2");
  7210. std::vector<std::string> fields;
  7211. fields.push_back(absl::StrFormat(" \"certificate_file\": \"%s\"",
  7212. kClientCertPath));
  7213. fields.push_back(absl::StrFormat(" \"private_key_file\": \"%s\"",
  7214. kClientKeyPath));
  7215. fields.push_back(absl::StrFormat(" \"ca_certificate_file\": \"%s\"",
  7216. kCaCertPath));
  7217. builder.AddCertificateProviderPlugin("file_plugin", "file_watcher",
  7218. absl::StrJoin(fields, ",\n"));
  7219. CreateClientsAndServers(builder);
  7220. StartAllBackends();
  7221. root_cert_ = ReadFile(kCaCertPath);
  7222. bad_root_cert_ = ReadFile(kBadClientCertPath);
  7223. identity_pair_ = ReadTlsIdentityPair(kClientKeyPath, kClientCertPath);
  7224. // TODO(yashykt): Use different client certs here instead of reusing
  7225. // server certs after https://github.com/grpc/grpc/pull/24876 is merged
  7226. fallback_identity_pair_ =
  7227. ReadTlsIdentityPair(kServerKeyPath, kServerCertPath);
  7228. bad_identity_pair_ =
  7229. ReadTlsIdentityPair(kBadClientKeyPath, kBadClientCertPath);
  7230. server_san_exact_.set_exact("*.test.google.fr");
  7231. server_san_prefix_.set_prefix("waterzooi.test.google");
  7232. server_san_suffix_.set_suffix("google.fr");
  7233. server_san_contains_.set_contains("google");
  7234. server_san_regex_.mutable_safe_regex()->mutable_google_re2();
  7235. server_san_regex_.mutable_safe_regex()->set_regex(
  7236. "(foo|waterzooi).test.google.(fr|be)");
  7237. bad_san_1_.set_exact("192.168.1.4");
  7238. bad_san_2_.set_exact("foo.test.google.in");
  7239. authenticated_identity_ = {"testclient"};
  7240. fallback_authenticated_identity_ = {"*.test.google.fr",
  7241. "waterzooi.test.google.be",
  7242. "*.test.youtube.com", "192.168.1.3"};
  7243. EdsResourceArgs args({
  7244. {"locality0", CreateEndpointsForBackends(0, 1)},
  7245. });
  7246. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  7247. }
  7248. void TearDown() override {
  7249. g_fake1_cert_data_map = nullptr;
  7250. g_fake2_cert_data_map = nullptr;
  7251. XdsEnd2endTest::TearDown();
  7252. }
  7253. // Sends CDS updates with the new security configuration and verifies that
  7254. // after propagation, this new configuration is used for connections. If \a
  7255. // identity_instance_name and \a root_instance_name are both empty,
  7256. // connections are expected to use fallback credentials.
  7257. void UpdateAndVerifyXdsSecurityConfiguration(
  7258. absl::string_view root_instance_name,
  7259. absl::string_view root_certificate_name,
  7260. absl::string_view identity_instance_name,
  7261. absl::string_view identity_certificate_name,
  7262. const std::vector<StringMatcher>& san_matchers,
  7263. const std::vector<std::string>& expected_authenticated_identity,
  7264. bool test_expects_failure = false) {
  7265. auto cluster = default_cluster_;
  7266. if (!identity_instance_name.empty() || !root_instance_name.empty()) {
  7267. auto* transport_socket = cluster.mutable_transport_socket();
  7268. transport_socket->set_name("envoy.transport_sockets.tls");
  7269. UpstreamTlsContext upstream_tls_context;
  7270. if (!identity_instance_name.empty()) {
  7271. upstream_tls_context.mutable_common_tls_context()
  7272. ->mutable_tls_certificate_provider_instance()
  7273. ->set_instance_name(std::string(identity_instance_name));
  7274. upstream_tls_context.mutable_common_tls_context()
  7275. ->mutable_tls_certificate_provider_instance()
  7276. ->set_certificate_name(std::string(identity_certificate_name));
  7277. }
  7278. if (!root_instance_name.empty()) {
  7279. upstream_tls_context.mutable_common_tls_context()
  7280. ->mutable_validation_context()
  7281. ->mutable_ca_certificate_provider_instance()
  7282. ->set_instance_name(std::string(root_instance_name));
  7283. upstream_tls_context.mutable_common_tls_context()
  7284. ->mutable_validation_context()
  7285. ->mutable_ca_certificate_provider_instance()
  7286. ->set_certificate_name(std::string(root_certificate_name));
  7287. }
  7288. if (!san_matchers.empty()) {
  7289. auto* validation_context =
  7290. upstream_tls_context.mutable_common_tls_context()
  7291. ->mutable_validation_context();
  7292. for (const auto& san_matcher : san_matchers) {
  7293. *validation_context->add_match_subject_alt_names() = san_matcher;
  7294. }
  7295. }
  7296. transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
  7297. }
  7298. balancer_->ads_service()->SetCdsResource(cluster);
  7299. // The updates might take time to have an effect, so use a retry loop.
  7300. constexpr int kRetryCount = 100;
  7301. int num_tries = 0;
  7302. for (; num_tries < kRetryCount; num_tries++) {
  7303. // Give some time for the updates to propagate.
  7304. gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(100));
  7305. if (test_expects_failure) {
  7306. // Restart the servers to force a reconnection so that previously
  7307. // connected subchannels are not used for the RPC.
  7308. ShutdownBackend(0);
  7309. StartBackend(0);
  7310. if (SendRpc().ok()) {
  7311. gpr_log(GPR_ERROR, "RPC succeeded. Failure expected. Trying again.");
  7312. continue;
  7313. }
  7314. } else {
  7315. WaitForBackend(0, WaitForBackendOptions().set_allow_failures(true));
  7316. Status status = SendRpc();
  7317. if (!status.ok()) {
  7318. gpr_log(GPR_ERROR, "RPC failed. code=%d message=%s Trying again.",
  7319. status.error_code(), status.error_message().c_str());
  7320. continue;
  7321. }
  7322. if (backends_[0]->backend_service()->last_peer_identity() !=
  7323. expected_authenticated_identity) {
  7324. gpr_log(
  7325. GPR_ERROR,
  7326. "Expected client identity does not match. (actual) %s vs "
  7327. "(expected) %s Trying again.",
  7328. absl::StrJoin(
  7329. backends_[0]->backend_service()->last_peer_identity(), ",")
  7330. .c_str(),
  7331. absl::StrJoin(expected_authenticated_identity, ",").c_str());
  7332. continue;
  7333. }
  7334. }
  7335. break;
  7336. }
  7337. EXPECT_LT(num_tries, kRetryCount);
  7338. }
  7339. std::string root_cert_;
  7340. std::string bad_root_cert_;
  7341. grpc_core::PemKeyCertPairList identity_pair_;
  7342. grpc_core::PemKeyCertPairList fallback_identity_pair_;
  7343. grpc_core::PemKeyCertPairList bad_identity_pair_;
  7344. StringMatcher server_san_exact_;
  7345. StringMatcher server_san_prefix_;
  7346. StringMatcher server_san_suffix_;
  7347. StringMatcher server_san_contains_;
  7348. StringMatcher server_san_regex_;
  7349. StringMatcher bad_san_1_;
  7350. StringMatcher bad_san_2_;
  7351. std::vector<std::string> authenticated_identity_;
  7352. std::vector<std::string> fallback_authenticated_identity_;
  7353. };
  7354. TEST_P(XdsSecurityTest, UnknownTransportSocket) {
  7355. auto cluster = default_cluster_;
  7356. auto* transport_socket = cluster.mutable_transport_socket();
  7357. transport_socket->set_name("unknown_transport_socket");
  7358. balancer_->ads_service()->SetCdsResource(cluster);
  7359. const auto response_state = WaitForCdsNack();
  7360. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  7361. EXPECT_THAT(response_state->error_message,
  7362. ::testing::HasSubstr(
  7363. "Unrecognized transport socket: unknown_transport_socket"));
  7364. }
  7365. TEST_P(XdsSecurityTest,
  7366. TLSConfigurationWithoutValidationContextCertificateProviderInstance) {
  7367. auto cluster = default_cluster_;
  7368. auto* transport_socket = cluster.mutable_transport_socket();
  7369. transport_socket->set_name("envoy.transport_sockets.tls");
  7370. balancer_->ads_service()->SetCdsResource(cluster);
  7371. const auto response_state = WaitForCdsNack();
  7372. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  7373. EXPECT_THAT(response_state->error_message,
  7374. ::testing::HasSubstr("TLS configuration provided but no "
  7375. "ca_certificate_provider_instance found."));
  7376. }
  7377. TEST_P(
  7378. XdsSecurityTest,
  7379. MatchSubjectAltNamesProvidedWithoutValidationContextCertificateProviderInstance) {
  7380. auto cluster = default_cluster_;
  7381. auto* transport_socket = cluster.mutable_transport_socket();
  7382. transport_socket->set_name("envoy.transport_sockets.tls");
  7383. UpstreamTlsContext upstream_tls_context;
  7384. auto* validation_context = upstream_tls_context.mutable_common_tls_context()
  7385. ->mutable_validation_context();
  7386. *validation_context->add_match_subject_alt_names() = server_san_exact_;
  7387. transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
  7388. balancer_->ads_service()->SetCdsResource(cluster);
  7389. const auto response_state = WaitForCdsNack();
  7390. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  7391. EXPECT_THAT(response_state->error_message,
  7392. ::testing::HasSubstr("TLS configuration provided but no "
  7393. "ca_certificate_provider_instance found."));
  7394. }
  7395. TEST_P(
  7396. XdsSecurityTest,
  7397. TlsCertificateProviderInstanceWithoutValidationContextCertificateProviderInstance) {
  7398. auto cluster = default_cluster_;
  7399. auto* transport_socket = cluster.mutable_transport_socket();
  7400. transport_socket->set_name("envoy.transport_sockets.tls");
  7401. UpstreamTlsContext upstream_tls_context;
  7402. upstream_tls_context.mutable_common_tls_context()
  7403. ->mutable_tls_certificate_provider_instance()
  7404. ->set_instance_name(std::string("fake_plugin1"));
  7405. transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
  7406. balancer_->ads_service()->SetCdsResource(cluster);
  7407. const auto response_state = WaitForCdsNack();
  7408. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  7409. EXPECT_THAT(response_state->error_message,
  7410. ::testing::HasSubstr("TLS configuration provided but no "
  7411. "ca_certificate_provider_instance found."));
  7412. }
  7413. TEST_P(XdsSecurityTest, RegexSanMatcherDoesNotAllowIgnoreCase) {
  7414. auto cluster = default_cluster_;
  7415. auto* transport_socket = cluster.mutable_transport_socket();
  7416. transport_socket->set_name("envoy.transport_sockets.tls");
  7417. UpstreamTlsContext upstream_tls_context;
  7418. upstream_tls_context.mutable_common_tls_context()
  7419. ->mutable_validation_context()
  7420. ->mutable_ca_certificate_provider_instance()
  7421. ->set_instance_name(std::string("fake_plugin1"));
  7422. auto* validation_context = upstream_tls_context.mutable_common_tls_context()
  7423. ->mutable_validation_context();
  7424. StringMatcher matcher;
  7425. matcher.mutable_safe_regex()->mutable_google_re2();
  7426. matcher.mutable_safe_regex()->set_regex(
  7427. "(foo|waterzooi).test.google.(fr|be)");
  7428. matcher.set_ignore_case(true);
  7429. *validation_context->add_match_subject_alt_names() = matcher;
  7430. transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
  7431. balancer_->ads_service()->SetCdsResource(cluster);
  7432. const auto response_state = WaitForCdsNack();
  7433. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  7434. EXPECT_THAT(response_state->error_message,
  7435. ::testing::HasSubstr(
  7436. "StringMatcher: ignore_case has no effect for SAFE_REGEX."));
  7437. }
  7438. TEST_P(XdsSecurityTest, UnknownRootCertificateProvider) {
  7439. auto cluster = default_cluster_;
  7440. auto* transport_socket = cluster.mutable_transport_socket();
  7441. transport_socket->set_name("envoy.transport_sockets.tls");
  7442. UpstreamTlsContext upstream_tls_context;
  7443. upstream_tls_context.mutable_common_tls_context()
  7444. ->mutable_validation_context()
  7445. ->mutable_ca_certificate_provider_instance()
  7446. ->set_instance_name("unknown");
  7447. transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
  7448. balancer_->ads_service()->SetCdsResource(cluster);
  7449. const auto response_state = WaitForCdsNack();
  7450. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  7451. EXPECT_THAT(response_state->error_message,
  7452. ::testing::HasSubstr(
  7453. "Unrecognized certificate provider instance name: unknown"));
  7454. }
  7455. TEST_P(XdsSecurityTest, UnknownIdentityCertificateProvider) {
  7456. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7457. {"", {root_cert_, identity_pair_}}};
  7458. g_fake1_cert_data_map = &fake1_cert_map;
  7459. auto cluster = default_cluster_;
  7460. auto* transport_socket = cluster.mutable_transport_socket();
  7461. transport_socket->set_name("envoy.transport_sockets.tls");
  7462. UpstreamTlsContext upstream_tls_context;
  7463. upstream_tls_context.mutable_common_tls_context()
  7464. ->mutable_tls_certificate_provider_instance()
  7465. ->set_instance_name("unknown");
  7466. upstream_tls_context.mutable_common_tls_context()
  7467. ->mutable_validation_context()
  7468. ->mutable_ca_certificate_provider_instance()
  7469. ->set_instance_name("fake_plugin1");
  7470. transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
  7471. balancer_->ads_service()->SetCdsResource(cluster);
  7472. const auto response_state = WaitForCdsNack();
  7473. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  7474. EXPECT_THAT(response_state->error_message,
  7475. ::testing::HasSubstr(
  7476. "Unrecognized certificate provider instance name: unknown"));
  7477. g_fake1_cert_data_map = nullptr;
  7478. }
  7479. TEST_P(XdsSecurityTest,
  7480. NacksCertificateValidationContextWithVerifyCertificateSpki) {
  7481. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7482. {"", {root_cert_, identity_pair_}}};
  7483. g_fake1_cert_data_map = &fake1_cert_map;
  7484. auto cluster = default_cluster_;
  7485. auto* transport_socket = cluster.mutable_transport_socket();
  7486. transport_socket->set_name("envoy.transport_sockets.tls");
  7487. UpstreamTlsContext upstream_tls_context;
  7488. upstream_tls_context.mutable_common_tls_context()
  7489. ->mutable_validation_context()
  7490. ->mutable_ca_certificate_provider_instance()
  7491. ->set_instance_name("fake_plugin1");
  7492. upstream_tls_context.mutable_common_tls_context()
  7493. ->mutable_validation_context()
  7494. ->add_verify_certificate_spki("spki");
  7495. transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
  7496. balancer_->ads_service()->SetCdsResource(cluster);
  7497. const auto response_state = WaitForCdsNack();
  7498. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  7499. EXPECT_THAT(
  7500. response_state->error_message,
  7501. ::testing::HasSubstr(
  7502. "CertificateValidationContext: verify_certificate_spki unsupported"));
  7503. }
  7504. TEST_P(XdsSecurityTest,
  7505. NacksCertificateValidationContextWithVerifyCertificateHash) {
  7506. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7507. {"", {root_cert_, identity_pair_}}};
  7508. g_fake1_cert_data_map = &fake1_cert_map;
  7509. auto cluster = default_cluster_;
  7510. auto* transport_socket = cluster.mutable_transport_socket();
  7511. transport_socket->set_name("envoy.transport_sockets.tls");
  7512. UpstreamTlsContext upstream_tls_context;
  7513. upstream_tls_context.mutable_common_tls_context()
  7514. ->mutable_validation_context()
  7515. ->mutable_ca_certificate_provider_instance()
  7516. ->set_instance_name("fake_plugin1");
  7517. upstream_tls_context.mutable_common_tls_context()
  7518. ->mutable_validation_context()
  7519. ->add_verify_certificate_hash("hash");
  7520. transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
  7521. balancer_->ads_service()->SetCdsResource(cluster);
  7522. const auto response_state = WaitForCdsNack();
  7523. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  7524. EXPECT_THAT(
  7525. response_state->error_message,
  7526. ::testing::HasSubstr(
  7527. "CertificateValidationContext: verify_certificate_hash unsupported"));
  7528. }
  7529. TEST_P(XdsSecurityTest,
  7530. NacksCertificateValidationContextWithRequireSignedCertificateTimes) {
  7531. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7532. {"", {root_cert_, identity_pair_}}};
  7533. g_fake1_cert_data_map = &fake1_cert_map;
  7534. auto cluster = default_cluster_;
  7535. auto* transport_socket = cluster.mutable_transport_socket();
  7536. transport_socket->set_name("envoy.transport_sockets.tls");
  7537. UpstreamTlsContext upstream_tls_context;
  7538. upstream_tls_context.mutable_common_tls_context()
  7539. ->mutable_validation_context()
  7540. ->mutable_ca_certificate_provider_instance()
  7541. ->set_instance_name("fake_plugin1");
  7542. upstream_tls_context.mutable_common_tls_context()
  7543. ->mutable_validation_context()
  7544. ->mutable_require_signed_certificate_timestamp()
  7545. ->set_value(true);
  7546. transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
  7547. balancer_->ads_service()->SetCdsResource(cluster);
  7548. const auto response_state = WaitForCdsNack();
  7549. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  7550. EXPECT_THAT(
  7551. response_state->error_message,
  7552. ::testing::HasSubstr("CertificateValidationContext: "
  7553. "require_signed_certificate_timestamp unsupported"));
  7554. }
  7555. TEST_P(XdsSecurityTest, NacksCertificateValidationContextWithCrl) {
  7556. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7557. {"", {root_cert_, identity_pair_}}};
  7558. g_fake1_cert_data_map = &fake1_cert_map;
  7559. auto cluster = default_cluster_;
  7560. auto* transport_socket = cluster.mutable_transport_socket();
  7561. transport_socket->set_name("envoy.transport_sockets.tls");
  7562. UpstreamTlsContext upstream_tls_context;
  7563. upstream_tls_context.mutable_common_tls_context()
  7564. ->mutable_validation_context()
  7565. ->mutable_ca_certificate_provider_instance()
  7566. ->set_instance_name("fake_plugin1");
  7567. upstream_tls_context.mutable_common_tls_context()
  7568. ->mutable_validation_context()
  7569. ->mutable_crl();
  7570. transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
  7571. balancer_->ads_service()->SetCdsResource(cluster);
  7572. const auto response_state = WaitForCdsNack();
  7573. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  7574. EXPECT_THAT(
  7575. response_state->error_message,
  7576. ::testing::HasSubstr("CertificateValidationContext: crl unsupported"));
  7577. }
  7578. TEST_P(XdsSecurityTest,
  7579. NacksCertificateValidationContextWithCustomValidatorConfig) {
  7580. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7581. {"", {root_cert_, identity_pair_}}};
  7582. g_fake1_cert_data_map = &fake1_cert_map;
  7583. auto cluster = default_cluster_;
  7584. auto* transport_socket = cluster.mutable_transport_socket();
  7585. transport_socket->set_name("envoy.transport_sockets.tls");
  7586. UpstreamTlsContext upstream_tls_context;
  7587. upstream_tls_context.mutable_common_tls_context()
  7588. ->mutable_validation_context()
  7589. ->mutable_ca_certificate_provider_instance()
  7590. ->set_instance_name("fake_plugin1");
  7591. upstream_tls_context.mutable_common_tls_context()
  7592. ->mutable_validation_context()
  7593. ->mutable_custom_validator_config();
  7594. transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
  7595. balancer_->ads_service()->SetCdsResource(cluster);
  7596. const auto response_state = WaitForCdsNack();
  7597. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  7598. EXPECT_THAT(
  7599. response_state->error_message,
  7600. ::testing::HasSubstr(
  7601. "CertificateValidationContext: custom_validator_config unsupported"));
  7602. }
  7603. TEST_P(XdsSecurityTest, NacksValidationContextSdsSecretConfig) {
  7604. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7605. {"", {root_cert_, identity_pair_}}};
  7606. g_fake1_cert_data_map = &fake1_cert_map;
  7607. auto cluster = default_cluster_;
  7608. auto* transport_socket = cluster.mutable_transport_socket();
  7609. transport_socket->set_name("envoy.transport_sockets.tls");
  7610. UpstreamTlsContext upstream_tls_context;
  7611. upstream_tls_context.mutable_common_tls_context()
  7612. ->mutable_validation_context_sds_secret_config();
  7613. transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
  7614. balancer_->ads_service()->SetCdsResource(cluster);
  7615. const auto response_state = WaitForCdsNack();
  7616. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  7617. EXPECT_THAT(
  7618. response_state->error_message,
  7619. ::testing::HasSubstr("validation_context_sds_secret_config unsupported"));
  7620. }
  7621. TEST_P(XdsSecurityTest, NacksTlsParams) {
  7622. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7623. {"", {root_cert_, identity_pair_}}};
  7624. g_fake1_cert_data_map = &fake1_cert_map;
  7625. auto cluster = default_cluster_;
  7626. auto* transport_socket = cluster.mutable_transport_socket();
  7627. transport_socket->set_name("envoy.transport_sockets.tls");
  7628. UpstreamTlsContext upstream_tls_context;
  7629. upstream_tls_context.mutable_common_tls_context()
  7630. ->mutable_validation_context()
  7631. ->mutable_ca_certificate_provider_instance()
  7632. ->set_instance_name("fake_plugin1");
  7633. upstream_tls_context.mutable_common_tls_context()->mutable_tls_params();
  7634. transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
  7635. balancer_->ads_service()->SetCdsResource(cluster);
  7636. const auto response_state = WaitForCdsNack();
  7637. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  7638. EXPECT_THAT(response_state->error_message,
  7639. ::testing::HasSubstr("tls_params unsupported"));
  7640. }
  7641. TEST_P(XdsSecurityTest, NacksCustomHandshaker) {
  7642. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7643. {"", {root_cert_, identity_pair_}}};
  7644. g_fake1_cert_data_map = &fake1_cert_map;
  7645. auto cluster = default_cluster_;
  7646. auto* transport_socket = cluster.mutable_transport_socket();
  7647. transport_socket->set_name("envoy.transport_sockets.tls");
  7648. UpstreamTlsContext upstream_tls_context;
  7649. upstream_tls_context.mutable_common_tls_context()
  7650. ->mutable_validation_context()
  7651. ->mutable_ca_certificate_provider_instance()
  7652. ->set_instance_name("fake_plugin1");
  7653. upstream_tls_context.mutable_common_tls_context()
  7654. ->mutable_custom_handshaker();
  7655. transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
  7656. balancer_->ads_service()->SetCdsResource(cluster);
  7657. const auto response_state = WaitForCdsNack();
  7658. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  7659. EXPECT_THAT(response_state->error_message,
  7660. ::testing::HasSubstr("custom_handshaker unsupported"));
  7661. }
  7662. TEST_P(XdsSecurityTest, NacksTlsCertificates) {
  7663. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7664. {"", {root_cert_, identity_pair_}}};
  7665. g_fake1_cert_data_map = &fake1_cert_map;
  7666. auto cluster = default_cluster_;
  7667. auto* transport_socket = cluster.mutable_transport_socket();
  7668. transport_socket->set_name("envoy.transport_sockets.tls");
  7669. UpstreamTlsContext upstream_tls_context;
  7670. upstream_tls_context.mutable_common_tls_context()
  7671. ->mutable_validation_context()
  7672. ->mutable_ca_certificate_provider_instance()
  7673. ->set_instance_name("fake_plugin1");
  7674. upstream_tls_context.mutable_common_tls_context()->add_tls_certificates();
  7675. transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
  7676. balancer_->ads_service()->SetCdsResource(cluster);
  7677. const auto response_state = WaitForCdsNack();
  7678. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  7679. EXPECT_THAT(response_state->error_message,
  7680. ::testing::HasSubstr("tls_certificates unsupported"));
  7681. }
  7682. TEST_P(XdsSecurityTest, NacksTlsCertificateSdsSecretConfigs) {
  7683. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7684. {"", {root_cert_, identity_pair_}}};
  7685. g_fake1_cert_data_map = &fake1_cert_map;
  7686. auto cluster = default_cluster_;
  7687. auto* transport_socket = cluster.mutable_transport_socket();
  7688. transport_socket->set_name("envoy.transport_sockets.tls");
  7689. UpstreamTlsContext upstream_tls_context;
  7690. upstream_tls_context.mutable_common_tls_context()
  7691. ->mutable_validation_context()
  7692. ->mutable_ca_certificate_provider_instance()
  7693. ->set_instance_name("fake_plugin1");
  7694. upstream_tls_context.mutable_common_tls_context()
  7695. ->add_tls_certificate_sds_secret_configs();
  7696. transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
  7697. balancer_->ads_service()->SetCdsResource(cluster);
  7698. const auto response_state = WaitForCdsNack();
  7699. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  7700. EXPECT_THAT(
  7701. response_state->error_message,
  7702. ::testing::HasSubstr("tls_certificate_sds_secret_configs unsupported"));
  7703. }
  7704. TEST_P(XdsSecurityTest, TestTlsConfigurationInCombinedValidationContext) {
  7705. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7706. {"", {root_cert_, identity_pair_}}};
  7707. g_fake1_cert_data_map = &fake1_cert_map;
  7708. auto cluster = default_cluster_;
  7709. auto* transport_socket = cluster.mutable_transport_socket();
  7710. transport_socket->set_name("envoy.transport_sockets.tls");
  7711. UpstreamTlsContext upstream_tls_context;
  7712. upstream_tls_context.mutable_common_tls_context()
  7713. ->mutable_combined_validation_context()
  7714. ->mutable_default_validation_context()
  7715. ->mutable_ca_certificate_provider_instance()
  7716. ->set_instance_name("fake_plugin1");
  7717. transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
  7718. balancer_->ads_service()->SetCdsResource(cluster);
  7719. WaitForBackend(0, WaitForBackendOptions().set_allow_failures(true));
  7720. Status status = SendRpc();
  7721. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  7722. << " message=" << status.error_message();
  7723. }
  7724. // TODO(yashykt): Remove this test once we stop supporting old fields
  7725. TEST_P(XdsSecurityTest,
  7726. TestTlsConfigurationInValidationContextCertificateProviderInstance) {
  7727. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7728. {"", {root_cert_, identity_pair_}}};
  7729. g_fake1_cert_data_map = &fake1_cert_map;
  7730. auto cluster = default_cluster_;
  7731. auto* transport_socket = cluster.mutable_transport_socket();
  7732. transport_socket->set_name("envoy.transport_sockets.tls");
  7733. UpstreamTlsContext upstream_tls_context;
  7734. upstream_tls_context.mutable_common_tls_context()
  7735. ->mutable_combined_validation_context()
  7736. ->mutable_validation_context_certificate_provider_instance()
  7737. ->set_instance_name("fake_plugin1");
  7738. transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
  7739. balancer_->ads_service()->SetCdsResource(cluster);
  7740. WaitForBackend(0, WaitForBackendOptions().set_allow_failures(true));
  7741. Status status = SendRpc();
  7742. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  7743. << " message=" << status.error_message();
  7744. }
  7745. TEST_P(XdsSecurityTest, TestMtlsConfigurationWithNoSanMatchers) {
  7746. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7747. {"", {root_cert_, identity_pair_}}};
  7748. g_fake1_cert_data_map = &fake1_cert_map;
  7749. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  7750. "", {}, authenticated_identity_);
  7751. g_fake1_cert_data_map = nullptr;
  7752. }
  7753. TEST_P(XdsSecurityTest, TestMtlsConfigurationWithExactSanMatcher) {
  7754. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7755. {"", {root_cert_, identity_pair_}}};
  7756. g_fake1_cert_data_map = &fake1_cert_map;
  7757. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  7758. "", {server_san_exact_},
  7759. authenticated_identity_);
  7760. g_fake1_cert_data_map = nullptr;
  7761. }
  7762. TEST_P(XdsSecurityTest, TestMtlsConfigurationWithPrefixSanMatcher) {
  7763. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7764. {"", {root_cert_, identity_pair_}}};
  7765. g_fake1_cert_data_map = &fake1_cert_map;
  7766. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  7767. "", {server_san_prefix_},
  7768. authenticated_identity_);
  7769. g_fake1_cert_data_map = nullptr;
  7770. }
  7771. TEST_P(XdsSecurityTest, TestMtlsConfigurationWithSuffixSanMatcher) {
  7772. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7773. {"", {root_cert_, identity_pair_}}};
  7774. g_fake1_cert_data_map = &fake1_cert_map;
  7775. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  7776. "", {server_san_suffix_},
  7777. authenticated_identity_);
  7778. g_fake1_cert_data_map = nullptr;
  7779. }
  7780. TEST_P(XdsSecurityTest, TestMtlsConfigurationWithContainsSanMatcher) {
  7781. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7782. {"", {root_cert_, identity_pair_}}};
  7783. g_fake1_cert_data_map = &fake1_cert_map;
  7784. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  7785. "", {server_san_contains_},
  7786. authenticated_identity_);
  7787. g_fake1_cert_data_map = nullptr;
  7788. }
  7789. TEST_P(XdsSecurityTest, TestMtlsConfigurationWithRegexSanMatcher) {
  7790. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7791. {"", {root_cert_, identity_pair_}}};
  7792. g_fake1_cert_data_map = &fake1_cert_map;
  7793. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  7794. "", {server_san_regex_},
  7795. authenticated_identity_);
  7796. g_fake1_cert_data_map = nullptr;
  7797. }
  7798. TEST_P(XdsSecurityTest, TestMtlsConfigurationWithSanMatchersUpdate) {
  7799. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7800. {"", {root_cert_, identity_pair_}}};
  7801. g_fake1_cert_data_map = &fake1_cert_map;
  7802. UpdateAndVerifyXdsSecurityConfiguration(
  7803. "fake_plugin1", "", "fake_plugin1", "",
  7804. {server_san_exact_, server_san_prefix_}, authenticated_identity_);
  7805. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  7806. "", {bad_san_1_, bad_san_2_}, {},
  7807. true /* failure */);
  7808. UpdateAndVerifyXdsSecurityConfiguration(
  7809. "fake_plugin1", "", "fake_plugin1", "",
  7810. {server_san_prefix_, server_san_regex_}, authenticated_identity_);
  7811. g_fake1_cert_data_map = nullptr;
  7812. }
  7813. TEST_P(XdsSecurityTest, TestMtlsConfigurationWithRootPluginUpdate) {
  7814. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7815. {"", {root_cert_, identity_pair_}}};
  7816. g_fake1_cert_data_map = &fake1_cert_map;
  7817. FakeCertificateProvider::CertDataMap fake2_cert_map = {
  7818. {"", {bad_root_cert_, bad_identity_pair_}}};
  7819. g_fake2_cert_data_map = &fake2_cert_map;
  7820. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  7821. "", {server_san_exact_},
  7822. authenticated_identity_);
  7823. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin2" /* bad root */, "",
  7824. "fake_plugin1", "", {}, {},
  7825. true /* failure */);
  7826. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  7827. "", {server_san_exact_},
  7828. authenticated_identity_);
  7829. g_fake1_cert_data_map = nullptr;
  7830. g_fake2_cert_data_map = nullptr;
  7831. }
  7832. TEST_P(XdsSecurityTest, TestMtlsConfigurationWithIdentityPluginUpdate) {
  7833. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7834. {"", {root_cert_, identity_pair_}}};
  7835. g_fake1_cert_data_map = &fake1_cert_map;
  7836. FakeCertificateProvider::CertDataMap fake2_cert_map = {
  7837. {"", {root_cert_, fallback_identity_pair_}}};
  7838. g_fake2_cert_data_map = &fake2_cert_map;
  7839. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  7840. "", {server_san_exact_},
  7841. authenticated_identity_);
  7842. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin2",
  7843. "", {server_san_exact_},
  7844. fallback_authenticated_identity_);
  7845. g_fake1_cert_data_map = nullptr;
  7846. g_fake2_cert_data_map = nullptr;
  7847. }
  7848. TEST_P(XdsSecurityTest, TestMtlsConfigurationWithBothPluginsUpdated) {
  7849. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7850. {"", {root_cert_, identity_pair_}}};
  7851. g_fake1_cert_data_map = &fake1_cert_map;
  7852. FakeCertificateProvider::CertDataMap fake2_cert_map = {
  7853. {"", {bad_root_cert_, bad_identity_pair_}},
  7854. {"good", {root_cert_, fallback_identity_pair_}}};
  7855. g_fake2_cert_data_map = &fake2_cert_map;
  7856. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin2", "", "fake_plugin2",
  7857. "", {}, {}, true /* failure */);
  7858. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  7859. "", {server_san_prefix_},
  7860. authenticated_identity_);
  7861. UpdateAndVerifyXdsSecurityConfiguration(
  7862. "fake_plugin2", "good", "fake_plugin2", "good", {server_san_prefix_},
  7863. fallback_authenticated_identity_);
  7864. g_fake1_cert_data_map = nullptr;
  7865. g_fake2_cert_data_map = nullptr;
  7866. }
  7867. TEST_P(XdsSecurityTest, TestMtlsConfigurationWithRootCertificateNameUpdate) {
  7868. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7869. {"", {root_cert_, identity_pair_}},
  7870. {"bad", {bad_root_cert_, bad_identity_pair_}}};
  7871. g_fake1_cert_data_map = &fake1_cert_map;
  7872. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  7873. "", {server_san_regex_},
  7874. authenticated_identity_);
  7875. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "bad", "fake_plugin1",
  7876. "", {server_san_regex_}, {},
  7877. true /* failure */);
  7878. g_fake1_cert_data_map = nullptr;
  7879. }
  7880. TEST_P(XdsSecurityTest,
  7881. TestMtlsConfigurationWithIdentityCertificateNameUpdate) {
  7882. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7883. {"", {root_cert_, identity_pair_}},
  7884. {"bad", {bad_root_cert_, bad_identity_pair_}}};
  7885. g_fake1_cert_data_map = &fake1_cert_map;
  7886. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  7887. "", {server_san_exact_},
  7888. authenticated_identity_);
  7889. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  7890. "bad", {server_san_exact_}, {},
  7891. true /* failure */);
  7892. g_fake1_cert_data_map = nullptr;
  7893. }
  7894. TEST_P(XdsSecurityTest,
  7895. TestMtlsConfigurationWithIdentityCertificateNameUpdateGoodCerts) {
  7896. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7897. {"", {root_cert_, identity_pair_}},
  7898. {"good", {root_cert_, fallback_identity_pair_}}};
  7899. g_fake1_cert_data_map = &fake1_cert_map;
  7900. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  7901. "", {server_san_exact_},
  7902. authenticated_identity_);
  7903. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  7904. "good", {server_san_exact_},
  7905. fallback_authenticated_identity_);
  7906. g_fake1_cert_data_map = nullptr;
  7907. }
  7908. TEST_P(XdsSecurityTest, TestMtlsConfigurationWithBothCertificateNamesUpdated) {
  7909. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7910. {"", {root_cert_, identity_pair_}},
  7911. {"bad", {bad_root_cert_, bad_identity_pair_}}};
  7912. g_fake1_cert_data_map = &fake1_cert_map;
  7913. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "bad", "fake_plugin1",
  7914. "bad", {server_san_prefix_}, {},
  7915. true /* failure */);
  7916. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  7917. "", {server_san_prefix_},
  7918. authenticated_identity_);
  7919. g_fake1_cert_data_map = nullptr;
  7920. }
  7921. TEST_P(XdsSecurityTest, TestTlsConfigurationWithNoSanMatchers) {
  7922. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7923. {"", {root_cert_, identity_pair_}}};
  7924. g_fake1_cert_data_map = &fake1_cert_map;
  7925. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "", {},
  7926. {} /* unauthenticated */);
  7927. g_fake1_cert_data_map = nullptr;
  7928. }
  7929. TEST_P(XdsSecurityTest, TestTlsConfigurationWithSanMatchers) {
  7930. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7931. {"", {root_cert_, identity_pair_}}};
  7932. g_fake1_cert_data_map = &fake1_cert_map;
  7933. UpdateAndVerifyXdsSecurityConfiguration(
  7934. "fake_plugin1", "", "", "",
  7935. {server_san_exact_, server_san_prefix_, server_san_regex_},
  7936. {} /* unauthenticated */);
  7937. g_fake1_cert_data_map = nullptr;
  7938. }
  7939. TEST_P(XdsSecurityTest, TestTlsConfigurationWithSanMatchersUpdate) {
  7940. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7941. {"", {root_cert_, identity_pair_}}};
  7942. g_fake1_cert_data_map = &fake1_cert_map;
  7943. UpdateAndVerifyXdsSecurityConfiguration(
  7944. "fake_plugin1", "", "", "", {server_san_exact_, server_san_prefix_},
  7945. {} /* unauthenticated */);
  7946. UpdateAndVerifyXdsSecurityConfiguration(
  7947. "fake_plugin1", "", "", "", {bad_san_1_, bad_san_2_},
  7948. {} /* unauthenticated */, true /* failure */);
  7949. UpdateAndVerifyXdsSecurityConfiguration(
  7950. "fake_plugin1", "", "", "", {server_san_prefix_, server_san_regex_},
  7951. {} /* unauthenticated */);
  7952. g_fake1_cert_data_map = nullptr;
  7953. }
  7954. TEST_P(XdsSecurityTest, TestTlsConfigurationWithRootCertificateNameUpdate) {
  7955. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7956. {"", {root_cert_, identity_pair_}},
  7957. {"bad", {bad_root_cert_, bad_identity_pair_}}};
  7958. g_fake1_cert_data_map = &fake1_cert_map;
  7959. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
  7960. {server_san_exact_},
  7961. {} /* unauthenticated */);
  7962. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "bad", "", "",
  7963. {server_san_exact_}, {},
  7964. true /* failure */);
  7965. g_fake1_cert_data_map = nullptr;
  7966. }
  7967. TEST_P(XdsSecurityTest, TestTlsConfigurationWithRootPluginUpdate) {
  7968. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7969. {"", {root_cert_, identity_pair_}}};
  7970. g_fake1_cert_data_map = &fake1_cert_map;
  7971. FakeCertificateProvider::CertDataMap fake2_cert_map = {
  7972. {"", {bad_root_cert_, bad_identity_pair_}}};
  7973. g_fake2_cert_data_map = &fake2_cert_map;
  7974. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
  7975. {server_san_exact_},
  7976. {} /* unauthenticated */);
  7977. UpdateAndVerifyXdsSecurityConfiguration(
  7978. "fake_plugin2", "", "", "", {server_san_exact_}, {}, true /* failure */);
  7979. g_fake1_cert_data_map = nullptr;
  7980. g_fake2_cert_data_map = nullptr;
  7981. }
  7982. TEST_P(XdsSecurityTest, TestFallbackConfiguration) {
  7983. UpdateAndVerifyXdsSecurityConfiguration("", "", "", "", {},
  7984. fallback_authenticated_identity_);
  7985. g_fake1_cert_data_map = nullptr;
  7986. }
  7987. TEST_P(XdsSecurityTest, TestMtlsToTls) {
  7988. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  7989. {"", {root_cert_, identity_pair_}}};
  7990. g_fake1_cert_data_map = &fake1_cert_map;
  7991. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  7992. "", {server_san_exact_},
  7993. authenticated_identity_);
  7994. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
  7995. {server_san_exact_},
  7996. {} /* unauthenticated */);
  7997. g_fake1_cert_data_map = nullptr;
  7998. }
  7999. TEST_P(XdsSecurityTest, TestMtlsToFallback) {
  8000. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  8001. {"", {root_cert_, identity_pair_}}};
  8002. g_fake1_cert_data_map = &fake1_cert_map;
  8003. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  8004. "", {server_san_exact_},
  8005. authenticated_identity_);
  8006. UpdateAndVerifyXdsSecurityConfiguration("", "", "", "", {},
  8007. fallback_authenticated_identity_);
  8008. g_fake1_cert_data_map = nullptr;
  8009. }
  8010. TEST_P(XdsSecurityTest, TestTlsToMtls) {
  8011. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  8012. {"", {root_cert_, identity_pair_}}};
  8013. g_fake1_cert_data_map = &fake1_cert_map;
  8014. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
  8015. {server_san_exact_},
  8016. {} /* unauthenticated */);
  8017. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  8018. "", {server_san_exact_},
  8019. authenticated_identity_);
  8020. g_fake1_cert_data_map = nullptr;
  8021. }
  8022. TEST_P(XdsSecurityTest, TestTlsToFallback) {
  8023. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  8024. {"", {root_cert_, identity_pair_}}};
  8025. g_fake1_cert_data_map = &fake1_cert_map;
  8026. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
  8027. {server_san_exact_},
  8028. {} /* unauthenticated */);
  8029. UpdateAndVerifyXdsSecurityConfiguration("", "", "", "", {},
  8030. fallback_authenticated_identity_);
  8031. g_fake1_cert_data_map = nullptr;
  8032. }
  8033. TEST_P(XdsSecurityTest, TestFallbackToMtls) {
  8034. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  8035. {"", {root_cert_, identity_pair_}}};
  8036. g_fake1_cert_data_map = &fake1_cert_map;
  8037. UpdateAndVerifyXdsSecurityConfiguration("", "", "", "", {},
  8038. fallback_authenticated_identity_);
  8039. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
  8040. "", {server_san_exact_},
  8041. authenticated_identity_);
  8042. g_fake1_cert_data_map = nullptr;
  8043. }
  8044. TEST_P(XdsSecurityTest, TestFallbackToTls) {
  8045. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  8046. {"", {root_cert_, identity_pair_}}};
  8047. g_fake1_cert_data_map = &fake1_cert_map;
  8048. UpdateAndVerifyXdsSecurityConfiguration("", "", "", "", {},
  8049. fallback_authenticated_identity_);
  8050. UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
  8051. {server_san_exact_},
  8052. {} /* unauthenticated */);
  8053. g_fake1_cert_data_map = nullptr;
  8054. }
  8055. TEST_P(XdsSecurityTest, TestFileWatcherCertificateProvider) {
  8056. UpdateAndVerifyXdsSecurityConfiguration("file_plugin", "", "file_plugin", "",
  8057. {server_san_exact_},
  8058. authenticated_identity_);
  8059. }
  8060. class XdsEnabledServerTest : public XdsEnd2endTest {
  8061. protected:
  8062. XdsEnabledServerTest()
  8063. : XdsEnd2endTest(1, 100, 0, true /* use_xds_enabled_server */) {}
  8064. void SetUp() override {
  8065. XdsEnd2endTest::SetUp();
  8066. EdsResourceArgs args({
  8067. {"locality0", CreateEndpointsForBackends(0, 1)},
  8068. });
  8069. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  8070. }
  8071. };
  8072. TEST_P(XdsEnabledServerTest, Basic) {
  8073. backends_[0]->Start();
  8074. WaitForBackend(0);
  8075. }
  8076. TEST_P(XdsEnabledServerTest, BadLdsUpdateNoApiListenerNorAddress) {
  8077. Listener listener = default_server_listener_;
  8078. listener.clear_address();
  8079. listener.set_name(
  8080. absl::StrCat("grpc/server?xds.resource.listening_address=",
  8081. ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
  8082. balancer_->ads_service()->SetLdsResource(listener);
  8083. backends_[0]->Start();
  8084. const auto response_state = WaitForLdsNack();
  8085. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  8086. EXPECT_THAT(
  8087. response_state->error_message,
  8088. ::testing::HasSubstr("Listener has neither address nor ApiListener"));
  8089. }
  8090. TEST_P(XdsEnabledServerTest, BadLdsUpdateBothApiListenerAndAddress) {
  8091. Listener listener = default_server_listener_;
  8092. listener.mutable_api_listener();
  8093. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  8094. backends_[0]->port(),
  8095. default_server_route_config_);
  8096. backends_[0]->Start();
  8097. const auto response_state = WaitForLdsNack();
  8098. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  8099. EXPECT_THAT(
  8100. response_state->error_message,
  8101. ::testing::HasSubstr("Listener has both address and ApiListener"));
  8102. }
  8103. TEST_P(XdsEnabledServerTest, NacksNonZeroXffNumTrusterHops) {
  8104. Listener listener = default_server_listener_;
  8105. HttpConnectionManager http_connection_manager =
  8106. ServerHcmAccessor().Unpack(listener);
  8107. http_connection_manager.set_xff_num_trusted_hops(1);
  8108. ServerHcmAccessor().Pack(http_connection_manager, &listener);
  8109. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  8110. backends_[0]->port(),
  8111. default_server_route_config_);
  8112. backends_[0]->Start();
  8113. const auto response_state = WaitForLdsNack();
  8114. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  8115. EXPECT_THAT(response_state->error_message,
  8116. ::testing::HasSubstr("'xff_num_trusted_hops' must be zero"));
  8117. }
  8118. TEST_P(XdsEnabledServerTest, NacksNonEmptyOriginalIpDetectionExtensions) {
  8119. Listener listener = default_server_listener_;
  8120. HttpConnectionManager http_connection_manager =
  8121. ServerHcmAccessor().Unpack(listener);
  8122. http_connection_manager.add_original_ip_detection_extensions();
  8123. ServerHcmAccessor().Pack(http_connection_manager, &listener);
  8124. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  8125. backends_[0]->port(),
  8126. default_server_route_config_);
  8127. backends_[0]->Start();
  8128. const auto response_state = WaitForLdsNack();
  8129. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  8130. EXPECT_THAT(
  8131. response_state->error_message,
  8132. ::testing::HasSubstr("'original_ip_detection_extensions' must be empty"));
  8133. }
  8134. TEST_P(XdsEnabledServerTest, UnsupportedL4Filter) {
  8135. Listener listener = default_server_listener_;
  8136. listener.mutable_default_filter_chain()->clear_filters();
  8137. listener.mutable_default_filter_chain()->add_filters()->mutable_typed_config()->PackFrom(default_listener_ /* any proto object other than HttpConnectionManager */);
  8138. balancer_->ads_service()->SetLdsResource(
  8139. PopulateServerListenerNameAndPort(listener, backends_[0]->port()));
  8140. backends_[0]->Start();
  8141. const auto response_state = WaitForLdsNack();
  8142. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  8143. EXPECT_THAT(response_state->error_message,
  8144. ::testing::HasSubstr("Unsupported filter type"));
  8145. }
  8146. TEST_P(XdsEnabledServerTest, NacksEmptyHttpFilterList) {
  8147. Listener listener = default_server_listener_;
  8148. HttpConnectionManager http_connection_manager =
  8149. ServerHcmAccessor().Unpack(listener);
  8150. http_connection_manager.clear_http_filters();
  8151. ServerHcmAccessor().Pack(http_connection_manager, &listener);
  8152. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  8153. backends_[0]->port(),
  8154. default_server_route_config_);
  8155. backends_[0]->Start();
  8156. const auto response_state = WaitForLdsNack();
  8157. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  8158. EXPECT_THAT(response_state->error_message,
  8159. ::testing::HasSubstr("Expected at least one HTTP filter"));
  8160. }
  8161. TEST_P(XdsEnabledServerTest, UnsupportedHttpFilter) {
  8162. Listener listener = default_server_listener_;
  8163. HttpConnectionManager http_connection_manager =
  8164. ServerHcmAccessor().Unpack(listener);
  8165. http_connection_manager.clear_http_filters();
  8166. auto* http_filter = http_connection_manager.add_http_filters();
  8167. http_filter->set_name("grpc.testing.unsupported_http_filter");
  8168. http_filter->mutable_typed_config()->set_type_url(
  8169. "grpc.testing.unsupported_http_filter");
  8170. http_filter = http_connection_manager.add_http_filters();
  8171. http_filter->set_name("router");
  8172. http_filter->mutable_typed_config()->PackFrom(
  8173. envoy::extensions::filters::http::router::v3::Router());
  8174. ServerHcmAccessor().Pack(http_connection_manager, &listener);
  8175. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  8176. backends_[0]->port(),
  8177. default_server_route_config_);
  8178. backends_[0]->Start();
  8179. const auto response_state = WaitForLdsNack();
  8180. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  8181. EXPECT_THAT(response_state->error_message,
  8182. ::testing::HasSubstr("no filter registered for config type "
  8183. "grpc.testing.unsupported_http_filter"));
  8184. }
  8185. TEST_P(XdsEnabledServerTest, HttpFilterNotSupportedOnServer) {
  8186. Listener listener = default_server_listener_;
  8187. HttpConnectionManager http_connection_manager =
  8188. ServerHcmAccessor().Unpack(listener);
  8189. http_connection_manager.clear_http_filters();
  8190. auto* http_filter = http_connection_manager.add_http_filters();
  8191. http_filter->set_name("grpc.testing.client_only_http_filter");
  8192. http_filter->mutable_typed_config()->set_type_url(
  8193. "grpc.testing.client_only_http_filter");
  8194. http_filter = http_connection_manager.add_http_filters();
  8195. http_filter->set_name("router");
  8196. http_filter->mutable_typed_config()->PackFrom(
  8197. envoy::extensions::filters::http::router::v3::Router());
  8198. ServerHcmAccessor().Pack(http_connection_manager, &listener);
  8199. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  8200. backends_[0]->port(),
  8201. default_server_route_config_);
  8202. backends_[0]->Start();
  8203. const auto response_state = WaitForLdsNack();
  8204. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  8205. EXPECT_THAT(
  8206. response_state->error_message,
  8207. ::testing::HasSubstr("Filter grpc.testing.client_only_http_filter is not "
  8208. "supported on servers"));
  8209. }
  8210. TEST_P(XdsEnabledServerTest,
  8211. HttpFilterNotSupportedOnServerIgnoredWhenOptional) {
  8212. Listener listener = default_server_listener_;
  8213. HttpConnectionManager http_connection_manager =
  8214. ServerHcmAccessor().Unpack(listener);
  8215. http_connection_manager.clear_http_filters();
  8216. auto* http_filter = http_connection_manager.add_http_filters();
  8217. http_filter->set_name("grpc.testing.client_only_http_filter");
  8218. http_filter->mutable_typed_config()->set_type_url(
  8219. "grpc.testing.client_only_http_filter");
  8220. http_filter->set_is_optional(true);
  8221. http_filter = http_connection_manager.add_http_filters();
  8222. http_filter->set_name("router");
  8223. http_filter->mutable_typed_config()->PackFrom(
  8224. envoy::extensions::filters::http::router::v3::Router());
  8225. ServerHcmAccessor().Pack(http_connection_manager, &listener);
  8226. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  8227. backends_[0]->port(),
  8228. default_server_route_config_);
  8229. backends_[0]->Start();
  8230. WaitForBackend(0);
  8231. auto response_state = balancer_->ads_service()->lds_response_state();
  8232. ASSERT_TRUE(response_state.has_value());
  8233. EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
  8234. }
  8235. // Verify that a mismatch of listening address results in "not serving"
  8236. // status.
  8237. TEST_P(XdsEnabledServerTest, ListenerAddressMismatch) {
  8238. Listener listener = default_server_listener_;
  8239. // Set a different listening address in the LDS update
  8240. listener.mutable_address()->mutable_socket_address()->set_address(
  8241. "192.168.1.1");
  8242. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  8243. backends_[0]->port(),
  8244. default_server_route_config_);
  8245. backends_[0]->Start();
  8246. backends_[0]->notifier()->WaitOnServingStatusChange(
  8247. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  8248. grpc::StatusCode::FAILED_PRECONDITION);
  8249. }
  8250. TEST_P(XdsEnabledServerTest, UseOriginalDstNotSupported) {
  8251. Listener listener = default_server_listener_;
  8252. listener.mutable_use_original_dst()->set_value(true);
  8253. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  8254. backends_[0]->port(),
  8255. default_server_route_config_);
  8256. backends_[0]->Start();
  8257. const auto response_state = WaitForLdsNack();
  8258. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  8259. EXPECT_THAT(
  8260. response_state->error_message,
  8261. ::testing::HasSubstr("Field \'use_original_dst\' is not supported."));
  8262. }
  8263. class XdsServerSecurityTest : public XdsEnd2endTest {
  8264. protected:
  8265. XdsServerSecurityTest()
  8266. : XdsEnd2endTest(1, 100, 0, true /* use_xds_enabled_server */) {}
  8267. void SetUp() override {
  8268. BootstrapBuilder builder = BootstrapBuilder();
  8269. builder.AddCertificateProviderPlugin("fake_plugin1", "fake1");
  8270. builder.AddCertificateProviderPlugin("fake_plugin2", "fake2");
  8271. std::vector<std::string> fields;
  8272. fields.push_back(absl::StrFormat(" \"certificate_file\": \"%s\"",
  8273. kClientCertPath));
  8274. fields.push_back(absl::StrFormat(" \"private_key_file\": \"%s\"",
  8275. kClientKeyPath));
  8276. fields.push_back(absl::StrFormat(" \"ca_certificate_file\": \"%s\"",
  8277. kCaCertPath));
  8278. builder.AddCertificateProviderPlugin("file_plugin", "file_watcher",
  8279. absl::StrJoin(fields, ",\n"));
  8280. CreateClientsAndServers(builder);
  8281. root_cert_ = ReadFile(kCaCertPath);
  8282. bad_root_cert_ = ReadFile(kBadClientCertPath);
  8283. identity_pair_ = ReadTlsIdentityPair(kServerKeyPath, kServerCertPath);
  8284. bad_identity_pair_ =
  8285. ReadTlsIdentityPair(kBadClientKeyPath, kBadClientCertPath);
  8286. identity_pair_2_ = ReadTlsIdentityPair(kClientKeyPath, kClientCertPath);
  8287. server_authenticated_identity_ = {"*.test.google.fr",
  8288. "waterzooi.test.google.be",
  8289. "*.test.youtube.com", "192.168.1.3"};
  8290. server_authenticated_identity_2_ = {"testclient"};
  8291. client_authenticated_identity_ = {"*.test.google.fr",
  8292. "waterzooi.test.google.be",
  8293. "*.test.youtube.com", "192.168.1.3"};
  8294. EdsResourceArgs args({
  8295. {"locality0", CreateEndpointsForBackends(0, 1)},
  8296. });
  8297. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  8298. }
  8299. void TearDown() override {
  8300. g_fake1_cert_data_map = nullptr;
  8301. g_fake2_cert_data_map = nullptr;
  8302. XdsEnd2endTest::TearDown();
  8303. }
  8304. void SetLdsUpdate(absl::string_view root_instance_name,
  8305. absl::string_view root_certificate_name,
  8306. absl::string_view identity_instance_name,
  8307. absl::string_view identity_certificate_name,
  8308. bool require_client_certificates) {
  8309. Listener listener = default_server_listener_;
  8310. auto* filter_chain = listener.mutable_default_filter_chain();
  8311. if (!identity_instance_name.empty()) {
  8312. auto* transport_socket = filter_chain->mutable_transport_socket();
  8313. transport_socket->set_name("envoy.transport_sockets.tls");
  8314. DownstreamTlsContext downstream_tls_context;
  8315. downstream_tls_context.mutable_common_tls_context()
  8316. ->mutable_tls_certificate_provider_instance()
  8317. ->set_instance_name(std::string(identity_instance_name));
  8318. downstream_tls_context.mutable_common_tls_context()
  8319. ->mutable_tls_certificate_provider_instance()
  8320. ->set_certificate_name(std::string(identity_certificate_name));
  8321. if (!root_instance_name.empty()) {
  8322. downstream_tls_context.mutable_common_tls_context()
  8323. ->mutable_validation_context()
  8324. ->mutable_ca_certificate_provider_instance()
  8325. ->set_instance_name(std::string(root_instance_name));
  8326. downstream_tls_context.mutable_common_tls_context()
  8327. ->mutable_validation_context()
  8328. ->mutable_ca_certificate_provider_instance()
  8329. ->set_certificate_name(std::string(root_certificate_name));
  8330. downstream_tls_context.mutable_require_client_certificate()->set_value(
  8331. require_client_certificates);
  8332. }
  8333. transport_socket->mutable_typed_config()->PackFrom(
  8334. downstream_tls_context);
  8335. }
  8336. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  8337. backends_[0]->port(),
  8338. default_server_route_config_);
  8339. }
  8340. std::shared_ptr<grpc::Channel> CreateMtlsChannel() {
  8341. ChannelArguments args;
  8342. // Override target name for host name check
  8343. args.SetString(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG,
  8344. ipv6_only_ ? "::1" : "127.0.0.1");
  8345. args.SetInt(GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL, 1);
  8346. std::string uri = absl::StrCat(
  8347. ipv6_only_ ? "ipv6:[::1]:" : "ipv4:127.0.0.1:", backends_[0]->port());
  8348. IdentityKeyCertPair key_cert_pair;
  8349. key_cert_pair.private_key = ReadFile(kServerKeyPath);
  8350. key_cert_pair.certificate_chain = ReadFile(kServerCertPath);
  8351. std::vector<IdentityKeyCertPair> identity_key_cert_pairs;
  8352. identity_key_cert_pairs.emplace_back(key_cert_pair);
  8353. auto certificate_provider = std::make_shared<StaticDataCertificateProvider>(
  8354. ReadFile(kCaCertPath), identity_key_cert_pairs);
  8355. grpc::experimental::TlsChannelCredentialsOptions options;
  8356. options.set_certificate_provider(std::move(certificate_provider));
  8357. options.watch_root_certs();
  8358. options.watch_identity_key_cert_pairs();
  8359. auto verifier =
  8360. ExternalCertificateVerifier::Create<SyncCertificateVerifier>(true);
  8361. options.set_verify_server_certs(true);
  8362. options.set_certificate_verifier(std::move(verifier));
  8363. auto channel_creds = grpc::experimental::TlsCredentials(options);
  8364. GPR_ASSERT(channel_creds.get() != nullptr);
  8365. return CreateCustomChannel(uri, channel_creds, args);
  8366. }
  8367. std::shared_ptr<grpc::Channel> CreateTlsChannel() {
  8368. ChannelArguments args;
  8369. // Override target name for host name check
  8370. args.SetString(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG,
  8371. ipv6_only_ ? "::1" : "127.0.0.1");
  8372. args.SetInt(GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL, 1);
  8373. std::string uri = absl::StrCat(
  8374. ipv6_only_ ? "ipv6:[::1]:" : "ipv4:127.0.0.1:", backends_[0]->port());
  8375. auto certificate_provider =
  8376. std::make_shared<StaticDataCertificateProvider>(ReadFile(kCaCertPath));
  8377. grpc::experimental::TlsChannelCredentialsOptions options;
  8378. options.set_certificate_provider(std::move(certificate_provider));
  8379. options.watch_root_certs();
  8380. auto verifier =
  8381. ExternalCertificateVerifier::Create<SyncCertificateVerifier>(true);
  8382. options.set_verify_server_certs(true);
  8383. options.set_certificate_verifier(std::move(verifier));
  8384. auto channel_creds = grpc::experimental::TlsCredentials(options);
  8385. GPR_ASSERT(channel_creds.get() != nullptr);
  8386. return CreateCustomChannel(uri, channel_creds, args);
  8387. }
  8388. std::shared_ptr<grpc::Channel> CreateInsecureChannel() {
  8389. ChannelArguments args;
  8390. // Override target name for host name check
  8391. args.SetString(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG,
  8392. ipv6_only_ ? "::1" : "127.0.0.1");
  8393. args.SetInt(GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL, 1);
  8394. std::string uri = absl::StrCat(
  8395. ipv6_only_ ? "ipv6:[::1]:" : "ipv4:127.0.0.1:", backends_[0]->port());
  8396. return CreateCustomChannel(uri, InsecureChannelCredentials(), args);
  8397. }
  8398. void SendRpc(
  8399. std::function<std::shared_ptr<grpc::Channel>()> channel_creator,
  8400. std::vector<std::string> expected_server_identity,
  8401. std::vector<std::string> expected_client_identity,
  8402. bool test_expects_failure = false,
  8403. absl::optional<grpc::StatusCode> expected_status = absl::nullopt) {
  8404. gpr_log(GPR_INFO, "Sending RPC");
  8405. int num_tries = 0;
  8406. constexpr int kRetryCount = 100;
  8407. auto overall_deadline = absl::Now() + absl::Seconds(5);
  8408. for (; num_tries < kRetryCount || absl::Now() < overall_deadline;
  8409. num_tries++) {
  8410. auto channel = channel_creator();
  8411. auto stub = grpc::testing::EchoTestService::NewStub(channel);
  8412. ClientContext context;
  8413. context.set_wait_for_ready(true);
  8414. context.set_deadline(grpc_timeout_milliseconds_to_deadline(2000));
  8415. EchoRequest request;
  8416. // TODO(yashykt): Skipping the cancelled check on the server since the
  8417. // server's graceful shutdown isn't as per spec and the check isn't
  8418. // necessary for what we want to test here anyway.
  8419. // https://github.com/grpc/grpc/issues/24237
  8420. request.mutable_param()->set_skip_cancelled_check(true);
  8421. request.set_message(kRequestMessage);
  8422. EchoResponse response;
  8423. Status status = stub->Echo(&context, request, &response);
  8424. if (test_expects_failure) {
  8425. if (status.ok()) {
  8426. gpr_log(GPR_ERROR, "RPC succeeded. Failure expected. Trying again.");
  8427. continue;
  8428. }
  8429. if (expected_status.has_value() &&
  8430. *expected_status != status.error_code()) {
  8431. gpr_log(GPR_ERROR,
  8432. "Expected status does not match Actual(%d) vs Expected(%d)",
  8433. status.error_code(), *expected_status);
  8434. continue;
  8435. }
  8436. } else {
  8437. if (!status.ok()) {
  8438. gpr_log(GPR_ERROR, "RPC failed. code=%d message=%s Trying again.",
  8439. status.error_code(), status.error_message().c_str());
  8440. continue;
  8441. }
  8442. EXPECT_EQ(response.message(), kRequestMessage);
  8443. std::vector<std::string> peer_identity;
  8444. for (const auto& entry : context.auth_context()->GetPeerIdentity()) {
  8445. peer_identity.emplace_back(
  8446. std::string(entry.data(), entry.size()).c_str());
  8447. }
  8448. if (peer_identity != expected_server_identity) {
  8449. gpr_log(GPR_ERROR,
  8450. "Expected server identity does not match. (actual) %s vs "
  8451. "(expected) %s Trying again.",
  8452. absl::StrJoin(peer_identity, ",").c_str(),
  8453. absl::StrJoin(expected_server_identity, ",").c_str());
  8454. continue;
  8455. }
  8456. if (backends_[0]->backend_service()->last_peer_identity() !=
  8457. expected_client_identity) {
  8458. gpr_log(
  8459. GPR_ERROR,
  8460. "Expected client identity does not match. (actual) %s vs "
  8461. "(expected) %s Trying again.",
  8462. absl::StrJoin(
  8463. backends_[0]->backend_service()->last_peer_identity(), ",")
  8464. .c_str(),
  8465. absl::StrJoin(expected_client_identity, ",").c_str());
  8466. continue;
  8467. }
  8468. }
  8469. break;
  8470. }
  8471. EXPECT_LT(num_tries, kRetryCount);
  8472. }
  8473. std::string root_cert_;
  8474. std::string bad_root_cert_;
  8475. grpc_core::PemKeyCertPairList identity_pair_;
  8476. grpc_core::PemKeyCertPairList bad_identity_pair_;
  8477. grpc_core::PemKeyCertPairList identity_pair_2_;
  8478. std::vector<std::string> server_authenticated_identity_;
  8479. std::vector<std::string> server_authenticated_identity_2_;
  8480. std::vector<std::string> client_authenticated_identity_;
  8481. };
  8482. TEST_P(XdsServerSecurityTest, UnknownTransportSocket) {
  8483. Listener listener = default_server_listener_;
  8484. auto* filter_chain = listener.mutable_default_filter_chain();
  8485. auto* transport_socket = filter_chain->mutable_transport_socket();
  8486. transport_socket->set_name("unknown_transport_socket");
  8487. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  8488. backends_[0]->port(),
  8489. default_server_route_config_);
  8490. backends_[0]->Start();
  8491. const auto response_state = WaitForLdsNack();
  8492. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  8493. EXPECT_THAT(response_state->error_message,
  8494. ::testing::HasSubstr(
  8495. "Unrecognized transport socket: unknown_transport_socket"));
  8496. }
  8497. TEST_P(XdsServerSecurityTest, NacksRequireSNI) {
  8498. Listener listener = default_server_listener_;
  8499. auto* filter_chain = listener.mutable_default_filter_chain();
  8500. auto* transport_socket = filter_chain->mutable_transport_socket();
  8501. transport_socket->set_name("envoy.transport_sockets.tls");
  8502. DownstreamTlsContext downstream_tls_context;
  8503. downstream_tls_context.mutable_common_tls_context()
  8504. ->mutable_tls_certificate_provider_instance()
  8505. ->set_instance_name("fake_plugin1");
  8506. downstream_tls_context.mutable_require_sni()->set_value(true);
  8507. transport_socket->mutable_typed_config()->PackFrom(downstream_tls_context);
  8508. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  8509. backends_[0]->port(),
  8510. default_server_route_config_);
  8511. backends_[0]->Start();
  8512. const auto response_state = WaitForLdsNack();
  8513. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  8514. EXPECT_THAT(response_state->error_message,
  8515. ::testing::HasSubstr("require_sni: unsupported"));
  8516. }
  8517. TEST_P(XdsServerSecurityTest, NacksOcspStaplePolicyOtherThanLenientStapling) {
  8518. Listener listener = default_server_listener_;
  8519. auto* filter_chain = listener.mutable_default_filter_chain();
  8520. auto* transport_socket = filter_chain->mutable_transport_socket();
  8521. transport_socket->set_name("envoy.transport_sockets.tls");
  8522. DownstreamTlsContext downstream_tls_context;
  8523. downstream_tls_context.mutable_common_tls_context()
  8524. ->mutable_tls_certificate_provider_instance()
  8525. ->set_instance_name("fake_plugin1");
  8526. downstream_tls_context.set_ocsp_staple_policy(
  8527. envoy::extensions::transport_sockets::tls::v3::
  8528. DownstreamTlsContext_OcspStaplePolicy_STRICT_STAPLING);
  8529. transport_socket->mutable_typed_config()->PackFrom(downstream_tls_context);
  8530. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  8531. backends_[0]->port(),
  8532. default_server_route_config_);
  8533. backends_[0]->Start();
  8534. const auto response_state = WaitForLdsNack();
  8535. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  8536. EXPECT_THAT(response_state->error_message,
  8537. ::testing::HasSubstr(
  8538. "ocsp_staple_policy: Only LENIENT_STAPLING supported"));
  8539. }
  8540. TEST_P(
  8541. XdsServerSecurityTest,
  8542. NacksRequiringClientCertificateWithoutValidationCertificateProviderInstance) {
  8543. Listener listener = default_server_listener_;
  8544. auto* filter_chain = listener.mutable_default_filter_chain();
  8545. auto* transport_socket = filter_chain->mutable_transport_socket();
  8546. transport_socket->set_name("envoy.transport_sockets.tls");
  8547. DownstreamTlsContext downstream_tls_context;
  8548. downstream_tls_context.mutable_common_tls_context()
  8549. ->mutable_tls_certificate_provider_instance()
  8550. ->set_instance_name("fake_plugin1");
  8551. downstream_tls_context.mutable_require_client_certificate()->set_value(true);
  8552. transport_socket->mutable_typed_config()->PackFrom(downstream_tls_context);
  8553. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  8554. backends_[0]->port(),
  8555. default_server_route_config_);
  8556. backends_[0]->Start();
  8557. const auto response_state = WaitForLdsNack();
  8558. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  8559. EXPECT_THAT(response_state->error_message,
  8560. ::testing::HasSubstr(
  8561. "TLS configuration requires client certificates but no "
  8562. "certificate provider instance specified for validation."));
  8563. }
  8564. TEST_P(XdsServerSecurityTest,
  8565. NacksTlsConfigurationWithoutIdentityProviderInstance) {
  8566. Listener listener = default_server_listener_;
  8567. auto* filter_chain = listener.mutable_default_filter_chain();
  8568. auto* transport_socket = filter_chain->mutable_transport_socket();
  8569. transport_socket->set_name("envoy.transport_sockets.tls");
  8570. DownstreamTlsContext downstream_tls_context;
  8571. transport_socket->mutable_typed_config()->PackFrom(downstream_tls_context);
  8572. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  8573. backends_[0]->port(),
  8574. default_server_route_config_);
  8575. backends_[0]->Start();
  8576. const auto response_state = WaitForLdsNack();
  8577. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  8578. EXPECT_THAT(response_state->error_message,
  8579. ::testing::HasSubstr("TLS configuration provided but no "
  8580. "tls_certificate_provider_instance found."));
  8581. }
  8582. TEST_P(XdsServerSecurityTest, NacksMatchSubjectAltNames) {
  8583. Listener listener = default_server_listener_;
  8584. auto* filter_chain = listener.mutable_default_filter_chain();
  8585. auto* transport_socket = filter_chain->mutable_transport_socket();
  8586. transport_socket->set_name("envoy.transport_sockets.tls");
  8587. DownstreamTlsContext downstream_tls_context;
  8588. downstream_tls_context.mutable_common_tls_context()
  8589. ->mutable_tls_certificate_provider_instance()
  8590. ->set_instance_name("fake_plugin1");
  8591. downstream_tls_context.mutable_common_tls_context()
  8592. ->mutable_validation_context()
  8593. ->add_match_subject_alt_names()
  8594. ->set_exact("*.test.google.fr");
  8595. transport_socket->mutable_typed_config()->PackFrom(downstream_tls_context);
  8596. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  8597. backends_[0]->port(),
  8598. default_server_route_config_);
  8599. backends_[0]->Start();
  8600. const auto response_state = WaitForLdsNack();
  8601. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  8602. EXPECT_THAT(
  8603. response_state->error_message,
  8604. ::testing::HasSubstr("match_subject_alt_names not supported on servers"));
  8605. }
  8606. TEST_P(XdsServerSecurityTest, UnknownIdentityCertificateProvider) {
  8607. SetLdsUpdate("", "", "unknown", "", false);
  8608. SendRpc([this]() { return CreateTlsChannel(); }, {}, {},
  8609. true /* test_expects_failure */);
  8610. backends_[0]->Start();
  8611. const auto response_state = WaitForLdsNack();
  8612. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  8613. EXPECT_THAT(response_state->error_message,
  8614. ::testing::HasSubstr(
  8615. "Unrecognized certificate provider instance name: unknown"));
  8616. }
  8617. TEST_P(XdsServerSecurityTest, UnknownRootCertificateProvider) {
  8618. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  8619. {"", {root_cert_, identity_pair_}}};
  8620. SetLdsUpdate("unknown", "", "fake_plugin1", "", false);
  8621. backends_[0]->Start();
  8622. const auto response_state = WaitForLdsNack();
  8623. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  8624. EXPECT_THAT(response_state->error_message,
  8625. ::testing::HasSubstr(
  8626. "Unrecognized certificate provider instance name: unknown"));
  8627. }
  8628. TEST_P(XdsServerSecurityTest,
  8629. TestDeprecateTlsCertificateCertificateProviderInstanceField) {
  8630. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  8631. {"", {root_cert_, identity_pair_}}};
  8632. g_fake1_cert_data_map = &fake1_cert_map;
  8633. Listener listener = default_server_listener_;
  8634. auto* filter_chain = listener.mutable_default_filter_chain();
  8635. filter_chain->mutable_filters()->at(0).mutable_typed_config()->PackFrom(
  8636. ServerHcmAccessor().Unpack(listener));
  8637. auto* transport_socket = filter_chain->mutable_transport_socket();
  8638. transport_socket->set_name("envoy.transport_sockets.tls");
  8639. DownstreamTlsContext downstream_tls_context;
  8640. downstream_tls_context.mutable_common_tls_context()
  8641. ->mutable_tls_certificate_certificate_provider_instance()
  8642. ->set_instance_name("fake_plugin1");
  8643. transport_socket->mutable_typed_config()->PackFrom(downstream_tls_context);
  8644. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  8645. backends_[0]->port(),
  8646. default_server_route_config_);
  8647. backends_[0]->Start();
  8648. SendRpc([this]() { return CreateTlsChannel(); },
  8649. server_authenticated_identity_, {});
  8650. }
  8651. TEST_P(XdsServerSecurityTest, CertificatesNotAvailable) {
  8652. FakeCertificateProvider::CertDataMap fake1_cert_map;
  8653. g_fake1_cert_data_map = &fake1_cert_map;
  8654. SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
  8655. SendRpc([this]() { return CreateMtlsChannel(); }, {}, {},
  8656. true /* test_expects_failure */);
  8657. }
  8658. TEST_P(XdsServerSecurityTest, TestMtls) {
  8659. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  8660. {"", {root_cert_, identity_pair_}}};
  8661. g_fake1_cert_data_map = &fake1_cert_map;
  8662. SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
  8663. backends_[0]->Start();
  8664. SendRpc([this]() { return CreateMtlsChannel(); },
  8665. server_authenticated_identity_, client_authenticated_identity_);
  8666. }
  8667. TEST_P(XdsServerSecurityTest, TestMtlsWithRootPluginUpdate) {
  8668. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  8669. {"", {root_cert_, identity_pair_}}};
  8670. g_fake1_cert_data_map = &fake1_cert_map;
  8671. FakeCertificateProvider::CertDataMap fake2_cert_map = {
  8672. {"", {bad_root_cert_, bad_identity_pair_}}};
  8673. g_fake2_cert_data_map = &fake2_cert_map;
  8674. SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
  8675. backends_[0]->Start();
  8676. SendRpc([this]() { return CreateMtlsChannel(); },
  8677. server_authenticated_identity_, client_authenticated_identity_);
  8678. SetLdsUpdate("fake_plugin2", "", "fake_plugin1", "", true);
  8679. SendRpc([this]() { return CreateMtlsChannel(); }, {}, {},
  8680. true /* test_expects_failure */);
  8681. }
  8682. TEST_P(XdsServerSecurityTest, TestMtlsWithIdentityPluginUpdate) {
  8683. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  8684. {"", {root_cert_, identity_pair_}}};
  8685. g_fake1_cert_data_map = &fake1_cert_map;
  8686. FakeCertificateProvider::CertDataMap fake2_cert_map = {
  8687. {"", {root_cert_, identity_pair_2_}}};
  8688. g_fake2_cert_data_map = &fake2_cert_map;
  8689. SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
  8690. backends_[0]->Start();
  8691. SendRpc([this]() { return CreateMtlsChannel(); },
  8692. server_authenticated_identity_, client_authenticated_identity_);
  8693. SetLdsUpdate("fake_plugin1", "", "fake_plugin2", "", true);
  8694. SendRpc([this]() { return CreateMtlsChannel(); },
  8695. server_authenticated_identity_2_, client_authenticated_identity_);
  8696. }
  8697. TEST_P(XdsServerSecurityTest, TestMtlsWithBothPluginsUpdated) {
  8698. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  8699. {"", {root_cert_, identity_pair_}}};
  8700. g_fake1_cert_data_map = &fake1_cert_map;
  8701. FakeCertificateProvider::CertDataMap fake2_cert_map = {
  8702. {"good", {root_cert_, identity_pair_2_}},
  8703. {"", {bad_root_cert_, bad_identity_pair_}}};
  8704. g_fake2_cert_data_map = &fake2_cert_map;
  8705. SetLdsUpdate("fake_plugin2", "", "fake_plugin2", "", true);
  8706. backends_[0]->Start();
  8707. SendRpc([this]() { return CreateMtlsChannel(); }, {}, {},
  8708. true /* test_expects_failure */);
  8709. SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
  8710. SendRpc([this]() { return CreateMtlsChannel(); },
  8711. server_authenticated_identity_, client_authenticated_identity_);
  8712. SetLdsUpdate("fake_plugin2", "good", "fake_plugin2", "good", true);
  8713. SendRpc([this]() { return CreateMtlsChannel(); },
  8714. server_authenticated_identity_2_, client_authenticated_identity_);
  8715. }
  8716. TEST_P(XdsServerSecurityTest, TestMtlsWithRootCertificateNameUpdate) {
  8717. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  8718. {"", {root_cert_, identity_pair_}},
  8719. {"bad", {bad_root_cert_, bad_identity_pair_}}};
  8720. g_fake1_cert_data_map = &fake1_cert_map;
  8721. SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
  8722. backends_[0]->Start();
  8723. SendRpc([this]() { return CreateMtlsChannel(); },
  8724. server_authenticated_identity_, client_authenticated_identity_);
  8725. SetLdsUpdate("fake_plugin1", "bad", "fake_plugin1", "", true);
  8726. SendRpc([this]() { return CreateMtlsChannel(); }, {}, {},
  8727. true /* test_expects_failure */);
  8728. }
  8729. TEST_P(XdsServerSecurityTest, TestMtlsWithIdentityCertificateNameUpdate) {
  8730. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  8731. {"", {root_cert_, identity_pair_}},
  8732. {"good", {root_cert_, identity_pair_2_}}};
  8733. g_fake1_cert_data_map = &fake1_cert_map;
  8734. SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
  8735. backends_[0]->Start();
  8736. SendRpc([this]() { return CreateMtlsChannel(); },
  8737. server_authenticated_identity_, client_authenticated_identity_);
  8738. SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "good", true);
  8739. SendRpc([this]() { return CreateMtlsChannel(); },
  8740. server_authenticated_identity_2_, client_authenticated_identity_);
  8741. }
  8742. TEST_P(XdsServerSecurityTest, TestMtlsWithBothCertificateNamesUpdated) {
  8743. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  8744. {"", {root_cert_, identity_pair_}},
  8745. {"good", {root_cert_, identity_pair_2_}}};
  8746. g_fake1_cert_data_map = &fake1_cert_map;
  8747. SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
  8748. backends_[0]->Start();
  8749. SendRpc([this]() { return CreateMtlsChannel(); },
  8750. server_authenticated_identity_, client_authenticated_identity_);
  8751. SetLdsUpdate("fake_plugin1", "good", "fake_plugin1", "good", true);
  8752. SendRpc([this]() { return CreateMtlsChannel(); },
  8753. server_authenticated_identity_2_, client_authenticated_identity_);
  8754. }
  8755. TEST_P(XdsServerSecurityTest, TestMtlsNotRequiringButProvidingClientCerts) {
  8756. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  8757. {"", {root_cert_, identity_pair_}}};
  8758. g_fake1_cert_data_map = &fake1_cert_map;
  8759. SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", false);
  8760. backends_[0]->Start();
  8761. SendRpc([this]() { return CreateMtlsChannel(); },
  8762. server_authenticated_identity_, client_authenticated_identity_);
  8763. }
  8764. TEST_P(XdsServerSecurityTest, TestMtlsNotRequiringAndNotProvidingClientCerts) {
  8765. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  8766. {"", {root_cert_, identity_pair_}}};
  8767. g_fake1_cert_data_map = &fake1_cert_map;
  8768. SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", false);
  8769. backends_[0]->Start();
  8770. SendRpc([this]() { return CreateTlsChannel(); },
  8771. server_authenticated_identity_, {});
  8772. }
  8773. TEST_P(XdsServerSecurityTest, TestTls) {
  8774. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  8775. {"", {root_cert_, identity_pair_}}};
  8776. g_fake1_cert_data_map = &fake1_cert_map;
  8777. SetLdsUpdate("", "", "fake_plugin1", "", false);
  8778. backends_[0]->Start();
  8779. SendRpc([this]() { return CreateTlsChannel(); },
  8780. server_authenticated_identity_, {});
  8781. }
  8782. TEST_P(XdsServerSecurityTest, TestTlsWithIdentityPluginUpdate) {
  8783. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  8784. {"", {root_cert_, identity_pair_}}};
  8785. g_fake1_cert_data_map = &fake1_cert_map;
  8786. FakeCertificateProvider::CertDataMap fake2_cert_map = {
  8787. {"", {root_cert_, identity_pair_2_}}};
  8788. g_fake2_cert_data_map = &fake2_cert_map;
  8789. SetLdsUpdate("", "", "fake_plugin1", "", false);
  8790. backends_[0]->Start();
  8791. SendRpc([this]() { return CreateTlsChannel(); },
  8792. server_authenticated_identity_, {});
  8793. SetLdsUpdate("", "", "fake_plugin2", "", false);
  8794. SendRpc([this]() { return CreateTlsChannel(); },
  8795. server_authenticated_identity_2_, {});
  8796. }
  8797. TEST_P(XdsServerSecurityTest, TestTlsWithIdentityCertificateNameUpdate) {
  8798. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  8799. {"", {root_cert_, identity_pair_}},
  8800. {"good", {root_cert_, identity_pair_2_}}};
  8801. g_fake1_cert_data_map = &fake1_cert_map;
  8802. SetLdsUpdate("", "", "fake_plugin1", "", false);
  8803. backends_[0]->Start();
  8804. SendRpc([this]() { return CreateTlsChannel(); },
  8805. server_authenticated_identity_, {});
  8806. SetLdsUpdate("", "", "fake_plugin1", "good", false);
  8807. SendRpc([this]() { return CreateTlsChannel(); },
  8808. server_authenticated_identity_2_, {});
  8809. }
  8810. TEST_P(XdsServerSecurityTest, TestFallback) {
  8811. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  8812. {"", {root_cert_, identity_pair_}}};
  8813. g_fake1_cert_data_map = &fake1_cert_map;
  8814. SetLdsUpdate("", "", "", "", false);
  8815. backends_[0]->Start();
  8816. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
  8817. }
  8818. TEST_P(XdsServerSecurityTest, TestMtlsToTls) {
  8819. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  8820. {"", {root_cert_, identity_pair_}}};
  8821. g_fake1_cert_data_map = &fake1_cert_map;
  8822. SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
  8823. backends_[0]->Start();
  8824. SendRpc([this]() { return CreateTlsChannel(); }, {}, {},
  8825. true /* test_expects_failure */);
  8826. SetLdsUpdate("", "", "fake_plugin1", "", false);
  8827. SendRpc([this]() { return CreateTlsChannel(); },
  8828. server_authenticated_identity_, {});
  8829. }
  8830. TEST_P(XdsServerSecurityTest, TestTlsToMtls) {
  8831. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  8832. {"", {root_cert_, identity_pair_}}};
  8833. g_fake1_cert_data_map = &fake1_cert_map;
  8834. SetLdsUpdate("", "", "fake_plugin1", "", false);
  8835. backends_[0]->Start();
  8836. SendRpc([this]() { return CreateTlsChannel(); },
  8837. server_authenticated_identity_, {});
  8838. SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
  8839. SendRpc([this]() { return CreateTlsChannel(); }, {}, {},
  8840. true /* test_expects_failure */);
  8841. }
  8842. TEST_P(XdsServerSecurityTest, TestMtlsToFallback) {
  8843. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  8844. {"", {root_cert_, identity_pair_}}};
  8845. g_fake1_cert_data_map = &fake1_cert_map;
  8846. SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", false);
  8847. backends_[0]->Start();
  8848. SendRpc([this]() { return CreateMtlsChannel(); },
  8849. server_authenticated_identity_, client_authenticated_identity_);
  8850. SetLdsUpdate("", "", "", "", false);
  8851. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
  8852. }
  8853. TEST_P(XdsServerSecurityTest, TestFallbackToMtls) {
  8854. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  8855. {"", {root_cert_, identity_pair_}}};
  8856. g_fake1_cert_data_map = &fake1_cert_map;
  8857. SetLdsUpdate("", "", "", "", false);
  8858. backends_[0]->Start();
  8859. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
  8860. SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
  8861. SendRpc([this]() { return CreateMtlsChannel(); },
  8862. server_authenticated_identity_, client_authenticated_identity_);
  8863. }
  8864. TEST_P(XdsServerSecurityTest, TestTlsToFallback) {
  8865. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  8866. {"", {root_cert_, identity_pair_}}};
  8867. g_fake1_cert_data_map = &fake1_cert_map;
  8868. SetLdsUpdate("", "", "fake_plugin1", "", false);
  8869. backends_[0]->Start();
  8870. SendRpc([this]() { return CreateTlsChannel(); },
  8871. server_authenticated_identity_, {});
  8872. SetLdsUpdate("", "", "", "", false);
  8873. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
  8874. }
  8875. TEST_P(XdsServerSecurityTest, TestFallbackToTls) {
  8876. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  8877. {"", {root_cert_, identity_pair_}}};
  8878. g_fake1_cert_data_map = &fake1_cert_map;
  8879. SetLdsUpdate("", "", "", "", false);
  8880. backends_[0]->Start();
  8881. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
  8882. SetLdsUpdate("", "", "fake_plugin1", "", false);
  8883. SendRpc([this]() { return CreateTlsChannel(); },
  8884. server_authenticated_identity_, {});
  8885. }
  8886. class XdsEnabledServerStatusNotificationTest : public XdsServerSecurityTest {
  8887. protected:
  8888. void SetValidLdsUpdate() { SetLdsUpdate("", "", "", "", false); }
  8889. void SetInvalidLdsUpdate() {
  8890. Listener listener = default_server_listener_;
  8891. listener.clear_address();
  8892. listener.set_name(absl::StrCat(
  8893. "grpc/server?xds.resource.listening_address=",
  8894. ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
  8895. balancer_->ads_service()->SetLdsResource(listener);
  8896. }
  8897. void UnsetLdsUpdate() {
  8898. balancer_->ads_service()->UnsetResource(
  8899. kLdsTypeUrl, absl::StrCat("grpc/server?xds.resource.listening_address=",
  8900. ipv6_only_ ? "[::1]:" : "127.0.0.1:",
  8901. backends_[0]->port()));
  8902. }
  8903. };
  8904. TEST_P(XdsEnabledServerStatusNotificationTest, ServingStatus) {
  8905. SetValidLdsUpdate();
  8906. backends_[0]->Start();
  8907. backends_[0]->notifier()->WaitOnServingStatusChange(
  8908. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  8909. grpc::StatusCode::OK);
  8910. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
  8911. }
  8912. TEST_P(XdsEnabledServerStatusNotificationTest, NotServingStatus) {
  8913. SetInvalidLdsUpdate();
  8914. backends_[0]->Start();
  8915. backends_[0]->notifier()->WaitOnServingStatusChange(
  8916. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  8917. grpc::StatusCode::UNAVAILABLE);
  8918. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  8919. true /* test_expects_failure */);
  8920. }
  8921. TEST_P(XdsEnabledServerStatusNotificationTest, ErrorUpdateWhenAlreadyServing) {
  8922. SetValidLdsUpdate();
  8923. backends_[0]->Start();
  8924. backends_[0]->notifier()->WaitOnServingStatusChange(
  8925. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  8926. grpc::StatusCode::OK);
  8927. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
  8928. // Invalid update does not lead to a change in the serving status.
  8929. SetInvalidLdsUpdate();
  8930. do {
  8931. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
  8932. } while (!balancer_->ads_service()->lds_response_state().has_value());
  8933. backends_[0]->notifier()->WaitOnServingStatusChange(
  8934. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  8935. grpc::StatusCode::OK);
  8936. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
  8937. }
  8938. TEST_P(XdsEnabledServerStatusNotificationTest,
  8939. NotServingStatusToServingStatusTransition) {
  8940. SetInvalidLdsUpdate();
  8941. backends_[0]->Start();
  8942. backends_[0]->notifier()->WaitOnServingStatusChange(
  8943. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  8944. grpc::StatusCode::UNAVAILABLE);
  8945. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  8946. true /* test_expects_failure */);
  8947. // Send a valid LDS update to change to serving status
  8948. SetValidLdsUpdate();
  8949. backends_[0]->notifier()->WaitOnServingStatusChange(
  8950. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  8951. grpc::StatusCode::OK);
  8952. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
  8953. }
  8954. // This test verifies that the resource getting deleted when already serving
  8955. // results in future connections being dropped.
  8956. TEST_P(XdsEnabledServerStatusNotificationTest,
  8957. ServingStatusToNonServingStatusTransition) {
  8958. SetValidLdsUpdate();
  8959. backends_[0]->Start();
  8960. backends_[0]->notifier()->WaitOnServingStatusChange(
  8961. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  8962. grpc::StatusCode::OK);
  8963. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
  8964. // Deleting the resource should result in a non-serving status.
  8965. UnsetLdsUpdate();
  8966. backends_[0]->notifier()->WaitOnServingStatusChange(
  8967. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  8968. grpc::StatusCode::NOT_FOUND);
  8969. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  8970. true /* test_expects_failure */);
  8971. }
  8972. TEST_P(XdsEnabledServerStatusNotificationTest, RepeatedServingStatusChanges) {
  8973. backends_[0]->Start();
  8974. for (int i = 0; i < 5; i++) {
  8975. // Send a valid LDS update to get the server to start listening
  8976. SetValidLdsUpdate();
  8977. backends_[0]->notifier()->WaitOnServingStatusChange(
  8978. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:",
  8979. backends_[0]->port()),
  8980. grpc::StatusCode::OK);
  8981. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
  8982. // Deleting the resource will make the server start rejecting connections
  8983. UnsetLdsUpdate();
  8984. backends_[0]->notifier()->WaitOnServingStatusChange(
  8985. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:",
  8986. backends_[0]->port()),
  8987. grpc::StatusCode::NOT_FOUND);
  8988. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  8989. true /* test_expects_failure */);
  8990. }
  8991. }
  8992. TEST_P(XdsEnabledServerStatusNotificationTest, ExistingRpcsOnResourceDeletion) {
  8993. // Send a valid LDS update to get the server to start listening
  8994. SetValidLdsUpdate();
  8995. backends_[0]->Start();
  8996. backends_[0]->notifier()->WaitOnServingStatusChange(
  8997. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  8998. grpc::StatusCode::OK);
  8999. constexpr int kNumChannels = 10;
  9000. struct StreamingRpc {
  9001. std::shared_ptr<Channel> channel;
  9002. std::unique_ptr<grpc::testing::EchoTestService::Stub> stub;
  9003. ClientContext context;
  9004. std::unique_ptr<ClientReaderWriter<EchoRequest, EchoResponse>> stream;
  9005. } streaming_rpcs[kNumChannels];
  9006. EchoRequest request;
  9007. EchoResponse response;
  9008. request.set_message("Hello");
  9009. for (int i = 0; i < kNumChannels; i++) {
  9010. streaming_rpcs[i].channel = CreateInsecureChannel();
  9011. streaming_rpcs[i].stub =
  9012. grpc::testing::EchoTestService::NewStub(streaming_rpcs[i].channel);
  9013. streaming_rpcs[i].context.set_wait_for_ready(true);
  9014. streaming_rpcs[i].stream =
  9015. streaming_rpcs[i].stub->BidiStream(&streaming_rpcs[i].context);
  9016. EXPECT_TRUE(streaming_rpcs[i].stream->Write(request));
  9017. streaming_rpcs[i].stream->Read(&response);
  9018. EXPECT_EQ(request.message(), response.message());
  9019. }
  9020. // Deleting the resource will make the server start rejecting connections
  9021. UnsetLdsUpdate();
  9022. backends_[0]->notifier()->WaitOnServingStatusChange(
  9023. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  9024. grpc::StatusCode::NOT_FOUND);
  9025. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  9026. true /* test_expects_failure */);
  9027. for (int i = 0; i < kNumChannels; i++) {
  9028. EXPECT_TRUE(streaming_rpcs[i].stream->Write(request));
  9029. streaming_rpcs[i].stream->Read(&response);
  9030. EXPECT_EQ(request.message(), response.message());
  9031. EXPECT_TRUE(streaming_rpcs[i].stream->WritesDone());
  9032. auto status = streaming_rpcs[i].stream->Finish();
  9033. EXPECT_TRUE(status.ok())
  9034. << status.error_message() << ", " << status.error_details() << ", "
  9035. << streaming_rpcs[i].context.debug_error_string();
  9036. // New RPCs on the existing channels should fail.
  9037. ClientContext new_context;
  9038. new_context.set_deadline(grpc_timeout_milliseconds_to_deadline(1000));
  9039. EXPECT_FALSE(
  9040. streaming_rpcs[i].stub->Echo(&new_context, request, &response).ok());
  9041. }
  9042. }
  9043. TEST_P(XdsEnabledServerStatusNotificationTest,
  9044. ExistingRpcsFailOnResourceUpdateAfterDrainGraceTimeExpires) {
  9045. constexpr int kDrainGraceTimeMs = 100;
  9046. xds_drain_grace_time_ms_ = kDrainGraceTimeMs;
  9047. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  9048. {"", {root_cert_, identity_pair_}}};
  9049. g_fake1_cert_data_map = &fake1_cert_map;
  9050. // Send a valid LDS update to get the server to start listening
  9051. SetValidLdsUpdate();
  9052. backends_[0]->Start();
  9053. backends_[0]->notifier()->WaitOnServingStatusChange(
  9054. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  9055. grpc::StatusCode::OK);
  9056. constexpr int kNumChannels = 10;
  9057. struct StreamingRpc {
  9058. std::shared_ptr<Channel> channel;
  9059. std::unique_ptr<grpc::testing::EchoTestService::Stub> stub;
  9060. ClientContext context;
  9061. std::unique_ptr<ClientReaderWriter<EchoRequest, EchoResponse>> stream;
  9062. } streaming_rpcs[kNumChannels];
  9063. EchoRequest request;
  9064. EchoResponse response;
  9065. request.set_message("Hello");
  9066. for (int i = 0; i < kNumChannels; i++) {
  9067. streaming_rpcs[i].channel = CreateInsecureChannel();
  9068. streaming_rpcs[i].stub =
  9069. grpc::testing::EchoTestService::NewStub(streaming_rpcs[i].channel);
  9070. streaming_rpcs[i].context.set_wait_for_ready(true);
  9071. streaming_rpcs[i].stream =
  9072. streaming_rpcs[i].stub->BidiStream(&streaming_rpcs[i].context);
  9073. EXPECT_TRUE(streaming_rpcs[i].stream->Write(request));
  9074. streaming_rpcs[i].stream->Read(&response);
  9075. EXPECT_EQ(request.message(), response.message());
  9076. }
  9077. grpc_core::Timestamp update_time = NowFromCycleCounter();
  9078. // Update the resource.
  9079. SetLdsUpdate("", "", "fake_plugin1", "", false);
  9080. // Wait for the updated resource to take effect.
  9081. SendRpc([this]() { return CreateTlsChannel(); },
  9082. server_authenticated_identity_, {});
  9083. // After the drain grace time expires, the existing RPCs should all fail.
  9084. for (int i = 0; i < kNumChannels; i++) {
  9085. // Wait for the drain grace time to expire
  9086. EXPECT_FALSE(streaming_rpcs[i].stream->Read(&response));
  9087. // Make sure that the drain grace interval is honored.
  9088. EXPECT_GE(NowFromCycleCounter() - update_time,
  9089. grpc_core::Duration::Milliseconds(kDrainGraceTimeMs));
  9090. auto status = streaming_rpcs[i].stream->Finish();
  9091. EXPECT_EQ(status.error_code(), grpc::StatusCode::UNAVAILABLE)
  9092. << status.error_code() << ", " << status.error_message() << ", "
  9093. << status.error_details() << ", "
  9094. << streaming_rpcs[i].context.debug_error_string();
  9095. }
  9096. }
  9097. using XdsServerFilterChainMatchTest = XdsServerSecurityTest;
  9098. TEST_P(XdsServerFilterChainMatchTest,
  9099. DefaultFilterChainUsedWhenNoFilterChainMentioned) {
  9100. backends_[0]->Start();
  9101. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
  9102. }
  9103. TEST_P(XdsServerFilterChainMatchTest,
  9104. DefaultFilterChainUsedWhenOtherFilterChainsDontMatch) {
  9105. Listener listener = default_server_listener_;
  9106. // Add a filter chain that will never get matched
  9107. auto* filter_chain = listener.add_filter_chains();
  9108. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9109. ServerHcmAccessor().Unpack(listener));
  9110. filter_chain->mutable_filter_chain_match()
  9111. ->mutable_destination_port()
  9112. ->set_value(8080);
  9113. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  9114. backends_[0]->port(),
  9115. default_server_route_config_);
  9116. backends_[0]->Start();
  9117. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
  9118. }
  9119. TEST_P(XdsServerFilterChainMatchTest,
  9120. FilterChainsWithDestinationPortDontMatch) {
  9121. Listener listener = default_server_listener_;
  9122. // Add filter chain with destination port that should never get matched
  9123. auto* filter_chain = listener.add_filter_chains();
  9124. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9125. ServerHcmAccessor().Unpack(listener));
  9126. filter_chain->mutable_filter_chain_match()
  9127. ->mutable_destination_port()
  9128. ->set_value(8080);
  9129. listener.clear_default_filter_chain();
  9130. balancer_->ads_service()->SetLdsResource(
  9131. PopulateServerListenerNameAndPort(listener, backends_[0]->port()));
  9132. backends_[0]->Start();
  9133. // RPC should fail since no matching filter chain was found and no default
  9134. // filter chain is configured.
  9135. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  9136. true /* test_expects_failure */);
  9137. }
  9138. TEST_P(XdsServerFilterChainMatchTest, FilterChainsWithServerNamesDontMatch) {
  9139. Listener listener = default_server_listener_;
  9140. // Add filter chain with server name that should never get matched
  9141. auto* filter_chain = listener.add_filter_chains();
  9142. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9143. ServerHcmAccessor().Unpack(listener));
  9144. filter_chain->mutable_filter_chain_match()->add_server_names("server_name");
  9145. listener.clear_default_filter_chain();
  9146. balancer_->ads_service()->SetLdsResource(
  9147. PopulateServerListenerNameAndPort(listener, backends_[0]->port()));
  9148. backends_[0]->Start();
  9149. // RPC should fail since no matching filter chain was found and no default
  9150. // filter chain is configured.
  9151. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  9152. true /* test_expects_failure */);
  9153. }
  9154. TEST_P(XdsServerFilterChainMatchTest,
  9155. FilterChainsWithTransportProtocolsOtherThanRawBufferDontMatch) {
  9156. Listener listener = default_server_listener_;
  9157. // Add filter chain with transport protocol "tls" that should never match
  9158. auto* filter_chain = listener.add_filter_chains();
  9159. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9160. ServerHcmAccessor().Unpack(listener));
  9161. filter_chain->mutable_filter_chain_match()->set_transport_protocol("tls");
  9162. listener.clear_default_filter_chain();
  9163. balancer_->ads_service()->SetLdsResource(
  9164. PopulateServerListenerNameAndPort(listener, backends_[0]->port()));
  9165. backends_[0]->Start();
  9166. // RPC should fail since no matching filter chain was found and no default
  9167. // filter chain is configured.
  9168. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  9169. true /* test_expects_failure */);
  9170. }
  9171. TEST_P(XdsServerFilterChainMatchTest,
  9172. FilterChainsWithApplicationProtocolsDontMatch) {
  9173. Listener listener = default_server_listener_;
  9174. // Add filter chain with application protocol that should never get matched
  9175. auto* filter_chain = listener.add_filter_chains();
  9176. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9177. ServerHcmAccessor().Unpack(listener));
  9178. filter_chain->mutable_filter_chain_match()->add_application_protocols("h2");
  9179. listener.clear_default_filter_chain();
  9180. balancer_->ads_service()->SetLdsResource(
  9181. PopulateServerListenerNameAndPort(listener, backends_[0]->port()));
  9182. backends_[0]->Start();
  9183. // RPC should fail since no matching filter chain was found and no default
  9184. // filter chain is configured.
  9185. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  9186. true /* test_expects_failure */);
  9187. }
  9188. TEST_P(XdsServerFilterChainMatchTest,
  9189. FilterChainsWithTransportProtocolRawBufferIsPreferred) {
  9190. Listener listener = default_server_listener_;
  9191. // Add filter chain with "raw_buffer" transport protocol
  9192. auto* filter_chain = listener.add_filter_chains();
  9193. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9194. ServerHcmAccessor().Unpack(listener));
  9195. filter_chain->mutable_filter_chain_match()->set_transport_protocol(
  9196. "raw_buffer");
  9197. // Add another filter chain with no transport protocol set but application
  9198. // protocol set (fails match)
  9199. filter_chain = listener.add_filter_chains();
  9200. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9201. ServerHcmAccessor().Unpack(listener));
  9202. filter_chain->mutable_filter_chain_match()->add_application_protocols("h2");
  9203. listener.clear_default_filter_chain();
  9204. balancer_->ads_service()->SetLdsResource(
  9205. PopulateServerListenerNameAndPort(listener, backends_[0]->port()));
  9206. backends_[0]->Start();
  9207. // A successful RPC proves that filter chains that mention "raw_buffer" as
  9208. // the transport protocol are chosen as the best match in the round.
  9209. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
  9210. }
  9211. TEST_P(XdsServerFilterChainMatchTest,
  9212. FilterChainsWithMoreSpecificDestinationPrefixRangesArePreferred) {
  9213. Listener listener = default_server_listener_;
  9214. // Add filter chain with prefix range (length 4 and 16) but with server name
  9215. // mentioned. (Prefix range is matched first.)
  9216. auto* filter_chain = listener.add_filter_chains();
  9217. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9218. ServerHcmAccessor().Unpack(listener));
  9219. auto* prefix_range =
  9220. filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
  9221. prefix_range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
  9222. prefix_range->mutable_prefix_len()->set_value(4);
  9223. prefix_range =
  9224. filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
  9225. prefix_range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
  9226. prefix_range->mutable_prefix_len()->set_value(16);
  9227. filter_chain->mutable_filter_chain_match()->add_server_names("server_name");
  9228. // Add filter chain with two prefix ranges (length 8 and 24). Since 24 is
  9229. // the highest match, it should be chosen.
  9230. filter_chain = listener.add_filter_chains();
  9231. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9232. ServerHcmAccessor().Unpack(listener));
  9233. prefix_range =
  9234. filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
  9235. prefix_range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
  9236. prefix_range->mutable_prefix_len()->set_value(8);
  9237. prefix_range =
  9238. filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
  9239. prefix_range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
  9240. prefix_range->mutable_prefix_len()->set_value(24);
  9241. // Add another filter chain with a non-matching prefix range (with length
  9242. // 30)
  9243. filter_chain = listener.add_filter_chains();
  9244. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9245. ServerHcmAccessor().Unpack(listener));
  9246. prefix_range =
  9247. filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
  9248. prefix_range->set_address_prefix("192.168.1.1");
  9249. prefix_range->mutable_prefix_len()->set_value(30);
  9250. filter_chain->mutable_filter_chain_match()->add_server_names("server_name");
  9251. // Add another filter chain with no prefix range mentioned
  9252. filter_chain = listener.add_filter_chains();
  9253. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9254. ServerHcmAccessor().Unpack(listener));
  9255. filter_chain->mutable_filter_chain_match()->add_server_names("server_name");
  9256. listener.clear_default_filter_chain();
  9257. balancer_->ads_service()->SetLdsResource(
  9258. PopulateServerListenerNameAndPort(listener, backends_[0]->port()));
  9259. backends_[0]->Start();
  9260. // A successful RPC proves that the filter chain with the longest matching
  9261. // prefix range was the best match.
  9262. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
  9263. }
  9264. TEST_P(XdsServerFilterChainMatchTest,
  9265. FilterChainsThatMentionSourceTypeArePreferred) {
  9266. Listener listener = default_server_listener_;
  9267. // Add filter chain with the local source type (best match)
  9268. auto* filter_chain = listener.add_filter_chains();
  9269. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9270. ServerHcmAccessor().Unpack(listener));
  9271. filter_chain->mutable_filter_chain_match()->set_source_type(
  9272. FilterChainMatch::SAME_IP_OR_LOOPBACK);
  9273. // Add filter chain with the external source type but bad source port.
  9274. // Note that backends_[0]->port() will never be a match for the source port
  9275. // because it is already being used by a backend.
  9276. filter_chain = listener.add_filter_chains();
  9277. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9278. ServerHcmAccessor().Unpack(listener));
  9279. filter_chain->mutable_filter_chain_match()->set_source_type(
  9280. FilterChainMatch::EXTERNAL);
  9281. filter_chain->mutable_filter_chain_match()->add_source_ports(
  9282. backends_[0]->port());
  9283. // Add filter chain with the default source type (ANY) but bad source port.
  9284. filter_chain = listener.add_filter_chains();
  9285. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9286. ServerHcmAccessor().Unpack(listener));
  9287. filter_chain->mutable_filter_chain_match()->add_source_ports(
  9288. backends_[0]->port());
  9289. listener.clear_default_filter_chain();
  9290. balancer_->ads_service()->SetLdsResource(
  9291. PopulateServerListenerNameAndPort(listener, backends_[0]->port()));
  9292. backends_[0]->Start();
  9293. // A successful RPC proves that the filter chain with the longest matching
  9294. // prefix range was the best match.
  9295. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
  9296. }
  9297. TEST_P(XdsServerFilterChainMatchTest,
  9298. FilterChainsWithMoreSpecificSourcePrefixRangesArePreferred) {
  9299. Listener listener = default_server_listener_;
  9300. // Add filter chain with source prefix range (length 16) but with a bad
  9301. // source port mentioned. (Prefix range is matched first.) Note that
  9302. // backends_[0]->port() will never be a match for the source port because it
  9303. // is already being used by a backend.
  9304. auto* filter_chain = listener.add_filter_chains();
  9305. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9306. ServerHcmAccessor().Unpack(listener));
  9307. auto* source_prefix_range =
  9308. filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
  9309. source_prefix_range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
  9310. source_prefix_range->mutable_prefix_len()->set_value(4);
  9311. source_prefix_range =
  9312. filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
  9313. source_prefix_range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
  9314. source_prefix_range->mutable_prefix_len()->set_value(16);
  9315. filter_chain->mutable_filter_chain_match()->add_source_ports(
  9316. backends_[0]->port());
  9317. // Add filter chain with two source prefix ranges (length 8 and 24). Since
  9318. // 24 is the highest match, it should be chosen.
  9319. filter_chain = listener.add_filter_chains();
  9320. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9321. ServerHcmAccessor().Unpack(listener));
  9322. source_prefix_range =
  9323. filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
  9324. source_prefix_range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
  9325. source_prefix_range->mutable_prefix_len()->set_value(8);
  9326. source_prefix_range =
  9327. filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
  9328. source_prefix_range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
  9329. source_prefix_range->mutable_prefix_len()->set_value(24);
  9330. // Add another filter chain with a non-matching source prefix range (with
  9331. // length 30) and bad source port
  9332. filter_chain = listener.add_filter_chains();
  9333. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9334. ServerHcmAccessor().Unpack(listener));
  9335. source_prefix_range =
  9336. filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
  9337. source_prefix_range->set_address_prefix("192.168.1.1");
  9338. source_prefix_range->mutable_prefix_len()->set_value(30);
  9339. filter_chain->mutable_filter_chain_match()->add_source_ports(
  9340. backends_[0]->port());
  9341. // Add another filter chain with no source prefix range mentioned and bad
  9342. // source port
  9343. filter_chain = listener.add_filter_chains();
  9344. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9345. ServerHcmAccessor().Unpack(listener));
  9346. filter_chain->mutable_filter_chain_match()->add_source_ports(
  9347. backends_[0]->port());
  9348. listener.clear_default_filter_chain();
  9349. balancer_->ads_service()->SetLdsResource(
  9350. PopulateServerListenerNameAndPort(listener, backends_[0]->port()));
  9351. backends_[0]->Start();
  9352. // A successful RPC proves that the filter chain with the longest matching
  9353. // source prefix range was the best match.
  9354. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
  9355. }
  9356. TEST_P(XdsServerFilterChainMatchTest,
  9357. FilterChainsWithMoreSpecificSourcePortArePreferred) {
  9358. Listener listener = default_server_listener_;
  9359. auto* filter_chain = listener.add_filter_chains();
  9360. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9361. ServerHcmAccessor().Unpack(listener));
  9362. // Since we don't know which port will be used by the channel, just add all
  9363. // ports except for 0.
  9364. for (int i = 1; i < 65536; i++) {
  9365. filter_chain->mutable_filter_chain_match()->add_source_ports(i);
  9366. }
  9367. // Add another filter chain with no source port mentioned with a bad
  9368. // DownstreamTlsContext configuration.
  9369. filter_chain = listener.add_filter_chains();
  9370. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9371. ServerHcmAccessor().Unpack(listener));
  9372. auto* transport_socket = filter_chain->mutable_transport_socket();
  9373. transport_socket->set_name("envoy.transport_sockets.tls");
  9374. DownstreamTlsContext downstream_tls_context;
  9375. downstream_tls_context.mutable_common_tls_context()
  9376. ->mutable_tls_certificate_provider_instance()
  9377. ->set_instance_name("fake_plugin1");
  9378. transport_socket->mutable_typed_config()->PackFrom(downstream_tls_context);
  9379. listener.clear_default_filter_chain();
  9380. balancer_->ads_service()->SetLdsResource(
  9381. PopulateServerListenerNameAndPort(listener, backends_[0]->port()));
  9382. backends_[0]->Start();
  9383. // A successful RPC proves that the filter chain with matching source port
  9384. // was chosen.
  9385. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
  9386. }
  9387. TEST_P(XdsServerFilterChainMatchTest, DuplicateMatchNacked) {
  9388. Listener listener = default_server_listener_;
  9389. // Add filter chain
  9390. auto* filter_chain = listener.add_filter_chains();
  9391. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9392. ServerHcmAccessor().Unpack(listener));
  9393. // Add a duplicate filter chain
  9394. filter_chain = listener.add_filter_chains();
  9395. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9396. ServerHcmAccessor().Unpack(listener));
  9397. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  9398. backends_[0]->port(),
  9399. default_server_route_config_);
  9400. backends_[0]->Start();
  9401. const auto response_state = WaitForLdsNack();
  9402. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  9403. EXPECT_THAT(
  9404. response_state->error_message,
  9405. ::testing::HasSubstr(
  9406. "Duplicate matching rules detected when adding filter chain: {}"));
  9407. }
  9408. TEST_P(XdsServerFilterChainMatchTest, DuplicateMatchOnPrefixRangesNacked) {
  9409. Listener listener = default_server_listener_;
  9410. // Add filter chain with prefix range
  9411. auto* filter_chain = listener.add_filter_chains();
  9412. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9413. ServerHcmAccessor().Unpack(listener));
  9414. auto* prefix_range =
  9415. filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
  9416. prefix_range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
  9417. prefix_range->mutable_prefix_len()->set_value(16);
  9418. prefix_range =
  9419. filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
  9420. prefix_range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
  9421. prefix_range->mutable_prefix_len()->set_value(24);
  9422. // Add a filter chain with a duplicate prefix range entry
  9423. filter_chain = listener.add_filter_chains();
  9424. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9425. ServerHcmAccessor().Unpack(listener));
  9426. prefix_range =
  9427. filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
  9428. prefix_range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
  9429. prefix_range->mutable_prefix_len()->set_value(16);
  9430. prefix_range =
  9431. filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
  9432. prefix_range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
  9433. prefix_range->mutable_prefix_len()->set_value(32);
  9434. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  9435. backends_[0]->port(),
  9436. default_server_route_config_);
  9437. backends_[0]->Start();
  9438. const auto response_state = WaitForLdsNack();
  9439. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  9440. if (ipv6_only_) {
  9441. EXPECT_THAT(
  9442. response_state->error_message,
  9443. ::testing::HasSubstr(
  9444. "Duplicate matching rules detected when adding filter chain: "
  9445. "{prefix_ranges={{address_prefix=[::]:0, prefix_len=16}, "
  9446. "{address_prefix=[::]:0, prefix_len=32}}}"));
  9447. } else {
  9448. EXPECT_THAT(
  9449. response_state->error_message,
  9450. ::testing::HasSubstr(
  9451. "Duplicate matching rules detected when adding filter chain: "
  9452. "{prefix_ranges={{address_prefix=127.0.0.0:0, prefix_len=16}, "
  9453. "{address_prefix=127.0.0.1:0, prefix_len=32}}}"));
  9454. }
  9455. }
  9456. TEST_P(XdsServerFilterChainMatchTest, DuplicateMatchOnTransportProtocolNacked) {
  9457. Listener listener = default_server_listener_;
  9458. // Add filter chain with "raw_buffer" transport protocol
  9459. auto* filter_chain = listener.add_filter_chains();
  9460. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9461. ServerHcmAccessor().Unpack(listener));
  9462. filter_chain->mutable_filter_chain_match()->set_transport_protocol(
  9463. "raw_buffer");
  9464. // Add a duplicate filter chain with the same "raw_buffer" transport
  9465. // protocol entry
  9466. filter_chain = listener.add_filter_chains();
  9467. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9468. ServerHcmAccessor().Unpack(listener));
  9469. filter_chain->mutable_filter_chain_match()->set_transport_protocol(
  9470. "raw_buffer");
  9471. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  9472. backends_[0]->port(),
  9473. default_server_route_config_);
  9474. backends_[0]->Start();
  9475. const auto response_state = WaitForLdsNack();
  9476. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  9477. EXPECT_THAT(
  9478. response_state->error_message,
  9479. ::testing::HasSubstr("Duplicate matching rules detected when adding "
  9480. "filter chain: {transport_protocol=raw_buffer}"));
  9481. }
  9482. TEST_P(XdsServerFilterChainMatchTest, DuplicateMatchOnLocalSourceTypeNacked) {
  9483. Listener listener = default_server_listener_;
  9484. // Add filter chain with the local source type
  9485. auto* filter_chain = listener.add_filter_chains();
  9486. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9487. ServerHcmAccessor().Unpack(listener));
  9488. filter_chain->mutable_filter_chain_match()->set_source_type(
  9489. FilterChainMatch::SAME_IP_OR_LOOPBACK);
  9490. // Add a duplicate filter chain with the same local source type entry
  9491. filter_chain = listener.add_filter_chains();
  9492. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9493. ServerHcmAccessor().Unpack(listener));
  9494. filter_chain->mutable_filter_chain_match()->set_source_type(
  9495. FilterChainMatch::SAME_IP_OR_LOOPBACK);
  9496. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  9497. backends_[0]->port(),
  9498. default_server_route_config_);
  9499. backends_[0]->Start();
  9500. const auto response_state = WaitForLdsNack();
  9501. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  9502. EXPECT_THAT(
  9503. response_state->error_message,
  9504. ::testing::HasSubstr("Duplicate matching rules detected when adding "
  9505. "filter chain: {source_type=SAME_IP_OR_LOOPBACK}"));
  9506. }
  9507. TEST_P(XdsServerFilterChainMatchTest,
  9508. DuplicateMatchOnExternalSourceTypeNacked) {
  9509. Listener listener = default_server_listener_;
  9510. // Add filter chain with the external source type
  9511. auto* filter_chain = listener.add_filter_chains();
  9512. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9513. ServerHcmAccessor().Unpack(listener));
  9514. filter_chain->mutable_filter_chain_match()->set_source_type(
  9515. FilterChainMatch::EXTERNAL);
  9516. // Add a duplicate filter chain with the same external source type entry
  9517. filter_chain = listener.add_filter_chains();
  9518. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9519. ServerHcmAccessor().Unpack(listener));
  9520. filter_chain->mutable_filter_chain_match()->set_source_type(
  9521. FilterChainMatch::EXTERNAL);
  9522. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  9523. backends_[0]->port(),
  9524. default_server_route_config_);
  9525. backends_[0]->Start();
  9526. const auto response_state = WaitForLdsNack();
  9527. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  9528. EXPECT_THAT(
  9529. response_state->error_message,
  9530. ::testing::HasSubstr("Duplicate matching rules detected when adding "
  9531. "filter chain: {source_type=EXTERNAL}"));
  9532. }
  9533. TEST_P(XdsServerFilterChainMatchTest,
  9534. DuplicateMatchOnSourcePrefixRangesNacked) {
  9535. Listener listener = default_server_listener_;
  9536. // Add filter chain with source prefix range
  9537. auto* filter_chain = listener.add_filter_chains();
  9538. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9539. ServerHcmAccessor().Unpack(listener));
  9540. auto* prefix_range =
  9541. filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
  9542. prefix_range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
  9543. prefix_range->mutable_prefix_len()->set_value(16);
  9544. prefix_range =
  9545. filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
  9546. prefix_range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
  9547. prefix_range->mutable_prefix_len()->set_value(24);
  9548. // Add a filter chain with a duplicate source prefix range entry
  9549. filter_chain = listener.add_filter_chains();
  9550. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9551. ServerHcmAccessor().Unpack(listener));
  9552. prefix_range =
  9553. filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
  9554. prefix_range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
  9555. prefix_range->mutable_prefix_len()->set_value(16);
  9556. prefix_range =
  9557. filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
  9558. prefix_range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
  9559. prefix_range->mutable_prefix_len()->set_value(32);
  9560. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  9561. backends_[0]->port(),
  9562. default_server_route_config_);
  9563. backends_[0]->Start();
  9564. const auto response_state = WaitForLdsNack();
  9565. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  9566. if (ipv6_only_) {
  9567. EXPECT_THAT(
  9568. response_state->error_message,
  9569. ::testing::HasSubstr(
  9570. "Duplicate matching rules detected when adding filter chain: "
  9571. "{source_prefix_ranges={{address_prefix=[::]:0, prefix_len=16}, "
  9572. "{address_prefix=[::]:0, prefix_len=32}}}"));
  9573. } else {
  9574. EXPECT_THAT(
  9575. response_state->error_message,
  9576. ::testing::HasSubstr(
  9577. "Duplicate matching rules detected when adding filter chain: "
  9578. "{source_prefix_ranges={{address_prefix=127.0.0.0:0, "
  9579. "prefix_len=16}, "
  9580. "{address_prefix=127.0.0.1:0, prefix_len=32}}}"));
  9581. }
  9582. }
  9583. TEST_P(XdsServerFilterChainMatchTest, DuplicateMatchOnSourcePortNacked) {
  9584. Listener listener = default_server_listener_;
  9585. // Add filter chain with the external source type
  9586. auto* filter_chain = listener.add_filter_chains();
  9587. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9588. ServerHcmAccessor().Unpack(listener));
  9589. filter_chain->mutable_filter_chain_match()->add_source_ports(8080);
  9590. // Add a duplicate filter chain with the same source port entry
  9591. filter_chain = listener.add_filter_chains();
  9592. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9593. ServerHcmAccessor().Unpack(listener));
  9594. filter_chain->mutable_filter_chain_match()->add_source_ports(8080);
  9595. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  9596. backends_[0]->port(),
  9597. default_server_route_config_);
  9598. backends_[0]->Start();
  9599. const auto response_state = WaitForLdsNack();
  9600. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  9601. EXPECT_THAT(
  9602. response_state->error_message,
  9603. ::testing::HasSubstr("Duplicate matching rules detected when adding "
  9604. "filter chain: {source_ports={8080}}"));
  9605. }
  9606. class XdsServerRdsTest : public XdsEnabledServerStatusNotificationTest {
  9607. protected:
  9608. static void SetUpTestSuite() {
  9609. gpr_setenv("GRPC_XDS_EXPERIMENTAL_RBAC", "true");
  9610. }
  9611. static void TearDownTestSuite() {
  9612. gpr_unsetenv("GRPC_XDS_EXPERIMENTAL_RBAC");
  9613. }
  9614. };
  9615. TEST_P(XdsServerRdsTest, Basic) {
  9616. backends_[0]->Start();
  9617. backends_[0]->notifier()->WaitOnServingStatusChange(
  9618. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  9619. grpc::StatusCode::OK);
  9620. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
  9621. }
  9622. TEST_P(XdsServerRdsTest, NacksInvalidDomainPattern) {
  9623. RouteConfiguration route_config = default_server_route_config_;
  9624. route_config.mutable_virtual_hosts()->at(0).add_domains("");
  9625. SetServerListenerNameAndRouteConfiguration(
  9626. balancer_.get(), default_server_listener_, backends_[0]->port(),
  9627. route_config);
  9628. backends_[0]->Start();
  9629. const auto response_state = WaitForRouteConfigNack();
  9630. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  9631. EXPECT_THAT(response_state->error_message,
  9632. ::testing::HasSubstr("Invalid domain pattern \"\""));
  9633. }
  9634. TEST_P(XdsServerRdsTest, NacksEmptyDomainsList) {
  9635. RouteConfiguration route_config = default_server_route_config_;
  9636. route_config.mutable_virtual_hosts()->at(0).clear_domains();
  9637. SetServerListenerNameAndRouteConfiguration(
  9638. balancer_.get(), default_server_listener_, backends_[0]->port(),
  9639. route_config);
  9640. backends_[0]->Start();
  9641. const auto response_state = WaitForRouteConfigNack();
  9642. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  9643. EXPECT_THAT(response_state->error_message,
  9644. ::testing::HasSubstr("VirtualHost has no domains"));
  9645. }
  9646. TEST_P(XdsServerRdsTest, NacksEmptyRoutesList) {
  9647. RouteConfiguration route_config = default_server_route_config_;
  9648. route_config.mutable_virtual_hosts()->at(0).clear_routes();
  9649. SetServerListenerNameAndRouteConfiguration(
  9650. balancer_.get(), default_server_listener_, backends_[0]->port(),
  9651. route_config);
  9652. backends_[0]->Start();
  9653. const auto response_state = WaitForRouteConfigNack();
  9654. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  9655. EXPECT_THAT(response_state->error_message,
  9656. ::testing::HasSubstr("No route found in the virtual host"));
  9657. }
  9658. TEST_P(XdsServerRdsTest, NacksEmptyMatch) {
  9659. RouteConfiguration route_config = default_server_route_config_;
  9660. route_config.mutable_virtual_hosts()
  9661. ->at(0)
  9662. .mutable_routes()
  9663. ->at(0)
  9664. .clear_match();
  9665. SetServerListenerNameAndRouteConfiguration(
  9666. balancer_.get(), default_server_listener_, backends_[0]->port(),
  9667. route_config);
  9668. backends_[0]->Start();
  9669. const auto response_state = WaitForRouteConfigNack();
  9670. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  9671. EXPECT_THAT(response_state->error_message,
  9672. ::testing::HasSubstr("Match can't be null"));
  9673. }
  9674. TEST_P(XdsServerRdsTest, FailsRouteMatchesOtherThanNonForwardingAction) {
  9675. SetServerListenerNameAndRouteConfiguration(
  9676. balancer_.get(), default_server_listener_, backends_[0]->port(),
  9677. default_route_config_ /* inappropriate route config for servers */);
  9678. backends_[0]->Start();
  9679. // The server should be ready to serve but RPCs should fail.
  9680. backends_[0]->notifier()->WaitOnServingStatusChange(
  9681. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  9682. grpc::StatusCode::OK);
  9683. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  9684. true /* test_expects_failure */);
  9685. }
  9686. // Test that non-inline route configuration also works for non-default filter
  9687. // chains
  9688. TEST_P(XdsServerRdsTest, NonInlineRouteConfigurationNonDefaultFilterChain) {
  9689. if (!GetParam().enable_rds_testing()) {
  9690. return;
  9691. }
  9692. Listener listener = default_server_listener_;
  9693. auto* filter_chain = listener.add_filter_chains();
  9694. HttpConnectionManager http_connection_manager =
  9695. ServerHcmAccessor().Unpack(listener);
  9696. auto* rds = http_connection_manager.mutable_rds();
  9697. rds->set_route_config_name(kDefaultServerRouteConfigurationName);
  9698. rds->mutable_config_source()->mutable_self();
  9699. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9700. http_connection_manager);
  9701. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  9702. backends_[0]->port(),
  9703. default_server_route_config_);
  9704. backends_[0]->Start();
  9705. backends_[0]->notifier()->WaitOnServingStatusChange(
  9706. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  9707. grpc::StatusCode::OK);
  9708. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
  9709. }
  9710. TEST_P(XdsServerRdsTest, NonInlineRouteConfigurationNotAvailable) {
  9711. if (!GetParam().enable_rds_testing()) {
  9712. return;
  9713. }
  9714. Listener listener = default_server_listener_;
  9715. PopulateServerListenerNameAndPort(listener, backends_[0]->port());
  9716. HttpConnectionManager http_connection_manager =
  9717. ServerHcmAccessor().Unpack(listener);
  9718. auto* rds = http_connection_manager.mutable_rds();
  9719. rds->set_route_config_name("unknown_server_route_config");
  9720. rds->mutable_config_source()->mutable_self();
  9721. listener.add_filter_chains()->add_filters()->mutable_typed_config()->PackFrom(
  9722. http_connection_manager);
  9723. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  9724. backends_[0]->port(),
  9725. default_server_route_config_);
  9726. backends_[0]->Start();
  9727. backends_[0]->notifier()->WaitOnServingStatusChange(
  9728. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  9729. grpc::StatusCode::OK);
  9730. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  9731. true /* test_expects_failure */);
  9732. }
  9733. // TODO(yashykt): Once https://github.com/grpc/grpc/issues/24035 is fixed, we
  9734. // should add tests that make sure that different route configs are used for
  9735. // incoming connections with a different match.
  9736. TEST_P(XdsServerRdsTest, MultipleRouteConfigurations) {
  9737. Listener listener = default_server_listener_;
  9738. // Set a filter chain with a new route config name
  9739. auto new_route_config = default_server_route_config_;
  9740. new_route_config.set_name("new_server_route_config");
  9741. HttpConnectionManager http_connection_manager =
  9742. ServerHcmAccessor().Unpack(listener);
  9743. auto* rds = http_connection_manager.mutable_rds();
  9744. rds->set_route_config_name(new_route_config.name());
  9745. rds->mutable_config_source()->mutable_self();
  9746. listener.add_filter_chains()->add_filters()->mutable_typed_config()->PackFrom(
  9747. http_connection_manager);
  9748. // Set another filter chain with another route config name
  9749. auto another_route_config = default_server_route_config_;
  9750. another_route_config.set_name("another_server_route_config");
  9751. http_connection_manager.mutable_rds()->set_route_config_name(
  9752. another_route_config.name());
  9753. auto* filter_chain = listener.add_filter_chains();
  9754. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9755. http_connection_manager);
  9756. filter_chain->mutable_filter_chain_match()->set_source_type(
  9757. FilterChainMatch::SAME_IP_OR_LOOPBACK);
  9758. // Add another filter chain with the same route config name
  9759. filter_chain = listener.add_filter_chains();
  9760. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9761. http_connection_manager);
  9762. filter_chain->mutable_filter_chain_match()->set_source_type(
  9763. FilterChainMatch::EXTERNAL);
  9764. // Add another filter chain with an inline route config
  9765. filter_chain = listener.add_filter_chains();
  9766. filter_chain->mutable_filter_chain_match()->add_source_ports(1234);
  9767. http_connection_manager = ServerHcmAccessor().Unpack(listener);
  9768. *http_connection_manager.mutable_route_config() =
  9769. default_server_route_config_;
  9770. filter_chain->add_filters()->mutable_typed_config()->PackFrom(
  9771. http_connection_manager);
  9772. // Set resources on the ADS service
  9773. balancer_->ads_service()->SetRdsResource(new_route_config);
  9774. balancer_->ads_service()->SetRdsResource(another_route_config);
  9775. SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
  9776. backends_[0]->port(),
  9777. default_server_route_config_);
  9778. backends_[0]->Start();
  9779. backends_[0]->notifier()->WaitOnServingStatusChange(
  9780. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  9781. grpc::StatusCode::OK);
  9782. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
  9783. }
  9784. // Tests RBAC configurations on the server with RDS testing and route config
  9785. // override permutations.
  9786. class XdsRbacTest : public XdsServerRdsTest {
  9787. protected:
  9788. void SetServerRbacPolicies(Listener listener,
  9789. const std::vector<RBAC>& rbac_policies) {
  9790. HttpConnectionManager http_connection_manager =
  9791. ServerHcmAccessor().Unpack(listener);
  9792. http_connection_manager.clear_http_filters();
  9793. RouteConfiguration route_config = default_server_route_config_;
  9794. int count = 0;
  9795. for (auto& rbac : rbac_policies) {
  9796. auto* filter = http_connection_manager.add_http_filters();
  9797. std::string filter_name = absl::StrFormat("rbac%d", ++count);
  9798. filter->set_name(filter_name);
  9799. switch (GetParam().filter_config_setup()) {
  9800. case TestType::FilterConfigSetup::kHTTPConnectionManagerOriginal:
  9801. filter->mutable_typed_config()->PackFrom(rbac);
  9802. break;
  9803. case TestType::FilterConfigSetup::kRouteOverride:
  9804. filter->mutable_typed_config()->PackFrom(RBAC());
  9805. google::protobuf::Any filter_config;
  9806. RBACPerRoute rbac_per_route;
  9807. *rbac_per_route.mutable_rbac() = rbac;
  9808. filter_config.PackFrom(rbac_per_route);
  9809. auto* config_map = route_config.mutable_virtual_hosts(0)
  9810. ->mutable_routes(0)
  9811. ->mutable_typed_per_filter_config();
  9812. (*config_map)[filter_name] = std::move(filter_config);
  9813. }
  9814. }
  9815. auto* filter = http_connection_manager.add_http_filters();
  9816. filter->set_name("router");
  9817. filter->mutable_typed_config()->PackFrom(
  9818. envoy::extensions::filters::http::router::v3::Router());
  9819. ServerHcmAccessor().Pack(http_connection_manager, &listener);
  9820. SetServerListenerNameAndRouteConfiguration(
  9821. balancer_.get(), listener, backends_[0]->port(), route_config);
  9822. }
  9823. void SetServerRbacPolicy(Listener listener, const RBAC& rbac) {
  9824. SetServerRbacPolicies(std::move(listener), {rbac});
  9825. }
  9826. void SetServerRbacPolicy(const RBAC& rbac) {
  9827. SetServerRbacPolicy(default_server_listener_, rbac);
  9828. }
  9829. };
  9830. TEST_P(XdsRbacTest, AbsentRbacPolicy) {
  9831. SetServerRbacPolicy(RBAC());
  9832. backends_[0]->Start();
  9833. backends_[0]->notifier()->WaitOnServingStatusChange(
  9834. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  9835. grpc::StatusCode::OK);
  9836. // An absent RBAC policy leads to all RPCs being accepted.
  9837. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
  9838. }
  9839. TEST_P(XdsRbacTest, LogAction) {
  9840. RBAC rbac;
  9841. auto* rules = rbac.mutable_rules();
  9842. rules->set_action(envoy::config::rbac::v3::RBAC_Action_LOG);
  9843. SetServerRbacPolicy(rbac);
  9844. backends_[0]->Start();
  9845. backends_[0]->notifier()->WaitOnServingStatusChange(
  9846. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  9847. grpc::StatusCode::OK);
  9848. // A Log action is identical to no rbac policy being configured.
  9849. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
  9850. }
  9851. using XdsRbacNackTest = XdsRbacTest;
  9852. TEST_P(XdsRbacNackTest, NacksSchemePrincipalHeader) {
  9853. RBAC rbac;
  9854. auto* rules = rbac.mutable_rules();
  9855. rules->set_action(envoy::config::rbac::v3::RBAC_Action_ALLOW);
  9856. Policy policy;
  9857. auto* header = policy.add_principals()->mutable_header();
  9858. header->set_name(":scheme");
  9859. header->set_exact_match("http");
  9860. policy.add_permissions()->set_any(true);
  9861. (*rules->mutable_policies())["policy"] = policy;
  9862. SetServerRbacPolicy(rbac);
  9863. backends_[0]->Start();
  9864. if (GetParam().enable_rds_testing() &&
  9865. GetParam().filter_config_setup() ==
  9866. TestType::FilterConfigSetup::kRouteOverride) {
  9867. const auto response_state = WaitForRdsNack();
  9868. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  9869. EXPECT_THAT(response_state->error_message,
  9870. ::testing::HasSubstr("':scheme' not allowed in header"));
  9871. } else {
  9872. const auto response_state = WaitForLdsNack();
  9873. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  9874. EXPECT_THAT(response_state->error_message,
  9875. ::testing::HasSubstr("':scheme' not allowed in header"));
  9876. }
  9877. }
  9878. TEST_P(XdsRbacNackTest, NacksGrpcPrefixedPrincipalHeaders) {
  9879. RBAC rbac;
  9880. auto* rules = rbac.mutable_rules();
  9881. rules->set_action(envoy::config::rbac::v3::RBAC_Action_ALLOW);
  9882. Policy policy;
  9883. auto* header = policy.add_principals()->mutable_header();
  9884. header->set_name("grpc-status");
  9885. header->set_exact_match("0");
  9886. policy.add_permissions()->set_any(true);
  9887. (*rules->mutable_policies())["policy"] = policy;
  9888. SetServerRbacPolicy(rbac);
  9889. backends_[0]->Start();
  9890. if (GetParam().enable_rds_testing() &&
  9891. GetParam().filter_config_setup() ==
  9892. TestType::FilterConfigSetup::kRouteOverride) {
  9893. const auto response_state = WaitForRdsNack();
  9894. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  9895. EXPECT_THAT(response_state->error_message,
  9896. ::testing::HasSubstr("'grpc-' prefixes not allowed in header"));
  9897. } else {
  9898. const auto response_state = WaitForLdsNack();
  9899. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  9900. EXPECT_THAT(response_state->error_message,
  9901. ::testing::HasSubstr("'grpc-' prefixes not allowed in header"));
  9902. }
  9903. }
  9904. TEST_P(XdsRbacNackTest, NacksSchemePermissionHeader) {
  9905. RBAC rbac;
  9906. auto* rules = rbac.mutable_rules();
  9907. rules->set_action(envoy::config::rbac::v3::RBAC_Action_ALLOW);
  9908. Policy policy;
  9909. auto* header = policy.add_permissions()->mutable_header();
  9910. header->set_name(":scheme");
  9911. header->set_exact_match("http");
  9912. policy.add_principals()->set_any(true);
  9913. (*rules->mutable_policies())["policy"] = policy;
  9914. SetServerRbacPolicy(rbac);
  9915. backends_[0]->Start();
  9916. if (GetParam().enable_rds_testing() &&
  9917. GetParam().filter_config_setup() ==
  9918. TestType::FilterConfigSetup::kRouteOverride) {
  9919. const auto response_state = WaitForRdsNack();
  9920. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  9921. EXPECT_THAT(response_state->error_message,
  9922. ::testing::HasSubstr("':scheme' not allowed in header"));
  9923. } else {
  9924. const auto response_state = WaitForLdsNack();
  9925. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  9926. EXPECT_THAT(response_state->error_message,
  9927. ::testing::HasSubstr("':scheme' not allowed in header"));
  9928. }
  9929. }
  9930. TEST_P(XdsRbacNackTest, NacksGrpcPrefixedPermissionHeaders) {
  9931. RBAC rbac;
  9932. auto* rules = rbac.mutable_rules();
  9933. rules->set_action(envoy::config::rbac::v3::RBAC_Action_ALLOW);
  9934. Policy policy;
  9935. auto* header = policy.add_permissions()->mutable_header();
  9936. header->set_name("grpc-status");
  9937. header->set_exact_match("0");
  9938. policy.add_principals()->set_any(true);
  9939. (*rules->mutable_policies())["policy"] = policy;
  9940. SetServerRbacPolicy(rbac);
  9941. backends_[0]->Start();
  9942. if (GetParam().enable_rds_testing() &&
  9943. GetParam().filter_config_setup() ==
  9944. TestType::FilterConfigSetup::kRouteOverride) {
  9945. const auto response_state = WaitForRdsNack();
  9946. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  9947. EXPECT_THAT(response_state->error_message,
  9948. ::testing::HasSubstr("'grpc-' prefixes not allowed in header"));
  9949. } else {
  9950. const auto response_state = WaitForLdsNack();
  9951. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  9952. EXPECT_THAT(response_state->error_message,
  9953. ::testing::HasSubstr("'grpc-' prefixes not allowed in header"));
  9954. }
  9955. }
  9956. // Tests RBAC policies where a route override is always present. Action
  9957. // permutations are not added.
  9958. using XdsRbacTestWithRouteOverrideAlwaysPresent = XdsRbacTest;
  9959. TEST_P(XdsRbacTestWithRouteOverrideAlwaysPresent, EmptyRBACPerRouteOverride) {
  9960. HttpConnectionManager http_connection_manager;
  9961. Listener listener = default_server_listener_;
  9962. RouteConfiguration route_config = default_server_route_config_;
  9963. auto* filter = http_connection_manager.add_http_filters();
  9964. filter->set_name("rbac");
  9965. // Create a top-level RBAC policy with a DENY action for all RPCs
  9966. RBAC rbac;
  9967. auto* rules = rbac.mutable_rules();
  9968. rules->set_action(RBAC_Action_DENY);
  9969. Policy policy;
  9970. policy.add_permissions()->set_any(true);
  9971. policy.add_principals()->set_any(true);
  9972. (*rules->mutable_policies())["policy"] = policy;
  9973. filter->mutable_typed_config()->PackFrom(rbac);
  9974. // Override with an Empty RBACPerRoute policy which should result in RBAC
  9975. // being disabled and RPCs being allowed.
  9976. google::protobuf::Any filter_config;
  9977. filter_config.PackFrom(RBACPerRoute());
  9978. auto* config_map = route_config.mutable_virtual_hosts(0)
  9979. ->mutable_routes(0)
  9980. ->mutable_typed_per_filter_config();
  9981. (*config_map)["rbac"] = std::move(filter_config);
  9982. filter = http_connection_manager.add_http_filters();
  9983. filter->set_name("router");
  9984. filter->mutable_typed_config()->PackFrom(
  9985. envoy::extensions::filters::http::router::v3::Router());
  9986. ServerHcmAccessor().Pack(http_connection_manager, &listener);
  9987. SetServerListenerNameAndRouteConfiguration(
  9988. balancer_.get(), listener, backends_[0]->port(), route_config);
  9989. backends_[0]->Start();
  9990. backends_[0]->notifier()->WaitOnServingStatusChange(
  9991. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  9992. grpc::StatusCode::OK);
  9993. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
  9994. }
  9995. // Test a non-empty top level RBAC with a non-empty RBACPerRouteOverride
  9996. TEST_P(XdsRbacTestWithRouteOverrideAlwaysPresent,
  9997. NonEmptyTopLevelRBACNonEmptyPerRouteOverride) {
  9998. HttpConnectionManager http_connection_manager;
  9999. Listener listener = default_server_listener_;
  10000. RouteConfiguration route_config = default_server_route_config_;
  10001. auto* filter = http_connection_manager.add_http_filters();
  10002. filter->set_name("rbac");
  10003. // Create a top-level RBAC policy with a DENY action for all RPCs
  10004. RBAC rbac;
  10005. auto* rules = rbac.mutable_rules();
  10006. rules->set_action(RBAC_Action_DENY);
  10007. Policy policy;
  10008. policy.add_permissions()->set_any(true);
  10009. policy.add_principals()->set_any(true);
  10010. (*rules->mutable_policies())["policy"] = policy;
  10011. filter->mutable_typed_config()->PackFrom(rbac);
  10012. // Override with a non-empty RBACPerRoute policy which allows all RPCs.
  10013. google::protobuf::Any filter_config;
  10014. RBACPerRoute rbac_per_route;
  10015. rules = rbac_per_route.mutable_rbac()->mutable_rules();
  10016. rules->set_action(RBAC_Action_ALLOW);
  10017. (*rules->mutable_policies())["policy"] = policy;
  10018. filter_config.PackFrom(RBACPerRoute());
  10019. auto* config_map = route_config.mutable_virtual_hosts(0)
  10020. ->mutable_routes(0)
  10021. ->mutable_typed_per_filter_config();
  10022. (*config_map)["rbac"] = std::move(filter_config);
  10023. filter = http_connection_manager.add_http_filters();
  10024. filter->set_name("router");
  10025. filter->mutable_typed_config()->PackFrom(
  10026. envoy::extensions::filters::http::router::v3::Router());
  10027. ServerHcmAccessor().Pack(http_connection_manager, &listener);
  10028. SetServerListenerNameAndRouteConfiguration(
  10029. balancer_.get(), listener, backends_[0]->port(), route_config);
  10030. backends_[0]->Start();
  10031. backends_[0]->notifier()->WaitOnServingStatusChange(
  10032. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  10033. grpc::StatusCode::OK);
  10034. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
  10035. }
  10036. // Adds Action Permutations to XdsRbacTest
  10037. using XdsRbacTestWithActionPermutations = XdsRbacTest;
  10038. TEST_P(XdsRbacTestWithActionPermutations, EmptyRbacPolicy) {
  10039. RBAC rbac;
  10040. rbac.mutable_rules()->set_action(GetParam().rbac_action());
  10041. SetServerRbacPolicy(rbac);
  10042. backends_[0]->Start();
  10043. backends_[0]->notifier()->WaitOnServingStatusChange(
  10044. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  10045. grpc::StatusCode::OK);
  10046. // An empty RBAC policy leads to all RPCs being rejected.
  10047. SendRpc(
  10048. [this]() { return CreateInsecureChannel(); }, {}, {},
  10049. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
  10050. grpc::StatusCode::PERMISSION_DENIED);
  10051. }
  10052. TEST_P(XdsRbacTestWithActionPermutations, AnyPermissionAnyPrincipal) {
  10053. RBAC rbac;
  10054. auto* rules = rbac.mutable_rules();
  10055. rules->set_action(GetParam().rbac_action());
  10056. Policy policy;
  10057. policy.add_permissions()->set_any(true);
  10058. policy.add_principals()->set_any(true);
  10059. (*rules->mutable_policies())["policy"] = policy;
  10060. SetServerRbacPolicy(rbac);
  10061. backends_[0]->Start();
  10062. backends_[0]->notifier()->WaitOnServingStatusChange(
  10063. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  10064. grpc::StatusCode::OK);
  10065. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  10066. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
  10067. grpc::StatusCode::PERMISSION_DENIED);
  10068. }
  10069. TEST_P(XdsRbacTestWithActionPermutations, MultipleRbacPolicies) {
  10070. RBAC always_allow;
  10071. auto* rules = always_allow.mutable_rules();
  10072. rules->set_action(RBAC_Action_ALLOW);
  10073. Policy policy;
  10074. policy.add_permissions()->set_any(true);
  10075. policy.add_principals()->set_any(true);
  10076. (*rules->mutable_policies())["policy"] = policy;
  10077. RBAC rbac;
  10078. rules = rbac.mutable_rules();
  10079. rules->set_action(GetParam().rbac_action());
  10080. (*rules->mutable_policies())["policy"] = policy;
  10081. SetServerRbacPolicies(default_server_listener_,
  10082. {always_allow, rbac, always_allow});
  10083. backends_[0]->Start();
  10084. backends_[0]->notifier()->WaitOnServingStatusChange(
  10085. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  10086. grpc::StatusCode::OK);
  10087. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  10088. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
  10089. grpc::StatusCode::PERMISSION_DENIED);
  10090. }
  10091. TEST_P(XdsRbacTestWithActionPermutations, MethodPostPermissionAnyPrincipal) {
  10092. RBAC rbac;
  10093. auto* rules = rbac.mutable_rules();
  10094. rules->set_action(GetParam().rbac_action());
  10095. Policy policy;
  10096. auto* header = policy.add_permissions()->mutable_header();
  10097. header->set_name(":method");
  10098. header->set_exact_match("POST");
  10099. policy.add_principals()->set_any(true);
  10100. (*rules->mutable_policies())["policy"] = policy;
  10101. SetServerRbacPolicy(rbac);
  10102. backends_[0]->Start();
  10103. backends_[0]->notifier()->WaitOnServingStatusChange(
  10104. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  10105. grpc::StatusCode::OK);
  10106. // All RPCs use POST method by default
  10107. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  10108. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
  10109. grpc::StatusCode::PERMISSION_DENIED);
  10110. // Test an RPC with a different method type
  10111. auto stub = grpc::testing::EchoTestService::NewStub(CreateInsecureChannel());
  10112. ClientContext context;
  10113. context.set_wait_for_ready(true);
  10114. context.set_deadline(grpc_timeout_milliseconds_to_deadline(2000));
  10115. context.set_cacheable(true);
  10116. EchoRequest request;
  10117. request.set_message(kRequestMessage);
  10118. EchoResponse response;
  10119. Status status = stub->Echo(&context, request, &response);
  10120. EXPECT_EQ(status.error_code(), GetParam().rbac_action() == RBAC_Action_DENY
  10121. ? grpc::StatusCode::OK
  10122. : grpc::StatusCode::PERMISSION_DENIED)
  10123. << status.error_code() << ", " << status.error_message() << ", "
  10124. << status.error_details() << ", " << context.debug_error_string();
  10125. }
  10126. TEST_P(XdsRbacTestWithActionPermutations, MethodGetPermissionAnyPrincipal) {
  10127. RBAC rbac;
  10128. auto* rules = rbac.mutable_rules();
  10129. rules->set_action(GetParam().rbac_action());
  10130. Policy policy;
  10131. auto* header = policy.add_permissions()->mutable_header();
  10132. header->set_name(":method");
  10133. header->set_exact_match("GET");
  10134. policy.add_principals()->set_any(true);
  10135. (*rules->mutable_policies())["policy"] = policy;
  10136. SetServerRbacPolicy(rbac);
  10137. backends_[0]->Start();
  10138. backends_[0]->notifier()->WaitOnServingStatusChange(
  10139. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  10140. grpc::StatusCode::OK);
  10141. // Send a cacheable RPC so that GET method is used
  10142. auto stub = grpc::testing::EchoTestService::NewStub(CreateInsecureChannel());
  10143. ClientContext context;
  10144. context.set_wait_for_ready(true);
  10145. context.set_deadline(grpc_timeout_milliseconds_to_deadline(2000));
  10146. context.set_cacheable(true);
  10147. EchoRequest request;
  10148. request.set_message(kRequestMessage);
  10149. EchoResponse response;
  10150. Status status = stub->Echo(&context, request, &response);
  10151. EXPECT_EQ(status.error_code(), GetParam().rbac_action() == RBAC_Action_ALLOW
  10152. ? grpc::StatusCode::OK
  10153. : grpc::StatusCode::PERMISSION_DENIED)
  10154. << status.error_code() << ", " << status.error_message() << ", "
  10155. << status.error_details() << ", " << context.debug_error_string();
  10156. // Test an RPC with a different method type
  10157. SendRpc(
  10158. [this]() { return CreateInsecureChannel(); }, {}, {},
  10159. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
  10160. grpc::StatusCode::PERMISSION_DENIED);
  10161. }
  10162. TEST_P(XdsRbacTestWithActionPermutations, MethodPutPermissionAnyPrincipal) {
  10163. RBAC rbac;
  10164. auto* rules = rbac.mutable_rules();
  10165. rules->set_action(GetParam().rbac_action());
  10166. Policy policy;
  10167. auto* header = policy.add_permissions()->mutable_header();
  10168. header->set_name(":method");
  10169. header->set_exact_match("PUT");
  10170. policy.add_principals()->set_any(true);
  10171. (*rules->mutable_policies())["policy"] = policy;
  10172. SetServerRbacPolicy(rbac);
  10173. backends_[0]->Start();
  10174. backends_[0]->notifier()->WaitOnServingStatusChange(
  10175. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  10176. grpc::StatusCode::OK);
  10177. // Send an idempotent RPC so that PUT method is used
  10178. auto stub = grpc::testing::EchoTestService::NewStub(CreateInsecureChannel());
  10179. ClientContext context;
  10180. context.set_wait_for_ready(true);
  10181. context.set_deadline(grpc_timeout_milliseconds_to_deadline(2000));
  10182. context.set_idempotent(true);
  10183. EchoRequest request;
  10184. request.set_message(kRequestMessage);
  10185. EchoResponse response;
  10186. Status status = stub->Echo(&context, request, &response);
  10187. EXPECT_EQ(status.error_code(), GetParam().rbac_action() == RBAC_Action_ALLOW
  10188. ? grpc::StatusCode::OK
  10189. : grpc::StatusCode::PERMISSION_DENIED)
  10190. << status.error_code() << ", " << status.error_message() << ", "
  10191. << status.error_details() << ", " << context.debug_error_string();
  10192. // Test an RPC with a different method type
  10193. SendRpc(
  10194. [this]() { return CreateInsecureChannel(); }, {}, {},
  10195. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
  10196. grpc::StatusCode::PERMISSION_DENIED);
  10197. }
  10198. TEST_P(XdsRbacTestWithActionPermutations, UrlPathPermissionAnyPrincipal) {
  10199. RBAC rbac;
  10200. auto* rules = rbac.mutable_rules();
  10201. rules->set_action(GetParam().rbac_action());
  10202. Policy policy;
  10203. policy.add_permissions()->mutable_url_path()->mutable_path()->set_exact(
  10204. "/grpc.testing.EchoTestService/Echo");
  10205. policy.add_principals()->set_any(true);
  10206. (*rules->mutable_policies())["policy"] = policy;
  10207. SetServerRbacPolicy(rbac);
  10208. backends_[0]->Start();
  10209. backends_[0]->notifier()->WaitOnServingStatusChange(
  10210. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  10211. grpc::StatusCode::OK);
  10212. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  10213. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
  10214. grpc::StatusCode::PERMISSION_DENIED);
  10215. // Test an RPC with a different URL path
  10216. auto stub = grpc::testing::EchoTestService::NewStub(CreateInsecureChannel());
  10217. ClientContext context;
  10218. context.set_wait_for_ready(true);
  10219. context.set_deadline(grpc_timeout_milliseconds_to_deadline(2000));
  10220. EchoRequest request;
  10221. request.set_message(kRequestMessage);
  10222. EchoResponse response;
  10223. Status status = stub->Echo1(&context, request, &response);
  10224. EXPECT_TRUE(GetParam().rbac_action() == RBAC_Action_DENY ? status.ok()
  10225. : !status.ok())
  10226. << status.error_code() << ", " << status.error_message() << ", "
  10227. << status.error_details() << ", " << context.debug_error_string();
  10228. }
  10229. TEST_P(XdsRbacTestWithActionPermutations, DestinationIpPermissionAnyPrincipal) {
  10230. RBAC rbac;
  10231. auto* rules = rbac.mutable_rules();
  10232. rules->set_action(GetParam().rbac_action());
  10233. Policy policy;
  10234. auto* range = policy.add_permissions()->mutable_destination_ip();
  10235. range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
  10236. range->mutable_prefix_len()->set_value(ipv6_only_ ? 128 : 32);
  10237. policy.add_principals()->set_any(true);
  10238. (*rules->mutable_policies())["policy"] = policy;
  10239. SetServerRbacPolicy(rbac);
  10240. backends_[0]->Start();
  10241. backends_[0]->notifier()->WaitOnServingStatusChange(
  10242. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  10243. grpc::StatusCode::OK);
  10244. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  10245. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
  10246. grpc::StatusCode::PERMISSION_DENIED);
  10247. // Change the policy itself for a negative test where there is no match.
  10248. policy.clear_permissions();
  10249. range = policy.add_permissions()->mutable_destination_ip();
  10250. range->set_address_prefix(ipv6_only_ ? "::2" : "127.0.0.2");
  10251. range->mutable_prefix_len()->set_value(ipv6_only_ ? 128 : 32);
  10252. (*rules->mutable_policies())["policy"] = policy;
  10253. SetServerRbacPolicy(rbac);
  10254. SendRpc(
  10255. [this]() { return CreateInsecureChannel(); }, {}, {},
  10256. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
  10257. grpc::StatusCode::PERMISSION_DENIED);
  10258. }
  10259. TEST_P(XdsRbacTestWithActionPermutations,
  10260. DestinationPortPermissionAnyPrincipal) {
  10261. RBAC rbac;
  10262. auto* rules = rbac.mutable_rules();
  10263. rules->set_action(GetParam().rbac_action());
  10264. Policy policy;
  10265. policy.add_permissions()->set_destination_port(backends_[0]->port());
  10266. policy.add_principals()->set_any(true);
  10267. (*rules->mutable_policies())["policy"] = policy;
  10268. SetServerRbacPolicy(rbac);
  10269. backends_[0]->Start();
  10270. backends_[0]->notifier()->WaitOnServingStatusChange(
  10271. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  10272. grpc::StatusCode::OK);
  10273. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  10274. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
  10275. grpc::StatusCode::PERMISSION_DENIED);
  10276. // Change the policy itself for a negative test where there is no match.
  10277. policy.clear_permissions();
  10278. policy.add_permissions()->set_destination_port(1);
  10279. (*rules->mutable_policies())["policy"] = policy;
  10280. SetServerRbacPolicy(rbac);
  10281. SendRpc(
  10282. [this]() { return CreateInsecureChannel(); }, {}, {},
  10283. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
  10284. grpc::StatusCode::PERMISSION_DENIED);
  10285. }
  10286. TEST_P(XdsRbacTestWithActionPermutations, MetadataPermissionAnyPrincipal) {
  10287. RBAC rbac;
  10288. auto* rules = rbac.mutable_rules();
  10289. rules->set_action(GetParam().rbac_action());
  10290. Policy policy;
  10291. policy.add_permissions()->mutable_metadata();
  10292. policy.add_principals()->set_any(true);
  10293. (*rules->mutable_policies())["policy"] = policy;
  10294. SetServerRbacPolicy(rbac);
  10295. backends_[0]->Start();
  10296. backends_[0]->notifier()->WaitOnServingStatusChange(
  10297. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  10298. grpc::StatusCode::OK);
  10299. SendRpc(
  10300. [this]() { return CreateInsecureChannel(); }, {}, {},
  10301. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
  10302. grpc::StatusCode::PERMISSION_DENIED);
  10303. // Test metadata with inverted match
  10304. policy.clear_permissions();
  10305. policy.add_permissions()->mutable_metadata()->set_invert(true);
  10306. (*rules->mutable_policies())["policy"] = policy;
  10307. SetServerRbacPolicy(rbac);
  10308. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  10309. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
  10310. grpc::StatusCode::PERMISSION_DENIED);
  10311. }
  10312. TEST_P(XdsRbacTestWithActionPermutations, ReqServerNamePermissionAnyPrincipal) {
  10313. RBAC rbac;
  10314. auto* rules = rbac.mutable_rules();
  10315. rules->set_action(GetParam().rbac_action());
  10316. Policy policy;
  10317. policy.add_principals()->set_any(true);
  10318. policy.add_permissions()->mutable_requested_server_name()->set_exact(
  10319. "server_name");
  10320. (*rules->mutable_policies())["policy"] = policy;
  10321. SetServerRbacPolicy(rbac);
  10322. backends_[0]->Start();
  10323. backends_[0]->notifier()->WaitOnServingStatusChange(
  10324. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  10325. grpc::StatusCode::OK);
  10326. SendRpc(
  10327. [this]() { return CreateInsecureChannel(); }, {}, {},
  10328. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
  10329. grpc::StatusCode::PERMISSION_DENIED);
  10330. policy.clear_permissions();
  10331. policy.add_permissions()->mutable_requested_server_name()->set_exact("");
  10332. (*rules->mutable_policies())["policy"] = policy;
  10333. SetServerRbacPolicy(rbac);
  10334. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  10335. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
  10336. grpc::StatusCode::PERMISSION_DENIED);
  10337. }
  10338. TEST_P(XdsRbacTestWithActionPermutations, NotRulePermissionAnyPrincipal) {
  10339. RBAC rbac;
  10340. auto* rules = rbac.mutable_rules();
  10341. rules->set_action(GetParam().rbac_action());
  10342. Policy policy;
  10343. policy.add_permissions()
  10344. ->mutable_not_rule()
  10345. ->mutable_requested_server_name()
  10346. ->set_exact("server_name");
  10347. policy.add_principals()->set_any(true);
  10348. (*rules->mutable_policies())["policy"] = policy;
  10349. SetServerRbacPolicy(rbac);
  10350. backends_[0]->Start();
  10351. backends_[0]->notifier()->WaitOnServingStatusChange(
  10352. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  10353. grpc::StatusCode::OK);
  10354. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  10355. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
  10356. grpc::StatusCode::PERMISSION_DENIED);
  10357. // Change the policy itself for a negative test where there is no match.
  10358. policy.clear_permissions();
  10359. policy.add_permissions()->mutable_not_rule()->set_any(true);
  10360. (*rules->mutable_policies())["policy"] = policy;
  10361. SetServerRbacPolicy(rbac);
  10362. SendRpc(
  10363. [this]() { return CreateInsecureChannel(); }, {}, {},
  10364. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
  10365. grpc::StatusCode::PERMISSION_DENIED);
  10366. }
  10367. TEST_P(XdsRbacTestWithActionPermutations, AndRulePermissionAnyPrincipal) {
  10368. RBAC rbac;
  10369. auto* rules = rbac.mutable_rules();
  10370. rules->set_action(GetParam().rbac_action());
  10371. Policy policy;
  10372. auto* and_rules = policy.add_permissions()->mutable_and_rules();
  10373. and_rules->add_rules()->set_any(true);
  10374. and_rules->add_rules()->set_destination_port(backends_[0]->port());
  10375. policy.add_principals()->set_any(true);
  10376. (*rules->mutable_policies())["policy"] = policy;
  10377. SetServerRbacPolicy(rbac);
  10378. backends_[0]->Start();
  10379. backends_[0]->notifier()->WaitOnServingStatusChange(
  10380. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  10381. grpc::StatusCode::OK);
  10382. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  10383. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
  10384. grpc::StatusCode::PERMISSION_DENIED);
  10385. // Change the policy itself for a negative test where there is no match.
  10386. and_rules = (*policy.mutable_permissions())[0].mutable_and_rules();
  10387. (*and_rules->mutable_rules())[1].set_destination_port(1);
  10388. (*rules->mutable_policies())["policy"] = policy;
  10389. SetServerRbacPolicy(rbac);
  10390. SendRpc(
  10391. [this]() { return CreateInsecureChannel(); }, {}, {},
  10392. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
  10393. grpc::StatusCode::PERMISSION_DENIED);
  10394. }
  10395. TEST_P(XdsRbacTestWithActionPermutations, OrRulePermissionAnyPrincipal) {
  10396. RBAC rbac;
  10397. auto* rules = rbac.mutable_rules();
  10398. rules->set_action(GetParam().rbac_action());
  10399. Policy policy;
  10400. auto* or_rules = policy.add_permissions()->mutable_or_rules();
  10401. or_rules->add_rules()->mutable_not_rule()->set_any(true);
  10402. or_rules->add_rules()->set_destination_port(backends_[0]->port());
  10403. policy.add_principals()->set_any(true);
  10404. (*rules->mutable_policies())["policy"] = policy;
  10405. SetServerRbacPolicy(rbac);
  10406. backends_[0]->Start();
  10407. backends_[0]->notifier()->WaitOnServingStatusChange(
  10408. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  10409. grpc::StatusCode::OK);
  10410. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  10411. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
  10412. grpc::StatusCode::PERMISSION_DENIED);
  10413. // Change the policy itself for a negative test where there is no match.
  10414. or_rules = (*policy.mutable_permissions())[0].mutable_or_rules();
  10415. (*or_rules->mutable_rules())[1].set_destination_port(1);
  10416. (*rules->mutable_policies())["policy"] = policy;
  10417. SetServerRbacPolicy(rbac);
  10418. SendRpc(
  10419. [this]() { return CreateInsecureChannel(); }, {}, {},
  10420. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
  10421. grpc::StatusCode::PERMISSION_DENIED);
  10422. }
  10423. TEST_P(XdsRbacTestWithActionPermutations, AnyPermissionMethodPostPrincipal) {
  10424. RBAC rbac;
  10425. auto* rules = rbac.mutable_rules();
  10426. rules->set_action(GetParam().rbac_action());
  10427. Policy policy;
  10428. auto* header = policy.add_principals()->mutable_header();
  10429. header->set_name(":method");
  10430. header->set_exact_match("POST");
  10431. policy.add_permissions()->set_any(true);
  10432. (*rules->mutable_policies())["policy"] = policy;
  10433. SetServerRbacPolicy(rbac);
  10434. backends_[0]->Start();
  10435. backends_[0]->notifier()->WaitOnServingStatusChange(
  10436. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  10437. grpc::StatusCode::OK);
  10438. // All RPCs use POST method by default
  10439. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  10440. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
  10441. grpc::StatusCode::PERMISSION_DENIED);
  10442. // Test an RPC with a different method type
  10443. auto stub = grpc::testing::EchoTestService::NewStub(CreateInsecureChannel());
  10444. ClientContext context;
  10445. context.set_wait_for_ready(true);
  10446. context.set_deadline(grpc_timeout_milliseconds_to_deadline(2000));
  10447. context.set_cacheable(true);
  10448. EchoRequest request;
  10449. request.set_message(kRequestMessage);
  10450. EchoResponse response;
  10451. Status status = stub->Echo(&context, request, &response);
  10452. EXPECT_EQ(status.error_code(), GetParam().rbac_action() == RBAC_Action_DENY
  10453. ? grpc::StatusCode::OK
  10454. : grpc::StatusCode::PERMISSION_DENIED)
  10455. << status.error_code() << ", " << status.error_message() << ", "
  10456. << status.error_details() << ", " << context.debug_error_string();
  10457. }
  10458. TEST_P(XdsRbacTestWithActionPermutations, AnyPermissionMethodGetPrincipal) {
  10459. RBAC rbac;
  10460. auto* rules = rbac.mutable_rules();
  10461. rules->set_action(GetParam().rbac_action());
  10462. Policy policy;
  10463. auto* header = policy.add_principals()->mutable_header();
  10464. header->set_name(":method");
  10465. header->set_exact_match("GET");
  10466. policy.add_permissions()->set_any(true);
  10467. (*rules->mutable_policies())["policy"] = policy;
  10468. SetServerRbacPolicy(rbac);
  10469. backends_[0]->Start();
  10470. backends_[0]->notifier()->WaitOnServingStatusChange(
  10471. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  10472. grpc::StatusCode::OK);
  10473. // Send a cacheable RPC so that GET method is used
  10474. auto stub = grpc::testing::EchoTestService::NewStub(CreateInsecureChannel());
  10475. ClientContext context;
  10476. context.set_wait_for_ready(true);
  10477. context.set_deadline(grpc_timeout_milliseconds_to_deadline(2000));
  10478. context.set_cacheable(true);
  10479. EchoRequest request;
  10480. request.set_message(kRequestMessage);
  10481. EchoResponse response;
  10482. Status status = stub->Echo(&context, request, &response);
  10483. EXPECT_TRUE(GetParam().rbac_action() == RBAC_Action_ALLOW ? status.ok()
  10484. : !status.ok())
  10485. << status.error_code() << ", " << status.error_message() << ", "
  10486. << status.error_details() << ", " << context.debug_error_string();
  10487. // Test an RPC with a different method type
  10488. SendRpc(
  10489. [this]() { return CreateInsecureChannel(); }, {}, {},
  10490. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
  10491. grpc::StatusCode::PERMISSION_DENIED);
  10492. }
  10493. TEST_P(XdsRbacTestWithActionPermutations, AnyPermissionMethodPutPrincipal) {
  10494. RBAC rbac;
  10495. auto* rules = rbac.mutable_rules();
  10496. rules->set_action(GetParam().rbac_action());
  10497. Policy policy;
  10498. auto* header = policy.add_principals()->mutable_header();
  10499. header->set_name(":method");
  10500. header->set_exact_match("PUT");
  10501. policy.add_permissions()->set_any(true);
  10502. (*rules->mutable_policies())["policy"] = policy;
  10503. SetServerRbacPolicy(rbac);
  10504. backends_[0]->Start();
  10505. backends_[0]->notifier()->WaitOnServingStatusChange(
  10506. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  10507. grpc::StatusCode::OK);
  10508. // Send an idempotent RPC so that PUT method is used
  10509. auto stub = grpc::testing::EchoTestService::NewStub(CreateInsecureChannel());
  10510. ClientContext context;
  10511. context.set_wait_for_ready(true);
  10512. context.set_deadline(grpc_timeout_milliseconds_to_deadline(2000));
  10513. context.set_idempotent(true);
  10514. EchoRequest request;
  10515. request.set_message(kRequestMessage);
  10516. EchoResponse response;
  10517. Status status = stub->Echo(&context, request, &response);
  10518. EXPECT_TRUE(GetParam().rbac_action() == RBAC_Action_ALLOW ? status.ok()
  10519. : !status.ok())
  10520. << status.error_code() << ", " << status.error_message() << ", "
  10521. << status.error_details() << ", " << context.debug_error_string();
  10522. // Test an RPC with a different method type
  10523. SendRpc(
  10524. [this]() { return CreateInsecureChannel(); }, {}, {},
  10525. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
  10526. grpc::StatusCode::PERMISSION_DENIED);
  10527. }
  10528. TEST_P(XdsRbacTestWithActionPermutations, AnyPermissionUrlPathPrincipal) {
  10529. RBAC rbac;
  10530. auto* rules = rbac.mutable_rules();
  10531. rules->set_action(GetParam().rbac_action());
  10532. Policy policy;
  10533. policy.add_principals()->mutable_url_path()->mutable_path()->set_exact(
  10534. "/grpc.testing.EchoTestService/Echo");
  10535. policy.add_permissions()->set_any(true);
  10536. (*rules->mutable_policies())["policy"] = policy;
  10537. SetServerRbacPolicy(rbac);
  10538. backends_[0]->Start();
  10539. backends_[0]->notifier()->WaitOnServingStatusChange(
  10540. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  10541. grpc::StatusCode::OK);
  10542. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  10543. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
  10544. grpc::StatusCode::PERMISSION_DENIED);
  10545. // Test an RPC with a different URL path
  10546. auto stub = grpc::testing::EchoTestService::NewStub(CreateInsecureChannel());
  10547. ClientContext context;
  10548. context.set_wait_for_ready(true);
  10549. context.set_deadline(grpc_timeout_milliseconds_to_deadline(2000));
  10550. EchoRequest request;
  10551. request.set_message(kRequestMessage);
  10552. EchoResponse response;
  10553. Status status = stub->Echo1(&context, request, &response);
  10554. EXPECT_TRUE(GetParam().rbac_action() == RBAC_Action_DENY ? status.ok()
  10555. : !status.ok())
  10556. << status.error_code() << ", " << status.error_message() << ", "
  10557. << status.error_details() << ", " << context.debug_error_string();
  10558. }
  10559. TEST_P(XdsRbacTestWithActionPermutations,
  10560. AnyPermissionDirectRemoteIpPrincipal) {
  10561. RBAC rbac;
  10562. auto* rules = rbac.mutable_rules();
  10563. rules->set_action(GetParam().rbac_action());
  10564. Policy policy;
  10565. auto* range = policy.add_principals()->mutable_direct_remote_ip();
  10566. range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
  10567. range->mutable_prefix_len()->set_value(ipv6_only_ ? 128 : 32);
  10568. policy.add_permissions()->set_any(true);
  10569. (*rules->mutable_policies())["policy"] = policy;
  10570. SetServerRbacPolicy(rbac);
  10571. backends_[0]->Start();
  10572. backends_[0]->notifier()->WaitOnServingStatusChange(
  10573. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  10574. grpc::StatusCode::OK);
  10575. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  10576. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
  10577. grpc::StatusCode::PERMISSION_DENIED);
  10578. // Change the policy itself for a negative test where there is no match.
  10579. policy.clear_principals();
  10580. range = policy.add_principals()->mutable_direct_remote_ip();
  10581. range->set_address_prefix(ipv6_only_ ? "::2" : "127.0.0.2");
  10582. range->mutable_prefix_len()->set_value(ipv6_only_ ? 128 : 32);
  10583. (*rules->mutable_policies())["policy"] = policy;
  10584. SetServerRbacPolicy(rbac);
  10585. SendRpc(
  10586. [this]() { return CreateInsecureChannel(); }, {}, {},
  10587. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
  10588. grpc::StatusCode::PERMISSION_DENIED);
  10589. }
  10590. TEST_P(XdsRbacTestWithActionPermutations, AnyPermissionRemoteIpPrincipal) {
  10591. RBAC rbac;
  10592. auto* rules = rbac.mutable_rules();
  10593. rules->set_action(GetParam().rbac_action());
  10594. Policy policy;
  10595. auto* range = policy.add_principals()->mutable_remote_ip();
  10596. range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
  10597. range->mutable_prefix_len()->set_value(ipv6_only_ ? 128 : 32);
  10598. policy.add_permissions()->set_any(true);
  10599. (*rules->mutable_policies())["policy"] = policy;
  10600. SetServerRbacPolicy(rbac);
  10601. backends_[0]->Start();
  10602. backends_[0]->notifier()->WaitOnServingStatusChange(
  10603. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  10604. grpc::StatusCode::OK);
  10605. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  10606. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
  10607. grpc::StatusCode::PERMISSION_DENIED);
  10608. // Change the policy itself for a negative test where there is no match.
  10609. policy.clear_principals();
  10610. range = policy.add_principals()->mutable_remote_ip();
  10611. range->set_address_prefix(ipv6_only_ ? "::2" : "127.0.0.2");
  10612. range->mutable_prefix_len()->set_value(ipv6_only_ ? 128 : 32);
  10613. (*rules->mutable_policies())["policy"] = policy;
  10614. SetServerRbacPolicy(rbac);
  10615. SendRpc(
  10616. [this]() { return CreateInsecureChannel(); }, {}, {},
  10617. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
  10618. grpc::StatusCode::PERMISSION_DENIED);
  10619. }
  10620. TEST_P(XdsRbacTestWithActionPermutations, AnyPermissionAuthenticatedPrincipal) {
  10621. FakeCertificateProvider::CertDataMap fake1_cert_map = {
  10622. {"", {root_cert_, identity_pair_}}};
  10623. g_fake1_cert_data_map = &fake1_cert_map;
  10624. Listener listener = default_server_listener_;
  10625. auto* filter_chain = listener.mutable_default_filter_chain();
  10626. auto* transport_socket = filter_chain->mutable_transport_socket();
  10627. transport_socket->set_name("envoy.transport_sockets.tls");
  10628. DownstreamTlsContext downstream_tls_context;
  10629. downstream_tls_context.mutable_common_tls_context()
  10630. ->mutable_tls_certificate_provider_instance()
  10631. ->set_instance_name("fake_plugin1");
  10632. downstream_tls_context.mutable_common_tls_context()
  10633. ->mutable_validation_context()
  10634. ->mutable_ca_certificate_provider_instance()
  10635. ->set_instance_name("fake_plugin1");
  10636. downstream_tls_context.mutable_require_client_certificate()->set_value(true);
  10637. transport_socket->mutable_typed_config()->PackFrom(downstream_tls_context);
  10638. RBAC rbac;
  10639. auto* rules = rbac.mutable_rules();
  10640. rules->set_action(GetParam().rbac_action());
  10641. Policy policy;
  10642. policy.add_principals()
  10643. ->mutable_authenticated()
  10644. ->mutable_principal_name()
  10645. ->set_exact("*.test.google.fr");
  10646. policy.add_permissions()->set_any(true);
  10647. (*rules->mutable_policies())["policy"] = policy;
  10648. SetServerRbacPolicy(listener, rbac);
  10649. backends_[0]->Start();
  10650. backends_[0]->notifier()->WaitOnServingStatusChange(
  10651. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  10652. grpc::StatusCode::OK);
  10653. SendRpc([this]() { return CreateMtlsChannel(); },
  10654. server_authenticated_identity_, client_authenticated_identity_,
  10655. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
  10656. grpc::StatusCode::PERMISSION_DENIED);
  10657. }
  10658. TEST_P(XdsRbacTestWithActionPermutations, AnyPermissionMetadataPrincipal) {
  10659. RBAC rbac;
  10660. auto* rules = rbac.mutable_rules();
  10661. rules->set_action(GetParam().rbac_action());
  10662. Policy policy;
  10663. policy.add_principals()->mutable_metadata();
  10664. policy.add_permissions()->set_any(true);
  10665. (*rules->mutable_policies())["policy"] = policy;
  10666. SetServerRbacPolicy(rbac);
  10667. backends_[0]->Start();
  10668. backends_[0]->notifier()->WaitOnServingStatusChange(
  10669. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  10670. grpc::StatusCode::OK);
  10671. SendRpc(
  10672. [this]() { return CreateInsecureChannel(); }, {}, {},
  10673. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
  10674. grpc::StatusCode::PERMISSION_DENIED);
  10675. // Test metadata with inverted match
  10676. policy.clear_principals();
  10677. policy.add_principals()->mutable_metadata()->set_invert(true);
  10678. (*rules->mutable_policies())["policy"] = policy;
  10679. SetServerRbacPolicy(rbac);
  10680. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  10681. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
  10682. grpc::StatusCode::PERMISSION_DENIED);
  10683. }
  10684. TEST_P(XdsRbacTestWithActionPermutations, AnyPermissionNotIdPrincipal) {
  10685. RBAC rbac;
  10686. auto* rules = rbac.mutable_rules();
  10687. rules->set_action(GetParam().rbac_action());
  10688. Policy policy;
  10689. policy.add_principals()
  10690. ->mutable_not_id()
  10691. ->mutable_url_path()
  10692. ->mutable_path()
  10693. ->set_exact("/grpc.testing.EchoTestService/Echo1");
  10694. policy.add_permissions()->set_any(true);
  10695. (*rules->mutable_policies())["policy"] = policy;
  10696. SetServerRbacPolicy(rbac);
  10697. backends_[0]->Start();
  10698. backends_[0]->notifier()->WaitOnServingStatusChange(
  10699. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  10700. grpc::StatusCode::OK);
  10701. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  10702. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
  10703. grpc::StatusCode::PERMISSION_DENIED);
  10704. // Change the policy itself for a negative test where there is no match.
  10705. policy.clear_principals();
  10706. policy.add_principals()->mutable_not_id()->set_any(true);
  10707. (*rules->mutable_policies())["policy"] = policy;
  10708. SetServerRbacPolicy(rbac);
  10709. SendRpc(
  10710. [this]() { return CreateInsecureChannel(); }, {}, {},
  10711. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
  10712. grpc::StatusCode::PERMISSION_DENIED);
  10713. }
  10714. TEST_P(XdsRbacTestWithActionPermutations, AnyPermissionAndIdPrincipal) {
  10715. RBAC rbac;
  10716. auto* rules = rbac.mutable_rules();
  10717. rules->set_action(GetParam().rbac_action());
  10718. Policy policy;
  10719. auto* and_ids = policy.add_principals()->mutable_and_ids();
  10720. and_ids->add_ids()->set_any(true);
  10721. and_ids->add_ids()->mutable_url_path()->mutable_path()->set_exact(
  10722. "/grpc.testing.EchoTestService/Echo");
  10723. policy.add_permissions()->set_any(true);
  10724. (*rules->mutable_policies())["policy"] = policy;
  10725. SetServerRbacPolicy(rbac);
  10726. backends_[0]->Start();
  10727. backends_[0]->notifier()->WaitOnServingStatusChange(
  10728. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  10729. grpc::StatusCode::OK);
  10730. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  10731. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
  10732. grpc::StatusCode::PERMISSION_DENIED);
  10733. // Change the policy itself for a negative test where there is no match.
  10734. and_ids = (*policy.mutable_principals())[0].mutable_and_ids();
  10735. (*and_ids->mutable_ids())[1].mutable_url_path()->mutable_path()->set_exact(
  10736. "/grpc.testing.EchoTestService/Echo1");
  10737. (*rules->mutable_policies())["policy"] = policy;
  10738. SetServerRbacPolicy(rbac);
  10739. SendRpc(
  10740. [this]() { return CreateInsecureChannel(); }, {}, {},
  10741. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
  10742. grpc::StatusCode::PERMISSION_DENIED);
  10743. }
  10744. TEST_P(XdsRbacTestWithActionPermutations, AnyPermissionOrIdPrincipal) {
  10745. RBAC rbac;
  10746. auto* rules = rbac.mutable_rules();
  10747. rules->set_action(GetParam().rbac_action());
  10748. Policy policy;
  10749. auto* or_ids = policy.add_principals()->mutable_or_ids();
  10750. or_ids->add_ids()->mutable_not_id()->set_any(true);
  10751. or_ids->add_ids()->mutable_url_path()->mutable_path()->set_exact(
  10752. "/grpc.testing.EchoTestService/Echo");
  10753. policy.add_permissions()->set_any(true);
  10754. (*rules->mutable_policies())["policy"] = policy;
  10755. SetServerRbacPolicy(rbac);
  10756. backends_[0]->Start();
  10757. backends_[0]->notifier()->WaitOnServingStatusChange(
  10758. absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
  10759. grpc::StatusCode::OK);
  10760. SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
  10761. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
  10762. grpc::StatusCode::PERMISSION_DENIED);
  10763. // Change the policy itself for a negative test where there is no match.
  10764. or_ids = (*policy.mutable_principals())[0].mutable_or_ids();
  10765. (*or_ids->mutable_ids())[1].mutable_url_path()->mutable_path()->set_exact(
  10766. "/grpc.testing.EchoTestService/Echo1");
  10767. (*rules->mutable_policies())["policy"] = policy;
  10768. SetServerRbacPolicy(rbac);
  10769. SendRpc(
  10770. [this]() { return CreateInsecureChannel(); }, {}, {},
  10771. /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
  10772. grpc::StatusCode::PERMISSION_DENIED);
  10773. }
  10774. using EdsTest = BasicTest;
  10775. // Tests that EDS client should send a NACK if the EDS update contains
  10776. // sparse priorities.
  10777. TEST_P(EdsTest, NacksSparsePriorityList) {
  10778. EdsResourceArgs args({
  10779. {"locality0", CreateEndpointsForBackends(), kDefaultLocalityWeight, 1},
  10780. });
  10781. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  10782. const auto response_state = WaitForEdsNack();
  10783. ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
  10784. EXPECT_THAT(response_state->error_message,
  10785. ::testing::HasSubstr("sparse priority list"));
  10786. }
  10787. // In most of our tests, we use different names for different resource
  10788. // types, to make sure that there are no cut-and-paste errors in the code
  10789. // that cause us to look at data for the wrong resource type. So we add
  10790. // this test to make sure that the EDS resource name defaults to the
  10791. // cluster name if not specified in the CDS resource.
  10792. TEST_P(EdsTest, EdsServiceNameDefaultsToClusterName) {
  10793. EdsResourceArgs args({
  10794. {"locality0", CreateEndpointsForBackends()},
  10795. });
  10796. balancer_->ads_service()->SetEdsResource(
  10797. BuildEdsResource(args, kDefaultClusterName));
  10798. Cluster cluster = default_cluster_;
  10799. cluster.mutable_eds_cluster_config()->clear_service_name();
  10800. balancer_->ads_service()->SetCdsResource(cluster);
  10801. CheckRpcSendOk();
  10802. }
  10803. class TimeoutTest : public XdsEnd2endTest {
  10804. protected:
  10805. TimeoutTest()
  10806. : XdsEnd2endTest(/*num_backends=*/4,
  10807. /*client_load_reporting_interval_seconds=*/100,
  10808. /*xds_resource_does_not_exist_timeout_ms=*/500,
  10809. /*use_xds_enabled_server=*/false) {}
  10810. void SetUp() override {
  10811. XdsEnd2endTest::SetUp();
  10812. StartAllBackends();
  10813. }
  10814. };
  10815. TEST_P(TimeoutTest, LdsServerIgnoresRequest) {
  10816. balancer_->ads_service()->IgnoreResourceType(kLdsTypeUrl);
  10817. CheckRpcSendFailure();
  10818. }
  10819. TEST_P(TimeoutTest, LdsResourceNotPresentInRequest) {
  10820. balancer_->ads_service()->UnsetResource(kLdsTypeUrl, kServerName);
  10821. CheckRpcSendFailure();
  10822. }
  10823. TEST_P(TimeoutTest, LdsSecondResourceNotPresentInRequest) {
  10824. ASSERT_NE(GetParam().bootstrap_source(), TestType::kBootstrapFromChannelArg)
  10825. << "This test cannot use bootstrap from channel args, because it "
  10826. "needs two channels to use the same XdsClient instance.";
  10827. EdsResourceArgs args({
  10828. {"locality0", CreateEndpointsForBackends()},
  10829. });
  10830. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  10831. WaitForAllBackends();
  10832. // Create second channel for a new server name.
  10833. // This should fail because there is no LDS resource for this server name.
  10834. auto channel2 =
  10835. CreateChannel(/*failover_timeout=*/0, "new-server.example.com");
  10836. auto stub2 = grpc::testing::EchoTestService::NewStub(channel2);
  10837. ClientContext context;
  10838. EchoRequest request;
  10839. EchoResponse response;
  10840. RpcOptions rpc_options;
  10841. rpc_options.SetupRpc(&context, &request);
  10842. auto status =
  10843. SendRpcMethod(stub2.get(), rpc_options, &context, request, &response);
  10844. EXPECT_EQ(StatusCode::UNAVAILABLE, status.error_code());
  10845. }
  10846. TEST_P(TimeoutTest, RdsServerIgnoresRequest) {
  10847. balancer_->ads_service()->IgnoreResourceType(kRdsTypeUrl);
  10848. CheckRpcSendFailure();
  10849. }
  10850. TEST_P(TimeoutTest, RdsResourceNotPresentInRequest) {
  10851. balancer_->ads_service()->UnsetResource(kRdsTypeUrl,
  10852. kDefaultRouteConfigurationName);
  10853. CheckRpcSendFailure();
  10854. }
  10855. TEST_P(TimeoutTest, RdsSecondResourceNotPresentInRequest) {
  10856. ASSERT_NE(GetParam().bootstrap_source(), TestType::kBootstrapFromChannelArg)
  10857. << "This test cannot use bootstrap from channel args, because it "
  10858. "needs two channels to use the same XdsClient instance.";
  10859. EdsResourceArgs args({
  10860. {"locality0", CreateEndpointsForBackends()},
  10861. });
  10862. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  10863. // Add listener for 2nd channel, but no RDS resource.
  10864. const char* kNewServerName = "new-server.example.com";
  10865. Listener listener = default_listener_;
  10866. listener.set_name(kNewServerName);
  10867. HttpConnectionManager http_connection_manager =
  10868. ClientHcmAccessor().Unpack(listener);
  10869. auto* rds = http_connection_manager.mutable_rds();
  10870. rds->set_route_config_name("rds_resource_does_not_exist");
  10871. rds->mutable_config_source()->mutable_self();
  10872. ClientHcmAccessor().Pack(http_connection_manager, &listener);
  10873. balancer_->ads_service()->SetLdsResource(listener);
  10874. WaitForAllBackends();
  10875. // Create second channel for a new server name.
  10876. // This should fail because the LDS resource points to a non-existent RDS
  10877. // resource.
  10878. auto channel2 = CreateChannel(/*failover_timeout=*/0, kNewServerName);
  10879. auto stub2 = grpc::testing::EchoTestService::NewStub(channel2);
  10880. ClientContext context;
  10881. EchoRequest request;
  10882. EchoResponse response;
  10883. RpcOptions rpc_options;
  10884. rpc_options.SetupRpc(&context, &request);
  10885. auto status =
  10886. SendRpcMethod(stub2.get(), rpc_options, &context, request, &response);
  10887. EXPECT_EQ(StatusCode::UNAVAILABLE, status.error_code());
  10888. }
  10889. TEST_P(TimeoutTest, CdsServerIgnoresRequest) {
  10890. balancer_->ads_service()->IgnoreResourceType(kCdsTypeUrl);
  10891. CheckRpcSendFailure();
  10892. }
  10893. TEST_P(TimeoutTest, CdsResourceNotPresentInRequest) {
  10894. balancer_->ads_service()->UnsetResource(kCdsTypeUrl, kDefaultClusterName);
  10895. CheckRpcSendFailure();
  10896. }
  10897. TEST_P(TimeoutTest, CdsSecondResourceNotPresentInRequest) {
  10898. EdsResourceArgs args({
  10899. {"locality0", CreateEndpointsForBackends()},
  10900. });
  10901. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  10902. WaitForAllBackends();
  10903. // Change route config to point to non-existing cluster.
  10904. const char* kNewClusterName = "new_cluster_name";
  10905. RouteConfiguration route_config = default_route_config_;
  10906. route_config.mutable_virtual_hosts(0)
  10907. ->mutable_routes(0)
  10908. ->mutable_route()
  10909. ->set_cluster(kNewClusterName);
  10910. balancer_->ads_service()->SetRdsResource(route_config);
  10911. // New cluster times out.
  10912. // May need to wait a bit for the change to propagate to the client.
  10913. gpr_timespec deadline = grpc_timeout_seconds_to_deadline(10);
  10914. bool error_seen = false;
  10915. do {
  10916. auto status = SendRpc();
  10917. if (status.error_code() == StatusCode::UNAVAILABLE) {
  10918. error_seen = true;
  10919. break;
  10920. }
  10921. } while (gpr_time_cmp(gpr_now(GPR_CLOCK_MONOTONIC), deadline) < 0);
  10922. EXPECT_TRUE(error_seen);
  10923. }
  10924. TEST_P(TimeoutTest, EdsServerIgnoresRequest) {
  10925. balancer_->ads_service()->IgnoreResourceType(kEdsTypeUrl);
  10926. CheckRpcSendFailure();
  10927. }
  10928. TEST_P(TimeoutTest, EdsResourceNotPresentInRequest) {
  10929. // No need to remove EDS resource, since the test suite does not add it
  10930. // by default.
  10931. CheckRpcSendFailure();
  10932. }
  10933. TEST_P(TimeoutTest, EdsSecondResourceNotPresentInRequest) {
  10934. EdsResourceArgs args({
  10935. {"locality0", CreateEndpointsForBackends()},
  10936. });
  10937. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  10938. WaitForAllBackends();
  10939. // New cluster that points to a non-existant EDS resource.
  10940. const char* kNewClusterName = "new_cluster_name";
  10941. Cluster cluster = default_cluster_;
  10942. cluster.set_name(kNewClusterName);
  10943. cluster.mutable_eds_cluster_config()->set_service_name(
  10944. "eds_service_name_does_not_exist");
  10945. balancer_->ads_service()->SetCdsResource(cluster);
  10946. // Now add a route pointing to the new cluster.
  10947. RouteConfiguration route_config = default_route_config_;
  10948. auto* route = route_config.mutable_virtual_hosts(0)->mutable_routes(0);
  10949. *route_config.mutable_virtual_hosts(0)->add_routes() = *route;
  10950. route->mutable_match()->set_path("/grpc.testing.EchoTestService/Echo1");
  10951. route->mutable_route()->set_cluster(kNewClusterName);
  10952. balancer_->ads_service()->SetRdsResource(route_config);
  10953. // New EDS resource times out.
  10954. // May need to wait a bit for the RDS change to propagate to the client.
  10955. gpr_timespec deadline = grpc_timeout_seconds_to_deadline(10);
  10956. bool error_seen = false;
  10957. do {
  10958. auto status = SendRpc(RpcOptions().set_rpc_method(METHOD_ECHO1));
  10959. if (status.error_code() == StatusCode::UNAVAILABLE) {
  10960. error_seen = true;
  10961. break;
  10962. }
  10963. } while (gpr_time_cmp(gpr_now(GPR_CLOCK_MONOTONIC), deadline) < 0);
  10964. EXPECT_TRUE(error_seen);
  10965. }
  10966. using LocalityMapTest = BasicTest;
  10967. // Tests that the localities in a locality map are picked according to their
  10968. // weights.
  10969. TEST_P(LocalityMapTest, WeightedRoundRobin) {
  10970. const int kLocalityWeight0 = 2;
  10971. const int kLocalityWeight1 = 8;
  10972. const int kTotalLocalityWeight = kLocalityWeight0 + kLocalityWeight1;
  10973. const double kLocalityWeightRate0 =
  10974. static_cast<double>(kLocalityWeight0) / kTotalLocalityWeight;
  10975. const double kLocalityWeightRate1 =
  10976. static_cast<double>(kLocalityWeight1) / kTotalLocalityWeight;
  10977. const double kErrorTolerance = 0.05;
  10978. const size_t kNumRpcs =
  10979. ComputeIdealNumRpcs(kLocalityWeightRate0, kErrorTolerance);
  10980. // ADS response contains 2 localities, each of which contains 1 backend.
  10981. EdsResourceArgs args({
  10982. {"locality0", CreateEndpointsForBackends(0, 1), kLocalityWeight0},
  10983. {"locality1", CreateEndpointsForBackends(1, 2), kLocalityWeight1},
  10984. });
  10985. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  10986. // Wait for both backends to be ready.
  10987. WaitForAllBackends(0, 2);
  10988. // Send kNumRpcs RPCs.
  10989. CheckRpcSendOk(kNumRpcs);
  10990. // The locality picking rates should be roughly equal to the expectation.
  10991. const double locality_picked_rate_0 =
  10992. static_cast<double>(backends_[0]->backend_service()->request_count()) /
  10993. kNumRpcs;
  10994. const double locality_picked_rate_1 =
  10995. static_cast<double>(backends_[1]->backend_service()->request_count()) /
  10996. kNumRpcs;
  10997. EXPECT_THAT(locality_picked_rate_0,
  10998. ::testing::DoubleNear(kLocalityWeightRate0, kErrorTolerance));
  10999. EXPECT_THAT(locality_picked_rate_1,
  11000. ::testing::DoubleNear(kLocalityWeightRate1, kErrorTolerance));
  11001. }
  11002. // Tests that we correctly handle a locality containing no endpoints.
  11003. TEST_P(LocalityMapTest, LocalityContainingNoEndpoints) {
  11004. const size_t kNumRpcs = 5000;
  11005. // EDS response contains 2 localities, one with no endpoints.
  11006. EdsResourceArgs args({
  11007. {"locality0", CreateEndpointsForBackends()},
  11008. {"locality1", {}},
  11009. });
  11010. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11011. // Wait for both backends to be ready.
  11012. WaitForAllBackends();
  11013. // Send kNumRpcs RPCs.
  11014. CheckRpcSendOk(kNumRpcs);
  11015. // All traffic should go to the reachable locality.
  11016. EXPECT_EQ(backends_[0]->backend_service()->request_count(),
  11017. kNumRpcs / backends_.size());
  11018. EXPECT_EQ(backends_[1]->backend_service()->request_count(),
  11019. kNumRpcs / backends_.size());
  11020. EXPECT_EQ(backends_[2]->backend_service()->request_count(),
  11021. kNumRpcs / backends_.size());
  11022. EXPECT_EQ(backends_[3]->backend_service()->request_count(),
  11023. kNumRpcs / backends_.size());
  11024. }
  11025. // EDS update with no localities.
  11026. TEST_P(LocalityMapTest, NoLocalities) {
  11027. balancer_->ads_service()->SetEdsResource(BuildEdsResource({}));
  11028. Status status = SendRpc();
  11029. EXPECT_FALSE(status.ok());
  11030. EXPECT_EQ(status.error_code(), StatusCode::UNAVAILABLE);
  11031. }
  11032. // Tests that the locality map can work properly even when it contains a large
  11033. // number of localities.
  11034. TEST_P(LocalityMapTest, StressTest) {
  11035. const size_t kNumLocalities = 100;
  11036. const uint32_t kRpcTimeoutMs = 5000;
  11037. // The first ADS response contains kNumLocalities localities, each of which
  11038. // contains backend 0.
  11039. EdsResourceArgs args;
  11040. for (size_t i = 0; i < kNumLocalities; ++i) {
  11041. std::string name = absl::StrCat("locality", i);
  11042. EdsResourceArgs::Locality locality(name, CreateEndpointsForBackends(0, 1));
  11043. args.locality_list.emplace_back(std::move(locality));
  11044. }
  11045. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11046. // Wait until backend 0 is ready, before which kNumLocalities localities are
  11047. // received and handled by the xds policy.
  11048. WaitForBackend(0, WaitForBackendOptions().set_reset_counters(false),
  11049. RpcOptions().set_timeout_ms(kRpcTimeoutMs));
  11050. EXPECT_EQ(0U, backends_[1]->backend_service()->request_count());
  11051. // The second ADS response contains 1 locality, which contains backend 1.
  11052. args = EdsResourceArgs({
  11053. {"locality0", CreateEndpointsForBackends(1, 2)},
  11054. });
  11055. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11056. // Wait until backend 1 is ready, before which kNumLocalities localities are
  11057. // removed by the xds policy.
  11058. WaitForBackend(1);
  11059. }
  11060. // Tests that the localities in a locality map are picked correctly after
  11061. // update (addition, modification, deletion).
  11062. TEST_P(LocalityMapTest, UpdateMap) {
  11063. const size_t kNumRpcs = 3000;
  11064. // The locality weight for the first 3 localities.
  11065. const std::vector<int> kLocalityWeights0 = {2, 3, 4};
  11066. const double kTotalLocalityWeight0 =
  11067. std::accumulate(kLocalityWeights0.begin(), kLocalityWeights0.end(), 0);
  11068. std::vector<double> locality_weight_rate_0;
  11069. locality_weight_rate_0.reserve(kLocalityWeights0.size());
  11070. for (int weight : kLocalityWeights0) {
  11071. locality_weight_rate_0.push_back(weight / kTotalLocalityWeight0);
  11072. }
  11073. // Delete the first locality, keep the second locality, change the third
  11074. // locality's weight from 4 to 2, and add a new locality with weight 6.
  11075. const std::vector<int> kLocalityWeights1 = {3, 2, 6};
  11076. const double kTotalLocalityWeight1 =
  11077. std::accumulate(kLocalityWeights1.begin(), kLocalityWeights1.end(), 0);
  11078. std::vector<double> locality_weight_rate_1 = {
  11079. 0 /* placeholder for locality 0 */};
  11080. for (int weight : kLocalityWeights1) {
  11081. locality_weight_rate_1.push_back(weight / kTotalLocalityWeight1);
  11082. }
  11083. EdsResourceArgs args({
  11084. {"locality0", CreateEndpointsForBackends(0, 1), 2},
  11085. {"locality1", CreateEndpointsForBackends(1, 2), 3},
  11086. {"locality2", CreateEndpointsForBackends(2, 3), 4},
  11087. });
  11088. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11089. // Wait for the first 3 backends to be ready.
  11090. WaitForAllBackends(0, 3);
  11091. gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
  11092. // Send kNumRpcs RPCs.
  11093. CheckRpcSendOk(kNumRpcs);
  11094. gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
  11095. // The picking rates of the first 3 backends should be roughly equal to the
  11096. // expectation.
  11097. std::vector<double> locality_picked_rates;
  11098. for (size_t i = 0; i < 3; ++i) {
  11099. locality_picked_rates.push_back(
  11100. static_cast<double>(backends_[i]->backend_service()->request_count()) /
  11101. kNumRpcs);
  11102. }
  11103. const double kErrorTolerance = 0.2;
  11104. for (size_t i = 0; i < 3; ++i) {
  11105. gpr_log(GPR_INFO, "Locality %" PRIuPTR " rate %f", i,
  11106. locality_picked_rates[i]);
  11107. EXPECT_THAT(
  11108. locality_picked_rates[i],
  11109. ::testing::AllOf(
  11110. ::testing::Ge(locality_weight_rate_0[i] * (1 - kErrorTolerance)),
  11111. ::testing::Le(locality_weight_rate_0[i] * (1 + kErrorTolerance))));
  11112. }
  11113. args = EdsResourceArgs({
  11114. {"locality1", CreateEndpointsForBackends(1, 2), 3},
  11115. {"locality2", CreateEndpointsForBackends(2, 3), 2},
  11116. {"locality3", CreateEndpointsForBackends(3, 4), 6},
  11117. });
  11118. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11119. // Backend 3 hasn't received any request.
  11120. EXPECT_EQ(0U, backends_[3]->backend_service()->request_count());
  11121. // Wait until the locality update has been processed, as signaled by backend
  11122. // 3 receiving a request.
  11123. WaitForAllBackends(3, 4);
  11124. gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
  11125. // Send kNumRpcs RPCs.
  11126. CheckRpcSendOk(kNumRpcs);
  11127. gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
  11128. // Backend 0 no longer receives any request.
  11129. EXPECT_EQ(0U, backends_[0]->backend_service()->request_count());
  11130. // The picking rates of the last 3 backends should be roughly equal to the
  11131. // expectation.
  11132. locality_picked_rates = {0 /* placeholder for backend 0 */};
  11133. for (size_t i = 1; i < 4; ++i) {
  11134. locality_picked_rates.push_back(
  11135. static_cast<double>(backends_[i]->backend_service()->request_count()) /
  11136. kNumRpcs);
  11137. }
  11138. for (size_t i = 1; i < 4; ++i) {
  11139. gpr_log(GPR_INFO, "Locality %" PRIuPTR " rate %f", i,
  11140. locality_picked_rates[i]);
  11141. EXPECT_THAT(
  11142. locality_picked_rates[i],
  11143. ::testing::AllOf(
  11144. ::testing::Ge(locality_weight_rate_1[i] * (1 - kErrorTolerance)),
  11145. ::testing::Le(locality_weight_rate_1[i] * (1 + kErrorTolerance))));
  11146. }
  11147. }
  11148. // Tests that we don't fail RPCs when replacing all of the localities in
  11149. // a given priority.
  11150. TEST_P(LocalityMapTest, ReplaceAllLocalitiesInPriority) {
  11151. EdsResourceArgs args({
  11152. {"locality0", CreateEndpointsForBackends(0, 1)},
  11153. });
  11154. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11155. args = EdsResourceArgs({
  11156. {"locality1", CreateEndpointsForBackends(1, 2)},
  11157. });
  11158. std::thread delayed_resource_setter(
  11159. std::bind(&BasicTest::SetEdsResourceWithDelay, this, balancer_.get(),
  11160. BuildEdsResource(args), 5000));
  11161. // Wait for the first backend to be ready.
  11162. WaitForBackend(0);
  11163. // Keep sending RPCs until we switch over to backend 1, which tells us
  11164. // that we received the update. No RPCs should fail during this
  11165. // transition.
  11166. WaitForBackend(1);
  11167. delayed_resource_setter.join();
  11168. }
  11169. class FailoverTest : public BasicTest {
  11170. public:
  11171. void SetUp() override {
  11172. BasicTest::SetUp();
  11173. ResetStub(500);
  11174. }
  11175. };
  11176. // Localities with the highest priority are used when multiple priority exist.
  11177. TEST_P(FailoverTest, ChooseHighestPriority) {
  11178. EdsResourceArgs args({
  11179. {"locality0", CreateEndpointsForBackends(0, 1), kDefaultLocalityWeight,
  11180. 1},
  11181. {"locality1", CreateEndpointsForBackends(1, 2), kDefaultLocalityWeight,
  11182. 2},
  11183. {"locality2", CreateEndpointsForBackends(2, 3), kDefaultLocalityWeight,
  11184. 3},
  11185. {"locality3", CreateEndpointsForBackends(3, 4), kDefaultLocalityWeight,
  11186. 0},
  11187. });
  11188. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11189. WaitForBackend(3, WaitForBackendOptions().set_reset_counters(false));
  11190. for (size_t i = 0; i < 3; ++i) {
  11191. EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
  11192. }
  11193. }
  11194. // Does not choose priority with no endpoints.
  11195. TEST_P(FailoverTest, DoesNotUsePriorityWithNoEndpoints) {
  11196. EdsResourceArgs args({
  11197. {"locality0", CreateEndpointsForBackends(0, 1), kDefaultLocalityWeight,
  11198. 1},
  11199. {"locality1", CreateEndpointsForBackends(1, 2), kDefaultLocalityWeight,
  11200. 2},
  11201. {"locality2", CreateEndpointsForBackends(2, 3), kDefaultLocalityWeight,
  11202. 3},
  11203. {"locality3", {}, kDefaultLocalityWeight, 0},
  11204. });
  11205. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11206. WaitForBackend(0, WaitForBackendOptions().set_reset_counters(false));
  11207. for (size_t i = 1; i < 3; ++i) {
  11208. EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
  11209. }
  11210. }
  11211. // Does not choose locality with no endpoints.
  11212. TEST_P(FailoverTest, DoesNotUseLocalityWithNoEndpoints) {
  11213. EdsResourceArgs args({
  11214. {"locality0", {}, kDefaultLocalityWeight, 0},
  11215. {"locality1", CreateEndpointsForBackends(), kDefaultLocalityWeight, 0},
  11216. });
  11217. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11218. // Wait for all backends to be used.
  11219. WaitForAllBackends();
  11220. }
  11221. // If the higher priority localities are not reachable, failover to the
  11222. // highest priority among the rest.
  11223. TEST_P(FailoverTest, Failover) {
  11224. EdsResourceArgs args({
  11225. {"locality0", CreateEndpointsForBackends(0, 1), kDefaultLocalityWeight,
  11226. 1},
  11227. {"locality1", CreateEndpointsForBackends(1, 2), kDefaultLocalityWeight,
  11228. 2},
  11229. {"locality2", CreateEndpointsForBackends(2, 3), kDefaultLocalityWeight,
  11230. 3},
  11231. {"locality3", CreateEndpointsForBackends(3, 4), kDefaultLocalityWeight,
  11232. 0},
  11233. });
  11234. ShutdownBackend(3);
  11235. ShutdownBackend(0);
  11236. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11237. WaitForBackend(1, WaitForBackendOptions().set_reset_counters(false));
  11238. for (size_t i = 0; i < 4; ++i) {
  11239. if (i == 1) continue;
  11240. EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
  11241. }
  11242. }
  11243. // If a locality with higher priority than the current one becomes ready,
  11244. // switch to it.
  11245. TEST_P(FailoverTest, SwitchBackToHigherPriority) {
  11246. const size_t kNumRpcs = 100;
  11247. EdsResourceArgs args({
  11248. {"locality0", CreateEndpointsForBackends(0, 1), kDefaultLocalityWeight,
  11249. 1},
  11250. {"locality1", CreateEndpointsForBackends(1, 2), kDefaultLocalityWeight,
  11251. 2},
  11252. {"locality2", CreateEndpointsForBackends(2, 3), kDefaultLocalityWeight,
  11253. 3},
  11254. {"locality3", CreateEndpointsForBackends(3, 4), kDefaultLocalityWeight,
  11255. 0},
  11256. });
  11257. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11258. WaitForBackend(3);
  11259. ShutdownBackend(3);
  11260. ShutdownBackend(0);
  11261. WaitForBackend(
  11262. 1, WaitForBackendOptions().set_reset_counters(false).set_allow_failures(
  11263. true));
  11264. for (size_t i = 0; i < 4; ++i) {
  11265. if (i == 1) continue;
  11266. EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
  11267. }
  11268. StartBackend(0);
  11269. WaitForBackend(0);
  11270. CheckRpcSendOk(kNumRpcs);
  11271. EXPECT_EQ(kNumRpcs, backends_[0]->backend_service()->request_count());
  11272. }
  11273. // The first update only contains unavailable priorities. The second update
  11274. // contains available priorities.
  11275. TEST_P(FailoverTest, UpdateInitialUnavailable) {
  11276. EdsResourceArgs args({
  11277. {"locality0", CreateEndpointsForBackends(0, 1), kDefaultLocalityWeight,
  11278. 0},
  11279. {"locality1", CreateEndpointsForBackends(1, 2), kDefaultLocalityWeight,
  11280. 1},
  11281. });
  11282. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11283. args = EdsResourceArgs({
  11284. {"locality0", CreateEndpointsForBackends(0, 1), kDefaultLocalityWeight,
  11285. 0},
  11286. {"locality1", CreateEndpointsForBackends(1, 2), kDefaultLocalityWeight,
  11287. 1},
  11288. {"locality2", CreateEndpointsForBackends(2, 3), kDefaultLocalityWeight,
  11289. 2},
  11290. {"locality3", CreateEndpointsForBackends(3, 4), kDefaultLocalityWeight,
  11291. 3},
  11292. });
  11293. ShutdownBackend(0);
  11294. ShutdownBackend(1);
  11295. std::thread delayed_resource_setter(
  11296. std::bind(&BasicTest::SetEdsResourceWithDelay, this, balancer_.get(),
  11297. BuildEdsResource(args), 1000));
  11298. gpr_timespec deadline = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
  11299. gpr_time_from_millis(500, GPR_TIMESPAN));
  11300. // Send 0.5 second worth of RPCs.
  11301. do {
  11302. CheckRpcSendFailure();
  11303. } while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
  11304. WaitForBackend(
  11305. 2, WaitForBackendOptions().set_reset_counters(false).set_allow_failures(
  11306. true));
  11307. for (size_t i = 0; i < 4; ++i) {
  11308. if (i == 2) continue;
  11309. EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
  11310. }
  11311. delayed_resource_setter.join();
  11312. }
  11313. // Tests that after the localities' priorities are updated, we still choose
  11314. // the highest READY priority with the updated localities.
  11315. TEST_P(FailoverTest, UpdatePriority) {
  11316. const size_t kNumRpcs = 100;
  11317. EdsResourceArgs args({
  11318. {"locality0", CreateEndpointsForBackends(0, 1), kDefaultLocalityWeight,
  11319. 1},
  11320. {"locality1", CreateEndpointsForBackends(1, 2), kDefaultLocalityWeight,
  11321. 2},
  11322. {"locality2", CreateEndpointsForBackends(2, 3), kDefaultLocalityWeight,
  11323. 3},
  11324. {"locality3", CreateEndpointsForBackends(3, 4), kDefaultLocalityWeight,
  11325. 0},
  11326. });
  11327. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11328. args = EdsResourceArgs({
  11329. {"locality0", CreateEndpointsForBackends(0, 1), kDefaultLocalityWeight,
  11330. 2},
  11331. {"locality1", CreateEndpointsForBackends(1, 2), kDefaultLocalityWeight,
  11332. 0},
  11333. {"locality2", CreateEndpointsForBackends(2, 3), kDefaultLocalityWeight,
  11334. 1},
  11335. {"locality3", CreateEndpointsForBackends(3, 4), kDefaultLocalityWeight,
  11336. 3},
  11337. });
  11338. std::thread delayed_resource_setter(
  11339. std::bind(&BasicTest::SetEdsResourceWithDelay, this, balancer_.get(),
  11340. BuildEdsResource(args), 1000));
  11341. WaitForBackend(3, WaitForBackendOptions().set_reset_counters(false));
  11342. for (size_t i = 0; i < 3; ++i) {
  11343. EXPECT_EQ(0U, backends_[i]->backend_service()->request_count());
  11344. }
  11345. WaitForBackend(1);
  11346. CheckRpcSendOk(kNumRpcs);
  11347. EXPECT_EQ(kNumRpcs, backends_[1]->backend_service()->request_count());
  11348. delayed_resource_setter.join();
  11349. }
  11350. // Moves all localities in the current priority to a higher priority.
  11351. TEST_P(FailoverTest, MoveAllLocalitiesInCurrentPriorityToHigherPriority) {
  11352. // First update:
  11353. // - Priority 0 is locality 0, containing backend 0, which is down.
  11354. // - Priority 1 is locality 1, containing backends 1 and 2, which are up.
  11355. ShutdownBackend(0);
  11356. EdsResourceArgs args({
  11357. {"locality0", CreateEndpointsForBackends(0, 1), kDefaultLocalityWeight,
  11358. 0},
  11359. {"locality1", CreateEndpointsForBackends(1, 3), kDefaultLocalityWeight,
  11360. 1},
  11361. });
  11362. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11363. // Second update:
  11364. // - Priority 0 contains both localities 0 and 1.
  11365. // - Priority 1 is not present.
  11366. // - We add backend 3 to locality 1, just so we have a way to know
  11367. // when the update has been seen by the client.
  11368. args = EdsResourceArgs({
  11369. {"locality0", CreateEndpointsForBackends(0, 1), kDefaultLocalityWeight,
  11370. 0},
  11371. {"locality1", CreateEndpointsForBackends(1, 4), kDefaultLocalityWeight,
  11372. 0},
  11373. });
  11374. std::thread delayed_resource_setter(
  11375. std::bind(&BasicTest::SetEdsResourceWithDelay, this, balancer_.get(),
  11376. BuildEdsResource(args), 1000));
  11377. // When we get the first update, all backends in priority 0 are down,
  11378. // so we will create priority 1. Backends 1 and 2 should have traffic,
  11379. // but backend 3 should not.
  11380. WaitForAllBackends(1, 3, WaitForBackendOptions().set_reset_counters(false));
  11381. EXPECT_EQ(0UL, backends_[3]->backend_service()->request_count());
  11382. // When backend 3 gets traffic, we know the second update has been seen.
  11383. WaitForBackend(3);
  11384. // The ADS service of balancer 0 got at least 1 response.
  11385. EXPECT_TRUE(balancer_->ads_service()->eds_response_state().has_value());
  11386. delayed_resource_setter.join();
  11387. }
  11388. using DropTest = BasicTest;
  11389. // Tests that RPCs are dropped according to the drop config.
  11390. TEST_P(DropTest, Vanilla) {
  11391. const uint32_t kDropPerMillionForLb = 100000;
  11392. const uint32_t kDropPerMillionForThrottle = 200000;
  11393. const double kDropRateForLb = kDropPerMillionForLb / 1000000.0;
  11394. const double kDropRateForThrottle = kDropPerMillionForThrottle / 1000000.0;
  11395. const double kDropRateForLbAndThrottle =
  11396. kDropRateForLb + (1 - kDropRateForLb) * kDropRateForThrottle;
  11397. const double kErrorTolerance = 0.05;
  11398. const size_t kNumRpcs =
  11399. ComputeIdealNumRpcs(kDropRateForLbAndThrottle, kErrorTolerance);
  11400. // The ADS response contains two drop categories.
  11401. EdsResourceArgs args({
  11402. {"locality0", CreateEndpointsForBackends()},
  11403. });
  11404. args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
  11405. {kThrottleDropType, kDropPerMillionForThrottle}};
  11406. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11407. // Send kNumRpcs RPCs and count the drops.
  11408. size_t num_drops =
  11409. SendRpcsAndCountFailuresWithMessage(kNumRpcs, "EDS-configured drop: ");
  11410. // The drop rate should be roughly equal to the expectation.
  11411. const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
  11412. EXPECT_THAT(seen_drop_rate, ::testing::DoubleNear(kDropRateForLbAndThrottle,
  11413. kErrorTolerance));
  11414. }
  11415. // Tests that drop config is converted correctly from per hundred.
  11416. TEST_P(DropTest, DropPerHundred) {
  11417. const uint32_t kDropPerHundredForLb = 10;
  11418. const double kDropRateForLb = kDropPerHundredForLb / 100.0;
  11419. const double kErrorTolerance = 0.05;
  11420. const size_t kNumRpcs = ComputeIdealNumRpcs(kDropRateForLb, kErrorTolerance);
  11421. // The ADS response contains one drop category.
  11422. EdsResourceArgs args({
  11423. {"locality0", CreateEndpointsForBackends()},
  11424. });
  11425. args.drop_categories = {{kLbDropType, kDropPerHundredForLb}};
  11426. args.drop_denominator = FractionalPercent::HUNDRED;
  11427. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11428. // Send kNumRpcs RPCs and count the drops.
  11429. size_t num_drops =
  11430. SendRpcsAndCountFailuresWithMessage(kNumRpcs, "EDS-configured drop: ");
  11431. // The drop rate should be roughly equal to the expectation.
  11432. const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
  11433. EXPECT_THAT(seen_drop_rate,
  11434. ::testing::DoubleNear(kDropRateForLb, kErrorTolerance));
  11435. }
  11436. // Tests that drop config is converted correctly from per ten thousand.
  11437. TEST_P(DropTest, DropPerTenThousand) {
  11438. const uint32_t kDropPerTenThousandForLb = 1000;
  11439. const double kDropRateForLb = kDropPerTenThousandForLb / 10000.0;
  11440. const double kErrorTolerance = 0.05;
  11441. const size_t kNumRpcs = ComputeIdealNumRpcs(kDropRateForLb, kErrorTolerance);
  11442. // The ADS response contains one drop category.
  11443. EdsResourceArgs args({
  11444. {"locality0", CreateEndpointsForBackends()},
  11445. });
  11446. args.drop_categories = {{kLbDropType, kDropPerTenThousandForLb}};
  11447. args.drop_denominator = FractionalPercent::TEN_THOUSAND;
  11448. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11449. // Send kNumRpcs RPCs and count the drops.
  11450. size_t num_drops =
  11451. SendRpcsAndCountFailuresWithMessage(kNumRpcs, "EDS-configured drop: ");
  11452. // The drop rate should be roughly equal to the expectation.
  11453. const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
  11454. EXPECT_THAT(seen_drop_rate,
  11455. ::testing::DoubleNear(kDropRateForLb, kErrorTolerance));
  11456. }
  11457. // Tests that drop is working correctly after update.
  11458. TEST_P(DropTest, Update) {
  11459. const uint32_t kDropPerMillionForLb = 100000;
  11460. const uint32_t kDropPerMillionForThrottle = 200000;
  11461. const double kErrorTolerance = 0.05;
  11462. const double kDropRateForLb = kDropPerMillionForLb / 1000000.0;
  11463. const double kDropRateForThrottle = kDropPerMillionForThrottle / 1000000.0;
  11464. const double kDropRateForLbAndThrottle =
  11465. kDropRateForLb + (1 - kDropRateForLb) * kDropRateForThrottle;
  11466. const size_t kNumRpcsLbOnly =
  11467. ComputeIdealNumRpcs(kDropRateForLb, kErrorTolerance);
  11468. const size_t kNumRpcsBoth =
  11469. ComputeIdealNumRpcs(kDropRateForLbAndThrottle, kErrorTolerance);
  11470. // The first ADS response contains one drop category.
  11471. EdsResourceArgs args({
  11472. {"locality0", CreateEndpointsForBackends()},
  11473. });
  11474. args.drop_categories = {{kLbDropType, kDropPerMillionForLb}};
  11475. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11476. // Send kNumRpcsLbOnly RPCs and count the drops.
  11477. gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
  11478. size_t num_drops = SendRpcsAndCountFailuresWithMessage(
  11479. kNumRpcsLbOnly, "EDS-configured drop: ");
  11480. gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
  11481. // The drop rate should be roughly equal to the expectation.
  11482. double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcsLbOnly;
  11483. gpr_log(GPR_INFO, "First batch drop rate %f", seen_drop_rate);
  11484. EXPECT_THAT(seen_drop_rate,
  11485. ::testing::DoubleNear(kDropRateForLb, kErrorTolerance));
  11486. // The second ADS response contains two drop categories, send an update EDS
  11487. // response.
  11488. args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
  11489. {kThrottleDropType, kDropPerMillionForThrottle}};
  11490. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11491. // Wait until the drop rate increases to the middle of the two configs,
  11492. // which implies that the update has been in effect.
  11493. const double kDropRateThreshold =
  11494. (kDropRateForLb + kDropRateForLbAndThrottle) / 2;
  11495. size_t num_rpcs = kNumRpcsBoth;
  11496. while (seen_drop_rate < kDropRateThreshold) {
  11497. EchoResponse response;
  11498. const Status status = SendRpc(RpcOptions(), &response);
  11499. ++num_rpcs;
  11500. if (!status.ok() &&
  11501. absl::StartsWith(status.error_message(), "EDS-configured drop: ")) {
  11502. ++num_drops;
  11503. } else {
  11504. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  11505. << " message=" << status.error_message();
  11506. EXPECT_EQ(response.message(), kRequestMessage);
  11507. }
  11508. seen_drop_rate = static_cast<double>(num_drops) / num_rpcs;
  11509. }
  11510. // Send kNumRpcsBoth RPCs and count the drops.
  11511. gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
  11512. num_drops = SendRpcsAndCountFailuresWithMessage(kNumRpcsBoth,
  11513. "EDS-configured drop: ");
  11514. gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
  11515. // The new drop rate should be roughly equal to the expectation.
  11516. seen_drop_rate = static_cast<double>(num_drops) / kNumRpcsBoth;
  11517. gpr_log(GPR_INFO, "Second batch drop rate %f", seen_drop_rate);
  11518. EXPECT_THAT(seen_drop_rate, ::testing::DoubleNear(kDropRateForLbAndThrottle,
  11519. kErrorTolerance));
  11520. }
  11521. // Tests that all the RPCs are dropped if any drop category drops 100%.
  11522. TEST_P(DropTest, DropAll) {
  11523. const size_t kNumRpcs = 1000;
  11524. const uint32_t kDropPerMillionForLb = 100000;
  11525. const uint32_t kDropPerMillionForThrottle = 1000000;
  11526. // The ADS response contains two drop categories.
  11527. EdsResourceArgs args;
  11528. args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
  11529. {kThrottleDropType, kDropPerMillionForThrottle}};
  11530. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11531. // Send kNumRpcs RPCs and all of them are dropped.
  11532. size_t num_drops =
  11533. SendRpcsAndCountFailuresWithMessage(kNumRpcs, "EDS-configured drop: ");
  11534. EXPECT_EQ(num_drops, kNumRpcs);
  11535. }
  11536. class ClientLoadReportingTest : public XdsEnd2endTest {
  11537. public:
  11538. ClientLoadReportingTest() : XdsEnd2endTest(4, 3) {}
  11539. void SetUp() override {
  11540. XdsEnd2endTest::SetUp();
  11541. StartAllBackends();
  11542. }
  11543. };
  11544. // Tests that the load report received at the balancer is correct.
  11545. TEST_P(ClientLoadReportingTest, Vanilla) {
  11546. const size_t kNumRpcsPerAddress = 10;
  11547. const size_t kNumFailuresPerAddress = 3;
  11548. // TODO(juanlishen): Partition the backends after multiple localities is
  11549. // tested.
  11550. EdsResourceArgs args({
  11551. {"locality0", CreateEndpointsForBackends()},
  11552. });
  11553. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11554. // Wait until all backends are ready.
  11555. size_t num_warmup_rpcs = WaitForAllBackends();
  11556. // Send kNumRpcsPerAddress RPCs per server.
  11557. CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
  11558. CheckRpcSendFailure(CheckRpcSendFailureOptions()
  11559. .set_times(kNumFailuresPerAddress * num_backends_)
  11560. .set_rpc_options(RpcOptions().set_server_fail(true)));
  11561. // Check that each backend got the right number of requests.
  11562. for (size_t i = 0; i < backends_.size(); ++i) {
  11563. EXPECT_EQ(kNumRpcsPerAddress + kNumFailuresPerAddress,
  11564. backends_[i]->backend_service()->request_count());
  11565. }
  11566. // The load report received at the balancer should be correct.
  11567. std::vector<ClientStats> load_report =
  11568. balancer_->lrs_service()->WaitForLoadReport();
  11569. ASSERT_EQ(load_report.size(), 1UL);
  11570. ClientStats& client_stats = load_report.front();
  11571. EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + num_warmup_rpcs,
  11572. client_stats.total_successful_requests());
  11573. EXPECT_EQ(0U, client_stats.total_requests_in_progress());
  11574. EXPECT_EQ((kNumRpcsPerAddress + kNumFailuresPerAddress) * num_backends_ +
  11575. num_warmup_rpcs,
  11576. client_stats.total_issued_requests());
  11577. EXPECT_EQ(kNumFailuresPerAddress * num_backends_,
  11578. client_stats.total_error_requests());
  11579. EXPECT_EQ(0U, client_stats.total_dropped_requests());
  11580. // The LRS service got a single request, and sent a single response.
  11581. EXPECT_EQ(1U, balancer_->lrs_service()->request_count());
  11582. EXPECT_EQ(1U, balancer_->lrs_service()->response_count());
  11583. }
  11584. // Tests send_all_clusters.
  11585. TEST_P(ClientLoadReportingTest, SendAllClusters) {
  11586. balancer_->lrs_service()->set_send_all_clusters(true);
  11587. const size_t kNumRpcsPerAddress = 10;
  11588. const size_t kNumFailuresPerAddress = 3;
  11589. // TODO(juanlishen): Partition the backends after multiple localities is
  11590. // tested.
  11591. EdsResourceArgs args({
  11592. {"locality0", CreateEndpointsForBackends()},
  11593. });
  11594. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11595. // Wait until all backends are ready.
  11596. size_t num_warmup_rpcs = WaitForAllBackends();
  11597. // Send kNumRpcsPerAddress RPCs per server.
  11598. CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
  11599. CheckRpcSendFailure(CheckRpcSendFailureOptions()
  11600. .set_times(kNumFailuresPerAddress * num_backends_)
  11601. .set_rpc_options(RpcOptions().set_server_fail(true)));
  11602. // Check that each backend got the right number of requests.
  11603. for (size_t i = 0; i < backends_.size(); ++i) {
  11604. EXPECT_EQ(kNumRpcsPerAddress + kNumFailuresPerAddress,
  11605. backends_[i]->backend_service()->request_count());
  11606. }
  11607. // The load report received at the balancer should be correct.
  11608. std::vector<ClientStats> load_report =
  11609. balancer_->lrs_service()->WaitForLoadReport();
  11610. ASSERT_EQ(load_report.size(), 1UL);
  11611. ClientStats& client_stats = load_report.front();
  11612. EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + num_warmup_rpcs,
  11613. client_stats.total_successful_requests());
  11614. EXPECT_EQ(0U, client_stats.total_requests_in_progress());
  11615. EXPECT_EQ((kNumRpcsPerAddress + kNumFailuresPerAddress) * num_backends_ +
  11616. num_warmup_rpcs,
  11617. client_stats.total_issued_requests());
  11618. EXPECT_EQ(kNumFailuresPerAddress * num_backends_,
  11619. client_stats.total_error_requests());
  11620. EXPECT_EQ(0U, client_stats.total_dropped_requests());
  11621. // The LRS service got a single request, and sent a single response.
  11622. EXPECT_EQ(1U, balancer_->lrs_service()->request_count());
  11623. EXPECT_EQ(1U, balancer_->lrs_service()->response_count());
  11624. }
  11625. // Tests that we don't include stats for clusters that are not requested
  11626. // by the LRS server.
  11627. TEST_P(ClientLoadReportingTest, HonorsClustersRequestedByLrsServer) {
  11628. balancer_->lrs_service()->set_cluster_names({"bogus"});
  11629. const size_t kNumRpcsPerAddress = 100;
  11630. EdsResourceArgs args({
  11631. {"locality0", CreateEndpointsForBackends()},
  11632. });
  11633. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11634. // Wait until all backends are ready.
  11635. WaitForAllBackends();
  11636. // Send kNumRpcsPerAddress RPCs per server.
  11637. CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
  11638. // Each backend should have gotten 100 requests.
  11639. for (size_t i = 0; i < backends_.size(); ++i) {
  11640. EXPECT_EQ(kNumRpcsPerAddress,
  11641. backends_[i]->backend_service()->request_count());
  11642. }
  11643. // The LRS service got a single request, and sent a single response.
  11644. EXPECT_EQ(1U, balancer_->lrs_service()->request_count());
  11645. EXPECT_EQ(1U, balancer_->lrs_service()->response_count());
  11646. // The load report received at the balancer should be correct.
  11647. std::vector<ClientStats> load_report =
  11648. balancer_->lrs_service()->WaitForLoadReport();
  11649. ASSERT_EQ(load_report.size(), 0UL);
  11650. }
  11651. // Tests that if the balancer restarts, the client load report contains the
  11652. // stats before and after the restart correctly.
  11653. TEST_P(ClientLoadReportingTest, BalancerRestart) {
  11654. const size_t kNumBackendsFirstPass = backends_.size() / 2;
  11655. const size_t kNumBackendsSecondPass =
  11656. backends_.size() - kNumBackendsFirstPass;
  11657. EdsResourceArgs args({
  11658. {"locality0", CreateEndpointsForBackends(0, kNumBackendsFirstPass)},
  11659. });
  11660. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11661. // Wait until all backends returned by the balancer are ready.
  11662. size_t num_rpcs = WaitForAllBackends(
  11663. /*start_index=*/0, /*stop_index=*/kNumBackendsFirstPass);
  11664. std::vector<ClientStats> load_report =
  11665. balancer_->lrs_service()->WaitForLoadReport();
  11666. ASSERT_EQ(load_report.size(), 1UL);
  11667. ClientStats client_stats = std::move(load_report.front());
  11668. EXPECT_EQ(num_rpcs, client_stats.total_successful_requests());
  11669. EXPECT_EQ(0U, client_stats.total_requests_in_progress());
  11670. EXPECT_EQ(0U, client_stats.total_error_requests());
  11671. EXPECT_EQ(0U, client_stats.total_dropped_requests());
  11672. // Shut down the balancer.
  11673. balancer_->Shutdown();
  11674. // We should continue using the last EDS response we received from the
  11675. // balancer before it was shut down.
  11676. // Note: We need to use WaitForAllBackends() here instead of just
  11677. // CheckRpcSendOk(kNumBackendsFirstPass), because when the balancer
  11678. // shuts down, the XdsClient will generate an error to the
  11679. // ServiceConfigWatcher, which will cause the xds resolver to send a
  11680. // no-op update to the LB policy. When this update gets down to the
  11681. // round_robin child policy for the locality, it will generate a new
  11682. // subchannel list, which resets the start index randomly. So we need
  11683. // to be a little more permissive here to avoid spurious failures.
  11684. ResetBackendCounters();
  11685. num_rpcs = WaitForAllBackends(/*start_index=*/0,
  11686. /*stop_index=*/kNumBackendsFirstPass);
  11687. // Now restart the balancer, this time pointing to the new backends.
  11688. balancer_->Start();
  11689. args = EdsResourceArgs({
  11690. {"locality0", CreateEndpointsForBackends(kNumBackendsFirstPass)},
  11691. });
  11692. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11693. // Wait for queries to start going to one of the new backends.
  11694. // This tells us that we're now using the new serverlist.
  11695. num_rpcs += WaitForAllBackends(/*start_index=*/kNumBackendsFirstPass);
  11696. // Send one RPC per backend.
  11697. CheckRpcSendOk(kNumBackendsSecondPass);
  11698. num_rpcs += kNumBackendsSecondPass;
  11699. // Check client stats.
  11700. load_report = balancer_->lrs_service()->WaitForLoadReport();
  11701. ASSERT_EQ(load_report.size(), 1UL);
  11702. client_stats = std::move(load_report.front());
  11703. EXPECT_EQ(num_rpcs, client_stats.total_successful_requests());
  11704. EXPECT_EQ(0U, client_stats.total_requests_in_progress());
  11705. EXPECT_EQ(0U, client_stats.total_error_requests());
  11706. EXPECT_EQ(0U, client_stats.total_dropped_requests());
  11707. }
  11708. // Tests load reporting when switching over from one cluster to another.
  11709. TEST_P(ClientLoadReportingTest, ChangeClusters) {
  11710. const char* kNewClusterName = "new_cluster_name";
  11711. const char* kNewEdsServiceName = "new_eds_service_name";
  11712. balancer_->lrs_service()->set_cluster_names(
  11713. {kDefaultClusterName, kNewClusterName});
  11714. // cluster kDefaultClusterName -> locality0 -> backends 0 and 1
  11715. EdsResourceArgs args({
  11716. {"locality0", CreateEndpointsForBackends(0, 2)},
  11717. });
  11718. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11719. // cluster kNewClusterName -> locality1 -> backends 2 and 3
  11720. EdsResourceArgs args2({
  11721. {"locality1", CreateEndpointsForBackends(2, 4)},
  11722. });
  11723. balancer_->ads_service()->SetEdsResource(
  11724. BuildEdsResource(args2, kNewEdsServiceName));
  11725. // CDS resource for kNewClusterName.
  11726. Cluster new_cluster = default_cluster_;
  11727. new_cluster.set_name(kNewClusterName);
  11728. new_cluster.mutable_eds_cluster_config()->set_service_name(
  11729. kNewEdsServiceName);
  11730. balancer_->ads_service()->SetCdsResource(new_cluster);
  11731. // Wait for all backends to come online.
  11732. size_t num_rpcs = WaitForAllBackends(0, 2);
  11733. // The load report received at the balancer should be correct.
  11734. std::vector<ClientStats> load_report =
  11735. balancer_->lrs_service()->WaitForLoadReport();
  11736. EXPECT_THAT(
  11737. load_report,
  11738. ::testing::ElementsAre(::testing::AllOf(
  11739. ::testing::Property(&ClientStats::cluster_name, kDefaultClusterName),
  11740. ::testing::Property(
  11741. &ClientStats::locality_stats,
  11742. ::testing::ElementsAre(::testing::Pair(
  11743. "locality0",
  11744. ::testing::AllOf(
  11745. ::testing::Field(&ClientStats::LocalityStats::
  11746. total_successful_requests,
  11747. num_rpcs),
  11748. ::testing::Field(&ClientStats::LocalityStats::
  11749. total_requests_in_progress,
  11750. 0UL),
  11751. ::testing::Field(
  11752. &ClientStats::LocalityStats::total_error_requests,
  11753. 0UL),
  11754. ::testing::Field(
  11755. &ClientStats::LocalityStats::total_issued_requests,
  11756. num_rpcs))))),
  11757. ::testing::Property(&ClientStats::total_dropped_requests, 0UL))));
  11758. // Change RDS resource to point to new cluster.
  11759. RouteConfiguration new_route_config = default_route_config_;
  11760. new_route_config.mutable_virtual_hosts(0)
  11761. ->mutable_routes(0)
  11762. ->mutable_route()
  11763. ->set_cluster(kNewClusterName);
  11764. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
  11765. new_route_config);
  11766. // Wait for all new backends to be used.
  11767. num_rpcs = WaitForAllBackends(2, 4);
  11768. // The load report received at the balancer should be correct.
  11769. load_report = balancer_->lrs_service()->WaitForLoadReport();
  11770. EXPECT_THAT(
  11771. load_report,
  11772. ::testing::ElementsAre(
  11773. ::testing::AllOf(
  11774. ::testing::Property(&ClientStats::cluster_name,
  11775. kDefaultClusterName),
  11776. ::testing::Property(
  11777. &ClientStats::locality_stats,
  11778. ::testing::ElementsAre(::testing::Pair(
  11779. "locality0",
  11780. ::testing::AllOf(
  11781. ::testing::Field(&ClientStats::LocalityStats::
  11782. total_successful_requests,
  11783. ::testing::Lt(num_rpcs)),
  11784. ::testing::Field(&ClientStats::LocalityStats::
  11785. total_requests_in_progress,
  11786. 0UL),
  11787. ::testing::Field(
  11788. &ClientStats::LocalityStats::total_error_requests,
  11789. 0UL),
  11790. ::testing::Field(&ClientStats::LocalityStats::
  11791. total_issued_requests,
  11792. ::testing::Le(num_rpcs)))))),
  11793. ::testing::Property(&ClientStats::total_dropped_requests, 0UL)),
  11794. ::testing::AllOf(
  11795. ::testing::Property(&ClientStats::cluster_name, kNewClusterName),
  11796. ::testing::Property(
  11797. &ClientStats::locality_stats,
  11798. ::testing::ElementsAre(::testing::Pair(
  11799. "locality1",
  11800. ::testing::AllOf(
  11801. ::testing::Field(&ClientStats::LocalityStats::
  11802. total_successful_requests,
  11803. ::testing::Le(num_rpcs)),
  11804. ::testing::Field(&ClientStats::LocalityStats::
  11805. total_requests_in_progress,
  11806. 0UL),
  11807. ::testing::Field(
  11808. &ClientStats::LocalityStats::total_error_requests,
  11809. 0UL),
  11810. ::testing::Field(&ClientStats::LocalityStats::
  11811. total_issued_requests,
  11812. ::testing::Le(num_rpcs)))))),
  11813. ::testing::Property(&ClientStats::total_dropped_requests, 0UL))));
  11814. size_t total_ok = 0;
  11815. for (const ClientStats& client_stats : load_report) {
  11816. total_ok += client_stats.total_successful_requests();
  11817. }
  11818. EXPECT_EQ(total_ok, num_rpcs);
  11819. // The LRS service got a single request, and sent a single response.
  11820. EXPECT_EQ(1U, balancer_->lrs_service()->request_count());
  11821. EXPECT_EQ(1U, balancer_->lrs_service()->response_count());
  11822. }
  11823. class ClientLoadReportingWithDropTest : public XdsEnd2endTest {
  11824. public:
  11825. ClientLoadReportingWithDropTest() : XdsEnd2endTest(4, 20) {}
  11826. void SetUp() override {
  11827. XdsEnd2endTest::SetUp();
  11828. StartAllBackends();
  11829. }
  11830. };
  11831. // Tests that the drop stats are correctly reported by client load reporting.
  11832. TEST_P(ClientLoadReportingWithDropTest, Vanilla) {
  11833. const uint32_t kDropPerMillionForLb = 100000;
  11834. const uint32_t kDropPerMillionForThrottle = 200000;
  11835. const double kErrorTolerance = 0.05;
  11836. const double kDropRateForLb = kDropPerMillionForLb / 1000000.0;
  11837. const double kDropRateForThrottle = kDropPerMillionForThrottle / 1000000.0;
  11838. const double kDropRateForLbAndThrottle =
  11839. kDropRateForLb + (1 - kDropRateForLb) * kDropRateForThrottle;
  11840. const size_t kNumRpcs =
  11841. ComputeIdealNumRpcs(kDropRateForLbAndThrottle, kErrorTolerance);
  11842. const char kStatusMessageDropPrefix[] = "EDS-configured drop: ";
  11843. // The ADS response contains two drop categories.
  11844. EdsResourceArgs args({
  11845. {"locality0", CreateEndpointsForBackends()},
  11846. });
  11847. args.drop_categories = {{kLbDropType, kDropPerMillionForLb},
  11848. {kThrottleDropType, kDropPerMillionForThrottle}};
  11849. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11850. // Send kNumRpcs RPCs and count the drops.
  11851. size_t num_drops =
  11852. SendRpcsAndCountFailuresWithMessage(kNumRpcs, kStatusMessageDropPrefix);
  11853. // The drop rate should be roughly equal to the expectation.
  11854. const double seen_drop_rate = static_cast<double>(num_drops) / kNumRpcs;
  11855. EXPECT_THAT(seen_drop_rate, ::testing::DoubleNear(kDropRateForLbAndThrottle,
  11856. kErrorTolerance));
  11857. // Check client stats.
  11858. ClientStats client_stats;
  11859. do {
  11860. std::vector<ClientStats> load_reports =
  11861. balancer_->lrs_service()->WaitForLoadReport();
  11862. for (const auto& load_report : load_reports) {
  11863. client_stats += load_report;
  11864. }
  11865. } while (client_stats.total_issued_requests() +
  11866. client_stats.total_dropped_requests() <
  11867. kNumRpcs);
  11868. EXPECT_EQ(num_drops, client_stats.total_dropped_requests());
  11869. EXPECT_THAT(static_cast<double>(client_stats.dropped_requests(kLbDropType)) /
  11870. kNumRpcs,
  11871. ::testing::DoubleNear(kDropRateForLb, kErrorTolerance));
  11872. EXPECT_THAT(
  11873. static_cast<double>(client_stats.dropped_requests(kThrottleDropType)) /
  11874. (kNumRpcs * (1 - kDropRateForLb)),
  11875. ::testing::DoubleNear(kDropRateForThrottle, kErrorTolerance));
  11876. }
  11877. class FaultInjectionTest : public XdsEnd2endTest {
  11878. public:
  11879. FaultInjectionTest() : XdsEnd2endTest(1) {}
  11880. void SetUp() override {
  11881. XdsEnd2endTest::SetUp();
  11882. StartAllBackends();
  11883. }
  11884. // Builds a Listener with Fault Injection filter config. If the http_fault
  11885. // is nullptr, then assign an empty filter config. This filter config is
  11886. // required to enable the fault injection features.
  11887. static Listener BuildListenerWithFaultInjection(
  11888. const HTTPFault& http_fault = HTTPFault()) {
  11889. HttpConnectionManager http_connection_manager;
  11890. Listener listener;
  11891. listener.set_name(kServerName);
  11892. HttpFilter* fault_filter = http_connection_manager.add_http_filters();
  11893. fault_filter->set_name("envoy.fault");
  11894. fault_filter->mutable_typed_config()->PackFrom(http_fault);
  11895. HttpFilter* router_filter = http_connection_manager.add_http_filters();
  11896. router_filter->set_name("router");
  11897. router_filter->mutable_typed_config()->PackFrom(
  11898. envoy::extensions::filters::http::router::v3::Router());
  11899. listener.mutable_api_listener()->mutable_api_listener()->PackFrom(
  11900. http_connection_manager);
  11901. return listener;
  11902. }
  11903. RouteConfiguration BuildRouteConfigurationWithFaultInjection(
  11904. const HTTPFault& http_fault) {
  11905. // Package as Any
  11906. google::protobuf::Any filter_config;
  11907. filter_config.PackFrom(http_fault);
  11908. // Plug into the RouteConfiguration
  11909. RouteConfiguration new_route_config = default_route_config_;
  11910. auto* config_map = new_route_config.mutable_virtual_hosts(0)
  11911. ->mutable_routes(0)
  11912. ->mutable_typed_per_filter_config();
  11913. (*config_map)["envoy.fault"] = std::move(filter_config);
  11914. return new_route_config;
  11915. }
  11916. void SetFilterConfig(HTTPFault& http_fault) {
  11917. switch (GetParam().filter_config_setup()) {
  11918. case TestType::FilterConfigSetup::kRouteOverride: {
  11919. Listener listener = BuildListenerWithFaultInjection();
  11920. RouteConfiguration route =
  11921. BuildRouteConfigurationWithFaultInjection(http_fault);
  11922. SetListenerAndRouteConfiguration(balancer_.get(), listener, route);
  11923. break;
  11924. }
  11925. case TestType::FilterConfigSetup::kHTTPConnectionManagerOriginal: {
  11926. Listener listener = BuildListenerWithFaultInjection(http_fault);
  11927. SetListenerAndRouteConfiguration(balancer_.get(), listener,
  11928. default_route_config_);
  11929. }
  11930. };
  11931. }
  11932. };
  11933. // Test to ensure the most basic fault injection config works.
  11934. TEST_P(FaultInjectionTest, XdsFaultInjectionAlwaysAbort) {
  11935. const uint32_t kAbortPercentagePerHundred = 100;
  11936. // Construct the fault injection filter config
  11937. HTTPFault http_fault;
  11938. auto* abort_percentage = http_fault.mutable_abort()->mutable_percentage();
  11939. abort_percentage->set_numerator(kAbortPercentagePerHundred);
  11940. abort_percentage->set_denominator(FractionalPercent::HUNDRED);
  11941. http_fault.mutable_abort()->set_grpc_status(
  11942. static_cast<uint32_t>(StatusCode::ABORTED));
  11943. // Config fault injection via different setup
  11944. SetFilterConfig(http_fault);
  11945. // Fire several RPCs, and expect all of them to be aborted.
  11946. CheckRpcSendFailure(
  11947. CheckRpcSendFailureOptions()
  11948. .set_times(5)
  11949. .set_rpc_options(RpcOptions().set_wait_for_ready(true))
  11950. .set_expected_error_code(StatusCode::ABORTED));
  11951. }
  11952. // Without the listener config, the fault injection won't be enabled.
  11953. TEST_P(FaultInjectionTest, XdsFaultInjectionWithoutListenerFilter) {
  11954. const uint32_t kAbortPercentagePerHundred = 100;
  11955. // Create an EDS resource
  11956. EdsResourceArgs args({
  11957. {"locality0", CreateEndpointsForBackends()},
  11958. });
  11959. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11960. // Construct the fault injection filter config
  11961. HTTPFault http_fault;
  11962. auto* abort_percentage = http_fault.mutable_abort()->mutable_percentage();
  11963. abort_percentage->set_numerator(kAbortPercentagePerHundred);
  11964. abort_percentage->set_denominator(FractionalPercent::HUNDRED);
  11965. http_fault.mutable_abort()->set_grpc_status(
  11966. static_cast<uint32_t>(StatusCode::ABORTED));
  11967. // Turn on fault injection
  11968. RouteConfiguration route =
  11969. BuildRouteConfigurationWithFaultInjection(http_fault);
  11970. SetListenerAndRouteConfiguration(balancer_.get(), default_listener_, route);
  11971. // Fire several RPCs, and expect all of them to be pass.
  11972. CheckRpcSendOk(5, RpcOptions().set_wait_for_ready(true));
  11973. }
  11974. TEST_P(FaultInjectionTest, XdsFaultInjectionPercentageAbort) {
  11975. const uint32_t kAbortPercentagePerHundred = 50;
  11976. const double kAbortRate = kAbortPercentagePerHundred / 100.0;
  11977. const double kErrorTolerance = 0.05;
  11978. const size_t kNumRpcs = ComputeIdealNumRpcs(kAbortRate, kErrorTolerance);
  11979. // Create an EDS resource
  11980. EdsResourceArgs args({
  11981. {"locality0", CreateEndpointsForBackends()},
  11982. });
  11983. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  11984. // Construct the fault injection filter config
  11985. HTTPFault http_fault;
  11986. auto* abort_percentage = http_fault.mutable_abort()->mutable_percentage();
  11987. abort_percentage->set_numerator(kAbortPercentagePerHundred);
  11988. abort_percentage->set_denominator(FractionalPercent::HUNDRED);
  11989. http_fault.mutable_abort()->set_grpc_status(
  11990. static_cast<uint32_t>(StatusCode::ABORTED));
  11991. // Config fault injection via different setup
  11992. SetFilterConfig(http_fault);
  11993. // Send kNumRpcs RPCs and count the aborts.
  11994. size_t num_aborted =
  11995. SendRpcsAndCountFailuresWithMessage(kNumRpcs, "Fault injected");
  11996. // The abort rate should be roughly equal to the expectation.
  11997. const double seen_abort_rate = static_cast<double>(num_aborted) / kNumRpcs;
  11998. EXPECT_THAT(seen_abort_rate,
  11999. ::testing::DoubleNear(kAbortRate, kErrorTolerance));
  12000. }
  12001. TEST_P(FaultInjectionTest, XdsFaultInjectionPercentageAbortViaHeaders) {
  12002. const uint32_t kAbortPercentageCap = 100;
  12003. const uint32_t kAbortPercentage = 50;
  12004. const double kAbortRate = kAbortPercentage / 100.0;
  12005. const double kErrorTolerance = 0.05;
  12006. const size_t kNumRpcs = ComputeIdealNumRpcs(kAbortRate, kErrorTolerance);
  12007. // Create an EDS resource
  12008. EdsResourceArgs args({
  12009. {"locality0", CreateEndpointsForBackends()},
  12010. });
  12011. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  12012. // Construct the fault injection filter config
  12013. HTTPFault http_fault;
  12014. http_fault.mutable_abort()->mutable_header_abort();
  12015. http_fault.mutable_abort()->mutable_percentage()->set_numerator(
  12016. kAbortPercentageCap);
  12017. // Config fault injection via different setup
  12018. SetFilterConfig(http_fault);
  12019. // Send kNumRpcs RPCs and count the aborts.
  12020. std::vector<std::pair<std::string, std::string>> metadata = {
  12021. {"x-envoy-fault-abort-grpc-request", "10"},
  12022. {"x-envoy-fault-abort-percentage", std::to_string(kAbortPercentage)},
  12023. };
  12024. size_t num_aborted = SendRpcsAndCountFailuresWithMessage(
  12025. kNumRpcs, "Fault injected", RpcOptions().set_metadata(metadata));
  12026. // The abort rate should be roughly equal to the expectation.
  12027. const double seen_abort_rate = static_cast<double>(num_aborted) / kNumRpcs;
  12028. EXPECT_THAT(seen_abort_rate,
  12029. ::testing::DoubleNear(kAbortRate, kErrorTolerance));
  12030. }
  12031. TEST_P(FaultInjectionTest, XdsFaultInjectionPercentageDelay) {
  12032. const uint32_t kRpcTimeoutMilliseconds = grpc_test_slowdown_factor() * 3000;
  12033. const uint32_t kFixedDelaySeconds = 100;
  12034. const uint32_t kDelayPercentagePerHundred = 50;
  12035. const double kDelayRate = kDelayPercentagePerHundred / 100.0;
  12036. const double kErrorTolerance = 0.05;
  12037. const size_t kNumRpcs = ComputeIdealNumRpcs(kDelayRate, kErrorTolerance);
  12038. const size_t kMaxConcurrentRequests = kNumRpcs;
  12039. // Create an EDS resource
  12040. EdsResourceArgs args({
  12041. {"locality0", CreateEndpointsForBackends()},
  12042. });
  12043. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  12044. // Loosen the max concurrent request limit
  12045. Cluster cluster = default_cluster_;
  12046. auto* threshold = cluster.mutable_circuit_breakers()->add_thresholds();
  12047. threshold->set_priority(RoutingPriority::DEFAULT);
  12048. threshold->mutable_max_requests()->set_value(kMaxConcurrentRequests);
  12049. balancer_->ads_service()->SetCdsResource(cluster);
  12050. // Construct the fault injection filter config
  12051. HTTPFault http_fault;
  12052. auto* delay_percentage = http_fault.mutable_delay()->mutable_percentage();
  12053. delay_percentage->set_numerator(kDelayPercentagePerHundred);
  12054. delay_percentage->set_denominator(FractionalPercent::HUNDRED);
  12055. auto* fixed_delay = http_fault.mutable_delay()->mutable_fixed_delay();
  12056. fixed_delay->set_seconds(kFixedDelaySeconds);
  12057. // Config fault injection via different setup
  12058. SetFilterConfig(http_fault);
  12059. // Send kNumRpcs RPCs and count the delays.
  12060. RpcOptions rpc_options = RpcOptions()
  12061. .set_timeout_ms(kRpcTimeoutMilliseconds)
  12062. .set_skip_cancelled_check(true);
  12063. std::vector<ConcurrentRpc> rpcs =
  12064. SendConcurrentRpcs(stub_.get(), kNumRpcs, rpc_options);
  12065. size_t num_delayed = 0;
  12066. for (auto& rpc : rpcs) {
  12067. if (rpc.status.error_code() == StatusCode::OK) continue;
  12068. EXPECT_EQ(StatusCode::DEADLINE_EXCEEDED, rpc.status.error_code());
  12069. ++num_delayed;
  12070. }
  12071. // The delay rate should be roughly equal to the expectation.
  12072. const double seen_delay_rate = static_cast<double>(num_delayed) / kNumRpcs;
  12073. EXPECT_THAT(seen_delay_rate,
  12074. ::testing::DoubleNear(kDelayRate, kErrorTolerance));
  12075. }
  12076. TEST_P(FaultInjectionTest, XdsFaultInjectionPercentageDelayViaHeaders) {
  12077. const uint32_t kFixedDelayMilliseconds = 100000;
  12078. const uint32_t kRpcTimeoutMilliseconds = grpc_test_slowdown_factor() * 3000;
  12079. const uint32_t kDelayPercentageCap = 100;
  12080. const uint32_t kDelayPercentage = 50;
  12081. const double kDelayRate = kDelayPercentage / 100.0;
  12082. const double kErrorTolerance = 0.05;
  12083. const size_t kNumRpcs = ComputeIdealNumRpcs(kDelayRate, kErrorTolerance);
  12084. const size_t kMaxConcurrentRequests = kNumRpcs;
  12085. // Create an EDS resource
  12086. EdsResourceArgs args({
  12087. {"locality0", CreateEndpointsForBackends()},
  12088. });
  12089. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  12090. // Loosen the max concurrent request limit
  12091. Cluster cluster = default_cluster_;
  12092. auto* threshold = cluster.mutable_circuit_breakers()->add_thresholds();
  12093. threshold->set_priority(RoutingPriority::DEFAULT);
  12094. threshold->mutable_max_requests()->set_value(kMaxConcurrentRequests);
  12095. balancer_->ads_service()->SetCdsResource(cluster);
  12096. // Construct the fault injection filter config
  12097. HTTPFault http_fault;
  12098. http_fault.mutable_delay()->mutable_header_delay();
  12099. http_fault.mutable_delay()->mutable_percentage()->set_numerator(
  12100. kDelayPercentageCap);
  12101. // Config fault injection via different setup
  12102. SetFilterConfig(http_fault);
  12103. // Send kNumRpcs RPCs and count the delays.
  12104. std::vector<std::pair<std::string, std::string>> metadata = {
  12105. {"x-envoy-fault-delay-request", std::to_string(kFixedDelayMilliseconds)},
  12106. {"x-envoy-fault-delay-request-percentage",
  12107. std::to_string(kDelayPercentage)},
  12108. };
  12109. RpcOptions rpc_options = RpcOptions()
  12110. .set_metadata(metadata)
  12111. .set_timeout_ms(kRpcTimeoutMilliseconds)
  12112. .set_skip_cancelled_check(true);
  12113. std::vector<ConcurrentRpc> rpcs =
  12114. SendConcurrentRpcs(stub_.get(), kNumRpcs, rpc_options);
  12115. size_t num_delayed = 0;
  12116. for (auto& rpc : rpcs) {
  12117. if (rpc.status.error_code() == StatusCode::OK) continue;
  12118. EXPECT_EQ(StatusCode::DEADLINE_EXCEEDED, rpc.status.error_code());
  12119. ++num_delayed;
  12120. }
  12121. // The delay rate should be roughly equal to the expectation.
  12122. const double seen_delay_rate = static_cast<double>(num_delayed) / kNumRpcs;
  12123. EXPECT_THAT(seen_delay_rate,
  12124. ::testing::DoubleNear(kDelayRate, kErrorTolerance));
  12125. }
  12126. TEST_P(FaultInjectionTest, XdsFaultInjectionAbortAfterDelayForStreamCall) {
  12127. const uint32_t kFixedDelaySeconds = 1;
  12128. const uint32_t kRpcTimeoutMilliseconds = 100 * 1000; // 100s should not reach
  12129. // Create an EDS resource
  12130. EdsResourceArgs args({
  12131. {"locality0", CreateEndpointsForBackends()},
  12132. });
  12133. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  12134. // Construct the fault injection filter config
  12135. HTTPFault http_fault;
  12136. auto* abort_percentage = http_fault.mutable_abort()->mutable_percentage();
  12137. abort_percentage->set_numerator(100); // Always inject ABORT!
  12138. abort_percentage->set_denominator(FractionalPercent::HUNDRED);
  12139. http_fault.mutable_abort()->set_grpc_status(
  12140. static_cast<uint32_t>(StatusCode::ABORTED));
  12141. auto* delay_percentage = http_fault.mutable_delay()->mutable_percentage();
  12142. delay_percentage->set_numerator(100); // Always inject DELAY!
  12143. delay_percentage->set_denominator(FractionalPercent::HUNDRED);
  12144. auto* fixed_delay = http_fault.mutable_delay()->mutable_fixed_delay();
  12145. fixed_delay->set_seconds(kFixedDelaySeconds);
  12146. // Config fault injection via different setup
  12147. SetFilterConfig(http_fault);
  12148. // Send a stream RPC and check its status code
  12149. ClientContext context;
  12150. context.set_deadline(
  12151. grpc_timeout_milliseconds_to_deadline(kRpcTimeoutMilliseconds));
  12152. auto stream = stub_->BidiStream(&context);
  12153. stream->WritesDone();
  12154. auto status = stream->Finish();
  12155. EXPECT_EQ(StatusCode::ABORTED, status.error_code())
  12156. << status.error_message() << ", " << status.error_details() << ", "
  12157. << context.debug_error_string();
  12158. }
  12159. TEST_P(FaultInjectionTest, XdsFaultInjectionAlwaysDelayPercentageAbort) {
  12160. const uint32_t kAbortPercentagePerHundred = 50;
  12161. const double kAbortRate = kAbortPercentagePerHundred / 100.0;
  12162. const uint32_t kFixedDelaySeconds = 1;
  12163. const uint32_t kRpcTimeoutMilliseconds = 100 * 1000; // 100s should not reach
  12164. const uint32_t kConnectionTimeoutMilliseconds =
  12165. 10 * 1000; // 10s should not reach
  12166. const double kErrorTolerance = 0.05;
  12167. const size_t kNumRpcs = ComputeIdealNumRpcs(kAbortRate, kErrorTolerance);
  12168. const size_t kMaxConcurrentRequests = kNumRpcs;
  12169. // Create an EDS resource
  12170. EdsResourceArgs args({
  12171. {"locality0", CreateEndpointsForBackends()},
  12172. });
  12173. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  12174. // Loosen the max concurrent request limit
  12175. Cluster cluster = default_cluster_;
  12176. auto* threshold = cluster.mutable_circuit_breakers()->add_thresholds();
  12177. threshold->set_priority(RoutingPriority::DEFAULT);
  12178. threshold->mutable_max_requests()->set_value(kMaxConcurrentRequests);
  12179. balancer_->ads_service()->SetCdsResource(cluster);
  12180. // Construct the fault injection filter config
  12181. HTTPFault http_fault;
  12182. auto* abort_percentage = http_fault.mutable_abort()->mutable_percentage();
  12183. abort_percentage->set_numerator(kAbortPercentagePerHundred);
  12184. abort_percentage->set_denominator(FractionalPercent::HUNDRED);
  12185. http_fault.mutable_abort()->set_grpc_status(
  12186. static_cast<uint32_t>(StatusCode::ABORTED));
  12187. auto* delay_percentage = http_fault.mutable_delay()->mutable_percentage();
  12188. delay_percentage->set_numerator(1000000); // Always inject DELAY!
  12189. delay_percentage->set_denominator(FractionalPercent::MILLION);
  12190. auto* fixed_delay = http_fault.mutable_delay()->mutable_fixed_delay();
  12191. fixed_delay->set_seconds(kFixedDelaySeconds);
  12192. // Config fault injection via different setup
  12193. SetFilterConfig(http_fault);
  12194. // Allow the channel to connect to one backends, so the herd of queued RPCs
  12195. // won't be executed on the same ExecCtx object and using the cached Now()
  12196. // value, which causes millisecond level delay error.
  12197. channel_->WaitForConnected(
  12198. grpc_timeout_milliseconds_to_deadline(kConnectionTimeoutMilliseconds));
  12199. // Send kNumRpcs RPCs and count the aborts.
  12200. int num_aborted = 0;
  12201. RpcOptions rpc_options = RpcOptions().set_timeout_ms(kRpcTimeoutMilliseconds);
  12202. std::vector<ConcurrentRpc> rpcs =
  12203. SendConcurrentRpcs(stub_.get(), kNumRpcs, rpc_options);
  12204. for (auto& rpc : rpcs) {
  12205. EXPECT_GE(rpc.elapsed_time,
  12206. grpc_core::Duration::Seconds(kFixedDelaySeconds));
  12207. if (rpc.status.error_code() == StatusCode::OK) continue;
  12208. EXPECT_EQ("Fault injected", rpc.status.error_message());
  12209. ++num_aborted;
  12210. }
  12211. // The abort rate should be roughly equal to the expectation.
  12212. const double seen_abort_rate = static_cast<double>(num_aborted) / kNumRpcs;
  12213. EXPECT_THAT(seen_abort_rate,
  12214. ::testing::DoubleNear(kAbortRate, kErrorTolerance));
  12215. }
  12216. // This test and the above test apply different denominators to delay and
  12217. // abort. This ensures that we are using the right denominator for each
  12218. // injected fault in our code.
  12219. TEST_P(FaultInjectionTest,
  12220. XdsFaultInjectionAlwaysDelayPercentageAbortSwitchDenominator) {
  12221. const uint32_t kAbortPercentagePerMillion = 500000;
  12222. const double kAbortRate = kAbortPercentagePerMillion / 1000000.0;
  12223. const uint32_t kFixedDelaySeconds = 1; // 1s
  12224. const uint32_t kRpcTimeoutMilliseconds = 100 * 1000; // 100s should not reach
  12225. const uint32_t kConnectionTimeoutMilliseconds =
  12226. 10 * 1000; // 10s should not reach
  12227. const double kErrorTolerance = 0.05;
  12228. const size_t kNumRpcs = ComputeIdealNumRpcs(kAbortRate, kErrorTolerance);
  12229. const size_t kMaxConcurrentRequests = kNumRpcs;
  12230. // Create an EDS resource
  12231. EdsResourceArgs args({
  12232. {"locality0", CreateEndpointsForBackends()},
  12233. });
  12234. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  12235. // Loosen the max concurrent request limit
  12236. Cluster cluster = default_cluster_;
  12237. auto* threshold = cluster.mutable_circuit_breakers()->add_thresholds();
  12238. threshold->set_priority(RoutingPriority::DEFAULT);
  12239. threshold->mutable_max_requests()->set_value(kMaxConcurrentRequests);
  12240. balancer_->ads_service()->SetCdsResource(cluster);
  12241. // Construct the fault injection filter config
  12242. HTTPFault http_fault;
  12243. auto* abort_percentage = http_fault.mutable_abort()->mutable_percentage();
  12244. abort_percentage->set_numerator(kAbortPercentagePerMillion);
  12245. abort_percentage->set_denominator(FractionalPercent::MILLION);
  12246. http_fault.mutable_abort()->set_grpc_status(
  12247. static_cast<uint32_t>(StatusCode::ABORTED));
  12248. auto* delay_percentage = http_fault.mutable_delay()->mutable_percentage();
  12249. delay_percentage->set_numerator(100); // Always inject DELAY!
  12250. delay_percentage->set_denominator(FractionalPercent::HUNDRED);
  12251. auto* fixed_delay = http_fault.mutable_delay()->mutable_fixed_delay();
  12252. fixed_delay->set_seconds(kFixedDelaySeconds);
  12253. // Config fault injection via different setup
  12254. SetFilterConfig(http_fault);
  12255. // Allow the channel to connect to one backends, so the herd of queued RPCs
  12256. // won't be executed on the same ExecCtx object and using the cached Now()
  12257. // value, which causes millisecond level delay error.
  12258. channel_->WaitForConnected(
  12259. grpc_timeout_milliseconds_to_deadline(kConnectionTimeoutMilliseconds));
  12260. // Send kNumRpcs RPCs and count the aborts.
  12261. int num_aborted = 0;
  12262. RpcOptions rpc_options = RpcOptions().set_timeout_ms(kRpcTimeoutMilliseconds);
  12263. std::vector<ConcurrentRpc> rpcs =
  12264. SendConcurrentRpcs(stub_.get(), kNumRpcs, rpc_options);
  12265. for (auto& rpc : rpcs) {
  12266. EXPECT_GE(rpc.elapsed_time,
  12267. grpc_core::Duration::Seconds(kFixedDelaySeconds));
  12268. if (rpc.status.error_code() == StatusCode::OK) continue;
  12269. EXPECT_EQ("Fault injected", rpc.status.error_message());
  12270. ++num_aborted;
  12271. }
  12272. // The abort rate should be roughly equal to the expectation.
  12273. const double seen_abort_rate = static_cast<double>(num_aborted) / kNumRpcs;
  12274. EXPECT_THAT(seen_abort_rate,
  12275. ::testing::DoubleNear(kAbortRate, kErrorTolerance));
  12276. }
  12277. TEST_P(FaultInjectionTest, XdsFaultInjectionMaxFault) {
  12278. const uint32_t kMaxFault = 10;
  12279. const uint32_t kNumRpcs = 30; // kNumRpcs should be bigger than kMaxFault
  12280. const uint32_t kRpcTimeoutMs = 4000; // 4 seconds
  12281. const uint32_t kLongDelaySeconds = 100; // 100 seconds
  12282. const uint32_t kAlwaysDelayPercentage = 100;
  12283. // Create an EDS resource
  12284. EdsResourceArgs args({
  12285. {"locality0", CreateEndpointsForBackends()},
  12286. });
  12287. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  12288. // Construct the fault injection filter config
  12289. HTTPFault http_fault;
  12290. auto* delay_percentage = http_fault.mutable_delay()->mutable_percentage();
  12291. delay_percentage->set_numerator(
  12292. kAlwaysDelayPercentage); // Always inject DELAY!
  12293. delay_percentage->set_denominator(FractionalPercent::HUNDRED);
  12294. auto* fixed_delay = http_fault.mutable_delay()->mutable_fixed_delay();
  12295. fixed_delay->set_seconds(kLongDelaySeconds);
  12296. http_fault.mutable_max_active_faults()->set_value(kMaxFault);
  12297. // Config fault injection via different setup
  12298. SetFilterConfig(http_fault);
  12299. // Sends a batch of long running RPCs with long timeout to consume all
  12300. // active faults quota.
  12301. int num_delayed = 0;
  12302. RpcOptions rpc_options = RpcOptions().set_timeout_ms(kRpcTimeoutMs);
  12303. std::vector<ConcurrentRpc> rpcs =
  12304. SendConcurrentRpcs(stub_.get(), kNumRpcs, rpc_options);
  12305. for (auto& rpc : rpcs) {
  12306. if (rpc.status.error_code() == StatusCode::OK) continue;
  12307. EXPECT_EQ(StatusCode::DEADLINE_EXCEEDED, rpc.status.error_code());
  12308. ++num_delayed;
  12309. }
  12310. // Only kMaxFault number of RPC should be fault injected..
  12311. EXPECT_EQ(kMaxFault, num_delayed);
  12312. }
  12313. TEST_P(FaultInjectionTest, XdsFaultInjectionBidiStreamDelayOk) {
  12314. // kRpcTimeoutMilliseconds is 10s should never be reached.
  12315. const uint32_t kRpcTimeoutMilliseconds = grpc_test_slowdown_factor() * 10000;
  12316. const uint32_t kFixedDelaySeconds = 1;
  12317. const uint32_t kDelayPercentagePerHundred = 100;
  12318. // Create an EDS resource
  12319. EdsResourceArgs args({
  12320. {"locality0", CreateEndpointsForBackends()},
  12321. });
  12322. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  12323. // Construct the fault injection filter config
  12324. HTTPFault http_fault;
  12325. auto* delay_percentage = http_fault.mutable_delay()->mutable_percentage();
  12326. delay_percentage->set_numerator(kDelayPercentagePerHundred);
  12327. delay_percentage->set_denominator(FractionalPercent::HUNDRED);
  12328. auto* fixed_delay = http_fault.mutable_delay()->mutable_fixed_delay();
  12329. fixed_delay->set_seconds(kFixedDelaySeconds);
  12330. // Config fault injection via different setup
  12331. SetFilterConfig(http_fault);
  12332. ClientContext context;
  12333. context.set_deadline(
  12334. grpc_timeout_milliseconds_to_deadline(kRpcTimeoutMilliseconds));
  12335. auto stream = stub_->BidiStream(&context);
  12336. stream->WritesDone();
  12337. auto status = stream->Finish();
  12338. EXPECT_TRUE(status.ok()) << status.error_message() << ", "
  12339. << status.error_details() << ", "
  12340. << context.debug_error_string();
  12341. }
  12342. // This case catches a bug in the retry code that was triggered by a bad
  12343. // interaction with the FI code. See https://github.com/grpc/grpc/pull/27217
  12344. // for description.
  12345. TEST_P(FaultInjectionTest, XdsFaultInjectionBidiStreamDelayError) {
  12346. const uint32_t kRpcTimeoutMilliseconds = grpc_test_slowdown_factor() * 500;
  12347. const uint32_t kFixedDelaySeconds = 100;
  12348. const uint32_t kDelayPercentagePerHundred = 100;
  12349. // Create an EDS resource
  12350. EdsResourceArgs args({
  12351. {"locality0", CreateEndpointsForBackends()},
  12352. });
  12353. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  12354. // Construct the fault injection filter config
  12355. HTTPFault http_fault;
  12356. auto* delay_percentage = http_fault.mutable_delay()->mutable_percentage();
  12357. delay_percentage->set_numerator(kDelayPercentagePerHundred);
  12358. delay_percentage->set_denominator(FractionalPercent::HUNDRED);
  12359. auto* fixed_delay = http_fault.mutable_delay()->mutable_fixed_delay();
  12360. fixed_delay->set_seconds(kFixedDelaySeconds);
  12361. // Config fault injection via different setup
  12362. SetFilterConfig(http_fault);
  12363. ClientContext context;
  12364. context.set_deadline(
  12365. grpc_timeout_milliseconds_to_deadline(kRpcTimeoutMilliseconds));
  12366. auto stream = stub_->BidiStream(&context);
  12367. stream->WritesDone();
  12368. auto status = stream->Finish();
  12369. EXPECT_EQ(StatusCode::DEADLINE_EXCEEDED, status.error_code())
  12370. << status.error_message() << ", " << status.error_details() << ", "
  12371. << context.debug_error_string();
  12372. }
  12373. class BootstrapSourceTest : public XdsEnd2endTest {
  12374. public:
  12375. BootstrapSourceTest() : XdsEnd2endTest(4) {}
  12376. void SetUp() override {
  12377. XdsEnd2endTest::SetUp();
  12378. StartAllBackends();
  12379. }
  12380. };
  12381. TEST_P(BootstrapSourceTest, Vanilla) {
  12382. EdsResourceArgs args({
  12383. {"locality0", CreateEndpointsForBackends()},
  12384. });
  12385. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  12386. WaitForAllBackends();
  12387. }
  12388. #ifndef DISABLED_XDS_PROTO_IN_CC
  12389. class ClientStatusDiscoveryServiceTest : public XdsEnd2endTest {
  12390. public:
  12391. explicit ClientStatusDiscoveryServiceTest(
  12392. int xds_resource_does_not_exist_timeout_ms = 0)
  12393. : XdsEnd2endTest(1, 100, xds_resource_does_not_exist_timeout_ms) {
  12394. admin_server_thread_ = absl::make_unique<AdminServerThread>(this);
  12395. admin_server_thread_->Start();
  12396. std::string admin_server_address = absl::StrCat(
  12397. ipv6_only_ ? "[::1]:" : "127.0.0.1:", admin_server_thread_->port());
  12398. admin_channel_ = grpc::CreateChannel(
  12399. admin_server_address,
  12400. std::make_shared<SecureChannelCredentials>(
  12401. grpc_fake_transport_security_credentials_create()));
  12402. csds_stub_ =
  12403. envoy::service::status::v3::ClientStatusDiscoveryService::NewStub(
  12404. admin_channel_);
  12405. if (GetParam().use_csds_streaming()) {
  12406. stream_ = csds_stub_->StreamClientStatus(&stream_context_);
  12407. }
  12408. }
  12409. void SetUp() override {
  12410. XdsEnd2endTest::SetUp();
  12411. StartAllBackends();
  12412. }
  12413. ~ClientStatusDiscoveryServiceTest() override {
  12414. if (stream_ != nullptr) {
  12415. EXPECT_TRUE(stream_->WritesDone());
  12416. Status status = stream_->Finish();
  12417. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  12418. << " message=" << status.error_message();
  12419. }
  12420. admin_server_thread_->Shutdown();
  12421. }
  12422. envoy::service::status::v3::ClientStatusResponse FetchCsdsResponse() {
  12423. envoy::service::status::v3::ClientStatusResponse response;
  12424. if (!GetParam().use_csds_streaming()) {
  12425. // Fetch through unary pulls
  12426. ClientContext context;
  12427. Status status = csds_stub_->FetchClientStatus(
  12428. &context, envoy::service::status::v3::ClientStatusRequest(),
  12429. &response);
  12430. EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
  12431. << " message=" << status.error_message();
  12432. } else {
  12433. // Fetch through streaming pulls
  12434. EXPECT_TRUE(
  12435. stream_->Write(envoy::service::status::v3::ClientStatusRequest()));
  12436. EXPECT_TRUE(stream_->Read(&response));
  12437. }
  12438. return response;
  12439. }
  12440. private:
  12441. std::unique_ptr<AdminServerThread> admin_server_thread_;
  12442. std::shared_ptr<Channel> admin_channel_;
  12443. std::unique_ptr<
  12444. envoy::service::status::v3::ClientStatusDiscoveryService::Stub>
  12445. csds_stub_;
  12446. ClientContext stream_context_;
  12447. std::unique_ptr<
  12448. ClientReaderWriter<envoy::service::status::v3::ClientStatusRequest,
  12449. envoy::service::status::v3::ClientStatusResponse>>
  12450. stream_;
  12451. };
  12452. MATCHER_P4(EqNode, id, user_agent_name, user_agent_version, client_features,
  12453. "equals Node") {
  12454. bool ok = true;
  12455. ok &= ::testing::ExplainMatchResult(id, arg.id(), result_listener);
  12456. ok &= ::testing::ExplainMatchResult(user_agent_name, arg.user_agent_name(),
  12457. result_listener);
  12458. ok &= ::testing::ExplainMatchResult(
  12459. user_agent_version, arg.user_agent_version(), result_listener);
  12460. ok &= ::testing::ExplainMatchResult(client_features, arg.client_features(),
  12461. result_listener);
  12462. return ok;
  12463. }
  12464. MATCHER_P6(EqGenericXdsConfig, type_url, name, version_info, xds_config,
  12465. client_status, error_state, "equals GenericXdsConfig") {
  12466. bool ok = true;
  12467. ok &=
  12468. ::testing::ExplainMatchResult(type_url, arg.type_url(), result_listener);
  12469. ok &= ::testing::ExplainMatchResult(name, arg.name(), result_listener);
  12470. ok &= ::testing::ExplainMatchResult(version_info, arg.version_info(),
  12471. result_listener);
  12472. ok &= ::testing::ExplainMatchResult(xds_config, arg.xds_config(),
  12473. result_listener);
  12474. ok &= ::testing::ExplainMatchResult(client_status, arg.client_status(),
  12475. result_listener);
  12476. ok &= ::testing::ExplainMatchResult(error_state, arg.error_state(),
  12477. result_listener);
  12478. return ok;
  12479. }
  12480. MATCHER_P2(EqListener, name, api_listener, "equals Listener") {
  12481. bool ok = true;
  12482. ok &= ::testing::ExplainMatchResult(name, arg.name(), result_listener);
  12483. ok &= ::testing::ExplainMatchResult(
  12484. api_listener, arg.api_listener().api_listener(), result_listener);
  12485. return ok;
  12486. }
  12487. MATCHER_P(EqHttpConnectionManagerNotRds, route_config,
  12488. "equals HttpConnectionManager") {
  12489. bool ok = true;
  12490. ok &= ::testing::ExplainMatchResult(route_config, arg.route_config(),
  12491. result_listener);
  12492. return ok;
  12493. }
  12494. MATCHER_P(EqRouteConfigurationName, name, "equals RouteConfiguration") {
  12495. bool ok = true;
  12496. ok &= ::testing::ExplainMatchResult(name, arg.name(), result_listener);
  12497. return ok;
  12498. }
  12499. MATCHER_P2(EqRouteConfiguration, name, cluster_name,
  12500. "equals RouteConfiguration") {
  12501. bool ok = true;
  12502. ok &= ::testing::ExplainMatchResult(name, arg.name(), result_listener);
  12503. ok &= ::testing::ExplainMatchResult(
  12504. ::testing::ElementsAre(::testing::Property(
  12505. &envoy::config::route::v3::VirtualHost::routes,
  12506. ::testing::ElementsAre(::testing::Property(
  12507. &envoy::config::route::v3::Route::route,
  12508. ::testing::Property(
  12509. &envoy::config::route::v3::RouteAction::cluster,
  12510. cluster_name))))),
  12511. arg.virtual_hosts(), result_listener);
  12512. return ok;
  12513. }
  12514. MATCHER_P(EqCluster, name, "equals Cluster") {
  12515. bool ok = true;
  12516. ok &= ::testing::ExplainMatchResult(name, arg.name(), result_listener);
  12517. return ok;
  12518. }
  12519. MATCHER_P(EqEndpoint, port, "equals Endpoint") {
  12520. bool ok = true;
  12521. ok &= ::testing::ExplainMatchResult(
  12522. port, arg.address().socket_address().port_value(), result_listener);
  12523. return ok;
  12524. }
  12525. MATCHER_P2(EqLocalityLbEndpoints, port, weight, "equals LocalityLbEndpoints") {
  12526. bool ok = true;
  12527. ok &= ::testing::ExplainMatchResult(
  12528. ::testing::ElementsAre(::testing::Property(
  12529. &envoy::config::endpoint::v3::LbEndpoint::endpoint,
  12530. EqEndpoint(port))),
  12531. arg.lb_endpoints(), result_listener);
  12532. ok &= ::testing::ExplainMatchResult(
  12533. weight, arg.load_balancing_weight().value(), result_listener);
  12534. return ok;
  12535. }
  12536. MATCHER_P(EqClusterLoadAssignmentName, cluster_name,
  12537. "equals ClusterLoadAssignment") {
  12538. bool ok = true;
  12539. ok &= ::testing::ExplainMatchResult(cluster_name, arg.cluster_name(),
  12540. result_listener);
  12541. return ok;
  12542. }
  12543. MATCHER_P3(EqClusterLoadAssignment, cluster_name, port, weight,
  12544. "equals ClusterLoadAssignment") {
  12545. bool ok = true;
  12546. ok &= ::testing::ExplainMatchResult(cluster_name, arg.cluster_name(),
  12547. result_listener);
  12548. ok &= ::testing::ExplainMatchResult(
  12549. ::testing::ElementsAre(EqLocalityLbEndpoints(port, weight)),
  12550. arg.endpoints(), result_listener);
  12551. return ok;
  12552. }
  12553. MATCHER_P2(EqUpdateFailureState, details, version_info,
  12554. "equals UpdateFailureState") {
  12555. bool ok = true;
  12556. ok &= ::testing::ExplainMatchResult(details, arg.details(), result_listener);
  12557. ok &= ::testing::ExplainMatchResult(version_info, arg.version_info(),
  12558. result_listener);
  12559. return ok;
  12560. }
  12561. MATCHER_P(UnpackListener, matcher, "is a Listener") {
  12562. Listener config;
  12563. if (!::testing::ExplainMatchResult(true, arg.UnpackTo(&config),
  12564. result_listener)) {
  12565. return false;
  12566. }
  12567. return ::testing::ExplainMatchResult(matcher, config, result_listener);
  12568. }
  12569. MATCHER_P(UnpackRouteConfiguration, matcher, "is a RouteConfiguration") {
  12570. RouteConfiguration config;
  12571. if (!::testing::ExplainMatchResult(true, arg.UnpackTo(&config),
  12572. result_listener)) {
  12573. return false;
  12574. }
  12575. return ::testing::ExplainMatchResult(matcher, config, result_listener);
  12576. }
  12577. MATCHER_P(UnpackHttpConnectionManager, matcher, "is a HttpConnectionManager") {
  12578. HttpConnectionManager config;
  12579. if (!::testing::ExplainMatchResult(true, arg.UnpackTo(&config),
  12580. result_listener)) {
  12581. return false;
  12582. }
  12583. return ::testing::ExplainMatchResult(matcher, config, result_listener);
  12584. }
  12585. MATCHER_P(UnpackCluster, matcher, "is a Cluster") {
  12586. Cluster config;
  12587. if (!::testing::ExplainMatchResult(true, arg.UnpackTo(&config),
  12588. result_listener)) {
  12589. return false;
  12590. }
  12591. return ::testing::ExplainMatchResult(matcher, config, result_listener);
  12592. }
  12593. MATCHER_P(UnpackClusterLoadAssignment, matcher, "is a ClusterLoadAssignment") {
  12594. ClusterLoadAssignment config;
  12595. if (!::testing::ExplainMatchResult(true, arg.UnpackTo(&config),
  12596. result_listener)) {
  12597. return false;
  12598. }
  12599. return ::testing::ExplainMatchResult(matcher, config, result_listener);
  12600. }
  12601. MATCHER(IsRdsEnabledHCM, "is a RDS enabled HttpConnectionManager") {
  12602. return ::testing::ExplainMatchResult(
  12603. UnpackHttpConnectionManager(
  12604. ::testing::Property(&HttpConnectionManager::has_rds, true)),
  12605. arg, result_listener);
  12606. }
  12607. MATCHER_P2(EqNoRdsHCM, route_configuration_name, cluster_name,
  12608. "equals RDS disabled HttpConnectionManager") {
  12609. return ::testing::ExplainMatchResult(
  12610. UnpackHttpConnectionManager(EqHttpConnectionManagerNotRds(
  12611. EqRouteConfiguration(route_configuration_name, cluster_name))),
  12612. arg, result_listener);
  12613. }
  12614. TEST_P(ClientStatusDiscoveryServiceTest, XdsConfigDumpVanilla) {
  12615. const size_t kNumRpcs = 5;
  12616. EdsResourceArgs args({{"locality0", CreateEndpointsForBackends(0, 1)}});
  12617. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  12618. // Send several RPCs to ensure the xDS setup works
  12619. CheckRpcSendOk(kNumRpcs);
  12620. // Fetches the client config
  12621. auto csds_response = FetchCsdsResponse();
  12622. gpr_log(GPR_INFO, "xDS config dump: %s", csds_response.DebugString().c_str());
  12623. EXPECT_EQ(1, csds_response.config_size());
  12624. const auto& client_config = csds_response.config(0);
  12625. // Validate the Node information
  12626. EXPECT_THAT(client_config.node(),
  12627. EqNode("xds_end2end_test", ::testing::HasSubstr("C-core"),
  12628. ::testing::HasSubstr(grpc_version_string()),
  12629. ::testing::ElementsAre(
  12630. "envoy.lb.does_not_support_overprovisioning")));
  12631. // Listener matcher depends on whether RDS is enabled.
  12632. ::testing::Matcher<google::protobuf::Any> api_listener_matcher;
  12633. if (GetParam().enable_rds_testing()) {
  12634. api_listener_matcher = IsRdsEnabledHCM();
  12635. } else {
  12636. api_listener_matcher =
  12637. EqNoRdsHCM(kDefaultRouteConfigurationName, kDefaultClusterName);
  12638. }
  12639. // Construct list of all matchers.
  12640. std::vector<::testing::Matcher<
  12641. envoy::service::status::v3::ClientConfig_GenericXdsConfig>>
  12642. matchers = {
  12643. // Listener
  12644. EqGenericXdsConfig(
  12645. kLdsTypeUrl, kServerName, "1",
  12646. UnpackListener(EqListener(kServerName, api_listener_matcher)),
  12647. ClientResourceStatus::ACKED, ::testing::_),
  12648. // Cluster
  12649. EqGenericXdsConfig(kCdsTypeUrl, kDefaultClusterName, "1",
  12650. UnpackCluster(EqCluster(kDefaultClusterName)),
  12651. ClientResourceStatus::ACKED, ::testing::_),
  12652. // ClusterLoadAssignment
  12653. EqGenericXdsConfig(
  12654. kEdsTypeUrl, kDefaultEdsServiceName, "1",
  12655. UnpackClusterLoadAssignment(EqClusterLoadAssignment(
  12656. kDefaultEdsServiceName, backends_[0]->port(),
  12657. kDefaultLocalityWeight)),
  12658. ClientResourceStatus::ACKED, ::testing::_),
  12659. };
  12660. // If RDS is enabled, add matcher for RDS resource.
  12661. if (GetParam().enable_rds_testing()) {
  12662. matchers.push_back(EqGenericXdsConfig(
  12663. kRdsTypeUrl, kDefaultRouteConfigurationName, "1",
  12664. UnpackRouteConfiguration(EqRouteConfiguration(
  12665. kDefaultRouteConfigurationName, kDefaultClusterName)),
  12666. ClientResourceStatus::ACKED, ::testing::_));
  12667. }
  12668. // Validate the dumped xDS configs
  12669. EXPECT_THAT(client_config.generic_xds_configs(),
  12670. ::testing::UnorderedElementsAreArray(matchers))
  12671. << "Actual: " << client_config.DebugString();
  12672. }
  12673. TEST_P(ClientStatusDiscoveryServiceTest, XdsConfigDumpEmpty) {
  12674. // The CSDS service should not fail if XdsClient is not initialized or there
  12675. // is no working xDS configs.
  12676. FetchCsdsResponse();
  12677. }
  12678. TEST_P(ClientStatusDiscoveryServiceTest, XdsConfigDumpListenerError) {
  12679. int kFetchConfigRetries = 3;
  12680. int kFetchIntervalMilliseconds = 200;
  12681. EdsResourceArgs args({{"locality0", CreateEndpointsForBackends(0, 1)}});
  12682. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  12683. // Ensure the xDS resolver has working configs.
  12684. CheckRpcSendOk();
  12685. // Bad Listener should be rejected.
  12686. Listener listener;
  12687. listener.set_name(kServerName);
  12688. balancer_->ads_service()->SetLdsResource(listener);
  12689. // The old xDS configs should still be effective.
  12690. CheckRpcSendOk();
  12691. ::testing::Matcher<google::protobuf::Any> api_listener_matcher;
  12692. if (GetParam().enable_rds_testing()) {
  12693. api_listener_matcher = IsRdsEnabledHCM();
  12694. } else {
  12695. api_listener_matcher =
  12696. EqNoRdsHCM(kDefaultRouteConfigurationName, kDefaultClusterName);
  12697. }
  12698. for (int i = 0; i < kFetchConfigRetries; ++i) {
  12699. auto csds_response = FetchCsdsResponse();
  12700. // Check if error state is propagated
  12701. bool ok = ::testing::Value(
  12702. csds_response.config(0).generic_xds_configs(),
  12703. ::testing::Contains(EqGenericXdsConfig(
  12704. kLdsTypeUrl, kServerName, "1",
  12705. UnpackListener(EqListener(kServerName, api_listener_matcher)),
  12706. ClientResourceStatus::NACKED,
  12707. EqUpdateFailureState(
  12708. ::testing::HasSubstr(
  12709. "Listener has neither address nor ApiListener"),
  12710. "2"))));
  12711. if (ok) return; // TEST PASSED!
  12712. gpr_sleep_until(
  12713. grpc_timeout_milliseconds_to_deadline(kFetchIntervalMilliseconds));
  12714. }
  12715. FAIL() << "error_state not seen in CSDS responses";
  12716. }
  12717. TEST_P(ClientStatusDiscoveryServiceTest, XdsConfigDumpRouteError) {
  12718. int kFetchConfigRetries = 3;
  12719. int kFetchIntervalMilliseconds = 200;
  12720. EdsResourceArgs args({{"locality0", CreateEndpointsForBackends(0, 1)}});
  12721. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  12722. // Ensure the xDS resolver has working configs.
  12723. CheckRpcSendOk();
  12724. // Bad route config will be rejected.
  12725. RouteConfiguration route_config;
  12726. route_config.set_name(kDefaultRouteConfigurationName);
  12727. route_config.add_virtual_hosts();
  12728. SetRouteConfiguration(balancer_.get(), route_config);
  12729. // The old xDS configs should still be effective.
  12730. CheckRpcSendOk();
  12731. for (int i = 0; i < kFetchConfigRetries; ++i) {
  12732. auto csds_response = FetchCsdsResponse();
  12733. bool ok = false;
  12734. if (GetParam().enable_rds_testing()) {
  12735. ok = ::testing::Value(
  12736. csds_response.config(0).generic_xds_configs(),
  12737. ::testing::Contains(EqGenericXdsConfig(
  12738. kRdsTypeUrl, kDefaultRouteConfigurationName, "1",
  12739. UnpackRouteConfiguration(EqRouteConfiguration(
  12740. kDefaultRouteConfigurationName, kDefaultClusterName)),
  12741. ClientResourceStatus::NACKED,
  12742. EqUpdateFailureState(
  12743. ::testing::HasSubstr("VirtualHost has no domains"), "2"))));
  12744. } else {
  12745. ok = ::testing::Value(
  12746. csds_response.config(0).generic_xds_configs(),
  12747. ::testing::Contains(EqGenericXdsConfig(
  12748. kLdsTypeUrl, kServerName, "1",
  12749. UnpackListener(EqListener(
  12750. kServerName, EqNoRdsHCM(kDefaultRouteConfigurationName,
  12751. kDefaultClusterName))),
  12752. ClientResourceStatus::NACKED,
  12753. EqUpdateFailureState(
  12754. ::testing::HasSubstr("VirtualHost has no domains"), "2"))));
  12755. }
  12756. if (ok) return; // TEST PASSED!
  12757. gpr_sleep_until(
  12758. grpc_timeout_milliseconds_to_deadline(kFetchIntervalMilliseconds));
  12759. }
  12760. FAIL() << "error_state not seen in CSDS responses";
  12761. }
  12762. TEST_P(ClientStatusDiscoveryServiceTest, XdsConfigDumpClusterError) {
  12763. int kFetchConfigRetries = 3;
  12764. int kFetchIntervalMilliseconds = 200;
  12765. EdsResourceArgs args({{"locality0", CreateEndpointsForBackends(0, 1)}});
  12766. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  12767. // Ensure the xDS resolver has working configs.
  12768. CheckRpcSendOk();
  12769. // Listener without any route, will be rejected.
  12770. Cluster cluster;
  12771. cluster.set_name(kDefaultClusterName);
  12772. balancer_->ads_service()->SetCdsResource(cluster);
  12773. // The old xDS configs should still be effective.
  12774. CheckRpcSendOk();
  12775. for (int i = 0; i < kFetchConfigRetries; ++i) {
  12776. auto csds_response = FetchCsdsResponse();
  12777. // Check if error state is propagated
  12778. bool ok = ::testing::Value(
  12779. csds_response.config(0).generic_xds_configs(),
  12780. ::testing::Contains(EqGenericXdsConfig(
  12781. kCdsTypeUrl, kDefaultClusterName, "1",
  12782. UnpackCluster(EqCluster(kDefaultClusterName)),
  12783. ClientResourceStatus::NACKED,
  12784. EqUpdateFailureState(
  12785. ::testing::HasSubstr("DiscoveryType not found"), "2"))));
  12786. if (ok) return; // TEST PASSED!
  12787. gpr_sleep_until(
  12788. grpc_timeout_milliseconds_to_deadline(kFetchIntervalMilliseconds));
  12789. }
  12790. FAIL() << "error_state not seen in CSDS responses";
  12791. }
  12792. TEST_P(ClientStatusDiscoveryServiceTest, XdsConfigDumpEndpointError) {
  12793. int kFetchConfigRetries = 3;
  12794. int kFetchIntervalMilliseconds = 200;
  12795. EdsResourceArgs args({{"locality0", CreateEndpointsForBackends(0, 1)}});
  12796. balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
  12797. // Ensure the xDS resolver has working configs.
  12798. CheckRpcSendOk();
  12799. // Bad endpoint config will be rejected.
  12800. ClusterLoadAssignment cluster_load_assignment;
  12801. cluster_load_assignment.set_cluster_name(kDefaultEdsServiceName);
  12802. auto* endpoints = cluster_load_assignment.add_endpoints();
  12803. endpoints->mutable_load_balancing_weight()->set_value(1);
  12804. auto* endpoint = endpoints->add_lb_endpoints()->mutable_endpoint();
  12805. endpoint->mutable_address()->mutable_socket_address()->set_port_value(1 << 1);
  12806. balancer_->ads_service()->SetEdsResource(cluster_load_assignment);
  12807. // The old xDS configs should still be effective.
  12808. CheckRpcSendOk();
  12809. for (int i = 0; i < kFetchConfigRetries; ++i) {
  12810. auto csds_response = FetchCsdsResponse();
  12811. // Check if error state is propagated
  12812. bool ok = ::testing::Value(
  12813. csds_response.config(0).generic_xds_configs(),
  12814. ::testing::Contains(EqGenericXdsConfig(
  12815. kEdsTypeUrl, kDefaultEdsServiceName, "1",
  12816. UnpackClusterLoadAssignment(EqClusterLoadAssignment(
  12817. kDefaultEdsServiceName, backends_[0]->port(),
  12818. kDefaultLocalityWeight)),
  12819. ClientResourceStatus::NACKED,
  12820. EqUpdateFailureState(::testing::HasSubstr("Empty locality"),
  12821. "2"))));
  12822. if (ok) return; // TEST PASSED!
  12823. gpr_sleep_until(
  12824. grpc_timeout_milliseconds_to_deadline(kFetchIntervalMilliseconds));
  12825. }
  12826. FAIL() << "error_state not seen in CSDS responses";
  12827. }
  12828. TEST_P(ClientStatusDiscoveryServiceTest, XdsConfigDumpListenerRequested) {
  12829. int kTimeoutMillisecond = 1000;
  12830. balancer_->ads_service()->UnsetResource(kLdsTypeUrl, kServerName);
  12831. CheckRpcSendFailure(
  12832. CheckRpcSendFailureOptions()
  12833. .set_rpc_options(RpcOptions().set_timeout_ms(kTimeoutMillisecond))
  12834. .set_expected_error_code(StatusCode::DEADLINE_EXCEEDED));
  12835. auto csds_response = FetchCsdsResponse();
  12836. EXPECT_THAT(csds_response.config(0).generic_xds_configs(),
  12837. ::testing::Contains(EqGenericXdsConfig(
  12838. kLdsTypeUrl, kServerName, ::testing::_, ::testing::_,
  12839. ClientResourceStatus::REQUESTED, ::testing::_)));
  12840. }
  12841. TEST_P(ClientStatusDiscoveryServiceTest, XdsConfigDumpClusterRequested) {
  12842. int kTimeoutMillisecond = 1000;
  12843. std::string kClusterName1 = "cluster-1";
  12844. std::string kClusterName2 = "cluster-2";
  12845. // Create a route config requesting two non-existing clusters
  12846. RouteConfiguration route_config;
  12847. route_config.set_name(kDefaultRouteConfigurationName);
  12848. auto* vh = route_config.add_virtual_hosts();
  12849. // The VirtualHost must match the domain name, otherwise will cause resolver
  12850. // transient failure.
  12851. vh->add_domains("*");
  12852. auto* routes1 = vh->add_routes();
  12853. routes1->mutable_match()->set_prefix("");
  12854. routes1->mutable_route()->set_cluster(kClusterName1);
  12855. auto* routes2 = vh->add_routes();
  12856. routes2->mutable_match()->set_prefix("");
  12857. routes2->mutable_route()->set_cluster(kClusterName2);
  12858. SetRouteConfiguration(balancer_.get(), route_config);
  12859. // Try to get the configs plumb through
  12860. CheckRpcSendFailure(
  12861. CheckRpcSendFailureOptions()
  12862. .set_rpc_options(RpcOptions().set_timeout_ms(kTimeoutMillisecond))
  12863. .set_expected_error_code(StatusCode::DEADLINE_EXCEEDED));
  12864. auto csds_response = FetchCsdsResponse();
  12865. EXPECT_THAT(csds_response.config(0).generic_xds_configs(),
  12866. ::testing::AllOf(
  12867. ::testing::Contains(EqGenericXdsConfig(
  12868. kCdsTypeUrl, kClusterName1, ::testing::_, ::testing::_,
  12869. ClientResourceStatus::REQUESTED, ::testing::_)),
  12870. ::testing::Contains(EqGenericXdsConfig(
  12871. kCdsTypeUrl, kClusterName2, ::testing::_, ::testing::_,
  12872. ClientResourceStatus::REQUESTED, ::testing::_))));
  12873. }
  12874. class CsdsShortAdsTimeoutTest : public ClientStatusDiscoveryServiceTest {
  12875. protected:
  12876. // Shorten the ADS subscription timeout to speed up the test run.
  12877. CsdsShortAdsTimeoutTest()
  12878. : ClientStatusDiscoveryServiceTest(
  12879. /* xds_resource_does_not_exist_timeout_ms_ = */ 2000) {}
  12880. };
  12881. TEST_P(CsdsShortAdsTimeoutTest, XdsConfigDumpListenerDoesNotExist) {
  12882. int kTimeoutMillisecond = 1000000; // 1000s wait for the transient failure.
  12883. balancer_->ads_service()->UnsetResource(kLdsTypeUrl, kServerName);
  12884. CheckRpcSendFailure(
  12885. CheckRpcSendFailureOptions()
  12886. .set_rpc_options(RpcOptions().set_timeout_ms(kTimeoutMillisecond))
  12887. .set_expected_error_code(grpc::StatusCode::UNAVAILABLE));
  12888. auto csds_response = FetchCsdsResponse();
  12889. EXPECT_THAT(csds_response.config(0).generic_xds_configs(),
  12890. ::testing::Contains(EqGenericXdsConfig(
  12891. kLdsTypeUrl, kServerName, ::testing::_, ::testing::_,
  12892. ClientResourceStatus::DOES_NOT_EXIST, ::testing::_)));
  12893. }
  12894. TEST_P(CsdsShortAdsTimeoutTest, XdsConfigDumpRouteConfigDoesNotExist) {
  12895. if (!GetParam().enable_rds_testing()) return;
  12896. int kTimeoutMillisecond = 1000000; // 1000s wait for the transient failure.
  12897. balancer_->ads_service()->UnsetResource(kRdsTypeUrl,
  12898. kDefaultRouteConfigurationName);
  12899. CheckRpcSendFailure(
  12900. CheckRpcSendFailureOptions()
  12901. .set_rpc_options(RpcOptions().set_timeout_ms(kTimeoutMillisecond))
  12902. .set_expected_error_code(grpc::StatusCode::UNAVAILABLE));
  12903. auto csds_response = FetchCsdsResponse();
  12904. EXPECT_THAT(
  12905. csds_response.config(0).generic_xds_configs(),
  12906. ::testing::Contains(EqGenericXdsConfig(
  12907. kRdsTypeUrl, kDefaultRouteConfigurationName, ::testing::_,
  12908. ::testing::_, ClientResourceStatus::DOES_NOT_EXIST, ::testing::_)));
  12909. }
  12910. TEST_P(CsdsShortAdsTimeoutTest, XdsConfigDumpClusterDoesNotExist) {
  12911. int kTimeoutMillisecond = 1000000; // 1000s wait for the transient failure.
  12912. balancer_->ads_service()->UnsetResource(kCdsTypeUrl, kDefaultClusterName);
  12913. CheckRpcSendFailure(
  12914. CheckRpcSendFailureOptions()
  12915. .set_rpc_options(RpcOptions().set_timeout_ms(kTimeoutMillisecond))
  12916. .set_expected_error_code(grpc::StatusCode::UNAVAILABLE));
  12917. auto csds_response = FetchCsdsResponse();
  12918. EXPECT_THAT(csds_response.config(0).generic_xds_configs(),
  12919. ::testing::Contains(EqGenericXdsConfig(
  12920. kCdsTypeUrl, kDefaultClusterName, ::testing::_, ::testing::_,
  12921. ClientResourceStatus::DOES_NOT_EXIST, ::testing::_)));
  12922. }
  12923. TEST_P(CsdsShortAdsTimeoutTest, XdsConfigDumpEndpointDoesNotExist) {
  12924. int kTimeoutMillisecond = 1000000; // 1000s wait for the transient failure.
  12925. balancer_->ads_service()->UnsetResource(kEdsTypeUrl, kDefaultEdsServiceName);
  12926. CheckRpcSendFailure(
  12927. CheckRpcSendFailureOptions()
  12928. .set_rpc_options(RpcOptions().set_timeout_ms(kTimeoutMillisecond))
  12929. .set_expected_error_code(grpc::StatusCode::UNAVAILABLE));
  12930. auto csds_response = FetchCsdsResponse();
  12931. EXPECT_THAT(
  12932. csds_response.config(0).generic_xds_configs(),
  12933. ::testing::Contains(EqGenericXdsConfig(
  12934. kEdsTypeUrl, kDefaultEdsServiceName, ::testing::_, ::testing::_,
  12935. ClientResourceStatus::DOES_NOT_EXIST, ::testing::_)));
  12936. }
  12937. #endif // DISABLED_XDS_PROTO_IN_CC
  12938. std::string TestTypeName(const ::testing::TestParamInfo<TestType>& info) {
  12939. return info.param.AsString();
  12940. }
  12941. // Run both with and without load reporting.
  12942. INSTANTIATE_TEST_SUITE_P(
  12943. XdsTest, BasicTest,
  12944. ::testing::Values(TestType(), TestType().set_enable_load_reporting()),
  12945. &TestTypeName);
  12946. // Don't run with load reporting or v2 or RDS, since they are irrelevant to
  12947. // the tests.
  12948. INSTANTIATE_TEST_SUITE_P(XdsTest, SecureNamingTest,
  12949. ::testing::Values(TestType()), &TestTypeName);
  12950. // LDS depends on XdsResolver.
  12951. INSTANTIATE_TEST_SUITE_P(XdsTest, LdsTest, ::testing::Values(TestType()),
  12952. &TestTypeName);
  12953. INSTANTIATE_TEST_SUITE_P(XdsTest, LdsV2Test,
  12954. ::testing::Values(TestType().set_use_v2()),
  12955. &TestTypeName);
  12956. // LDS/RDS commmon tests depend on XdsResolver.
  12957. INSTANTIATE_TEST_SUITE_P(
  12958. XdsTest, LdsRdsTest,
  12959. ::testing::Values(TestType(), TestType().set_enable_rds_testing(),
  12960. // Also test with xDS v2.
  12961. TestType().set_enable_rds_testing().set_use_v2()),
  12962. &TestTypeName);
  12963. // CDS depends on XdsResolver.
  12964. INSTANTIATE_TEST_SUITE_P(
  12965. XdsTest, CdsTest,
  12966. ::testing::Values(TestType(), TestType().set_enable_load_reporting()),
  12967. &TestTypeName);
  12968. // CDS depends on XdsResolver.
  12969. // Security depends on v3.
  12970. // Not enabling load reporting or RDS, since those are irrelevant to these
  12971. // tests.
  12972. INSTANTIATE_TEST_SUITE_P(
  12973. XdsTest, XdsSecurityTest,
  12974. ::testing::Values(TestType().set_use_xds_credentials()), &TestTypeName);
  12975. // We are only testing the server here.
  12976. // Run with bootstrap from env var, so that we use a global XdsClient
  12977. // instance. Otherwise, we would need to use a separate fake resolver
  12978. // result generator on the client and server sides.
  12979. INSTANTIATE_TEST_SUITE_P(XdsTest, XdsEnabledServerTest,
  12980. ::testing::Values(TestType().set_bootstrap_source(
  12981. TestType::kBootstrapFromEnvVar)),
  12982. &TestTypeName);
  12983. // We are only testing the server here.
  12984. // Run with bootstrap from env var so that we use one XdsClient.
  12985. INSTANTIATE_TEST_SUITE_P(
  12986. XdsTest, XdsServerSecurityTest,
  12987. ::testing::Values(TestType()
  12988. .set_bootstrap_source(TestType::kBootstrapFromEnvVar)
  12989. .set_use_xds_credentials()),
  12990. &TestTypeName);
  12991. INSTANTIATE_TEST_SUITE_P(
  12992. XdsTest, XdsEnabledServerStatusNotificationTest,
  12993. ::testing::Values(TestType().set_use_xds_credentials()), &TestTypeName);
  12994. // Run with bootstrap from env var so that we use one XdsClient.
  12995. INSTANTIATE_TEST_SUITE_P(
  12996. XdsTest, XdsServerFilterChainMatchTest,
  12997. ::testing::Values(TestType()
  12998. .set_bootstrap_source(TestType::kBootstrapFromEnvVar)
  12999. .set_use_xds_credentials()),
  13000. &TestTypeName);
  13001. // Test xDS-enabled server with and without RDS.
  13002. // Run with bootstrap from env var so that we use one XdsClient.
  13003. INSTANTIATE_TEST_SUITE_P(
  13004. XdsTest, XdsServerRdsTest,
  13005. ::testing::Values(TestType()
  13006. .set_bootstrap_source(TestType::kBootstrapFromEnvVar)
  13007. .set_use_xds_credentials(),
  13008. TestType()
  13009. .set_bootstrap_source(TestType::kBootstrapFromEnvVar)
  13010. .set_use_xds_credentials()
  13011. .set_enable_rds_testing()),
  13012. &TestTypeName);
  13013. // We are only testing the server here.
  13014. // Run with bootstrap from env var, so that we use a global XdsClient
  13015. // instance. Otherwise, we would need to use a separate fake resolver
  13016. // result generator on the client and server sides.
  13017. INSTANTIATE_TEST_SUITE_P(
  13018. XdsTest, XdsRbacTest,
  13019. ::testing::Values(
  13020. TestType().set_use_xds_credentials().set_bootstrap_source(
  13021. TestType::kBootstrapFromEnvVar),
  13022. TestType()
  13023. .set_use_xds_credentials()
  13024. .set_enable_rds_testing()
  13025. .set_bootstrap_source(TestType::kBootstrapFromEnvVar),
  13026. TestType()
  13027. .set_use_xds_credentials()
  13028. .set_filter_config_setup(
  13029. TestType::FilterConfigSetup::kRouteOverride)
  13030. .set_bootstrap_source(TestType::kBootstrapFromEnvVar),
  13031. TestType()
  13032. .set_use_xds_credentials()
  13033. .set_enable_rds_testing()
  13034. .set_filter_config_setup(
  13035. TestType::FilterConfigSetup::kRouteOverride)
  13036. .set_bootstrap_source(TestType::kBootstrapFromEnvVar)),
  13037. &TestTypeName);
  13038. // We are only testing the server here.
  13039. // Run with bootstrap from env var, so that we use a global XdsClient
  13040. // instance. Otherwise, we would need to use a separate fake resolver
  13041. // result generator on the client and server sides.
  13042. // Note that we are simply using the default fake credentials instead of xds
  13043. // credentials for NACK tests to avoid a mismatch between the client and the
  13044. // server's security settings when using the WaitForNack() infrastructure.
  13045. INSTANTIATE_TEST_SUITE_P(
  13046. XdsTest, XdsRbacNackTest,
  13047. ::testing::Values(
  13048. TestType().set_bootstrap_source(TestType::kBootstrapFromEnvVar),
  13049. TestType().set_enable_rds_testing().set_bootstrap_source(
  13050. TestType::kBootstrapFromEnvVar),
  13051. TestType()
  13052. .set_filter_config_setup(
  13053. TestType::FilterConfigSetup::kRouteOverride)
  13054. .set_bootstrap_source(TestType::kBootstrapFromEnvVar),
  13055. TestType()
  13056. .set_enable_rds_testing()
  13057. .set_filter_config_setup(
  13058. TestType::FilterConfigSetup::kRouteOverride)
  13059. .set_bootstrap_source(TestType::kBootstrapFromEnvVar)),
  13060. &TestTypeName);
  13061. // We are only testing the server here.
  13062. // Run with bootstrap from env var, so that we use a global XdsClient
  13063. // instance. Otherwise, we would need to use a separate fake resolver
  13064. // result generator on the client and server sides.
  13065. INSTANTIATE_TEST_SUITE_P(
  13066. XdsTest, XdsRbacTestWithRouteOverrideAlwaysPresent,
  13067. ::testing::Values(
  13068. TestType()
  13069. .set_use_xds_credentials()
  13070. .set_filter_config_setup(
  13071. TestType::FilterConfigSetup::kRouteOverride)
  13072. .set_bootstrap_source(TestType::kBootstrapFromEnvVar),
  13073. TestType()
  13074. .set_use_xds_credentials()
  13075. .set_enable_rds_testing()
  13076. .set_filter_config_setup(
  13077. TestType::FilterConfigSetup::kRouteOverride)
  13078. .set_bootstrap_source(TestType::kBootstrapFromEnvVar)),
  13079. &TestTypeName);
  13080. // We are only testing the server here.
  13081. // Run with bootstrap from env var, so that we use a global XdsClient
  13082. // instance. Otherwise, we would need to use a separate fake resolver
  13083. // result generator on the client and server sides.
  13084. INSTANTIATE_TEST_SUITE_P(
  13085. XdsTest, XdsRbacTestWithActionPermutations,
  13086. ::testing::Values(
  13087. TestType()
  13088. .set_use_xds_credentials()
  13089. .set_rbac_action(RBAC_Action_ALLOW)
  13090. .set_bootstrap_source(TestType::kBootstrapFromEnvVar),
  13091. TestType()
  13092. .set_use_xds_credentials()
  13093. .set_rbac_action(RBAC_Action_DENY)
  13094. .set_bootstrap_source(TestType::kBootstrapFromEnvVar),
  13095. TestType()
  13096. .set_use_xds_credentials()
  13097. .set_enable_rds_testing()
  13098. .set_rbac_action(RBAC_Action_ALLOW)
  13099. .set_bootstrap_source(TestType::kBootstrapFromEnvVar),
  13100. TestType()
  13101. .set_use_xds_credentials()
  13102. .set_enable_rds_testing()
  13103. .set_rbac_action(RBAC_Action_DENY)
  13104. .set_bootstrap_source(TestType::kBootstrapFromEnvVar),
  13105. TestType()
  13106. .set_use_xds_credentials()
  13107. .set_filter_config_setup(
  13108. TestType::FilterConfigSetup::kRouteOverride)
  13109. .set_rbac_action(RBAC_Action_ALLOW)
  13110. .set_bootstrap_source(TestType::kBootstrapFromEnvVar),
  13111. TestType()
  13112. .set_use_xds_credentials()
  13113. .set_filter_config_setup(
  13114. TestType::FilterConfigSetup::kRouteOverride)
  13115. .set_rbac_action(RBAC_Action_DENY)
  13116. .set_bootstrap_source(TestType::kBootstrapFromEnvVar),
  13117. TestType()
  13118. .set_use_xds_credentials()
  13119. .set_enable_rds_testing()
  13120. .set_filter_config_setup(
  13121. TestType::FilterConfigSetup::kRouteOverride)
  13122. .set_rbac_action(RBAC_Action_ALLOW)
  13123. .set_bootstrap_source(TestType::kBootstrapFromEnvVar),
  13124. TestType()
  13125. .set_use_xds_credentials()
  13126. .set_enable_rds_testing()
  13127. .set_filter_config_setup(
  13128. TestType::FilterConfigSetup::kRouteOverride)
  13129. .set_rbac_action(RBAC_Action_DENY)
  13130. .set_bootstrap_source(TestType::kBootstrapFromEnvVar)),
  13131. &TestTypeName);
  13132. // EDS could be tested with or without XdsResolver, but the tests would
  13133. // be the same either way, so we test it only with XdsResolver.
  13134. INSTANTIATE_TEST_SUITE_P(
  13135. XdsTest, EdsTest,
  13136. ::testing::Values(TestType(), TestType().set_enable_load_reporting()),
  13137. &TestTypeName);
  13138. // Test initial resource timeouts for each resource type.
  13139. // Do this only for XdsResolver with RDS enabled, so that we can test
  13140. // all resource types.
  13141. // Run with V3 only, since the functionality is no different in V2.
  13142. // Run with bootstrap from env var so that multiple channels share the same
  13143. // XdsClient (needed for testing the timeout for the 2nd LDS and RDS resource).
  13144. INSTANTIATE_TEST_SUITE_P(
  13145. XdsTest, TimeoutTest,
  13146. ::testing::Values(TestType().set_enable_rds_testing().set_bootstrap_source(
  13147. TestType::kBootstrapFromEnvVar)),
  13148. &TestTypeName);
  13149. // XdsResolverOnlyTest depends on XdsResolver.
  13150. INSTANTIATE_TEST_SUITE_P(
  13151. XdsTest, XdsResolverOnlyTest,
  13152. ::testing::Values(TestType(), TestType().set_enable_load_reporting()),
  13153. &TestTypeName);
  13154. // Runs with bootstrap from env var, so that there's a global XdsClient.
  13155. INSTANTIATE_TEST_SUITE_P(
  13156. XdsTest, GlobalXdsClientTest,
  13157. ::testing::Values(
  13158. TestType().set_bootstrap_source(TestType::kBootstrapFromEnvVar),
  13159. TestType()
  13160. .set_bootstrap_source(TestType::kBootstrapFromEnvVar)
  13161. .set_enable_load_reporting()),
  13162. &TestTypeName);
  13163. INSTANTIATE_TEST_SUITE_P(
  13164. XdsTest, XdsFederationTest,
  13165. ::testing::Values(
  13166. TestType().set_bootstrap_source(TestType::kBootstrapFromEnvVar),
  13167. TestType()
  13168. .set_bootstrap_source(TestType::kBootstrapFromEnvVar)
  13169. .set_enable_rds_testing()),
  13170. &TestTypeName);
  13171. INSTANTIATE_TEST_SUITE_P(
  13172. XdsTest, XdsFederationLoadReportingTest,
  13173. ::testing::Values(TestType()
  13174. .set_bootstrap_source(TestType::kBootstrapFromEnvVar)
  13175. .set_enable_load_reporting(),
  13176. TestType()
  13177. .set_bootstrap_source(TestType::kBootstrapFromEnvVar)
  13178. .set_enable_load_reporting()
  13179. .set_enable_rds_testing()),
  13180. &TestTypeName);
  13181. INSTANTIATE_TEST_SUITE_P(
  13182. XdsTest, LocalityMapTest,
  13183. ::testing::Values(TestType(), TestType().set_enable_load_reporting()),
  13184. &TestTypeName);
  13185. INSTANTIATE_TEST_SUITE_P(
  13186. XdsTest, FailoverTest,
  13187. ::testing::Values(TestType(), TestType().set_enable_load_reporting()),
  13188. &TestTypeName);
  13189. INSTANTIATE_TEST_SUITE_P(
  13190. XdsTest, DropTest,
  13191. ::testing::Values(TestType(), TestType().set_enable_load_reporting()),
  13192. &TestTypeName);
  13193. // Load reporting tests are not run with load reporting disabled.
  13194. INSTANTIATE_TEST_SUITE_P(
  13195. XdsTest, ClientLoadReportingTest,
  13196. ::testing::Values(TestType().set_enable_load_reporting()), &TestTypeName);
  13197. INSTANTIATE_TEST_SUITE_P(
  13198. XdsTest, ClientLoadReportingWithDropTest,
  13199. ::testing::Values(TestType().set_enable_load_reporting()), &TestTypeName);
  13200. INSTANTIATE_TEST_SUITE_P(
  13201. XdsTest, FaultInjectionTest,
  13202. ::testing::Values(
  13203. TestType(), TestType().set_enable_rds_testing(),
  13204. TestType().set_filter_config_setup(
  13205. TestType::FilterConfigSetup::kRouteOverride),
  13206. TestType().set_enable_rds_testing().set_filter_config_setup(
  13207. TestType::FilterConfigSetup::kRouteOverride)),
  13208. &TestTypeName);
  13209. INSTANTIATE_TEST_SUITE_P(
  13210. XdsTest, BootstrapSourceTest,
  13211. ::testing::Values(
  13212. TestType().set_bootstrap_source(TestType::kBootstrapFromEnvVar),
  13213. TestType().set_bootstrap_source(TestType::kBootstrapFromFile)),
  13214. &TestTypeName);
  13215. #ifndef DISABLED_XDS_PROTO_IN_CC
  13216. // Run CSDS tests with RDS enabled and disabled.
  13217. // These need to run with the bootstrap from an env var instead of from
  13218. // a channel arg, since there needs to be a global XdsClient instance.
  13219. INSTANTIATE_TEST_SUITE_P(
  13220. XdsTest, ClientStatusDiscoveryServiceTest,
  13221. ::testing::Values(
  13222. TestType().set_bootstrap_source(TestType::kBootstrapFromEnvVar),
  13223. TestType()
  13224. .set_bootstrap_source(TestType::kBootstrapFromEnvVar)
  13225. .set_enable_rds_testing(),
  13226. TestType()
  13227. .set_bootstrap_source(TestType::kBootstrapFromEnvVar)
  13228. .set_use_csds_streaming(),
  13229. TestType()
  13230. .set_bootstrap_source(TestType::kBootstrapFromEnvVar)
  13231. .set_enable_rds_testing()
  13232. .set_use_csds_streaming()),
  13233. &TestTypeName);
  13234. INSTANTIATE_TEST_SUITE_P(
  13235. XdsTest, CsdsShortAdsTimeoutTest,
  13236. ::testing::Values(
  13237. TestType().set_bootstrap_source(TestType::kBootstrapFromEnvVar),
  13238. TestType()
  13239. .set_bootstrap_source(TestType::kBootstrapFromEnvVar)
  13240. .set_enable_rds_testing(),
  13241. TestType()
  13242. .set_bootstrap_source(TestType::kBootstrapFromEnvVar)
  13243. .set_use_csds_streaming(),
  13244. TestType()
  13245. .set_bootstrap_source(TestType::kBootstrapFromEnvVar)
  13246. .set_enable_rds_testing()
  13247. .set_use_csds_streaming()),
  13248. &TestTypeName);
  13249. #endif // DISABLED_XDS_PROTO_IN_CC
  13250. } // namespace
  13251. } // namespace testing
  13252. } // namespace grpc
  13253. int main(int argc, char** argv) {
  13254. grpc::testing::TestEnvironment env(argc, argv);
  13255. ::testing::InitGoogleTest(&argc, argv);
  13256. // Make the backup poller poll very frequently in order to pick up
  13257. // updates from all the subchannels's FDs.
  13258. GPR_GLOBAL_CONFIG_SET(grpc_client_channel_backup_poll_interval_ms, 1);
  13259. #if TARGET_OS_IPHONE
  13260. // Workaround Apple CFStream bug
  13261. gpr_setenv("grpc_cfstream", "0");
  13262. #endif
  13263. grpc_core::CertificateProviderRegistry::RegisterCertificateProviderFactory(
  13264. absl::make_unique<grpc::testing::FakeCertificateProviderFactory>(
  13265. "fake1", &grpc::testing::g_fake1_cert_data_map));
  13266. grpc_core::CertificateProviderRegistry::RegisterCertificateProviderFactory(
  13267. absl::make_unique<grpc::testing::FakeCertificateProviderFactory>(
  13268. "fake2", &grpc::testing::g_fake2_cert_data_map));
  13269. grpc_init();
  13270. grpc_core::XdsHttpFilterRegistry::RegisterFilter(
  13271. absl::make_unique<grpc::testing::NoOpHttpFilter>(
  13272. "grpc.testing.client_only_http_filter",
  13273. /* supported_on_clients = */ true, /* supported_on_servers = */ false,
  13274. /* is_terminal_filter */ false),
  13275. {"grpc.testing.client_only_http_filter"});
  13276. grpc_core::XdsHttpFilterRegistry::RegisterFilter(
  13277. absl::make_unique<grpc::testing::NoOpHttpFilter>(
  13278. "grpc.testing.server_only_http_filter",
  13279. /* supported_on_clients = */ false, /* supported_on_servers = */ true,
  13280. /* is_terminal_filter */ false),
  13281. {"grpc.testing.server_only_http_filter"});
  13282. grpc_core::XdsHttpFilterRegistry::RegisterFilter(
  13283. absl::make_unique<grpc::testing::NoOpHttpFilter>(
  13284. "grpc.testing.terminal_http_filter",
  13285. /* supported_on_clients = */ true, /* supported_on_servers = */ true,
  13286. /* is_terminal_filter */ true),
  13287. {"grpc.testing.terminal_http_filter"});
  13288. const auto result = RUN_ALL_TESTS();
  13289. grpc_shutdown();
  13290. return result;
  13291. }