end2end_test.go 220 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365
  1. /*
  2. *
  3. * Copyright 2014 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. //go:generate protoc --go_out=plugins=grpc:. codec_perf/perf.proto
  19. //go:generate protoc --go_out=plugins=grpc:. grpc_testing/test.proto
  20. package test
  21. import (
  22. "bufio"
  23. "bytes"
  24. "context"
  25. "crypto/tls"
  26. "errors"
  27. "flag"
  28. "fmt"
  29. "io"
  30. "math"
  31. "net"
  32. "net/http"
  33. "os"
  34. "reflect"
  35. "runtime"
  36. "strings"
  37. "sync"
  38. "sync/atomic"
  39. "syscall"
  40. "testing"
  41. "time"
  42. "github.com/golang/protobuf/proto"
  43. anypb "github.com/golang/protobuf/ptypes/any"
  44. "golang.org/x/net/http2"
  45. "golang.org/x/net/http2/hpack"
  46. spb "google.golang.org/genproto/googleapis/rpc/status"
  47. "google.golang.org/grpc"
  48. "google.golang.org/grpc/balancer/roundrobin"
  49. "google.golang.org/grpc/codes"
  50. "google.golang.org/grpc/connectivity"
  51. "google.golang.org/grpc/credentials"
  52. "google.golang.org/grpc/encoding"
  53. _ "google.golang.org/grpc/encoding/gzip"
  54. _ "google.golang.org/grpc/grpclog/glogger"
  55. "google.golang.org/grpc/health"
  56. healthgrpc "google.golang.org/grpc/health/grpc_health_v1"
  57. healthpb "google.golang.org/grpc/health/grpc_health_v1"
  58. "google.golang.org/grpc/internal/channelz"
  59. "google.golang.org/grpc/internal/grpcsync"
  60. "google.golang.org/grpc/internal/grpctest"
  61. "google.golang.org/grpc/internal/leakcheck"
  62. "google.golang.org/grpc/internal/testutils"
  63. "google.golang.org/grpc/internal/transport"
  64. "google.golang.org/grpc/metadata"
  65. "google.golang.org/grpc/peer"
  66. "google.golang.org/grpc/resolver"
  67. "google.golang.org/grpc/resolver/manual"
  68. _ "google.golang.org/grpc/resolver/passthrough"
  69. "google.golang.org/grpc/stats"
  70. "google.golang.org/grpc/status"
  71. "google.golang.org/grpc/tap"
  72. testpb "google.golang.org/grpc/test/grpc_testing"
  73. "google.golang.org/grpc/testdata"
  74. )
  75. func init() {
  76. channelz.TurnOn()
  77. }
  78. type s struct{}
  79. var lcFailed uint32
  80. type errorer struct {
  81. t *testing.T
  82. }
  83. func (e errorer) Errorf(format string, args ...interface{}) {
  84. atomic.StoreUint32(&lcFailed, 1)
  85. e.t.Errorf(format, args...)
  86. }
  87. func (s) Teardown(t *testing.T) {
  88. if atomic.LoadUint32(&lcFailed) == 1 {
  89. return
  90. }
  91. leakcheck.Check(errorer{t: t})
  92. if atomic.LoadUint32(&lcFailed) == 1 {
  93. t.Log("Leak check disabled for future tests")
  94. }
  95. }
  96. func Test(t *testing.T) {
  97. grpctest.RunSubTests(t, s{})
  98. }
  99. var (
  100. // For headers:
  101. testMetadata = metadata.MD{
  102. "key1": []string{"value1"},
  103. "key2": []string{"value2"},
  104. "key3-bin": []string{"binvalue1", string([]byte{1, 2, 3})},
  105. }
  106. testMetadata2 = metadata.MD{
  107. "key1": []string{"value12"},
  108. "key2": []string{"value22"},
  109. }
  110. // For trailers:
  111. testTrailerMetadata = metadata.MD{
  112. "tkey1": []string{"trailerValue1"},
  113. "tkey2": []string{"trailerValue2"},
  114. "tkey3-bin": []string{"trailerbinvalue1", string([]byte{3, 2, 1})},
  115. }
  116. testTrailerMetadata2 = metadata.MD{
  117. "tkey1": []string{"trailerValue12"},
  118. "tkey2": []string{"trailerValue22"},
  119. }
  120. // capital "Key" is illegal in HTTP/2.
  121. malformedHTTP2Metadata = metadata.MD{
  122. "Key": []string{"foo"},
  123. }
  124. testAppUA = "myApp1/1.0 myApp2/0.9"
  125. failAppUA = "fail-this-RPC"
  126. detailedError = status.ErrorProto(&spb.Status{
  127. Code: int32(codes.DataLoss),
  128. Message: "error for testing: " + failAppUA,
  129. Details: []*anypb.Any{{
  130. TypeUrl: "url",
  131. Value: []byte{6, 0, 0, 6, 1, 3},
  132. }},
  133. })
  134. )
  135. var raceMode bool // set by race.go in race mode
  136. type testServer struct {
  137. security string // indicate the authentication protocol used by this server.
  138. earlyFail bool // whether to error out the execution of a service handler prematurely.
  139. setAndSendHeader bool // whether to call setHeader and sendHeader.
  140. setHeaderOnly bool // whether to only call setHeader, not sendHeader.
  141. multipleSetTrailer bool // whether to call setTrailer multiple times.
  142. unaryCallSleepTime time.Duration
  143. }
  144. func (s *testServer) EmptyCall(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) {
  145. if md, ok := metadata.FromIncomingContext(ctx); ok {
  146. // For testing purpose, returns an error if user-agent is failAppUA.
  147. // To test that client gets the correct error.
  148. if ua, ok := md["user-agent"]; !ok || strings.HasPrefix(ua[0], failAppUA) {
  149. return nil, detailedError
  150. }
  151. var str []string
  152. for _, entry := range md["user-agent"] {
  153. str = append(str, "ua", entry)
  154. }
  155. grpc.SendHeader(ctx, metadata.Pairs(str...))
  156. }
  157. return new(testpb.Empty), nil
  158. }
  159. func newPayload(t testpb.PayloadType, size int32) (*testpb.Payload, error) {
  160. if size < 0 {
  161. return nil, fmt.Errorf("requested a response with invalid length %d", size)
  162. }
  163. body := make([]byte, size)
  164. switch t {
  165. case testpb.PayloadType_COMPRESSABLE:
  166. case testpb.PayloadType_UNCOMPRESSABLE:
  167. return nil, fmt.Errorf("PayloadType UNCOMPRESSABLE is not supported")
  168. default:
  169. return nil, fmt.Errorf("unsupported payload type: %d", t)
  170. }
  171. return &testpb.Payload{
  172. Type: t,
  173. Body: body,
  174. }, nil
  175. }
  176. func (s *testServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
  177. md, ok := metadata.FromIncomingContext(ctx)
  178. if ok {
  179. if _, exists := md[":authority"]; !exists {
  180. return nil, status.Errorf(codes.DataLoss, "expected an :authority metadata: %v", md)
  181. }
  182. if s.setAndSendHeader {
  183. if err := grpc.SetHeader(ctx, md); err != nil {
  184. return nil, status.Errorf(status.Code(err), "grpc.SetHeader(_, %v) = %v, want <nil>", md, err)
  185. }
  186. if err := grpc.SendHeader(ctx, testMetadata2); err != nil {
  187. return nil, status.Errorf(status.Code(err), "grpc.SendHeader(_, %v) = %v, want <nil>", testMetadata2, err)
  188. }
  189. } else if s.setHeaderOnly {
  190. if err := grpc.SetHeader(ctx, md); err != nil {
  191. return nil, status.Errorf(status.Code(err), "grpc.SetHeader(_, %v) = %v, want <nil>", md, err)
  192. }
  193. if err := grpc.SetHeader(ctx, testMetadata2); err != nil {
  194. return nil, status.Errorf(status.Code(err), "grpc.SetHeader(_, %v) = %v, want <nil>", testMetadata2, err)
  195. }
  196. } else {
  197. if err := grpc.SendHeader(ctx, md); err != nil {
  198. return nil, status.Errorf(status.Code(err), "grpc.SendHeader(_, %v) = %v, want <nil>", md, err)
  199. }
  200. }
  201. if err := grpc.SetTrailer(ctx, testTrailerMetadata); err != nil {
  202. return nil, status.Errorf(status.Code(err), "grpc.SetTrailer(_, %v) = %v, want <nil>", testTrailerMetadata, err)
  203. }
  204. if s.multipleSetTrailer {
  205. if err := grpc.SetTrailer(ctx, testTrailerMetadata2); err != nil {
  206. return nil, status.Errorf(status.Code(err), "grpc.SetTrailer(_, %v) = %v, want <nil>", testTrailerMetadata2, err)
  207. }
  208. }
  209. }
  210. pr, ok := peer.FromContext(ctx)
  211. if !ok {
  212. return nil, status.Error(codes.DataLoss, "failed to get peer from ctx")
  213. }
  214. if pr.Addr == net.Addr(nil) {
  215. return nil, status.Error(codes.DataLoss, "failed to get peer address")
  216. }
  217. if s.security != "" {
  218. // Check Auth info
  219. var authType, serverName string
  220. switch info := pr.AuthInfo.(type) {
  221. case credentials.TLSInfo:
  222. authType = info.AuthType()
  223. serverName = info.State.ServerName
  224. default:
  225. return nil, status.Error(codes.Unauthenticated, "Unknown AuthInfo type")
  226. }
  227. if authType != s.security {
  228. return nil, status.Errorf(codes.Unauthenticated, "Wrong auth type: got %q, want %q", authType, s.security)
  229. }
  230. if serverName != "x.test.youtube.com" {
  231. return nil, status.Errorf(codes.Unauthenticated, "Unknown server name %q", serverName)
  232. }
  233. }
  234. // Simulate some service delay.
  235. time.Sleep(s.unaryCallSleepTime)
  236. payload, err := newPayload(in.GetResponseType(), in.GetResponseSize())
  237. if err != nil {
  238. return nil, err
  239. }
  240. return &testpb.SimpleResponse{
  241. Payload: payload,
  242. }, nil
  243. }
  244. func (s *testServer) StreamingOutputCall(args *testpb.StreamingOutputCallRequest, stream testpb.TestService_StreamingOutputCallServer) error {
  245. if md, ok := metadata.FromIncomingContext(stream.Context()); ok {
  246. if _, exists := md[":authority"]; !exists {
  247. return status.Errorf(codes.DataLoss, "expected an :authority metadata: %v", md)
  248. }
  249. // For testing purpose, returns an error if user-agent is failAppUA.
  250. // To test that client gets the correct error.
  251. if ua, ok := md["user-agent"]; !ok || strings.HasPrefix(ua[0], failAppUA) {
  252. return status.Error(codes.DataLoss, "error for testing: "+failAppUA)
  253. }
  254. }
  255. cs := args.GetResponseParameters()
  256. for _, c := range cs {
  257. if us := c.GetIntervalUs(); us > 0 {
  258. time.Sleep(time.Duration(us) * time.Microsecond)
  259. }
  260. payload, err := newPayload(args.GetResponseType(), c.GetSize())
  261. if err != nil {
  262. return err
  263. }
  264. if err := stream.Send(&testpb.StreamingOutputCallResponse{
  265. Payload: payload,
  266. }); err != nil {
  267. return err
  268. }
  269. }
  270. return nil
  271. }
  272. func (s *testServer) StreamingInputCall(stream testpb.TestService_StreamingInputCallServer) error {
  273. var sum int
  274. for {
  275. in, err := stream.Recv()
  276. if err == io.EOF {
  277. return stream.SendAndClose(&testpb.StreamingInputCallResponse{
  278. AggregatedPayloadSize: int32(sum),
  279. })
  280. }
  281. if err != nil {
  282. return err
  283. }
  284. p := in.GetPayload().GetBody()
  285. sum += len(p)
  286. if s.earlyFail {
  287. return status.Error(codes.NotFound, "not found")
  288. }
  289. }
  290. }
  291. func (s *testServer) FullDuplexCall(stream testpb.TestService_FullDuplexCallServer) error {
  292. md, ok := metadata.FromIncomingContext(stream.Context())
  293. if ok {
  294. if s.setAndSendHeader {
  295. if err := stream.SetHeader(md); err != nil {
  296. return status.Errorf(status.Code(err), "%v.SetHeader(_, %v) = %v, want <nil>", stream, md, err)
  297. }
  298. if err := stream.SendHeader(testMetadata2); err != nil {
  299. return status.Errorf(status.Code(err), "%v.SendHeader(_, %v) = %v, want <nil>", stream, testMetadata2, err)
  300. }
  301. } else if s.setHeaderOnly {
  302. if err := stream.SetHeader(md); err != nil {
  303. return status.Errorf(status.Code(err), "%v.SetHeader(_, %v) = %v, want <nil>", stream, md, err)
  304. }
  305. if err := stream.SetHeader(testMetadata2); err != nil {
  306. return status.Errorf(status.Code(err), "%v.SetHeader(_, %v) = %v, want <nil>", stream, testMetadata2, err)
  307. }
  308. } else {
  309. if err := stream.SendHeader(md); err != nil {
  310. return status.Errorf(status.Code(err), "%v.SendHeader(%v) = %v, want %v", stream, md, err, nil)
  311. }
  312. }
  313. stream.SetTrailer(testTrailerMetadata)
  314. if s.multipleSetTrailer {
  315. stream.SetTrailer(testTrailerMetadata2)
  316. }
  317. }
  318. for {
  319. in, err := stream.Recv()
  320. if err == io.EOF {
  321. // read done.
  322. return nil
  323. }
  324. if err != nil {
  325. // to facilitate testSvrWriteStatusEarlyWrite
  326. if status.Code(err) == codes.ResourceExhausted {
  327. return status.Errorf(codes.Internal, "fake error for test testSvrWriteStatusEarlyWrite. true error: %s", err.Error())
  328. }
  329. return err
  330. }
  331. cs := in.GetResponseParameters()
  332. for _, c := range cs {
  333. if us := c.GetIntervalUs(); us > 0 {
  334. time.Sleep(time.Duration(us) * time.Microsecond)
  335. }
  336. payload, err := newPayload(in.GetResponseType(), c.GetSize())
  337. if err != nil {
  338. return err
  339. }
  340. if err := stream.Send(&testpb.StreamingOutputCallResponse{
  341. Payload: payload,
  342. }); err != nil {
  343. // to facilitate testSvrWriteStatusEarlyWrite
  344. if status.Code(err) == codes.ResourceExhausted {
  345. return status.Errorf(codes.Internal, "fake error for test testSvrWriteStatusEarlyWrite. true error: %s", err.Error())
  346. }
  347. return err
  348. }
  349. }
  350. }
  351. }
  352. func (s *testServer) HalfDuplexCall(stream testpb.TestService_HalfDuplexCallServer) error {
  353. var msgBuf []*testpb.StreamingOutputCallRequest
  354. for {
  355. in, err := stream.Recv()
  356. if err == io.EOF {
  357. // read done.
  358. break
  359. }
  360. if err != nil {
  361. return err
  362. }
  363. msgBuf = append(msgBuf, in)
  364. }
  365. for _, m := range msgBuf {
  366. cs := m.GetResponseParameters()
  367. for _, c := range cs {
  368. if us := c.GetIntervalUs(); us > 0 {
  369. time.Sleep(time.Duration(us) * time.Microsecond)
  370. }
  371. payload, err := newPayload(m.GetResponseType(), c.GetSize())
  372. if err != nil {
  373. return err
  374. }
  375. if err := stream.Send(&testpb.StreamingOutputCallResponse{
  376. Payload: payload,
  377. }); err != nil {
  378. return err
  379. }
  380. }
  381. }
  382. return nil
  383. }
  384. type env struct {
  385. name string
  386. network string // The type of network such as tcp, unix, etc.
  387. security string // The security protocol such as TLS, SSH, etc.
  388. httpHandler bool // whether to use the http.Handler ServerTransport; requires TLS
  389. balancer string // One of "round_robin", "pick_first", "v1", or "".
  390. customDialer func(string, string, time.Duration) (net.Conn, error)
  391. }
  392. func (e env) runnable() bool {
  393. if runtime.GOOS == "windows" && e.network == "unix" {
  394. return false
  395. }
  396. return true
  397. }
  398. func (e env) dialer(addr string, timeout time.Duration) (net.Conn, error) {
  399. if e.customDialer != nil {
  400. return e.customDialer(e.network, addr, timeout)
  401. }
  402. return net.DialTimeout(e.network, addr, timeout)
  403. }
  404. var (
  405. tcpClearEnv = env{name: "tcp-clear-v1-balancer", network: "tcp", balancer: "v1"}
  406. tcpTLSEnv = env{name: "tcp-tls-v1-balancer", network: "tcp", security: "tls", balancer: "v1"}
  407. tcpClearRREnv = env{name: "tcp-clear", network: "tcp", balancer: "round_robin"}
  408. tcpTLSRREnv = env{name: "tcp-tls", network: "tcp", security: "tls", balancer: "round_robin"}
  409. handlerEnv = env{name: "handler-tls", network: "tcp", security: "tls", httpHandler: true, balancer: "round_robin"}
  410. noBalancerEnv = env{name: "no-balancer", network: "tcp", security: "tls"}
  411. allEnv = []env{tcpClearEnv, tcpTLSEnv, tcpClearRREnv, tcpTLSRREnv, handlerEnv, noBalancerEnv}
  412. )
  413. var onlyEnv = flag.String("only_env", "", "If non-empty, one of 'tcp-clear', 'tcp-tls', 'unix-clear', 'unix-tls', or 'handler-tls' to only run the tests for that environment. Empty means all.")
  414. func listTestEnv() (envs []env) {
  415. if *onlyEnv != "" {
  416. for _, e := range allEnv {
  417. if e.name == *onlyEnv {
  418. if !e.runnable() {
  419. panic(fmt.Sprintf("--only_env environment %q does not run on %s", *onlyEnv, runtime.GOOS))
  420. }
  421. return []env{e}
  422. }
  423. }
  424. panic(fmt.Sprintf("invalid --only_env value %q", *onlyEnv))
  425. }
  426. for _, e := range allEnv {
  427. if e.runnable() {
  428. envs = append(envs, e)
  429. }
  430. }
  431. return envs
  432. }
  433. // test is an end-to-end test. It should be created with the newTest
  434. // func, modified as needed, and then started with its startServer method.
  435. // It should be cleaned up with the tearDown method.
  436. type test struct {
  437. t *testing.T
  438. e env
  439. ctx context.Context // valid for life of test, before tearDown
  440. cancel context.CancelFunc
  441. // Configurable knobs, after newTest returns:
  442. testServer testpb.TestServiceServer // nil means none
  443. healthServer *health.Server // nil means disabled
  444. maxStream uint32
  445. tapHandle tap.ServerInHandle
  446. maxMsgSize *int
  447. maxClientReceiveMsgSize *int
  448. maxClientSendMsgSize *int
  449. maxServerReceiveMsgSize *int
  450. maxServerSendMsgSize *int
  451. maxClientHeaderListSize *uint32
  452. maxServerHeaderListSize *uint32
  453. userAgent string
  454. // clientCompression and serverCompression are set to test the deprecated API
  455. // WithCompressor and WithDecompressor.
  456. clientCompression bool
  457. serverCompression bool
  458. // clientUseCompression is set to test the new compressor registration API UseCompressor.
  459. clientUseCompression bool
  460. // clientNopCompression is set to create a compressor whose type is not supported.
  461. clientNopCompression bool
  462. unaryClientInt grpc.UnaryClientInterceptor
  463. streamClientInt grpc.StreamClientInterceptor
  464. unaryServerInt grpc.UnaryServerInterceptor
  465. streamServerInt grpc.StreamServerInterceptor
  466. unknownHandler grpc.StreamHandler
  467. sc <-chan grpc.ServiceConfig
  468. customCodec encoding.Codec
  469. serverInitialWindowSize int32
  470. serverInitialConnWindowSize int32
  471. clientInitialWindowSize int32
  472. clientInitialConnWindowSize int32
  473. perRPCCreds credentials.PerRPCCredentials
  474. customDialOptions []grpc.DialOption
  475. customServerOptions []grpc.ServerOption
  476. resolverScheme string
  477. // All test dialing is blocking by default. Set this to true if dial
  478. // should be non-blocking.
  479. nonBlockingDial bool
  480. // srv and srvAddr are set once startServer is called.
  481. srv stopper
  482. srvAddr string
  483. // srvs and srvAddrs are set once startServers is called.
  484. srvs []*grpc.Server
  485. srvAddrs []string
  486. cc *grpc.ClientConn // nil until requested via clientConn
  487. restoreLogs func() // nil unless declareLogNoise is used
  488. }
  489. type stopper interface {
  490. Stop()
  491. GracefulStop()
  492. }
  493. func (te *test) tearDown() {
  494. if te.cancel != nil {
  495. te.cancel()
  496. te.cancel = nil
  497. }
  498. if te.cc != nil {
  499. te.cc.Close()
  500. te.cc = nil
  501. }
  502. if te.restoreLogs != nil {
  503. te.restoreLogs()
  504. te.restoreLogs = nil
  505. }
  506. if te.srv != nil {
  507. te.srv.Stop()
  508. }
  509. if len(te.srvs) != 0 {
  510. for _, s := range te.srvs {
  511. s.Stop()
  512. }
  513. }
  514. }
  515. // newTest returns a new test using the provided testing.T and
  516. // environment. It is returned with default values. Tests should
  517. // modify it before calling its startServer and clientConn methods.
  518. func newTest(t *testing.T, e env) *test {
  519. te := &test{
  520. t: t,
  521. e: e,
  522. maxStream: math.MaxUint32,
  523. }
  524. te.ctx, te.cancel = context.WithCancel(context.Background())
  525. return te
  526. }
  527. func (te *test) listenAndServe(ts testpb.TestServiceServer, listen func(network, address string) (net.Listener, error)) net.Listener {
  528. te.testServer = ts
  529. te.t.Logf("Running test in %s environment...", te.e.name)
  530. sopts := []grpc.ServerOption{grpc.MaxConcurrentStreams(te.maxStream)}
  531. if te.maxMsgSize != nil {
  532. sopts = append(sopts, grpc.MaxMsgSize(*te.maxMsgSize))
  533. }
  534. if te.maxServerReceiveMsgSize != nil {
  535. sopts = append(sopts, grpc.MaxRecvMsgSize(*te.maxServerReceiveMsgSize))
  536. }
  537. if te.maxServerSendMsgSize != nil {
  538. sopts = append(sopts, grpc.MaxSendMsgSize(*te.maxServerSendMsgSize))
  539. }
  540. if te.maxServerHeaderListSize != nil {
  541. sopts = append(sopts, grpc.MaxHeaderListSize(*te.maxServerHeaderListSize))
  542. }
  543. if te.tapHandle != nil {
  544. sopts = append(sopts, grpc.InTapHandle(te.tapHandle))
  545. }
  546. if te.serverCompression {
  547. sopts = append(sopts,
  548. grpc.RPCCompressor(grpc.NewGZIPCompressor()),
  549. grpc.RPCDecompressor(grpc.NewGZIPDecompressor()),
  550. )
  551. }
  552. if te.unaryServerInt != nil {
  553. sopts = append(sopts, grpc.UnaryInterceptor(te.unaryServerInt))
  554. }
  555. if te.streamServerInt != nil {
  556. sopts = append(sopts, grpc.StreamInterceptor(te.streamServerInt))
  557. }
  558. if te.unknownHandler != nil {
  559. sopts = append(sopts, grpc.UnknownServiceHandler(te.unknownHandler))
  560. }
  561. if te.serverInitialWindowSize > 0 {
  562. sopts = append(sopts, grpc.InitialWindowSize(te.serverInitialWindowSize))
  563. }
  564. if te.serverInitialConnWindowSize > 0 {
  565. sopts = append(sopts, grpc.InitialConnWindowSize(te.serverInitialConnWindowSize))
  566. }
  567. la := "localhost:0"
  568. switch te.e.network {
  569. case "unix":
  570. la = "/tmp/testsock" + fmt.Sprintf("%d", time.Now().UnixNano())
  571. syscall.Unlink(la)
  572. }
  573. lis, err := listen(te.e.network, la)
  574. if err != nil {
  575. te.t.Fatalf("Failed to listen: %v", err)
  576. }
  577. switch te.e.security {
  578. case "tls":
  579. creds, err := credentials.NewServerTLSFromFile(testdata.Path("server1.pem"), testdata.Path("server1.key"))
  580. if err != nil {
  581. te.t.Fatalf("Failed to generate credentials %v", err)
  582. }
  583. sopts = append(sopts, grpc.Creds(creds))
  584. case "clientTimeoutCreds":
  585. sopts = append(sopts, grpc.Creds(&clientTimeoutCreds{}))
  586. }
  587. sopts = append(sopts, te.customServerOptions...)
  588. s := grpc.NewServer(sopts...)
  589. te.srv = s
  590. if te.healthServer != nil {
  591. healthgrpc.RegisterHealthServer(s, te.healthServer)
  592. }
  593. if te.testServer != nil {
  594. testpb.RegisterTestServiceServer(s, te.testServer)
  595. }
  596. addr := la
  597. switch te.e.network {
  598. case "unix":
  599. default:
  600. _, port, err := net.SplitHostPort(lis.Addr().String())
  601. if err != nil {
  602. te.t.Fatalf("Failed to parse listener address: %v", err)
  603. }
  604. addr = "localhost:" + port
  605. }
  606. te.srvAddr = addr
  607. if te.e.httpHandler {
  608. if te.e.security != "tls" {
  609. te.t.Fatalf("unsupported environment settings")
  610. }
  611. cert, err := tls.LoadX509KeyPair(testdata.Path("server1.pem"), testdata.Path("server1.key"))
  612. if err != nil {
  613. te.t.Fatal("Error creating TLS certificate: ", err)
  614. }
  615. hs := &http.Server{
  616. Handler: s,
  617. }
  618. err = http2.ConfigureServer(hs, &http2.Server{
  619. MaxConcurrentStreams: te.maxStream,
  620. })
  621. if err != nil {
  622. te.t.Fatal("error starting http2 server: ", err)
  623. }
  624. hs.TLSConfig.Certificates = []tls.Certificate{cert}
  625. tlsListener := tls.NewListener(lis, hs.TLSConfig)
  626. whs := &wrapHS{Listener: tlsListener, s: hs, conns: make(map[net.Conn]bool)}
  627. te.srv = whs
  628. go hs.Serve(whs)
  629. return lis
  630. }
  631. go s.Serve(lis)
  632. return lis
  633. }
  634. // TODO: delete wrapHS and wrapConn when Go1.6 and Go1.7 support are gone and
  635. // call s.Close and s.Shutdown instead.
  636. type wrapHS struct {
  637. sync.Mutex
  638. net.Listener
  639. s *http.Server
  640. conns map[net.Conn]bool
  641. }
  642. func (w *wrapHS) Accept() (net.Conn, error) {
  643. c, err := w.Listener.Accept()
  644. if err != nil {
  645. return nil, err
  646. }
  647. w.Lock()
  648. if w.conns == nil {
  649. w.Unlock()
  650. c.Close()
  651. return nil, errors.New("connection after listener closed")
  652. }
  653. w.conns[&wrapConn{Conn: c, hs: w}] = true
  654. w.Unlock()
  655. return c, nil
  656. }
  657. func (w *wrapHS) Stop() {
  658. w.Listener.Close()
  659. w.Lock()
  660. conns := w.conns
  661. w.conns = nil
  662. w.Unlock()
  663. for c := range conns {
  664. c.Close()
  665. }
  666. }
  667. // Poll for now..
  668. func (w *wrapHS) GracefulStop() {
  669. w.Listener.Close()
  670. for {
  671. w.Lock()
  672. l := len(w.conns)
  673. w.Unlock()
  674. if l == 0 {
  675. return
  676. }
  677. time.Sleep(50 * time.Millisecond)
  678. }
  679. }
  680. type wrapConn struct {
  681. net.Conn
  682. hs *wrapHS
  683. }
  684. func (w *wrapConn) Close() error {
  685. w.hs.Lock()
  686. delete(w.hs.conns, w.Conn)
  687. w.hs.Unlock()
  688. return w.Conn.Close()
  689. }
  690. func (te *test) startServerWithConnControl(ts testpb.TestServiceServer) *listenerWrapper {
  691. l := te.listenAndServe(ts, listenWithConnControl)
  692. return l.(*listenerWrapper)
  693. }
  694. // startServer starts a gRPC server listening. Callers should defer a
  695. // call to te.tearDown to clean up.
  696. func (te *test) startServer(ts testpb.TestServiceServer) {
  697. te.listenAndServe(ts, net.Listen)
  698. }
  699. type nopCompressor struct {
  700. grpc.Compressor
  701. }
  702. // NewNopCompressor creates a compressor to test the case that type is not supported.
  703. func NewNopCompressor() grpc.Compressor {
  704. return &nopCompressor{grpc.NewGZIPCompressor()}
  705. }
  706. func (c *nopCompressor) Type() string {
  707. return "nop"
  708. }
  709. type nopDecompressor struct {
  710. grpc.Decompressor
  711. }
  712. // NewNopDecompressor creates a decompressor to test the case that type is not supported.
  713. func NewNopDecompressor() grpc.Decompressor {
  714. return &nopDecompressor{grpc.NewGZIPDecompressor()}
  715. }
  716. func (d *nopDecompressor) Type() string {
  717. return "nop"
  718. }
  719. func (te *test) configDial(opts ...grpc.DialOption) ([]grpc.DialOption, string) {
  720. opts = append(opts, grpc.WithDialer(te.e.dialer), grpc.WithUserAgent(te.userAgent))
  721. if te.sc != nil {
  722. opts = append(opts, grpc.WithServiceConfig(te.sc))
  723. }
  724. if te.clientCompression {
  725. opts = append(opts,
  726. grpc.WithCompressor(grpc.NewGZIPCompressor()),
  727. grpc.WithDecompressor(grpc.NewGZIPDecompressor()),
  728. )
  729. }
  730. if te.clientUseCompression {
  731. opts = append(opts, grpc.WithDefaultCallOptions(grpc.UseCompressor("gzip")))
  732. }
  733. if te.clientNopCompression {
  734. opts = append(opts,
  735. grpc.WithCompressor(NewNopCompressor()),
  736. grpc.WithDecompressor(NewNopDecompressor()),
  737. )
  738. }
  739. if te.unaryClientInt != nil {
  740. opts = append(opts, grpc.WithUnaryInterceptor(te.unaryClientInt))
  741. }
  742. if te.streamClientInt != nil {
  743. opts = append(opts, grpc.WithStreamInterceptor(te.streamClientInt))
  744. }
  745. if te.maxMsgSize != nil {
  746. opts = append(opts, grpc.WithMaxMsgSize(*te.maxMsgSize))
  747. }
  748. if te.maxClientReceiveMsgSize != nil {
  749. opts = append(opts, grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(*te.maxClientReceiveMsgSize)))
  750. }
  751. if te.maxClientSendMsgSize != nil {
  752. opts = append(opts, grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(*te.maxClientSendMsgSize)))
  753. }
  754. if te.maxClientHeaderListSize != nil {
  755. opts = append(opts, grpc.WithMaxHeaderListSize(*te.maxClientHeaderListSize))
  756. }
  757. switch te.e.security {
  758. case "tls":
  759. creds, err := credentials.NewClientTLSFromFile(testdata.Path("ca.pem"), "x.test.youtube.com")
  760. if err != nil {
  761. te.t.Fatalf("Failed to load credentials: %v", err)
  762. }
  763. opts = append(opts, grpc.WithTransportCredentials(creds))
  764. case "clientTimeoutCreds":
  765. opts = append(opts, grpc.WithTransportCredentials(&clientTimeoutCreds{}))
  766. case "empty":
  767. // Don't add any transport creds option.
  768. default:
  769. opts = append(opts, grpc.WithInsecure())
  770. }
  771. // TODO(bar) switch balancer case "pick_first".
  772. var scheme string
  773. if te.resolverScheme == "" {
  774. scheme = "passthrough:///"
  775. } else {
  776. scheme = te.resolverScheme + ":///"
  777. }
  778. switch te.e.balancer {
  779. case "v1":
  780. opts = append(opts, grpc.WithBalancer(grpc.RoundRobin(nil)))
  781. case "round_robin":
  782. opts = append(opts, grpc.WithBalancerName(roundrobin.Name))
  783. }
  784. if te.clientInitialWindowSize > 0 {
  785. opts = append(opts, grpc.WithInitialWindowSize(te.clientInitialWindowSize))
  786. }
  787. if te.clientInitialConnWindowSize > 0 {
  788. opts = append(opts, grpc.WithInitialConnWindowSize(te.clientInitialConnWindowSize))
  789. }
  790. if te.perRPCCreds != nil {
  791. opts = append(opts, grpc.WithPerRPCCredentials(te.perRPCCreds))
  792. }
  793. if te.customCodec != nil {
  794. opts = append(opts, grpc.WithDefaultCallOptions(grpc.ForceCodec(te.customCodec)))
  795. }
  796. if !te.nonBlockingDial && te.srvAddr != "" {
  797. // Only do a blocking dial if server is up.
  798. opts = append(opts, grpc.WithBlock())
  799. }
  800. if te.srvAddr == "" {
  801. te.srvAddr = "client.side.only.test"
  802. }
  803. opts = append(opts, te.customDialOptions...)
  804. return opts, scheme
  805. }
  806. func (te *test) clientConnWithConnControl() (*grpc.ClientConn, *dialerWrapper) {
  807. if te.cc != nil {
  808. return te.cc, nil
  809. }
  810. opts, scheme := te.configDial()
  811. dw := &dialerWrapper{}
  812. // overwrite the dialer before
  813. opts = append(opts, grpc.WithDialer(dw.dialer))
  814. var err error
  815. te.cc, err = grpc.Dial(scheme+te.srvAddr, opts...)
  816. if err != nil {
  817. te.t.Fatalf("Dial(%q) = %v", scheme+te.srvAddr, err)
  818. }
  819. return te.cc, dw
  820. }
  821. func (te *test) clientConn(opts ...grpc.DialOption) *grpc.ClientConn {
  822. if te.cc != nil {
  823. return te.cc
  824. }
  825. var scheme string
  826. opts, scheme = te.configDial(opts...)
  827. var err error
  828. te.cc, err = grpc.Dial(scheme+te.srvAddr, opts...)
  829. if err != nil {
  830. te.t.Fatalf("Dial(%q) = %v", scheme+te.srvAddr, err)
  831. }
  832. return te.cc
  833. }
  834. func (te *test) declareLogNoise(phrases ...string) {
  835. te.restoreLogs = declareLogNoise(te.t, phrases...)
  836. }
  837. func (te *test) withServerTester(fn func(st *serverTester)) {
  838. c, err := te.e.dialer(te.srvAddr, 10*time.Second)
  839. if err != nil {
  840. te.t.Fatal(err)
  841. }
  842. defer c.Close()
  843. if te.e.security == "tls" {
  844. c = tls.Client(c, &tls.Config{
  845. InsecureSkipVerify: true,
  846. NextProtos: []string{http2.NextProtoTLS},
  847. })
  848. }
  849. st := newServerTesterFromConn(te.t, c)
  850. st.greet()
  851. fn(st)
  852. }
  853. type lazyConn struct {
  854. net.Conn
  855. beLazy int32
  856. }
  857. func (l *lazyConn) Write(b []byte) (int, error) {
  858. if atomic.LoadInt32(&(l.beLazy)) == 1 {
  859. time.Sleep(time.Second)
  860. }
  861. return l.Conn.Write(b)
  862. }
  863. func (s) TestContextDeadlineNotIgnored(t *testing.T) {
  864. e := noBalancerEnv
  865. var lc *lazyConn
  866. e.customDialer = func(network, addr string, timeout time.Duration) (net.Conn, error) {
  867. conn, err := net.DialTimeout(network, addr, timeout)
  868. if err != nil {
  869. return nil, err
  870. }
  871. lc = &lazyConn{Conn: conn}
  872. return lc, nil
  873. }
  874. te := newTest(t, e)
  875. te.startServer(&testServer{security: e.security})
  876. defer te.tearDown()
  877. cc := te.clientConn()
  878. tc := testpb.NewTestServiceClient(cc)
  879. if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); err != nil {
  880. t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, <nil>", err)
  881. }
  882. atomic.StoreInt32(&(lc.beLazy), 1)
  883. ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
  884. defer cancel()
  885. t1 := time.Now()
  886. if _, err := tc.EmptyCall(ctx, &testpb.Empty{}); status.Code(err) != codes.DeadlineExceeded {
  887. t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, context.DeadlineExceeded", err)
  888. }
  889. if time.Since(t1) > 2*time.Second {
  890. t.Fatalf("TestService/EmptyCall(_, _) ran over the deadline")
  891. }
  892. }
  893. func (s) TestTimeoutOnDeadServer(t *testing.T) {
  894. for _, e := range listTestEnv() {
  895. testTimeoutOnDeadServer(t, e)
  896. }
  897. }
  898. func testTimeoutOnDeadServer(t *testing.T, e env) {
  899. te := newTest(t, e)
  900. te.userAgent = testAppUA
  901. te.declareLogNoise(
  902. "transport: http2Client.notifyError got notified that the client transport was broken EOF",
  903. "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing",
  904. "grpc: addrConn.resetTransport failed to create client transport: connection error",
  905. )
  906. te.startServer(&testServer{security: e.security})
  907. defer te.tearDown()
  908. cc := te.clientConn()
  909. tc := testpb.NewTestServiceClient(cc)
  910. if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.WaitForReady(true)); err != nil {
  911. t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, <nil>", err)
  912. }
  913. te.srv.Stop()
  914. // Wait for the client to notice the connection is gone.
  915. ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
  916. state := cc.GetState()
  917. for ; state == connectivity.Ready && cc.WaitForStateChange(ctx, state); state = cc.GetState() {
  918. }
  919. cancel()
  920. if state == connectivity.Ready {
  921. t.Fatalf("Timed out waiting for non-ready state")
  922. }
  923. ctx, cancel = context.WithTimeout(context.Background(), time.Millisecond)
  924. _, err := tc.EmptyCall(ctx, &testpb.Empty{}, grpc.WaitForReady(true))
  925. cancel()
  926. if e.balancer != "" && status.Code(err) != codes.DeadlineExceeded {
  927. // If e.balancer == nil, the ac will stop reconnecting because the dialer returns non-temp error,
  928. // the error will be an internal error.
  929. t.Fatalf("TestService/EmptyCall(%v, _) = _, %v, want _, error code: %s", ctx, err, codes.DeadlineExceeded)
  930. }
  931. awaitNewConnLogOutput()
  932. }
  933. func (s) TestServerGracefulStopIdempotent(t *testing.T) {
  934. for _, e := range listTestEnv() {
  935. if e.name == "handler-tls" {
  936. continue
  937. }
  938. testServerGracefulStopIdempotent(t, e)
  939. }
  940. }
  941. func testServerGracefulStopIdempotent(t *testing.T, e env) {
  942. te := newTest(t, e)
  943. te.userAgent = testAppUA
  944. te.startServer(&testServer{security: e.security})
  945. defer te.tearDown()
  946. for i := 0; i < 3; i++ {
  947. te.srv.GracefulStop()
  948. }
  949. }
  950. func (s) TestServerGoAway(t *testing.T) {
  951. for _, e := range listTestEnv() {
  952. if e.name == "handler-tls" {
  953. continue
  954. }
  955. testServerGoAway(t, e)
  956. }
  957. }
  958. func testServerGoAway(t *testing.T, e env) {
  959. te := newTest(t, e)
  960. te.userAgent = testAppUA
  961. te.startServer(&testServer{security: e.security})
  962. defer te.tearDown()
  963. cc := te.clientConn()
  964. tc := testpb.NewTestServiceClient(cc)
  965. // Finish an RPC to make sure the connection is good.
  966. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  967. defer cancel()
  968. if _, err := tc.EmptyCall(ctx, &testpb.Empty{}, grpc.WaitForReady(true)); err != nil {
  969. t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, <nil>", err)
  970. }
  971. ch := make(chan struct{})
  972. go func() {
  973. te.srv.GracefulStop()
  974. close(ch)
  975. }()
  976. // Loop until the server side GoAway signal is propagated to the client.
  977. for {
  978. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
  979. if _, err := tc.EmptyCall(ctx, &testpb.Empty{}); err != nil && status.Code(err) != codes.DeadlineExceeded {
  980. cancel()
  981. break
  982. }
  983. cancel()
  984. }
  985. // A new RPC should fail.
  986. ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
  987. defer cancel()
  988. if _, err := tc.EmptyCall(ctx, &testpb.Empty{}); status.Code(err) != codes.Unavailable && status.Code(err) != codes.Internal {
  989. t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s or %s", err, codes.Unavailable, codes.Internal)
  990. }
  991. <-ch
  992. awaitNewConnLogOutput()
  993. }
  994. func (s) TestServerGoAwayPendingRPC(t *testing.T) {
  995. for _, e := range listTestEnv() {
  996. if e.name == "handler-tls" {
  997. continue
  998. }
  999. testServerGoAwayPendingRPC(t, e)
  1000. }
  1001. }
  1002. func testServerGoAwayPendingRPC(t *testing.T, e env) {
  1003. te := newTest(t, e)
  1004. te.userAgent = testAppUA
  1005. te.declareLogNoise(
  1006. "transport: http2Client.notifyError got notified that the client transport was broken EOF",
  1007. "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing",
  1008. "grpc: addrConn.resetTransport failed to create client transport: connection error",
  1009. )
  1010. te.startServer(&testServer{security: e.security})
  1011. defer te.tearDown()
  1012. cc := te.clientConn()
  1013. tc := testpb.NewTestServiceClient(cc)
  1014. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  1015. stream, err := tc.FullDuplexCall(ctx, grpc.WaitForReady(true))
  1016. if err != nil {
  1017. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  1018. }
  1019. // Finish an RPC to make sure the connection is good.
  1020. if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.WaitForReady(true)); err != nil {
  1021. t.Fatalf("%v.EmptyCall(_, _, _) = _, %v, want _, <nil>", tc, err)
  1022. }
  1023. ch := make(chan struct{})
  1024. go func() {
  1025. te.srv.GracefulStop()
  1026. close(ch)
  1027. }()
  1028. // Loop until the server side GoAway signal is propagated to the client.
  1029. start := time.Now()
  1030. errored := false
  1031. for time.Since(start) < time.Second {
  1032. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
  1033. _, err := tc.EmptyCall(ctx, &testpb.Empty{}, grpc.WaitForReady(true))
  1034. cancel()
  1035. if err != nil {
  1036. errored = true
  1037. break
  1038. }
  1039. }
  1040. if !errored {
  1041. t.Fatalf("GoAway never received by client")
  1042. }
  1043. respParam := []*testpb.ResponseParameters{{Size: 1}}
  1044. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(100))
  1045. if err != nil {
  1046. t.Fatal(err)
  1047. }
  1048. req := &testpb.StreamingOutputCallRequest{
  1049. ResponseType: testpb.PayloadType_COMPRESSABLE,
  1050. ResponseParameters: respParam,
  1051. Payload: payload,
  1052. }
  1053. // The existing RPC should be still good to proceed.
  1054. if err := stream.Send(req); err != nil {
  1055. t.Fatalf("%v.Send(_) = %v, want <nil>", stream, err)
  1056. }
  1057. if _, err := stream.Recv(); err != nil {
  1058. t.Fatalf("%v.Recv() = _, %v, want _, <nil>", stream, err)
  1059. }
  1060. // The RPC will run until canceled.
  1061. cancel()
  1062. <-ch
  1063. awaitNewConnLogOutput()
  1064. }
  1065. func (s) TestServerMultipleGoAwayPendingRPC(t *testing.T) {
  1066. for _, e := range listTestEnv() {
  1067. if e.name == "handler-tls" {
  1068. continue
  1069. }
  1070. testServerMultipleGoAwayPendingRPC(t, e)
  1071. }
  1072. }
  1073. func testServerMultipleGoAwayPendingRPC(t *testing.T, e env) {
  1074. te := newTest(t, e)
  1075. te.userAgent = testAppUA
  1076. te.declareLogNoise(
  1077. "transport: http2Client.notifyError got notified that the client transport was broken EOF",
  1078. "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing",
  1079. "grpc: addrConn.resetTransport failed to create client transport: connection error",
  1080. )
  1081. te.startServer(&testServer{security: e.security})
  1082. defer te.tearDown()
  1083. cc := te.clientConn()
  1084. tc := testpb.NewTestServiceClient(cc)
  1085. ctx, cancel := context.WithCancel(context.Background())
  1086. stream, err := tc.FullDuplexCall(ctx, grpc.WaitForReady(true))
  1087. if err != nil {
  1088. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  1089. }
  1090. // Finish an RPC to make sure the connection is good.
  1091. if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.WaitForReady(true)); err != nil {
  1092. t.Fatalf("%v.EmptyCall(_, _, _) = _, %v, want _, <nil>", tc, err)
  1093. }
  1094. ch1 := make(chan struct{})
  1095. go func() {
  1096. te.srv.GracefulStop()
  1097. close(ch1)
  1098. }()
  1099. ch2 := make(chan struct{})
  1100. go func() {
  1101. te.srv.GracefulStop()
  1102. close(ch2)
  1103. }()
  1104. // Loop until the server side GoAway signal is propagated to the client.
  1105. for {
  1106. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
  1107. if _, err := tc.EmptyCall(ctx, &testpb.Empty{}, grpc.WaitForReady(true)); err != nil {
  1108. cancel()
  1109. break
  1110. }
  1111. cancel()
  1112. }
  1113. select {
  1114. case <-ch1:
  1115. t.Fatal("GracefulStop() terminated early")
  1116. case <-ch2:
  1117. t.Fatal("GracefulStop() terminated early")
  1118. default:
  1119. }
  1120. respParam := []*testpb.ResponseParameters{
  1121. {
  1122. Size: 1,
  1123. },
  1124. }
  1125. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(100))
  1126. if err != nil {
  1127. t.Fatal(err)
  1128. }
  1129. req := &testpb.StreamingOutputCallRequest{
  1130. ResponseType: testpb.PayloadType_COMPRESSABLE,
  1131. ResponseParameters: respParam,
  1132. Payload: payload,
  1133. }
  1134. // The existing RPC should be still good to proceed.
  1135. if err := stream.Send(req); err != nil {
  1136. t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, req, err)
  1137. }
  1138. if _, err := stream.Recv(); err != nil {
  1139. t.Fatalf("%v.Recv() = _, %v, want _, <nil>", stream, err)
  1140. }
  1141. if err := stream.CloseSend(); err != nil {
  1142. t.Fatalf("%v.CloseSend() = %v, want <nil>", stream, err)
  1143. }
  1144. <-ch1
  1145. <-ch2
  1146. cancel()
  1147. awaitNewConnLogOutput()
  1148. }
  1149. func (s) TestConcurrentClientConnCloseAndServerGoAway(t *testing.T) {
  1150. for _, e := range listTestEnv() {
  1151. if e.name == "handler-tls" {
  1152. continue
  1153. }
  1154. testConcurrentClientConnCloseAndServerGoAway(t, e)
  1155. }
  1156. }
  1157. func testConcurrentClientConnCloseAndServerGoAway(t *testing.T, e env) {
  1158. te := newTest(t, e)
  1159. te.userAgent = testAppUA
  1160. te.declareLogNoise(
  1161. "transport: http2Client.notifyError got notified that the client transport was broken EOF",
  1162. "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing",
  1163. "grpc: addrConn.resetTransport failed to create client transport: connection error",
  1164. )
  1165. te.startServer(&testServer{security: e.security})
  1166. defer te.tearDown()
  1167. cc := te.clientConn()
  1168. tc := testpb.NewTestServiceClient(cc)
  1169. if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.WaitForReady(true)); err != nil {
  1170. t.Fatalf("%v.EmptyCall(_, _, _) = _, %v, want _, <nil>", tc, err)
  1171. }
  1172. ch := make(chan struct{})
  1173. // Close ClientConn and Server concurrently.
  1174. go func() {
  1175. te.srv.GracefulStop()
  1176. close(ch)
  1177. }()
  1178. go func() {
  1179. cc.Close()
  1180. }()
  1181. <-ch
  1182. }
  1183. func (s) TestConcurrentServerStopAndGoAway(t *testing.T) {
  1184. for _, e := range listTestEnv() {
  1185. if e.name == "handler-tls" {
  1186. continue
  1187. }
  1188. testConcurrentServerStopAndGoAway(t, e)
  1189. }
  1190. }
  1191. func testConcurrentServerStopAndGoAway(t *testing.T, e env) {
  1192. te := newTest(t, e)
  1193. te.userAgent = testAppUA
  1194. te.declareLogNoise(
  1195. "transport: http2Client.notifyError got notified that the client transport was broken EOF",
  1196. "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing",
  1197. "grpc: addrConn.resetTransport failed to create client transport: connection error",
  1198. )
  1199. te.startServer(&testServer{security: e.security})
  1200. defer te.tearDown()
  1201. cc := te.clientConn()
  1202. tc := testpb.NewTestServiceClient(cc)
  1203. stream, err := tc.FullDuplexCall(context.Background(), grpc.WaitForReady(true))
  1204. if err != nil {
  1205. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  1206. }
  1207. // Finish an RPC to make sure the connection is good.
  1208. if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.WaitForReady(true)); err != nil {
  1209. t.Fatalf("%v.EmptyCall(_, _, _) = _, %v, want _, <nil>", tc, err)
  1210. }
  1211. ch := make(chan struct{})
  1212. go func() {
  1213. te.srv.GracefulStop()
  1214. close(ch)
  1215. }()
  1216. // Loop until the server side GoAway signal is propagated to the client.
  1217. for {
  1218. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
  1219. if _, err := tc.EmptyCall(ctx, &testpb.Empty{}, grpc.WaitForReady(true)); err != nil {
  1220. cancel()
  1221. break
  1222. }
  1223. cancel()
  1224. }
  1225. // Stop the server and close all the connections.
  1226. te.srv.Stop()
  1227. respParam := []*testpb.ResponseParameters{
  1228. {
  1229. Size: 1,
  1230. },
  1231. }
  1232. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(100))
  1233. if err != nil {
  1234. t.Fatal(err)
  1235. }
  1236. req := &testpb.StreamingOutputCallRequest{
  1237. ResponseType: testpb.PayloadType_COMPRESSABLE,
  1238. ResponseParameters: respParam,
  1239. Payload: payload,
  1240. }
  1241. sendStart := time.Now()
  1242. for {
  1243. if err := stream.Send(req); err == io.EOF {
  1244. // stream.Send should eventually send io.EOF
  1245. break
  1246. } else if err != nil {
  1247. // Send should never return a transport-level error.
  1248. t.Fatalf("stream.Send(%v) = %v; want <nil or io.EOF>", req, err)
  1249. }
  1250. if time.Since(sendStart) > 2*time.Second {
  1251. t.Fatalf("stream.Send(_) did not return io.EOF after 2s")
  1252. }
  1253. time.Sleep(time.Millisecond)
  1254. }
  1255. if _, err := stream.Recv(); err == nil || err == io.EOF {
  1256. t.Fatalf("%v.Recv() = _, %v, want _, <non-nil, non-EOF>", stream, err)
  1257. }
  1258. <-ch
  1259. awaitNewConnLogOutput()
  1260. }
  1261. func (s) TestClientConnCloseAfterGoAwayWithActiveStream(t *testing.T) {
  1262. for _, e := range listTestEnv() {
  1263. if e.name == "handler-tls" {
  1264. continue
  1265. }
  1266. testClientConnCloseAfterGoAwayWithActiveStream(t, e)
  1267. }
  1268. }
  1269. func testClientConnCloseAfterGoAwayWithActiveStream(t *testing.T, e env) {
  1270. te := newTest(t, e)
  1271. te.startServer(&testServer{security: e.security})
  1272. defer te.tearDown()
  1273. cc := te.clientConn()
  1274. tc := testpb.NewTestServiceClient(cc)
  1275. ctx, cancel := context.WithCancel(context.Background())
  1276. defer cancel()
  1277. if _, err := tc.FullDuplexCall(ctx); err != nil {
  1278. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want _, <nil>", tc, err)
  1279. }
  1280. done := make(chan struct{})
  1281. go func() {
  1282. te.srv.GracefulStop()
  1283. close(done)
  1284. }()
  1285. time.Sleep(50 * time.Millisecond)
  1286. cc.Close()
  1287. timeout := time.NewTimer(time.Second)
  1288. select {
  1289. case <-done:
  1290. case <-timeout.C:
  1291. t.Fatalf("Test timed-out.")
  1292. }
  1293. }
  1294. func (s) TestFailFast(t *testing.T) {
  1295. for _, e := range listTestEnv() {
  1296. testFailFast(t, e)
  1297. }
  1298. }
  1299. func testFailFast(t *testing.T, e env) {
  1300. te := newTest(t, e)
  1301. te.userAgent = testAppUA
  1302. te.declareLogNoise(
  1303. "transport: http2Client.notifyError got notified that the client transport was broken EOF",
  1304. "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing",
  1305. "grpc: addrConn.resetTransport failed to create client transport: connection error",
  1306. )
  1307. te.startServer(&testServer{security: e.security})
  1308. defer te.tearDown()
  1309. cc := te.clientConn()
  1310. tc := testpb.NewTestServiceClient(cc)
  1311. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  1312. defer cancel()
  1313. if _, err := tc.EmptyCall(ctx, &testpb.Empty{}); err != nil {
  1314. t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, <nil>", err)
  1315. }
  1316. // Stop the server and tear down all the existing connections.
  1317. te.srv.Stop()
  1318. // Loop until the server teardown is propagated to the client.
  1319. for {
  1320. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  1321. _, err := tc.EmptyCall(ctx, &testpb.Empty{})
  1322. cancel()
  1323. if status.Code(err) == codes.Unavailable {
  1324. break
  1325. }
  1326. t.Logf("%v.EmptyCall(_, _) = _, %v", tc, err)
  1327. time.Sleep(10 * time.Millisecond)
  1328. }
  1329. // The client keeps reconnecting and ongoing fail-fast RPCs should fail with code.Unavailable.
  1330. if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); status.Code(err) != codes.Unavailable {
  1331. t.Fatalf("TestService/EmptyCall(_, _, _) = _, %v, want _, error code: %s", err, codes.Unavailable)
  1332. }
  1333. if _, err := tc.StreamingInputCall(context.Background()); status.Code(err) != codes.Unavailable {
  1334. t.Fatalf("TestService/StreamingInputCall(_) = _, %v, want _, error code: %s", err, codes.Unavailable)
  1335. }
  1336. awaitNewConnLogOutput()
  1337. }
  1338. func testServiceConfigSetup(t *testing.T, e env) *test {
  1339. te := newTest(t, e)
  1340. te.userAgent = testAppUA
  1341. te.declareLogNoise(
  1342. "transport: http2Client.notifyError got notified that the client transport was broken EOF",
  1343. "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing",
  1344. "grpc: addrConn.resetTransport failed to create client transport: connection error",
  1345. "Failed to dial : context canceled; please retry.",
  1346. )
  1347. return te
  1348. }
  1349. func newBool(b bool) (a *bool) {
  1350. return &b
  1351. }
  1352. func newInt(b int) (a *int) {
  1353. return &b
  1354. }
  1355. func newDuration(b time.Duration) (a *time.Duration) {
  1356. a = new(time.Duration)
  1357. *a = b
  1358. return
  1359. }
  1360. func (s) TestGetMethodConfig(t *testing.T) {
  1361. te := testServiceConfigSetup(t, tcpClearRREnv)
  1362. defer te.tearDown()
  1363. r, rcleanup := manual.GenerateAndRegisterManualResolver()
  1364. defer rcleanup()
  1365. te.resolverScheme = r.Scheme()
  1366. cc := te.clientConn()
  1367. addrs := []resolver.Address{{Addr: te.srvAddr}}
  1368. r.UpdateState(resolver.State{
  1369. Addresses: addrs,
  1370. ServiceConfig: `{
  1371. "methodConfig": [
  1372. {
  1373. "name": [
  1374. {
  1375. "service": "grpc.testing.TestService",
  1376. "method": "EmptyCall"
  1377. }
  1378. ],
  1379. "waitForReady": true,
  1380. "timeout": ".001s"
  1381. },
  1382. {
  1383. "name": [
  1384. {
  1385. "service": "grpc.testing.TestService"
  1386. }
  1387. ],
  1388. "waitForReady": false
  1389. }
  1390. ]
  1391. }`})
  1392. tc := testpb.NewTestServiceClient(cc)
  1393. // Make sure service config has been processed by grpc.
  1394. for {
  1395. if cc.GetMethodConfig("/grpc.testing.TestService/EmptyCall").WaitForReady != nil {
  1396. break
  1397. }
  1398. time.Sleep(time.Millisecond)
  1399. }
  1400. // The following RPCs are expected to become non-fail-fast ones with 1ms deadline.
  1401. var err error
  1402. if _, err = tc.EmptyCall(context.Background(), &testpb.Empty{}); status.Code(err) != codes.DeadlineExceeded {
  1403. t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded)
  1404. }
  1405. r.UpdateState(resolver.State{Addresses: addrs, ServiceConfig: `{
  1406. "methodConfig": [
  1407. {
  1408. "name": [
  1409. {
  1410. "service": "grpc.testing.TestService",
  1411. "method": "UnaryCall"
  1412. }
  1413. ],
  1414. "waitForReady": true,
  1415. "timeout": ".001s"
  1416. },
  1417. {
  1418. "name": [
  1419. {
  1420. "service": "grpc.testing.TestService"
  1421. }
  1422. ],
  1423. "waitForReady": false
  1424. }
  1425. ]
  1426. }`})
  1427. // Make sure service config has been processed by grpc.
  1428. for {
  1429. if mc := cc.GetMethodConfig("/grpc.testing.TestService/EmptyCall"); mc.WaitForReady != nil && !*mc.WaitForReady {
  1430. break
  1431. }
  1432. time.Sleep(time.Millisecond)
  1433. }
  1434. // The following RPCs are expected to become fail-fast.
  1435. if _, err = tc.EmptyCall(context.Background(), &testpb.Empty{}); status.Code(err) != codes.Unavailable {
  1436. t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.Unavailable)
  1437. }
  1438. }
  1439. func (s) TestServiceConfigWaitForReady(t *testing.T) {
  1440. te := testServiceConfigSetup(t, tcpClearRREnv)
  1441. defer te.tearDown()
  1442. r, rcleanup := manual.GenerateAndRegisterManualResolver()
  1443. defer rcleanup()
  1444. // Case1: Client API set failfast to be false, and service config set wait_for_ready to be false, Client API should win, and the rpc will wait until deadline exceeds.
  1445. te.resolverScheme = r.Scheme()
  1446. cc := te.clientConn()
  1447. addrs := []resolver.Address{{Addr: te.srvAddr}}
  1448. r.UpdateState(resolver.State{
  1449. Addresses: addrs,
  1450. ServiceConfig: `{
  1451. "methodConfig": [
  1452. {
  1453. "name": [
  1454. {
  1455. "service": "grpc.testing.TestService",
  1456. "method": "EmptyCall"
  1457. },
  1458. {
  1459. "service": "grpc.testing.TestService",
  1460. "method": "FullDuplexCall"
  1461. }
  1462. ],
  1463. "waitForReady": false,
  1464. "timeout": ".001s"
  1465. }
  1466. ]
  1467. }`})
  1468. tc := testpb.NewTestServiceClient(cc)
  1469. // Make sure service config has been processed by grpc.
  1470. for {
  1471. if cc.GetMethodConfig("/grpc.testing.TestService/FullDuplexCall").WaitForReady != nil {
  1472. break
  1473. }
  1474. time.Sleep(time.Millisecond)
  1475. }
  1476. // The following RPCs are expected to become non-fail-fast ones with 1ms deadline.
  1477. var err error
  1478. if _, err = tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.WaitForReady(true)); status.Code(err) != codes.DeadlineExceeded {
  1479. t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded)
  1480. }
  1481. if _, err := tc.FullDuplexCall(context.Background(), grpc.WaitForReady(true)); status.Code(err) != codes.DeadlineExceeded {
  1482. t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want %s", err, codes.DeadlineExceeded)
  1483. }
  1484. // Generate a service config update.
  1485. // Case2:Client API set failfast to be false, and service config set wait_for_ready to be true, and the rpc will wait until deadline exceeds.
  1486. r.UpdateState(resolver.State{
  1487. Addresses: addrs,
  1488. ServiceConfig: `{
  1489. "methodConfig": [
  1490. {
  1491. "name": [
  1492. {
  1493. "service": "grpc.testing.TestService",
  1494. "method": "EmptyCall"
  1495. },
  1496. {
  1497. "service": "grpc.testing.TestService",
  1498. "method": "FullDuplexCall"
  1499. }
  1500. ],
  1501. "waitForReady": true,
  1502. "timeout": ".001s"
  1503. }
  1504. ]
  1505. }`})
  1506. // Wait for the new service config to take effect.
  1507. for {
  1508. if mc := cc.GetMethodConfig("/grpc.testing.TestService/EmptyCall"); mc.WaitForReady != nil && *mc.WaitForReady {
  1509. break
  1510. }
  1511. time.Sleep(time.Millisecond)
  1512. }
  1513. // The following RPCs are expected to become non-fail-fast ones with 1ms deadline.
  1514. if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); status.Code(err) != codes.DeadlineExceeded {
  1515. t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded)
  1516. }
  1517. if _, err := tc.FullDuplexCall(context.Background()); status.Code(err) != codes.DeadlineExceeded {
  1518. t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want %s", err, codes.DeadlineExceeded)
  1519. }
  1520. }
  1521. func (s) TestServiceConfigTimeout(t *testing.T) {
  1522. te := testServiceConfigSetup(t, tcpClearRREnv)
  1523. defer te.tearDown()
  1524. r, rcleanup := manual.GenerateAndRegisterManualResolver()
  1525. defer rcleanup()
  1526. // Case1: Client API sets timeout to be 1ns and ServiceConfig sets timeout to be 1hr. Timeout should be 1ns (min of 1ns and 1hr) and the rpc will wait until deadline exceeds.
  1527. te.resolverScheme = r.Scheme()
  1528. cc := te.clientConn()
  1529. addrs := []resolver.Address{{Addr: te.srvAddr}}
  1530. r.UpdateState(resolver.State{
  1531. Addresses: addrs,
  1532. ServiceConfig: `{
  1533. "methodConfig": [
  1534. {
  1535. "name": [
  1536. {
  1537. "service": "grpc.testing.TestService",
  1538. "method": "EmptyCall"
  1539. },
  1540. {
  1541. "service": "grpc.testing.TestService",
  1542. "method": "FullDuplexCall"
  1543. }
  1544. ],
  1545. "waitForReady": true,
  1546. "timeout": "3600s"
  1547. }
  1548. ]
  1549. }`})
  1550. tc := testpb.NewTestServiceClient(cc)
  1551. // Make sure service config has been processed by grpc.
  1552. for {
  1553. if cc.GetMethodConfig("/grpc.testing.TestService/FullDuplexCall").Timeout != nil {
  1554. break
  1555. }
  1556. time.Sleep(time.Millisecond)
  1557. }
  1558. // The following RPCs are expected to become non-fail-fast ones with 1ns deadline.
  1559. var err error
  1560. ctx, cancel := context.WithTimeout(context.Background(), time.Nanosecond)
  1561. if _, err = tc.EmptyCall(ctx, &testpb.Empty{}, grpc.WaitForReady(true)); status.Code(err) != codes.DeadlineExceeded {
  1562. t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded)
  1563. }
  1564. cancel()
  1565. ctx, cancel = context.WithTimeout(context.Background(), time.Nanosecond)
  1566. if _, err = tc.FullDuplexCall(ctx, grpc.WaitForReady(true)); status.Code(err) != codes.DeadlineExceeded {
  1567. t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want %s", err, codes.DeadlineExceeded)
  1568. }
  1569. cancel()
  1570. // Generate a service config update.
  1571. // Case2: Client API sets timeout to be 1hr and ServiceConfig sets timeout to be 1ns. Timeout should be 1ns (min of 1ns and 1hr) and the rpc will wait until deadline exceeds.
  1572. r.UpdateState(resolver.State{
  1573. Addresses: addrs,
  1574. ServiceConfig: `{
  1575. "methodConfig": [
  1576. {
  1577. "name": [
  1578. {
  1579. "service": "grpc.testing.TestService",
  1580. "method": "EmptyCall"
  1581. },
  1582. {
  1583. "service": "grpc.testing.TestService",
  1584. "method": "FullDuplexCall"
  1585. }
  1586. ],
  1587. "waitForReady": true,
  1588. "timeout": ".000000001s"
  1589. }
  1590. ]
  1591. }`})
  1592. // Wait for the new service config to take effect.
  1593. for {
  1594. if mc := cc.GetMethodConfig("/grpc.testing.TestService/FullDuplexCall"); mc.Timeout != nil && *mc.Timeout == time.Nanosecond {
  1595. break
  1596. }
  1597. time.Sleep(time.Millisecond)
  1598. }
  1599. ctx, cancel = context.WithTimeout(context.Background(), time.Hour)
  1600. if _, err = tc.EmptyCall(ctx, &testpb.Empty{}, grpc.WaitForReady(true)); status.Code(err) != codes.DeadlineExceeded {
  1601. t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded)
  1602. }
  1603. cancel()
  1604. ctx, cancel = context.WithTimeout(context.Background(), time.Hour)
  1605. if _, err = tc.FullDuplexCall(ctx, grpc.WaitForReady(true)); status.Code(err) != codes.DeadlineExceeded {
  1606. t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want %s", err, codes.DeadlineExceeded)
  1607. }
  1608. cancel()
  1609. }
  1610. func (s) TestServiceConfigMaxMsgSize(t *testing.T) {
  1611. e := tcpClearRREnv
  1612. r, rcleanup := manual.GenerateAndRegisterManualResolver()
  1613. defer rcleanup()
  1614. // Setting up values and objects shared across all test cases.
  1615. const smallSize = 1
  1616. const largeSize = 1024
  1617. const extraLargeSize = 2048
  1618. smallPayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, smallSize)
  1619. if err != nil {
  1620. t.Fatal(err)
  1621. }
  1622. largePayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, largeSize)
  1623. if err != nil {
  1624. t.Fatal(err)
  1625. }
  1626. extraLargePayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, extraLargeSize)
  1627. if err != nil {
  1628. t.Fatal(err)
  1629. }
  1630. scjs := `{
  1631. "methodConfig": [
  1632. {
  1633. "name": [
  1634. {
  1635. "service": "grpc.testing.TestService",
  1636. "method": "UnaryCall"
  1637. },
  1638. {
  1639. "service": "grpc.testing.TestService",
  1640. "method": "FullDuplexCall"
  1641. }
  1642. ],
  1643. "maxRequestMessageBytes": 2048,
  1644. "maxResponseMessageBytes": 2048
  1645. }
  1646. ]
  1647. }`
  1648. // Case1: sc set maxReqSize to 2048 (send), maxRespSize to 2048 (recv).
  1649. te1 := testServiceConfigSetup(t, e)
  1650. defer te1.tearDown()
  1651. te1.resolverScheme = r.Scheme()
  1652. te1.nonBlockingDial = true
  1653. te1.startServer(&testServer{security: e.security})
  1654. cc1 := te1.clientConn()
  1655. addrs := []resolver.Address{{Addr: te1.srvAddr}}
  1656. r.UpdateState(resolver.State{Addresses: addrs, ServiceConfig: scjs})
  1657. tc := testpb.NewTestServiceClient(cc1)
  1658. req := &testpb.SimpleRequest{
  1659. ResponseType: testpb.PayloadType_COMPRESSABLE,
  1660. ResponseSize: int32(extraLargeSize),
  1661. Payload: smallPayload,
  1662. }
  1663. for {
  1664. if cc1.GetMethodConfig("/grpc.testing.TestService/FullDuplexCall").MaxReqSize != nil {
  1665. break
  1666. }
  1667. time.Sleep(time.Millisecond)
  1668. }
  1669. // Test for unary RPC recv.
  1670. if _, err = tc.UnaryCall(context.Background(), req, grpc.WaitForReady(true)); err == nil || status.Code(err) != codes.ResourceExhausted {
  1671. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted)
  1672. }
  1673. // Test for unary RPC send.
  1674. req.Payload = extraLargePayload
  1675. req.ResponseSize = int32(smallSize)
  1676. if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted {
  1677. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted)
  1678. }
  1679. // Test for streaming RPC recv.
  1680. respParam := []*testpb.ResponseParameters{
  1681. {
  1682. Size: int32(extraLargeSize),
  1683. },
  1684. }
  1685. sreq := &testpb.StreamingOutputCallRequest{
  1686. ResponseType: testpb.PayloadType_COMPRESSABLE,
  1687. ResponseParameters: respParam,
  1688. Payload: smallPayload,
  1689. }
  1690. stream, err := tc.FullDuplexCall(te1.ctx)
  1691. if err != nil {
  1692. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  1693. }
  1694. if err = stream.Send(sreq); err != nil {
  1695. t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err)
  1696. }
  1697. if _, err = stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted {
  1698. t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted)
  1699. }
  1700. // Test for streaming RPC send.
  1701. respParam[0].Size = int32(smallSize)
  1702. sreq.Payload = extraLargePayload
  1703. stream, err = tc.FullDuplexCall(te1.ctx)
  1704. if err != nil {
  1705. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  1706. }
  1707. if err = stream.Send(sreq); err == nil || status.Code(err) != codes.ResourceExhausted {
  1708. t.Fatalf("%v.Send(%v) = %v, want _, error code: %s", stream, sreq, err, codes.ResourceExhausted)
  1709. }
  1710. // Case2: Client API set maxReqSize to 1024 (send), maxRespSize to 1024 (recv). Sc sets maxReqSize to 2048 (send), maxRespSize to 2048 (recv).
  1711. te2 := testServiceConfigSetup(t, e)
  1712. te2.resolverScheme = r.Scheme()
  1713. te2.nonBlockingDial = true
  1714. te2.maxClientReceiveMsgSize = newInt(1024)
  1715. te2.maxClientSendMsgSize = newInt(1024)
  1716. te2.startServer(&testServer{security: e.security})
  1717. defer te2.tearDown()
  1718. cc2 := te2.clientConn()
  1719. r.UpdateState(resolver.State{Addresses: []resolver.Address{{Addr: te2.srvAddr}}, ServiceConfig: scjs})
  1720. tc = testpb.NewTestServiceClient(cc2)
  1721. for {
  1722. if cc2.GetMethodConfig("/grpc.testing.TestService/FullDuplexCall").MaxReqSize != nil {
  1723. break
  1724. }
  1725. time.Sleep(time.Millisecond)
  1726. }
  1727. // Test for unary RPC recv.
  1728. req.Payload = smallPayload
  1729. req.ResponseSize = int32(largeSize)
  1730. if _, err = tc.UnaryCall(context.Background(), req, grpc.WaitForReady(true)); err == nil || status.Code(err) != codes.ResourceExhausted {
  1731. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted)
  1732. }
  1733. // Test for unary RPC send.
  1734. req.Payload = largePayload
  1735. req.ResponseSize = int32(smallSize)
  1736. if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted {
  1737. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted)
  1738. }
  1739. // Test for streaming RPC recv.
  1740. stream, err = tc.FullDuplexCall(te2.ctx)
  1741. respParam[0].Size = int32(largeSize)
  1742. sreq.Payload = smallPayload
  1743. if err != nil {
  1744. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  1745. }
  1746. if err = stream.Send(sreq); err != nil {
  1747. t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err)
  1748. }
  1749. if _, err = stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted {
  1750. t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted)
  1751. }
  1752. // Test for streaming RPC send.
  1753. respParam[0].Size = int32(smallSize)
  1754. sreq.Payload = largePayload
  1755. stream, err = tc.FullDuplexCall(te2.ctx)
  1756. if err != nil {
  1757. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  1758. }
  1759. if err = stream.Send(sreq); err == nil || status.Code(err) != codes.ResourceExhausted {
  1760. t.Fatalf("%v.Send(%v) = %v, want _, error code: %s", stream, sreq, err, codes.ResourceExhausted)
  1761. }
  1762. // Case3: Client API set maxReqSize to 4096 (send), maxRespSize to 4096 (recv). Sc sets maxReqSize to 2048 (send), maxRespSize to 2048 (recv).
  1763. te3 := testServiceConfigSetup(t, e)
  1764. te3.resolverScheme = r.Scheme()
  1765. te3.nonBlockingDial = true
  1766. te3.maxClientReceiveMsgSize = newInt(4096)
  1767. te3.maxClientSendMsgSize = newInt(4096)
  1768. te3.startServer(&testServer{security: e.security})
  1769. defer te3.tearDown()
  1770. cc3 := te3.clientConn()
  1771. r.UpdateState(resolver.State{Addresses: []resolver.Address{{Addr: te3.srvAddr}}, ServiceConfig: scjs})
  1772. tc = testpb.NewTestServiceClient(cc3)
  1773. for {
  1774. if cc3.GetMethodConfig("/grpc.testing.TestService/FullDuplexCall").MaxReqSize != nil {
  1775. break
  1776. }
  1777. time.Sleep(time.Millisecond)
  1778. }
  1779. // Test for unary RPC recv.
  1780. req.Payload = smallPayload
  1781. req.ResponseSize = int32(largeSize)
  1782. if _, err = tc.UnaryCall(context.Background(), req, grpc.WaitForReady(true)); err != nil {
  1783. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want <nil>", err)
  1784. }
  1785. req.ResponseSize = int32(extraLargeSize)
  1786. if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted {
  1787. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted)
  1788. }
  1789. // Test for unary RPC send.
  1790. req.Payload = largePayload
  1791. req.ResponseSize = int32(smallSize)
  1792. if _, err := tc.UnaryCall(context.Background(), req); err != nil {
  1793. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want <nil>", err)
  1794. }
  1795. req.Payload = extraLargePayload
  1796. if _, err = tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted {
  1797. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted)
  1798. }
  1799. // Test for streaming RPC recv.
  1800. stream, err = tc.FullDuplexCall(te3.ctx)
  1801. if err != nil {
  1802. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  1803. }
  1804. respParam[0].Size = int32(largeSize)
  1805. sreq.Payload = smallPayload
  1806. if err = stream.Send(sreq); err != nil {
  1807. t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err)
  1808. }
  1809. if _, err = stream.Recv(); err != nil {
  1810. t.Fatalf("%v.Recv() = _, %v, want <nil>", stream, err)
  1811. }
  1812. respParam[0].Size = int32(extraLargeSize)
  1813. if err = stream.Send(sreq); err != nil {
  1814. t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err)
  1815. }
  1816. if _, err = stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted {
  1817. t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted)
  1818. }
  1819. // Test for streaming RPC send.
  1820. respParam[0].Size = int32(smallSize)
  1821. sreq.Payload = largePayload
  1822. stream, err = tc.FullDuplexCall(te3.ctx)
  1823. if err != nil {
  1824. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  1825. }
  1826. if err := stream.Send(sreq); err != nil {
  1827. t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err)
  1828. }
  1829. sreq.Payload = extraLargePayload
  1830. if err := stream.Send(sreq); err == nil || status.Code(err) != codes.ResourceExhausted {
  1831. t.Fatalf("%v.Send(%v) = %v, want _, error code: %s", stream, sreq, err, codes.ResourceExhausted)
  1832. }
  1833. }
  1834. // Reading from a streaming RPC may fail with context canceled if timeout was
  1835. // set by service config (https://github.com/grpc/grpc-go/issues/1818). This
  1836. // test makes sure read from streaming RPC doesn't fail in this case.
  1837. func (s) TestStreamingRPCWithTimeoutInServiceConfigRecv(t *testing.T) {
  1838. te := testServiceConfigSetup(t, tcpClearRREnv)
  1839. te.startServer(&testServer{security: tcpClearRREnv.security})
  1840. defer te.tearDown()
  1841. r, rcleanup := manual.GenerateAndRegisterManualResolver()
  1842. defer rcleanup()
  1843. te.resolverScheme = r.Scheme()
  1844. te.nonBlockingDial = true
  1845. cc := te.clientConn()
  1846. tc := testpb.NewTestServiceClient(cc)
  1847. r.UpdateState(resolver.State{
  1848. Addresses: []resolver.Address{{Addr: te.srvAddr}},
  1849. ServiceConfig: `{
  1850. "methodConfig": [
  1851. {
  1852. "name": [
  1853. {
  1854. "service": "grpc.testing.TestService",
  1855. "method": "FullDuplexCall"
  1856. }
  1857. ],
  1858. "waitForReady": true,
  1859. "timeout": "10s"
  1860. }
  1861. ]
  1862. }`})
  1863. // Make sure service config has been processed by grpc.
  1864. for {
  1865. if cc.GetMethodConfig("/grpc.testing.TestService/FullDuplexCall").Timeout != nil {
  1866. break
  1867. }
  1868. time.Sleep(time.Millisecond)
  1869. }
  1870. ctx, cancel := context.WithCancel(context.Background())
  1871. defer cancel()
  1872. stream, err := tc.FullDuplexCall(ctx, grpc.WaitForReady(true))
  1873. if err != nil {
  1874. t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want <nil>", err)
  1875. }
  1876. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, 0)
  1877. if err != nil {
  1878. t.Fatalf("failed to newPayload: %v", err)
  1879. }
  1880. req := &testpb.StreamingOutputCallRequest{
  1881. ResponseType: testpb.PayloadType_COMPRESSABLE,
  1882. ResponseParameters: []*testpb.ResponseParameters{{Size: 0}},
  1883. Payload: payload,
  1884. }
  1885. if err := stream.Send(req); err != nil {
  1886. t.Fatalf("stream.Send(%v) = %v, want <nil>", req, err)
  1887. }
  1888. stream.CloseSend()
  1889. time.Sleep(time.Second)
  1890. // Sleep 1 second before recv to make sure the final status is received
  1891. // before the recv.
  1892. if _, err := stream.Recv(); err != nil {
  1893. t.Fatalf("stream.Recv = _, %v, want _, <nil>", err)
  1894. }
  1895. // Keep reading to drain the stream.
  1896. for {
  1897. if _, err := stream.Recv(); err != nil {
  1898. break
  1899. }
  1900. }
  1901. }
  1902. func (s) TestMaxMsgSizeClientDefault(t *testing.T) {
  1903. for _, e := range listTestEnv() {
  1904. testMaxMsgSizeClientDefault(t, e)
  1905. }
  1906. }
  1907. func testMaxMsgSizeClientDefault(t *testing.T, e env) {
  1908. te := newTest(t, e)
  1909. te.userAgent = testAppUA
  1910. te.declareLogNoise(
  1911. "transport: http2Client.notifyError got notified that the client transport was broken EOF",
  1912. "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing",
  1913. "grpc: addrConn.resetTransport failed to create client transport: connection error",
  1914. "Failed to dial : context canceled; please retry.",
  1915. )
  1916. te.startServer(&testServer{security: e.security})
  1917. defer te.tearDown()
  1918. tc := testpb.NewTestServiceClient(te.clientConn())
  1919. const smallSize = 1
  1920. const largeSize = 4 * 1024 * 1024
  1921. smallPayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, smallSize)
  1922. if err != nil {
  1923. t.Fatal(err)
  1924. }
  1925. req := &testpb.SimpleRequest{
  1926. ResponseType: testpb.PayloadType_COMPRESSABLE,
  1927. ResponseSize: int32(largeSize),
  1928. Payload: smallPayload,
  1929. }
  1930. // Test for unary RPC recv.
  1931. if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted {
  1932. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted)
  1933. }
  1934. respParam := []*testpb.ResponseParameters{
  1935. {
  1936. Size: int32(largeSize),
  1937. },
  1938. }
  1939. sreq := &testpb.StreamingOutputCallRequest{
  1940. ResponseType: testpb.PayloadType_COMPRESSABLE,
  1941. ResponseParameters: respParam,
  1942. Payload: smallPayload,
  1943. }
  1944. // Test for streaming RPC recv.
  1945. stream, err := tc.FullDuplexCall(te.ctx)
  1946. if err != nil {
  1947. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  1948. }
  1949. if err := stream.Send(sreq); err != nil {
  1950. t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err)
  1951. }
  1952. if _, err := stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted {
  1953. t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted)
  1954. }
  1955. }
  1956. func (s) TestMaxMsgSizeClientAPI(t *testing.T) {
  1957. for _, e := range listTestEnv() {
  1958. testMaxMsgSizeClientAPI(t, e)
  1959. }
  1960. }
  1961. func testMaxMsgSizeClientAPI(t *testing.T, e env) {
  1962. te := newTest(t, e)
  1963. te.userAgent = testAppUA
  1964. // To avoid error on server side.
  1965. te.maxServerSendMsgSize = newInt(5 * 1024 * 1024)
  1966. te.maxClientReceiveMsgSize = newInt(1024)
  1967. te.maxClientSendMsgSize = newInt(1024)
  1968. te.declareLogNoise(
  1969. "transport: http2Client.notifyError got notified that the client transport was broken EOF",
  1970. "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing",
  1971. "grpc: addrConn.resetTransport failed to create client transport: connection error",
  1972. "Failed to dial : context canceled; please retry.",
  1973. )
  1974. te.startServer(&testServer{security: e.security})
  1975. defer te.tearDown()
  1976. tc := testpb.NewTestServiceClient(te.clientConn())
  1977. const smallSize = 1
  1978. const largeSize = 1024
  1979. smallPayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, smallSize)
  1980. if err != nil {
  1981. t.Fatal(err)
  1982. }
  1983. largePayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, largeSize)
  1984. if err != nil {
  1985. t.Fatal(err)
  1986. }
  1987. req := &testpb.SimpleRequest{
  1988. ResponseType: testpb.PayloadType_COMPRESSABLE,
  1989. ResponseSize: int32(largeSize),
  1990. Payload: smallPayload,
  1991. }
  1992. // Test for unary RPC recv.
  1993. if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted {
  1994. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted)
  1995. }
  1996. // Test for unary RPC send.
  1997. req.Payload = largePayload
  1998. req.ResponseSize = int32(smallSize)
  1999. if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted {
  2000. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted)
  2001. }
  2002. respParam := []*testpb.ResponseParameters{
  2003. {
  2004. Size: int32(largeSize),
  2005. },
  2006. }
  2007. sreq := &testpb.StreamingOutputCallRequest{
  2008. ResponseType: testpb.PayloadType_COMPRESSABLE,
  2009. ResponseParameters: respParam,
  2010. Payload: smallPayload,
  2011. }
  2012. // Test for streaming RPC recv.
  2013. stream, err := tc.FullDuplexCall(te.ctx)
  2014. if err != nil {
  2015. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  2016. }
  2017. if err := stream.Send(sreq); err != nil {
  2018. t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err)
  2019. }
  2020. if _, err := stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted {
  2021. t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted)
  2022. }
  2023. // Test for streaming RPC send.
  2024. respParam[0].Size = int32(smallSize)
  2025. sreq.Payload = largePayload
  2026. stream, err = tc.FullDuplexCall(te.ctx)
  2027. if err != nil {
  2028. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  2029. }
  2030. if err := stream.Send(sreq); err == nil || status.Code(err) != codes.ResourceExhausted {
  2031. t.Fatalf("%v.Send(%v) = %v, want _, error code: %s", stream, sreq, err, codes.ResourceExhausted)
  2032. }
  2033. }
  2034. func (s) TestMaxMsgSizeServerAPI(t *testing.T) {
  2035. for _, e := range listTestEnv() {
  2036. testMaxMsgSizeServerAPI(t, e)
  2037. }
  2038. }
  2039. func testMaxMsgSizeServerAPI(t *testing.T, e env) {
  2040. te := newTest(t, e)
  2041. te.userAgent = testAppUA
  2042. te.maxServerReceiveMsgSize = newInt(1024)
  2043. te.maxServerSendMsgSize = newInt(1024)
  2044. te.declareLogNoise(
  2045. "transport: http2Client.notifyError got notified that the client transport was broken EOF",
  2046. "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing",
  2047. "grpc: addrConn.resetTransport failed to create client transport: connection error",
  2048. "Failed to dial : context canceled; please retry.",
  2049. )
  2050. te.startServer(&testServer{security: e.security})
  2051. defer te.tearDown()
  2052. tc := testpb.NewTestServiceClient(te.clientConn())
  2053. const smallSize = 1
  2054. const largeSize = 1024
  2055. smallPayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, smallSize)
  2056. if err != nil {
  2057. t.Fatal(err)
  2058. }
  2059. largePayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, largeSize)
  2060. if err != nil {
  2061. t.Fatal(err)
  2062. }
  2063. req := &testpb.SimpleRequest{
  2064. ResponseType: testpb.PayloadType_COMPRESSABLE,
  2065. ResponseSize: int32(largeSize),
  2066. Payload: smallPayload,
  2067. }
  2068. // Test for unary RPC send.
  2069. if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted {
  2070. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted)
  2071. }
  2072. // Test for unary RPC recv.
  2073. req.Payload = largePayload
  2074. req.ResponseSize = int32(smallSize)
  2075. if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted {
  2076. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted)
  2077. }
  2078. respParam := []*testpb.ResponseParameters{
  2079. {
  2080. Size: int32(largeSize),
  2081. },
  2082. }
  2083. sreq := &testpb.StreamingOutputCallRequest{
  2084. ResponseType: testpb.PayloadType_COMPRESSABLE,
  2085. ResponseParameters: respParam,
  2086. Payload: smallPayload,
  2087. }
  2088. // Test for streaming RPC send.
  2089. stream, err := tc.FullDuplexCall(te.ctx)
  2090. if err != nil {
  2091. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  2092. }
  2093. if err := stream.Send(sreq); err != nil {
  2094. t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err)
  2095. }
  2096. if _, err := stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted {
  2097. t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted)
  2098. }
  2099. // Test for streaming RPC recv.
  2100. respParam[0].Size = int32(smallSize)
  2101. sreq.Payload = largePayload
  2102. stream, err = tc.FullDuplexCall(te.ctx)
  2103. if err != nil {
  2104. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  2105. }
  2106. if err := stream.Send(sreq); err != nil {
  2107. t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err)
  2108. }
  2109. if _, err := stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted {
  2110. t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted)
  2111. }
  2112. }
  2113. func (s) TestTap(t *testing.T) {
  2114. for _, e := range listTestEnv() {
  2115. if e.name == "handler-tls" {
  2116. continue
  2117. }
  2118. testTap(t, e)
  2119. }
  2120. }
  2121. type myTap struct {
  2122. cnt int
  2123. }
  2124. func (t *myTap) handle(ctx context.Context, info *tap.Info) (context.Context, error) {
  2125. if info != nil {
  2126. if info.FullMethodName == "/grpc.testing.TestService/EmptyCall" {
  2127. t.cnt++
  2128. } else if info.FullMethodName == "/grpc.testing.TestService/UnaryCall" {
  2129. return nil, fmt.Errorf("tap error")
  2130. }
  2131. }
  2132. return ctx, nil
  2133. }
  2134. func testTap(t *testing.T, e env) {
  2135. te := newTest(t, e)
  2136. te.userAgent = testAppUA
  2137. ttap := &myTap{}
  2138. te.tapHandle = ttap.handle
  2139. te.declareLogNoise(
  2140. "transport: http2Client.notifyError got notified that the client transport was broken EOF",
  2141. "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing",
  2142. "grpc: addrConn.resetTransport failed to create client transport: connection error",
  2143. )
  2144. te.startServer(&testServer{security: e.security})
  2145. defer te.tearDown()
  2146. cc := te.clientConn()
  2147. tc := testpb.NewTestServiceClient(cc)
  2148. if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); err != nil {
  2149. t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, <nil>", err)
  2150. }
  2151. if ttap.cnt != 1 {
  2152. t.Fatalf("Get the count in ttap %d, want 1", ttap.cnt)
  2153. }
  2154. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, 31)
  2155. if err != nil {
  2156. t.Fatal(err)
  2157. }
  2158. req := &testpb.SimpleRequest{
  2159. ResponseType: testpb.PayloadType_COMPRESSABLE,
  2160. ResponseSize: 45,
  2161. Payload: payload,
  2162. }
  2163. if _, err := tc.UnaryCall(context.Background(), req); status.Code(err) != codes.Unavailable {
  2164. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, %s", err, codes.Unavailable)
  2165. }
  2166. }
  2167. func healthCheck(d time.Duration, cc *grpc.ClientConn, serviceName string) (*healthpb.HealthCheckResponse, error) {
  2168. ctx, cancel := context.WithTimeout(context.Background(), d)
  2169. defer cancel()
  2170. hc := healthgrpc.NewHealthClient(cc)
  2171. req := &healthpb.HealthCheckRequest{
  2172. Service: serviceName,
  2173. }
  2174. return hc.Check(ctx, req)
  2175. }
  2176. func (s) TestHealthCheckOnSuccess(t *testing.T) {
  2177. for _, e := range listTestEnv() {
  2178. testHealthCheckOnSuccess(t, e)
  2179. }
  2180. }
  2181. func testHealthCheckOnSuccess(t *testing.T, e env) {
  2182. te := newTest(t, e)
  2183. hs := health.NewServer()
  2184. hs.SetServingStatus("grpc.health.v1.Health", 1)
  2185. te.healthServer = hs
  2186. te.startServer(&testServer{security: e.security})
  2187. defer te.tearDown()
  2188. cc := te.clientConn()
  2189. if _, err := healthCheck(1*time.Second, cc, "grpc.health.v1.Health"); err != nil {
  2190. t.Fatalf("Health/Check(_, _) = _, %v, want _, <nil>", err)
  2191. }
  2192. }
  2193. func (s) TestHealthCheckOnFailure(t *testing.T) {
  2194. for _, e := range listTestEnv() {
  2195. testHealthCheckOnFailure(t, e)
  2196. }
  2197. }
  2198. func testHealthCheckOnFailure(t *testing.T, e env) {
  2199. te := newTest(t, e)
  2200. te.declareLogNoise(
  2201. "Failed to dial ",
  2202. "grpc: the client connection is closing; please retry",
  2203. )
  2204. hs := health.NewServer()
  2205. hs.SetServingStatus("grpc.health.v1.HealthCheck", 1)
  2206. te.healthServer = hs
  2207. te.startServer(&testServer{security: e.security})
  2208. defer te.tearDown()
  2209. cc := te.clientConn()
  2210. wantErr := status.Error(codes.DeadlineExceeded, "context deadline exceeded")
  2211. if _, err := healthCheck(0*time.Second, cc, "grpc.health.v1.Health"); !reflect.DeepEqual(err, wantErr) {
  2212. t.Fatalf("Health/Check(_, _) = _, %v, want _, error code %s", err, codes.DeadlineExceeded)
  2213. }
  2214. awaitNewConnLogOutput()
  2215. }
  2216. func (s) TestHealthCheckOff(t *testing.T) {
  2217. for _, e := range listTestEnv() {
  2218. // TODO(bradfitz): Temporarily skip this env due to #619.
  2219. if e.name == "handler-tls" {
  2220. continue
  2221. }
  2222. testHealthCheckOff(t, e)
  2223. }
  2224. }
  2225. func testHealthCheckOff(t *testing.T, e env) {
  2226. te := newTest(t, e)
  2227. te.startServer(&testServer{security: e.security})
  2228. defer te.tearDown()
  2229. want := status.Error(codes.Unimplemented, "unknown service grpc.health.v1.Health")
  2230. if _, err := healthCheck(1*time.Second, te.clientConn(), ""); !reflect.DeepEqual(err, want) {
  2231. t.Fatalf("Health/Check(_, _) = _, %v, want _, %v", err, want)
  2232. }
  2233. }
  2234. func (s) TestHealthWatchMultipleClients(t *testing.T) {
  2235. for _, e := range listTestEnv() {
  2236. testHealthWatchMultipleClients(t, e)
  2237. }
  2238. }
  2239. func testHealthWatchMultipleClients(t *testing.T, e env) {
  2240. const service = "grpc.health.v1.Health1"
  2241. hs := health.NewServer()
  2242. te := newTest(t, e)
  2243. te.healthServer = hs
  2244. te.startServer(&testServer{security: e.security})
  2245. defer te.tearDown()
  2246. cc := te.clientConn()
  2247. hc := healthgrpc.NewHealthClient(cc)
  2248. ctx, cancel := context.WithCancel(context.Background())
  2249. defer cancel()
  2250. req := &healthpb.HealthCheckRequest{
  2251. Service: service,
  2252. }
  2253. stream1, err := hc.Watch(ctx, req)
  2254. if err != nil {
  2255. t.Fatalf("error: %v", err)
  2256. }
  2257. healthWatchChecker(t, stream1, healthpb.HealthCheckResponse_SERVICE_UNKNOWN)
  2258. stream2, err := hc.Watch(ctx, req)
  2259. if err != nil {
  2260. t.Fatalf("error: %v", err)
  2261. }
  2262. healthWatchChecker(t, stream2, healthpb.HealthCheckResponse_SERVICE_UNKNOWN)
  2263. hs.SetServingStatus(service, healthpb.HealthCheckResponse_NOT_SERVING)
  2264. healthWatchChecker(t, stream1, healthpb.HealthCheckResponse_NOT_SERVING)
  2265. healthWatchChecker(t, stream2, healthpb.HealthCheckResponse_NOT_SERVING)
  2266. }
  2267. func (s) TestHealthWatchSameStatus(t *testing.T) {
  2268. for _, e := range listTestEnv() {
  2269. testHealthWatchSameStatus(t, e)
  2270. }
  2271. }
  2272. func testHealthWatchSameStatus(t *testing.T, e env) {
  2273. const service = "grpc.health.v1.Health1"
  2274. hs := health.NewServer()
  2275. te := newTest(t, e)
  2276. te.healthServer = hs
  2277. te.startServer(&testServer{security: e.security})
  2278. defer te.tearDown()
  2279. cc := te.clientConn()
  2280. hc := healthgrpc.NewHealthClient(cc)
  2281. ctx, cancel := context.WithCancel(context.Background())
  2282. defer cancel()
  2283. req := &healthpb.HealthCheckRequest{
  2284. Service: service,
  2285. }
  2286. stream1, err := hc.Watch(ctx, req)
  2287. if err != nil {
  2288. t.Fatalf("error: %v", err)
  2289. }
  2290. healthWatchChecker(t, stream1, healthpb.HealthCheckResponse_SERVICE_UNKNOWN)
  2291. hs.SetServingStatus(service, healthpb.HealthCheckResponse_SERVING)
  2292. healthWatchChecker(t, stream1, healthpb.HealthCheckResponse_SERVING)
  2293. hs.SetServingStatus(service, healthpb.HealthCheckResponse_SERVING)
  2294. hs.SetServingStatus(service, healthpb.HealthCheckResponse_NOT_SERVING)
  2295. healthWatchChecker(t, stream1, healthpb.HealthCheckResponse_NOT_SERVING)
  2296. }
  2297. func (s) TestHealthWatchServiceStatusSetBeforeStartingServer(t *testing.T) {
  2298. for _, e := range listTestEnv() {
  2299. testHealthWatchSetServiceStatusBeforeStartingServer(t, e)
  2300. }
  2301. }
  2302. func testHealthWatchSetServiceStatusBeforeStartingServer(t *testing.T, e env) {
  2303. const service = "grpc.health.v1.Health1"
  2304. hs := health.NewServer()
  2305. te := newTest(t, e)
  2306. te.healthServer = hs
  2307. hs.SetServingStatus(service, healthpb.HealthCheckResponse_SERVING)
  2308. te.startServer(&testServer{security: e.security})
  2309. defer te.tearDown()
  2310. cc := te.clientConn()
  2311. hc := healthgrpc.NewHealthClient(cc)
  2312. ctx, cancel := context.WithCancel(context.Background())
  2313. defer cancel()
  2314. req := &healthpb.HealthCheckRequest{
  2315. Service: service,
  2316. }
  2317. stream, err := hc.Watch(ctx, req)
  2318. if err != nil {
  2319. t.Fatalf("error: %v", err)
  2320. }
  2321. healthWatchChecker(t, stream, healthpb.HealthCheckResponse_SERVING)
  2322. }
  2323. func (s) TestHealthWatchDefaultStatusChange(t *testing.T) {
  2324. for _, e := range listTestEnv() {
  2325. testHealthWatchDefaultStatusChange(t, e)
  2326. }
  2327. }
  2328. func testHealthWatchDefaultStatusChange(t *testing.T, e env) {
  2329. const service = "grpc.health.v1.Health1"
  2330. hs := health.NewServer()
  2331. te := newTest(t, e)
  2332. te.healthServer = hs
  2333. te.startServer(&testServer{security: e.security})
  2334. defer te.tearDown()
  2335. cc := te.clientConn()
  2336. hc := healthgrpc.NewHealthClient(cc)
  2337. ctx, cancel := context.WithCancel(context.Background())
  2338. defer cancel()
  2339. req := &healthpb.HealthCheckRequest{
  2340. Service: service,
  2341. }
  2342. stream, err := hc.Watch(ctx, req)
  2343. if err != nil {
  2344. t.Fatalf("error: %v", err)
  2345. }
  2346. healthWatchChecker(t, stream, healthpb.HealthCheckResponse_SERVICE_UNKNOWN)
  2347. hs.SetServingStatus(service, healthpb.HealthCheckResponse_SERVING)
  2348. healthWatchChecker(t, stream, healthpb.HealthCheckResponse_SERVING)
  2349. }
  2350. func (s) TestHealthWatchSetServiceStatusBeforeClientCallsWatch(t *testing.T) {
  2351. for _, e := range listTestEnv() {
  2352. testHealthWatchSetServiceStatusBeforeClientCallsWatch(t, e)
  2353. }
  2354. }
  2355. func testHealthWatchSetServiceStatusBeforeClientCallsWatch(t *testing.T, e env) {
  2356. const service = "grpc.health.v1.Health1"
  2357. hs := health.NewServer()
  2358. te := newTest(t, e)
  2359. te.healthServer = hs
  2360. te.startServer(&testServer{security: e.security})
  2361. defer te.tearDown()
  2362. cc := te.clientConn()
  2363. hc := healthgrpc.NewHealthClient(cc)
  2364. ctx, cancel := context.WithCancel(context.Background())
  2365. defer cancel()
  2366. req := &healthpb.HealthCheckRequest{
  2367. Service: service,
  2368. }
  2369. hs.SetServingStatus(service, healthpb.HealthCheckResponse_SERVING)
  2370. stream, err := hc.Watch(ctx, req)
  2371. if err != nil {
  2372. t.Fatalf("error: %v", err)
  2373. }
  2374. healthWatchChecker(t, stream, healthpb.HealthCheckResponse_SERVING)
  2375. }
  2376. func (s) TestHealthWatchOverallServerHealthChange(t *testing.T) {
  2377. for _, e := range listTestEnv() {
  2378. testHealthWatchOverallServerHealthChange(t, e)
  2379. }
  2380. }
  2381. func testHealthWatchOverallServerHealthChange(t *testing.T, e env) {
  2382. const service = ""
  2383. hs := health.NewServer()
  2384. te := newTest(t, e)
  2385. te.healthServer = hs
  2386. te.startServer(&testServer{security: e.security})
  2387. defer te.tearDown()
  2388. cc := te.clientConn()
  2389. hc := healthgrpc.NewHealthClient(cc)
  2390. ctx, cancel := context.WithCancel(context.Background())
  2391. defer cancel()
  2392. req := &healthpb.HealthCheckRequest{
  2393. Service: service,
  2394. }
  2395. stream, err := hc.Watch(ctx, req)
  2396. if err != nil {
  2397. t.Fatalf("error: %v", err)
  2398. }
  2399. healthWatchChecker(t, stream, healthpb.HealthCheckResponse_SERVING)
  2400. hs.SetServingStatus(service, healthpb.HealthCheckResponse_NOT_SERVING)
  2401. healthWatchChecker(t, stream, healthpb.HealthCheckResponse_NOT_SERVING)
  2402. }
  2403. func healthWatchChecker(t *testing.T, stream healthgrpc.Health_WatchClient, expectedServingStatus healthpb.HealthCheckResponse_ServingStatus) {
  2404. response, err := stream.Recv()
  2405. if err != nil {
  2406. t.Fatalf("error on %v.Recv(): %v", stream, err)
  2407. }
  2408. if response.Status != expectedServingStatus {
  2409. t.Fatalf("response.Status is %v (%v expected)", response.Status, expectedServingStatus)
  2410. }
  2411. }
  2412. func (s) TestUnknownHandler(t *testing.T) {
  2413. // An example unknownHandler that returns a different code and a different method, making sure that we do not
  2414. // expose what methods are implemented to a client that is not authenticated.
  2415. unknownHandler := func(srv interface{}, stream grpc.ServerStream) error {
  2416. return status.Error(codes.Unauthenticated, "user unauthenticated")
  2417. }
  2418. for _, e := range listTestEnv() {
  2419. // TODO(bradfitz): Temporarily skip this env due to #619.
  2420. if e.name == "handler-tls" {
  2421. continue
  2422. }
  2423. testUnknownHandler(t, e, unknownHandler)
  2424. }
  2425. }
  2426. func testUnknownHandler(t *testing.T, e env, unknownHandler grpc.StreamHandler) {
  2427. te := newTest(t, e)
  2428. te.unknownHandler = unknownHandler
  2429. te.startServer(&testServer{security: e.security})
  2430. defer te.tearDown()
  2431. want := status.Error(codes.Unauthenticated, "user unauthenticated")
  2432. if _, err := healthCheck(1*time.Second, te.clientConn(), ""); !reflect.DeepEqual(err, want) {
  2433. t.Fatalf("Health/Check(_, _) = _, %v, want _, %v", err, want)
  2434. }
  2435. }
  2436. func (s) TestHealthCheckServingStatus(t *testing.T) {
  2437. for _, e := range listTestEnv() {
  2438. testHealthCheckServingStatus(t, e)
  2439. }
  2440. }
  2441. func testHealthCheckServingStatus(t *testing.T, e env) {
  2442. te := newTest(t, e)
  2443. hs := health.NewServer()
  2444. te.healthServer = hs
  2445. te.startServer(&testServer{security: e.security})
  2446. defer te.tearDown()
  2447. cc := te.clientConn()
  2448. out, err := healthCheck(1*time.Second, cc, "")
  2449. if err != nil {
  2450. t.Fatalf("Health/Check(_, _) = _, %v, want _, <nil>", err)
  2451. }
  2452. if out.Status != healthpb.HealthCheckResponse_SERVING {
  2453. t.Fatalf("Got the serving status %v, want SERVING", out.Status)
  2454. }
  2455. wantErr := status.Error(codes.NotFound, "unknown service")
  2456. if _, err := healthCheck(1*time.Second, cc, "grpc.health.v1.Health"); !reflect.DeepEqual(err, wantErr) {
  2457. t.Fatalf("Health/Check(_, _) = _, %v, want _, error code %s", err, codes.NotFound)
  2458. }
  2459. hs.SetServingStatus("grpc.health.v1.Health", healthpb.HealthCheckResponse_SERVING)
  2460. out, err = healthCheck(1*time.Second, cc, "grpc.health.v1.Health")
  2461. if err != nil {
  2462. t.Fatalf("Health/Check(_, _) = _, %v, want _, <nil>", err)
  2463. }
  2464. if out.Status != healthpb.HealthCheckResponse_SERVING {
  2465. t.Fatalf("Got the serving status %v, want SERVING", out.Status)
  2466. }
  2467. hs.SetServingStatus("grpc.health.v1.Health", healthpb.HealthCheckResponse_NOT_SERVING)
  2468. out, err = healthCheck(1*time.Second, cc, "grpc.health.v1.Health")
  2469. if err != nil {
  2470. t.Fatalf("Health/Check(_, _) = _, %v, want _, <nil>", err)
  2471. }
  2472. if out.Status != healthpb.HealthCheckResponse_NOT_SERVING {
  2473. t.Fatalf("Got the serving status %v, want NOT_SERVING", out.Status)
  2474. }
  2475. }
  2476. func (s) TestEmptyUnaryWithUserAgent(t *testing.T) {
  2477. for _, e := range listTestEnv() {
  2478. testEmptyUnaryWithUserAgent(t, e)
  2479. }
  2480. }
  2481. func testEmptyUnaryWithUserAgent(t *testing.T, e env) {
  2482. te := newTest(t, e)
  2483. te.userAgent = testAppUA
  2484. te.startServer(&testServer{security: e.security})
  2485. defer te.tearDown()
  2486. cc := te.clientConn()
  2487. tc := testpb.NewTestServiceClient(cc)
  2488. var header metadata.MD
  2489. reply, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.Header(&header))
  2490. if err != nil || !proto.Equal(&testpb.Empty{}, reply) {
  2491. t.Fatalf("TestService/EmptyCall(_, _) = %v, %v, want %v, <nil>", reply, err, &testpb.Empty{})
  2492. }
  2493. if v, ok := header["ua"]; !ok || !strings.HasPrefix(v[0], testAppUA) {
  2494. t.Fatalf("header[\"ua\"] = %q, %t, want string with prefix %q, true", v, ok, testAppUA)
  2495. }
  2496. te.srv.Stop()
  2497. }
  2498. func (s) TestFailedEmptyUnary(t *testing.T) {
  2499. for _, e := range listTestEnv() {
  2500. if e.name == "handler-tls" {
  2501. // This test covers status details, but
  2502. // Grpc-Status-Details-Bin is not support in handler_server.
  2503. continue
  2504. }
  2505. testFailedEmptyUnary(t, e)
  2506. }
  2507. }
  2508. func testFailedEmptyUnary(t *testing.T, e env) {
  2509. te := newTest(t, e)
  2510. te.userAgent = failAppUA
  2511. te.startServer(&testServer{security: e.security})
  2512. defer te.tearDown()
  2513. tc := testpb.NewTestServiceClient(te.clientConn())
  2514. ctx := metadata.NewOutgoingContext(context.Background(), testMetadata)
  2515. wantErr := detailedError
  2516. if _, err := tc.EmptyCall(ctx, &testpb.Empty{}); !reflect.DeepEqual(err, wantErr) {
  2517. t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %v", err, wantErr)
  2518. }
  2519. }
  2520. func (s) TestLargeUnary(t *testing.T) {
  2521. for _, e := range listTestEnv() {
  2522. testLargeUnary(t, e)
  2523. }
  2524. }
  2525. func testLargeUnary(t *testing.T, e env) {
  2526. te := newTest(t, e)
  2527. te.startServer(&testServer{security: e.security})
  2528. defer te.tearDown()
  2529. tc := testpb.NewTestServiceClient(te.clientConn())
  2530. const argSize = 271828
  2531. const respSize = 314159
  2532. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize)
  2533. if err != nil {
  2534. t.Fatal(err)
  2535. }
  2536. req := &testpb.SimpleRequest{
  2537. ResponseType: testpb.PayloadType_COMPRESSABLE,
  2538. ResponseSize: respSize,
  2539. Payload: payload,
  2540. }
  2541. reply, err := tc.UnaryCall(context.Background(), req)
  2542. if err != nil {
  2543. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, <nil>", err)
  2544. }
  2545. pt := reply.GetPayload().GetType()
  2546. ps := len(reply.GetPayload().GetBody())
  2547. if pt != testpb.PayloadType_COMPRESSABLE || ps != respSize {
  2548. t.Fatalf("Got the reply with type %d len %d; want %d, %d", pt, ps, testpb.PayloadType_COMPRESSABLE, respSize)
  2549. }
  2550. }
  2551. // Test backward-compatibility API for setting msg size limit.
  2552. func (s) TestExceedMsgLimit(t *testing.T) {
  2553. for _, e := range listTestEnv() {
  2554. testExceedMsgLimit(t, e)
  2555. }
  2556. }
  2557. func testExceedMsgLimit(t *testing.T, e env) {
  2558. te := newTest(t, e)
  2559. te.maxMsgSize = newInt(1024)
  2560. te.startServer(&testServer{security: e.security})
  2561. defer te.tearDown()
  2562. tc := testpb.NewTestServiceClient(te.clientConn())
  2563. argSize := int32(*te.maxMsgSize + 1)
  2564. const smallSize = 1
  2565. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize)
  2566. if err != nil {
  2567. t.Fatal(err)
  2568. }
  2569. smallPayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, smallSize)
  2570. if err != nil {
  2571. t.Fatal(err)
  2572. }
  2573. // Test on server side for unary RPC.
  2574. req := &testpb.SimpleRequest{
  2575. ResponseType: testpb.PayloadType_COMPRESSABLE,
  2576. ResponseSize: smallSize,
  2577. Payload: payload,
  2578. }
  2579. if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted {
  2580. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted)
  2581. }
  2582. // Test on client side for unary RPC.
  2583. req.ResponseSize = int32(*te.maxMsgSize) + 1
  2584. req.Payload = smallPayload
  2585. if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted {
  2586. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted)
  2587. }
  2588. // Test on server side for streaming RPC.
  2589. stream, err := tc.FullDuplexCall(te.ctx)
  2590. if err != nil {
  2591. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  2592. }
  2593. respParam := []*testpb.ResponseParameters{
  2594. {
  2595. Size: 1,
  2596. },
  2597. }
  2598. spayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(*te.maxMsgSize+1))
  2599. if err != nil {
  2600. t.Fatal(err)
  2601. }
  2602. sreq := &testpb.StreamingOutputCallRequest{
  2603. ResponseType: testpb.PayloadType_COMPRESSABLE,
  2604. ResponseParameters: respParam,
  2605. Payload: spayload,
  2606. }
  2607. if err := stream.Send(sreq); err != nil {
  2608. t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err)
  2609. }
  2610. if _, err := stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted {
  2611. t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted)
  2612. }
  2613. // Test on client side for streaming RPC.
  2614. stream, err = tc.FullDuplexCall(te.ctx)
  2615. if err != nil {
  2616. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  2617. }
  2618. respParam[0].Size = int32(*te.maxMsgSize) + 1
  2619. sreq.Payload = smallPayload
  2620. if err := stream.Send(sreq); err != nil {
  2621. t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err)
  2622. }
  2623. if _, err := stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted {
  2624. t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted)
  2625. }
  2626. }
  2627. func (s) TestPeerClientSide(t *testing.T) {
  2628. for _, e := range listTestEnv() {
  2629. testPeerClientSide(t, e)
  2630. }
  2631. }
  2632. func testPeerClientSide(t *testing.T, e env) {
  2633. te := newTest(t, e)
  2634. te.userAgent = testAppUA
  2635. te.startServer(&testServer{security: e.security})
  2636. defer te.tearDown()
  2637. tc := testpb.NewTestServiceClient(te.clientConn())
  2638. peer := new(peer.Peer)
  2639. if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.Peer(peer), grpc.WaitForReady(true)); err != nil {
  2640. t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, <nil>", err)
  2641. }
  2642. pa := peer.Addr.String()
  2643. if e.network == "unix" {
  2644. if pa != te.srvAddr {
  2645. t.Fatalf("peer.Addr = %v, want %v", pa, te.srvAddr)
  2646. }
  2647. return
  2648. }
  2649. _, pp, err := net.SplitHostPort(pa)
  2650. if err != nil {
  2651. t.Fatalf("Failed to parse address from peer.")
  2652. }
  2653. _, sp, err := net.SplitHostPort(te.srvAddr)
  2654. if err != nil {
  2655. t.Fatalf("Failed to parse address of test server.")
  2656. }
  2657. if pp != sp {
  2658. t.Fatalf("peer.Addr = localhost:%v, want localhost:%v", pp, sp)
  2659. }
  2660. }
  2661. // TestPeerNegative tests that if call fails setting peer
  2662. // doesn't cause a segmentation fault.
  2663. // issue#1141 https://github.com/grpc/grpc-go/issues/1141
  2664. func (s) TestPeerNegative(t *testing.T) {
  2665. for _, e := range listTestEnv() {
  2666. testPeerNegative(t, e)
  2667. }
  2668. }
  2669. func testPeerNegative(t *testing.T, e env) {
  2670. te := newTest(t, e)
  2671. te.startServer(&testServer{security: e.security})
  2672. defer te.tearDown()
  2673. cc := te.clientConn()
  2674. tc := testpb.NewTestServiceClient(cc)
  2675. peer := new(peer.Peer)
  2676. ctx, cancel := context.WithCancel(context.Background())
  2677. cancel()
  2678. tc.EmptyCall(ctx, &testpb.Empty{}, grpc.Peer(peer))
  2679. }
  2680. func (s) TestPeerFailedRPC(t *testing.T) {
  2681. for _, e := range listTestEnv() {
  2682. testPeerFailedRPC(t, e)
  2683. }
  2684. }
  2685. func testPeerFailedRPC(t *testing.T, e env) {
  2686. te := newTest(t, e)
  2687. te.maxServerReceiveMsgSize = newInt(1 * 1024)
  2688. te.startServer(&testServer{security: e.security})
  2689. defer te.tearDown()
  2690. tc := testpb.NewTestServiceClient(te.clientConn())
  2691. // first make a successful request to the server
  2692. if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); err != nil {
  2693. t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, <nil>", err)
  2694. }
  2695. // make a second request that will be rejected by the server
  2696. const largeSize = 5 * 1024
  2697. largePayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, largeSize)
  2698. if err != nil {
  2699. t.Fatal(err)
  2700. }
  2701. req := &testpb.SimpleRequest{
  2702. ResponseType: testpb.PayloadType_COMPRESSABLE,
  2703. Payload: largePayload,
  2704. }
  2705. peer := new(peer.Peer)
  2706. if _, err := tc.UnaryCall(context.Background(), req, grpc.Peer(peer)); err == nil || status.Code(err) != codes.ResourceExhausted {
  2707. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted)
  2708. } else {
  2709. pa := peer.Addr.String()
  2710. if e.network == "unix" {
  2711. if pa != te.srvAddr {
  2712. t.Fatalf("peer.Addr = %v, want %v", pa, te.srvAddr)
  2713. }
  2714. return
  2715. }
  2716. _, pp, err := net.SplitHostPort(pa)
  2717. if err != nil {
  2718. t.Fatalf("Failed to parse address from peer.")
  2719. }
  2720. _, sp, err := net.SplitHostPort(te.srvAddr)
  2721. if err != nil {
  2722. t.Fatalf("Failed to parse address of test server.")
  2723. }
  2724. if pp != sp {
  2725. t.Fatalf("peer.Addr = localhost:%v, want localhost:%v", pp, sp)
  2726. }
  2727. }
  2728. }
  2729. func (s) TestMetadataUnaryRPC(t *testing.T) {
  2730. for _, e := range listTestEnv() {
  2731. testMetadataUnaryRPC(t, e)
  2732. }
  2733. }
  2734. func testMetadataUnaryRPC(t *testing.T, e env) {
  2735. te := newTest(t, e)
  2736. te.startServer(&testServer{security: e.security})
  2737. defer te.tearDown()
  2738. tc := testpb.NewTestServiceClient(te.clientConn())
  2739. const argSize = 2718
  2740. const respSize = 314
  2741. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize)
  2742. if err != nil {
  2743. t.Fatal(err)
  2744. }
  2745. req := &testpb.SimpleRequest{
  2746. ResponseType: testpb.PayloadType_COMPRESSABLE,
  2747. ResponseSize: respSize,
  2748. Payload: payload,
  2749. }
  2750. var header, trailer metadata.MD
  2751. ctx := metadata.NewOutgoingContext(context.Background(), testMetadata)
  2752. if _, err := tc.UnaryCall(ctx, req, grpc.Header(&header), grpc.Trailer(&trailer)); err != nil {
  2753. t.Fatalf("TestService.UnaryCall(%v, _, _, _) = _, %v; want _, <nil>", ctx, err)
  2754. }
  2755. // Ignore optional response headers that Servers may set:
  2756. if header != nil {
  2757. delete(header, "trailer") // RFC 2616 says server SHOULD (but optional) declare trailers
  2758. delete(header, "date") // the Date header is also optional
  2759. delete(header, "user-agent")
  2760. delete(header, "content-type")
  2761. }
  2762. if !reflect.DeepEqual(header, testMetadata) {
  2763. t.Fatalf("Received header metadata %v, want %v", header, testMetadata)
  2764. }
  2765. if !reflect.DeepEqual(trailer, testTrailerMetadata) {
  2766. t.Fatalf("Received trailer metadata %v, want %v", trailer, testTrailerMetadata)
  2767. }
  2768. }
  2769. func (s) TestMultipleSetTrailerUnaryRPC(t *testing.T) {
  2770. for _, e := range listTestEnv() {
  2771. testMultipleSetTrailerUnaryRPC(t, e)
  2772. }
  2773. }
  2774. func testMultipleSetTrailerUnaryRPC(t *testing.T, e env) {
  2775. te := newTest(t, e)
  2776. te.startServer(&testServer{security: e.security, multipleSetTrailer: true})
  2777. defer te.tearDown()
  2778. tc := testpb.NewTestServiceClient(te.clientConn())
  2779. const (
  2780. argSize = 1
  2781. respSize = 1
  2782. )
  2783. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize)
  2784. if err != nil {
  2785. t.Fatal(err)
  2786. }
  2787. req := &testpb.SimpleRequest{
  2788. ResponseType: testpb.PayloadType_COMPRESSABLE,
  2789. ResponseSize: respSize,
  2790. Payload: payload,
  2791. }
  2792. var trailer metadata.MD
  2793. ctx := metadata.NewOutgoingContext(context.Background(), testMetadata)
  2794. if _, err := tc.UnaryCall(ctx, req, grpc.Trailer(&trailer), grpc.WaitForReady(true)); err != nil {
  2795. t.Fatalf("TestService.UnaryCall(%v, _, _, _) = _, %v; want _, <nil>", ctx, err)
  2796. }
  2797. expectedTrailer := metadata.Join(testTrailerMetadata, testTrailerMetadata2)
  2798. if !reflect.DeepEqual(trailer, expectedTrailer) {
  2799. t.Fatalf("Received trailer metadata %v, want %v", trailer, expectedTrailer)
  2800. }
  2801. }
  2802. func (s) TestMultipleSetTrailerStreamingRPC(t *testing.T) {
  2803. for _, e := range listTestEnv() {
  2804. testMultipleSetTrailerStreamingRPC(t, e)
  2805. }
  2806. }
  2807. func testMultipleSetTrailerStreamingRPC(t *testing.T, e env) {
  2808. te := newTest(t, e)
  2809. te.startServer(&testServer{security: e.security, multipleSetTrailer: true})
  2810. defer te.tearDown()
  2811. tc := testpb.NewTestServiceClient(te.clientConn())
  2812. ctx := metadata.NewOutgoingContext(context.Background(), testMetadata)
  2813. stream, err := tc.FullDuplexCall(ctx, grpc.WaitForReady(true))
  2814. if err != nil {
  2815. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  2816. }
  2817. if err := stream.CloseSend(); err != nil {
  2818. t.Fatalf("%v.CloseSend() got %v, want %v", stream, err, nil)
  2819. }
  2820. if _, err := stream.Recv(); err != io.EOF {
  2821. t.Fatalf("%v failed to complele the FullDuplexCall: %v", stream, err)
  2822. }
  2823. trailer := stream.Trailer()
  2824. expectedTrailer := metadata.Join(testTrailerMetadata, testTrailerMetadata2)
  2825. if !reflect.DeepEqual(trailer, expectedTrailer) {
  2826. t.Fatalf("Received trailer metadata %v, want %v", trailer, expectedTrailer)
  2827. }
  2828. }
  2829. func (s) TestSetAndSendHeaderUnaryRPC(t *testing.T) {
  2830. for _, e := range listTestEnv() {
  2831. if e.name == "handler-tls" {
  2832. continue
  2833. }
  2834. testSetAndSendHeaderUnaryRPC(t, e)
  2835. }
  2836. }
  2837. // To test header metadata is sent on SendHeader().
  2838. func testSetAndSendHeaderUnaryRPC(t *testing.T, e env) {
  2839. te := newTest(t, e)
  2840. te.startServer(&testServer{security: e.security, setAndSendHeader: true})
  2841. defer te.tearDown()
  2842. tc := testpb.NewTestServiceClient(te.clientConn())
  2843. const (
  2844. argSize = 1
  2845. respSize = 1
  2846. )
  2847. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize)
  2848. if err != nil {
  2849. t.Fatal(err)
  2850. }
  2851. req := &testpb.SimpleRequest{
  2852. ResponseType: testpb.PayloadType_COMPRESSABLE,
  2853. ResponseSize: respSize,
  2854. Payload: payload,
  2855. }
  2856. var header metadata.MD
  2857. ctx := metadata.NewOutgoingContext(context.Background(), testMetadata)
  2858. if _, err := tc.UnaryCall(ctx, req, grpc.Header(&header), grpc.WaitForReady(true)); err != nil {
  2859. t.Fatalf("TestService.UnaryCall(%v, _, _, _) = _, %v; want _, <nil>", ctx, err)
  2860. }
  2861. delete(header, "user-agent")
  2862. delete(header, "content-type")
  2863. expectedHeader := metadata.Join(testMetadata, testMetadata2)
  2864. if !reflect.DeepEqual(header, expectedHeader) {
  2865. t.Fatalf("Received header metadata %v, want %v", header, expectedHeader)
  2866. }
  2867. }
  2868. func (s) TestMultipleSetHeaderUnaryRPC(t *testing.T) {
  2869. for _, e := range listTestEnv() {
  2870. if e.name == "handler-tls" {
  2871. continue
  2872. }
  2873. testMultipleSetHeaderUnaryRPC(t, e)
  2874. }
  2875. }
  2876. // To test header metadata is sent when sending response.
  2877. func testMultipleSetHeaderUnaryRPC(t *testing.T, e env) {
  2878. te := newTest(t, e)
  2879. te.startServer(&testServer{security: e.security, setHeaderOnly: true})
  2880. defer te.tearDown()
  2881. tc := testpb.NewTestServiceClient(te.clientConn())
  2882. const (
  2883. argSize = 1
  2884. respSize = 1
  2885. )
  2886. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize)
  2887. if err != nil {
  2888. t.Fatal(err)
  2889. }
  2890. req := &testpb.SimpleRequest{
  2891. ResponseType: testpb.PayloadType_COMPRESSABLE,
  2892. ResponseSize: respSize,
  2893. Payload: payload,
  2894. }
  2895. var header metadata.MD
  2896. ctx := metadata.NewOutgoingContext(context.Background(), testMetadata)
  2897. if _, err := tc.UnaryCall(ctx, req, grpc.Header(&header), grpc.WaitForReady(true)); err != nil {
  2898. t.Fatalf("TestService.UnaryCall(%v, _, _, _) = _, %v; want _, <nil>", ctx, err)
  2899. }
  2900. delete(header, "user-agent")
  2901. delete(header, "content-type")
  2902. expectedHeader := metadata.Join(testMetadata, testMetadata2)
  2903. if !reflect.DeepEqual(header, expectedHeader) {
  2904. t.Fatalf("Received header metadata %v, want %v", header, expectedHeader)
  2905. }
  2906. }
  2907. func (s) TestMultipleSetHeaderUnaryRPCError(t *testing.T) {
  2908. for _, e := range listTestEnv() {
  2909. if e.name == "handler-tls" {
  2910. continue
  2911. }
  2912. testMultipleSetHeaderUnaryRPCError(t, e)
  2913. }
  2914. }
  2915. // To test header metadata is sent when sending status.
  2916. func testMultipleSetHeaderUnaryRPCError(t *testing.T, e env) {
  2917. te := newTest(t, e)
  2918. te.startServer(&testServer{security: e.security, setHeaderOnly: true})
  2919. defer te.tearDown()
  2920. tc := testpb.NewTestServiceClient(te.clientConn())
  2921. const (
  2922. argSize = 1
  2923. respSize = -1 // Invalid respSize to make RPC fail.
  2924. )
  2925. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize)
  2926. if err != nil {
  2927. t.Fatal(err)
  2928. }
  2929. req := &testpb.SimpleRequest{
  2930. ResponseType: testpb.PayloadType_COMPRESSABLE,
  2931. ResponseSize: respSize,
  2932. Payload: payload,
  2933. }
  2934. var header metadata.MD
  2935. ctx := metadata.NewOutgoingContext(context.Background(), testMetadata)
  2936. if _, err := tc.UnaryCall(ctx, req, grpc.Header(&header), grpc.WaitForReady(true)); err == nil {
  2937. t.Fatalf("TestService.UnaryCall(%v, _, _, _) = _, %v; want _, <non-nil>", ctx, err)
  2938. }
  2939. delete(header, "user-agent")
  2940. delete(header, "content-type")
  2941. expectedHeader := metadata.Join(testMetadata, testMetadata2)
  2942. if !reflect.DeepEqual(header, expectedHeader) {
  2943. t.Fatalf("Received header metadata %v, want %v", header, expectedHeader)
  2944. }
  2945. }
  2946. func (s) TestSetAndSendHeaderStreamingRPC(t *testing.T) {
  2947. for _, e := range listTestEnv() {
  2948. if e.name == "handler-tls" {
  2949. continue
  2950. }
  2951. testSetAndSendHeaderStreamingRPC(t, e)
  2952. }
  2953. }
  2954. // To test header metadata is sent on SendHeader().
  2955. func testSetAndSendHeaderStreamingRPC(t *testing.T, e env) {
  2956. te := newTest(t, e)
  2957. te.startServer(&testServer{security: e.security, setAndSendHeader: true})
  2958. defer te.tearDown()
  2959. tc := testpb.NewTestServiceClient(te.clientConn())
  2960. ctx := metadata.NewOutgoingContext(context.Background(), testMetadata)
  2961. stream, err := tc.FullDuplexCall(ctx)
  2962. if err != nil {
  2963. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  2964. }
  2965. if err := stream.CloseSend(); err != nil {
  2966. t.Fatalf("%v.CloseSend() got %v, want %v", stream, err, nil)
  2967. }
  2968. if _, err := stream.Recv(); err != io.EOF {
  2969. t.Fatalf("%v failed to complele the FullDuplexCall: %v", stream, err)
  2970. }
  2971. header, err := stream.Header()
  2972. if err != nil {
  2973. t.Fatalf("%v.Header() = _, %v, want _, <nil>", stream, err)
  2974. }
  2975. delete(header, "user-agent")
  2976. delete(header, "content-type")
  2977. expectedHeader := metadata.Join(testMetadata, testMetadata2)
  2978. if !reflect.DeepEqual(header, expectedHeader) {
  2979. t.Fatalf("Received header metadata %v, want %v", header, expectedHeader)
  2980. }
  2981. }
  2982. func (s) TestMultipleSetHeaderStreamingRPC(t *testing.T) {
  2983. for _, e := range listTestEnv() {
  2984. if e.name == "handler-tls" {
  2985. continue
  2986. }
  2987. testMultipleSetHeaderStreamingRPC(t, e)
  2988. }
  2989. }
  2990. // To test header metadata is sent when sending response.
  2991. func testMultipleSetHeaderStreamingRPC(t *testing.T, e env) {
  2992. te := newTest(t, e)
  2993. te.startServer(&testServer{security: e.security, setHeaderOnly: true})
  2994. defer te.tearDown()
  2995. tc := testpb.NewTestServiceClient(te.clientConn())
  2996. const (
  2997. argSize = 1
  2998. respSize = 1
  2999. )
  3000. ctx := metadata.NewOutgoingContext(context.Background(), testMetadata)
  3001. stream, err := tc.FullDuplexCall(ctx)
  3002. if err != nil {
  3003. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  3004. }
  3005. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize)
  3006. if err != nil {
  3007. t.Fatal(err)
  3008. }
  3009. req := &testpb.StreamingOutputCallRequest{
  3010. ResponseType: testpb.PayloadType_COMPRESSABLE,
  3011. ResponseParameters: []*testpb.ResponseParameters{
  3012. {Size: respSize},
  3013. },
  3014. Payload: payload,
  3015. }
  3016. if err := stream.Send(req); err != nil {
  3017. t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, req, err)
  3018. }
  3019. if _, err := stream.Recv(); err != nil {
  3020. t.Fatalf("%v.Recv() = %v, want <nil>", stream, err)
  3021. }
  3022. if err := stream.CloseSend(); err != nil {
  3023. t.Fatalf("%v.CloseSend() got %v, want %v", stream, err, nil)
  3024. }
  3025. if _, err := stream.Recv(); err != io.EOF {
  3026. t.Fatalf("%v failed to complele the FullDuplexCall: %v", stream, err)
  3027. }
  3028. header, err := stream.Header()
  3029. if err != nil {
  3030. t.Fatalf("%v.Header() = _, %v, want _, <nil>", stream, err)
  3031. }
  3032. delete(header, "user-agent")
  3033. delete(header, "content-type")
  3034. expectedHeader := metadata.Join(testMetadata, testMetadata2)
  3035. if !reflect.DeepEqual(header, expectedHeader) {
  3036. t.Fatalf("Received header metadata %v, want %v", header, expectedHeader)
  3037. }
  3038. }
  3039. func (s) TestMultipleSetHeaderStreamingRPCError(t *testing.T) {
  3040. for _, e := range listTestEnv() {
  3041. if e.name == "handler-tls" {
  3042. continue
  3043. }
  3044. testMultipleSetHeaderStreamingRPCError(t, e)
  3045. }
  3046. }
  3047. // To test header metadata is sent when sending status.
  3048. func testMultipleSetHeaderStreamingRPCError(t *testing.T, e env) {
  3049. te := newTest(t, e)
  3050. te.startServer(&testServer{security: e.security, setHeaderOnly: true})
  3051. defer te.tearDown()
  3052. tc := testpb.NewTestServiceClient(te.clientConn())
  3053. const (
  3054. argSize = 1
  3055. respSize = -1
  3056. )
  3057. ctx, cancel := context.WithCancel(context.Background())
  3058. defer cancel()
  3059. ctx = metadata.NewOutgoingContext(ctx, testMetadata)
  3060. stream, err := tc.FullDuplexCall(ctx)
  3061. if err != nil {
  3062. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  3063. }
  3064. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize)
  3065. if err != nil {
  3066. t.Fatal(err)
  3067. }
  3068. req := &testpb.StreamingOutputCallRequest{
  3069. ResponseType: testpb.PayloadType_COMPRESSABLE,
  3070. ResponseParameters: []*testpb.ResponseParameters{
  3071. {Size: respSize},
  3072. },
  3073. Payload: payload,
  3074. }
  3075. if err := stream.Send(req); err != nil {
  3076. t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, req, err)
  3077. }
  3078. if _, err := stream.Recv(); err == nil {
  3079. t.Fatalf("%v.Recv() = %v, want <non-nil>", stream, err)
  3080. }
  3081. header, err := stream.Header()
  3082. if err != nil {
  3083. t.Fatalf("%v.Header() = _, %v, want _, <nil>", stream, err)
  3084. }
  3085. delete(header, "user-agent")
  3086. delete(header, "content-type")
  3087. expectedHeader := metadata.Join(testMetadata, testMetadata2)
  3088. if !reflect.DeepEqual(header, expectedHeader) {
  3089. t.Fatalf("Received header metadata %v, want %v", header, expectedHeader)
  3090. }
  3091. if err := stream.CloseSend(); err != nil {
  3092. t.Fatalf("%v.CloseSend() got %v, want %v", stream, err, nil)
  3093. }
  3094. }
  3095. // TestMalformedHTTP2Metedata verfies the returned error when the client
  3096. // sends an illegal metadata.
  3097. func (s) TestMalformedHTTP2Metadata(t *testing.T) {
  3098. for _, e := range listTestEnv() {
  3099. if e.name == "handler-tls" {
  3100. // Failed with "server stops accepting new RPCs".
  3101. // Server stops accepting new RPCs when the client sends an illegal http2 header.
  3102. continue
  3103. }
  3104. testMalformedHTTP2Metadata(t, e)
  3105. }
  3106. }
  3107. func testMalformedHTTP2Metadata(t *testing.T, e env) {
  3108. te := newTest(t, e)
  3109. te.startServer(&testServer{security: e.security})
  3110. defer te.tearDown()
  3111. tc := testpb.NewTestServiceClient(te.clientConn())
  3112. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, 2718)
  3113. if err != nil {
  3114. t.Fatal(err)
  3115. }
  3116. req := &testpb.SimpleRequest{
  3117. ResponseType: testpb.PayloadType_COMPRESSABLE,
  3118. ResponseSize: 314,
  3119. Payload: payload,
  3120. }
  3121. ctx := metadata.NewOutgoingContext(context.Background(), malformedHTTP2Metadata)
  3122. if _, err := tc.UnaryCall(ctx, req); status.Code(err) != codes.Internal {
  3123. t.Fatalf("TestService.UnaryCall(%v, _) = _, %v; want _, %s", ctx, err, codes.Internal)
  3124. }
  3125. }
  3126. func (s) TestTransparentRetry(t *testing.T) {
  3127. for _, e := range listTestEnv() {
  3128. if e.name == "handler-tls" {
  3129. // Fails with RST_STREAM / FLOW_CONTROL_ERROR
  3130. continue
  3131. }
  3132. testTransparentRetry(t, e)
  3133. }
  3134. }
  3135. // This test makes sure RPCs are retried times when they receive a RST_STREAM
  3136. // with the REFUSED_STREAM error code, which the InTapHandle provokes.
  3137. func testTransparentRetry(t *testing.T, e env) {
  3138. te := newTest(t, e)
  3139. attempts := 0
  3140. successAttempt := 2
  3141. te.tapHandle = func(ctx context.Context, _ *tap.Info) (context.Context, error) {
  3142. attempts++
  3143. if attempts < successAttempt {
  3144. return nil, errors.New("not now")
  3145. }
  3146. return ctx, nil
  3147. }
  3148. te.startServer(&testServer{security: e.security})
  3149. defer te.tearDown()
  3150. cc := te.clientConn()
  3151. tsc := testpb.NewTestServiceClient(cc)
  3152. testCases := []struct {
  3153. successAttempt int
  3154. failFast bool
  3155. errCode codes.Code
  3156. }{{
  3157. successAttempt: 1,
  3158. }, {
  3159. successAttempt: 2,
  3160. }, {
  3161. successAttempt: 3,
  3162. errCode: codes.Unavailable,
  3163. }, {
  3164. successAttempt: 1,
  3165. failFast: true,
  3166. }, {
  3167. successAttempt: 2,
  3168. failFast: true,
  3169. errCode: codes.Unavailable, // We won't retry on fail fast.
  3170. }}
  3171. for _, tc := range testCases {
  3172. attempts = 0
  3173. successAttempt = tc.successAttempt
  3174. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  3175. _, err := tsc.EmptyCall(ctx, &testpb.Empty{}, grpc.WaitForReady(!tc.failFast))
  3176. cancel()
  3177. if status.Code(err) != tc.errCode {
  3178. t.Errorf("%+v: tsc.EmptyCall(_, _) = _, %v, want _, Code=%v", tc, err, tc.errCode)
  3179. }
  3180. }
  3181. }
  3182. func (s) TestCancel(t *testing.T) {
  3183. for _, e := range listTestEnv() {
  3184. testCancel(t, e)
  3185. }
  3186. }
  3187. func testCancel(t *testing.T, e env) {
  3188. te := newTest(t, e)
  3189. te.declareLogNoise("grpc: the client connection is closing; please retry")
  3190. te.startServer(&testServer{security: e.security, unaryCallSleepTime: time.Second})
  3191. defer te.tearDown()
  3192. cc := te.clientConn()
  3193. tc := testpb.NewTestServiceClient(cc)
  3194. const argSize = 2718
  3195. const respSize = 314
  3196. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize)
  3197. if err != nil {
  3198. t.Fatal(err)
  3199. }
  3200. req := &testpb.SimpleRequest{
  3201. ResponseType: testpb.PayloadType_COMPRESSABLE,
  3202. ResponseSize: respSize,
  3203. Payload: payload,
  3204. }
  3205. ctx, cancel := context.WithCancel(context.Background())
  3206. time.AfterFunc(1*time.Millisecond, cancel)
  3207. if r, err := tc.UnaryCall(ctx, req); status.Code(err) != codes.Canceled {
  3208. t.Fatalf("TestService/UnaryCall(_, _) = %v, %v; want _, error code: %s", r, err, codes.Canceled)
  3209. }
  3210. awaitNewConnLogOutput()
  3211. }
  3212. func (s) TestCancelNoIO(t *testing.T) {
  3213. for _, e := range listTestEnv() {
  3214. testCancelNoIO(t, e)
  3215. }
  3216. }
  3217. func testCancelNoIO(t *testing.T, e env) {
  3218. te := newTest(t, e)
  3219. te.declareLogNoise("http2Client.notifyError got notified that the client transport was broken")
  3220. te.maxStream = 1 // Only allows 1 live stream per server transport.
  3221. te.startServer(&testServer{security: e.security})
  3222. defer te.tearDown()
  3223. cc := te.clientConn()
  3224. tc := testpb.NewTestServiceClient(cc)
  3225. // Start one blocked RPC for which we'll never send streaming
  3226. // input. This will consume the 1 maximum concurrent streams,
  3227. // causing future RPCs to hang.
  3228. ctx, cancelFirst := context.WithCancel(context.Background())
  3229. _, err := tc.StreamingInputCall(ctx)
  3230. if err != nil {
  3231. t.Fatalf("%v.StreamingInputCall(_) = _, %v, want _, <nil>", tc, err)
  3232. }
  3233. // Loop until the ClientConn receives the initial settings
  3234. // frame from the server, notifying it about the maximum
  3235. // concurrent streams. We know when it's received it because
  3236. // an RPC will fail with codes.DeadlineExceeded instead of
  3237. // succeeding.
  3238. // TODO(bradfitz): add internal test hook for this (Issue 534)
  3239. for {
  3240. ctx, cancelSecond := context.WithTimeout(context.Background(), 50*time.Millisecond)
  3241. _, err := tc.StreamingInputCall(ctx)
  3242. cancelSecond()
  3243. if err == nil {
  3244. continue
  3245. }
  3246. if status.Code(err) == codes.DeadlineExceeded {
  3247. break
  3248. }
  3249. t.Fatalf("%v.StreamingInputCall(_) = _, %v, want _, %s", tc, err, codes.DeadlineExceeded)
  3250. }
  3251. // If there are any RPCs in flight before the client receives
  3252. // the max streams setting, let them be expired.
  3253. // TODO(bradfitz): add internal test hook for this (Issue 534)
  3254. time.Sleep(50 * time.Millisecond)
  3255. go func() {
  3256. time.Sleep(50 * time.Millisecond)
  3257. cancelFirst()
  3258. }()
  3259. // This should be blocked until the 1st is canceled, then succeed.
  3260. ctx, cancelThird := context.WithTimeout(context.Background(), 500*time.Millisecond)
  3261. if _, err := tc.StreamingInputCall(ctx); err != nil {
  3262. t.Errorf("%v.StreamingInputCall(_) = _, %v, want _, <nil>", tc, err)
  3263. }
  3264. cancelThird()
  3265. }
  3266. // The following tests the gRPC streaming RPC implementations.
  3267. // TODO(zhaoq): Have better coverage on error cases.
  3268. var (
  3269. reqSizes = []int{27182, 8, 1828, 45904}
  3270. respSizes = []int{31415, 9, 2653, 58979}
  3271. )
  3272. func (s) TestNoService(t *testing.T) {
  3273. for _, e := range listTestEnv() {
  3274. testNoService(t, e)
  3275. }
  3276. }
  3277. func testNoService(t *testing.T, e env) {
  3278. te := newTest(t, e)
  3279. te.startServer(nil)
  3280. defer te.tearDown()
  3281. cc := te.clientConn()
  3282. tc := testpb.NewTestServiceClient(cc)
  3283. stream, err := tc.FullDuplexCall(te.ctx, grpc.WaitForReady(true))
  3284. if err != nil {
  3285. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  3286. }
  3287. if _, err := stream.Recv(); status.Code(err) != codes.Unimplemented {
  3288. t.Fatalf("stream.Recv() = _, %v, want _, error code %s", err, codes.Unimplemented)
  3289. }
  3290. }
  3291. func (s) TestPingPong(t *testing.T) {
  3292. for _, e := range listTestEnv() {
  3293. testPingPong(t, e)
  3294. }
  3295. }
  3296. func testPingPong(t *testing.T, e env) {
  3297. te := newTest(t, e)
  3298. te.startServer(&testServer{security: e.security})
  3299. defer te.tearDown()
  3300. tc := testpb.NewTestServiceClient(te.clientConn())
  3301. stream, err := tc.FullDuplexCall(te.ctx)
  3302. if err != nil {
  3303. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  3304. }
  3305. var index int
  3306. for index < len(reqSizes) {
  3307. respParam := []*testpb.ResponseParameters{
  3308. {
  3309. Size: int32(respSizes[index]),
  3310. },
  3311. }
  3312. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(reqSizes[index]))
  3313. if err != nil {
  3314. t.Fatal(err)
  3315. }
  3316. req := &testpb.StreamingOutputCallRequest{
  3317. ResponseType: testpb.PayloadType_COMPRESSABLE,
  3318. ResponseParameters: respParam,
  3319. Payload: payload,
  3320. }
  3321. if err := stream.Send(req); err != nil {
  3322. t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, req, err)
  3323. }
  3324. reply, err := stream.Recv()
  3325. if err != nil {
  3326. t.Fatalf("%v.Recv() = %v, want <nil>", stream, err)
  3327. }
  3328. pt := reply.GetPayload().GetType()
  3329. if pt != testpb.PayloadType_COMPRESSABLE {
  3330. t.Fatalf("Got the reply of type %d, want %d", pt, testpb.PayloadType_COMPRESSABLE)
  3331. }
  3332. size := len(reply.GetPayload().GetBody())
  3333. if size != int(respSizes[index]) {
  3334. t.Fatalf("Got reply body of length %d, want %d", size, respSizes[index])
  3335. }
  3336. index++
  3337. }
  3338. if err := stream.CloseSend(); err != nil {
  3339. t.Fatalf("%v.CloseSend() got %v, want %v", stream, err, nil)
  3340. }
  3341. if _, err := stream.Recv(); err != io.EOF {
  3342. t.Fatalf("%v failed to complele the ping pong test: %v", stream, err)
  3343. }
  3344. }
  3345. func (s) TestMetadataStreamingRPC(t *testing.T) {
  3346. for _, e := range listTestEnv() {
  3347. testMetadataStreamingRPC(t, e)
  3348. }
  3349. }
  3350. func testMetadataStreamingRPC(t *testing.T, e env) {
  3351. te := newTest(t, e)
  3352. te.startServer(&testServer{security: e.security})
  3353. defer te.tearDown()
  3354. tc := testpb.NewTestServiceClient(te.clientConn())
  3355. ctx := metadata.NewOutgoingContext(te.ctx, testMetadata)
  3356. stream, err := tc.FullDuplexCall(ctx)
  3357. if err != nil {
  3358. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  3359. }
  3360. go func() {
  3361. headerMD, err := stream.Header()
  3362. if e.security == "tls" {
  3363. delete(headerMD, "transport_security_type")
  3364. }
  3365. delete(headerMD, "trailer") // ignore if present
  3366. delete(headerMD, "user-agent")
  3367. delete(headerMD, "content-type")
  3368. if err != nil || !reflect.DeepEqual(testMetadata, headerMD) {
  3369. t.Errorf("#1 %v.Header() = %v, %v, want %v, <nil>", stream, headerMD, err, testMetadata)
  3370. }
  3371. // test the cached value.
  3372. headerMD, err = stream.Header()
  3373. delete(headerMD, "trailer") // ignore if present
  3374. delete(headerMD, "user-agent")
  3375. delete(headerMD, "content-type")
  3376. if err != nil || !reflect.DeepEqual(testMetadata, headerMD) {
  3377. t.Errorf("#2 %v.Header() = %v, %v, want %v, <nil>", stream, headerMD, err, testMetadata)
  3378. }
  3379. err = func() error {
  3380. for index := 0; index < len(reqSizes); index++ {
  3381. respParam := []*testpb.ResponseParameters{
  3382. {
  3383. Size: int32(respSizes[index]),
  3384. },
  3385. }
  3386. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(reqSizes[index]))
  3387. if err != nil {
  3388. return err
  3389. }
  3390. req := &testpb.StreamingOutputCallRequest{
  3391. ResponseType: testpb.PayloadType_COMPRESSABLE,
  3392. ResponseParameters: respParam,
  3393. Payload: payload,
  3394. }
  3395. if err := stream.Send(req); err != nil {
  3396. return fmt.Errorf("%v.Send(%v) = %v, want <nil>", stream, req, err)
  3397. }
  3398. }
  3399. return nil
  3400. }()
  3401. // Tell the server we're done sending args.
  3402. stream.CloseSend()
  3403. if err != nil {
  3404. t.Error(err)
  3405. }
  3406. }()
  3407. for {
  3408. if _, err := stream.Recv(); err != nil {
  3409. break
  3410. }
  3411. }
  3412. trailerMD := stream.Trailer()
  3413. if !reflect.DeepEqual(testTrailerMetadata, trailerMD) {
  3414. t.Fatalf("%v.Trailer() = %v, want %v", stream, trailerMD, testTrailerMetadata)
  3415. }
  3416. }
  3417. func (s) TestServerStreaming(t *testing.T) {
  3418. for _, e := range listTestEnv() {
  3419. testServerStreaming(t, e)
  3420. }
  3421. }
  3422. func testServerStreaming(t *testing.T, e env) {
  3423. te := newTest(t, e)
  3424. te.startServer(&testServer{security: e.security})
  3425. defer te.tearDown()
  3426. tc := testpb.NewTestServiceClient(te.clientConn())
  3427. respParam := make([]*testpb.ResponseParameters, len(respSizes))
  3428. for i, s := range respSizes {
  3429. respParam[i] = &testpb.ResponseParameters{
  3430. Size: int32(s),
  3431. }
  3432. }
  3433. req := &testpb.StreamingOutputCallRequest{
  3434. ResponseType: testpb.PayloadType_COMPRESSABLE,
  3435. ResponseParameters: respParam,
  3436. }
  3437. stream, err := tc.StreamingOutputCall(context.Background(), req)
  3438. if err != nil {
  3439. t.Fatalf("%v.StreamingOutputCall(_) = _, %v, want <nil>", tc, err)
  3440. }
  3441. var rpcStatus error
  3442. var respCnt int
  3443. var index int
  3444. for {
  3445. reply, err := stream.Recv()
  3446. if err != nil {
  3447. rpcStatus = err
  3448. break
  3449. }
  3450. pt := reply.GetPayload().GetType()
  3451. if pt != testpb.PayloadType_COMPRESSABLE {
  3452. t.Fatalf("Got the reply of type %d, want %d", pt, testpb.PayloadType_COMPRESSABLE)
  3453. }
  3454. size := len(reply.GetPayload().GetBody())
  3455. if size != int(respSizes[index]) {
  3456. t.Fatalf("Got reply body of length %d, want %d", size, respSizes[index])
  3457. }
  3458. index++
  3459. respCnt++
  3460. }
  3461. if rpcStatus != io.EOF {
  3462. t.Fatalf("Failed to finish the server streaming rpc: %v, want <EOF>", rpcStatus)
  3463. }
  3464. if respCnt != len(respSizes) {
  3465. t.Fatalf("Got %d reply, want %d", len(respSizes), respCnt)
  3466. }
  3467. }
  3468. func (s) TestFailedServerStreaming(t *testing.T) {
  3469. for _, e := range listTestEnv() {
  3470. testFailedServerStreaming(t, e)
  3471. }
  3472. }
  3473. func testFailedServerStreaming(t *testing.T, e env) {
  3474. te := newTest(t, e)
  3475. te.userAgent = failAppUA
  3476. te.startServer(&testServer{security: e.security})
  3477. defer te.tearDown()
  3478. tc := testpb.NewTestServiceClient(te.clientConn())
  3479. respParam := make([]*testpb.ResponseParameters, len(respSizes))
  3480. for i, s := range respSizes {
  3481. respParam[i] = &testpb.ResponseParameters{
  3482. Size: int32(s),
  3483. }
  3484. }
  3485. req := &testpb.StreamingOutputCallRequest{
  3486. ResponseType: testpb.PayloadType_COMPRESSABLE,
  3487. ResponseParameters: respParam,
  3488. }
  3489. ctx := metadata.NewOutgoingContext(te.ctx, testMetadata)
  3490. stream, err := tc.StreamingOutputCall(ctx, req)
  3491. if err != nil {
  3492. t.Fatalf("%v.StreamingOutputCall(_) = _, %v, want <nil>", tc, err)
  3493. }
  3494. wantErr := status.Error(codes.DataLoss, "error for testing: "+failAppUA)
  3495. if _, err := stream.Recv(); !reflect.DeepEqual(err, wantErr) {
  3496. t.Fatalf("%v.Recv() = _, %v, want _, %v", stream, err, wantErr)
  3497. }
  3498. }
  3499. // concurrentSendServer is a TestServiceServer whose
  3500. // StreamingOutputCall makes ten serial Send calls, sending payloads
  3501. // "0".."9", inclusive. TestServerStreamingConcurrent verifies they
  3502. // were received in the correct order, and that there were no races.
  3503. //
  3504. // All other TestServiceServer methods crash if called.
  3505. type concurrentSendServer struct {
  3506. testpb.TestServiceServer
  3507. }
  3508. func (s concurrentSendServer) StreamingOutputCall(args *testpb.StreamingOutputCallRequest, stream testpb.TestService_StreamingOutputCallServer) error {
  3509. for i := 0; i < 10; i++ {
  3510. stream.Send(&testpb.StreamingOutputCallResponse{
  3511. Payload: &testpb.Payload{
  3512. Body: []byte{'0' + uint8(i)},
  3513. },
  3514. })
  3515. }
  3516. return nil
  3517. }
  3518. // Tests doing a bunch of concurrent streaming output calls.
  3519. func (s) TestServerStreamingConcurrent(t *testing.T) {
  3520. for _, e := range listTestEnv() {
  3521. testServerStreamingConcurrent(t, e)
  3522. }
  3523. }
  3524. func testServerStreamingConcurrent(t *testing.T, e env) {
  3525. te := newTest(t, e)
  3526. te.startServer(concurrentSendServer{})
  3527. defer te.tearDown()
  3528. cc := te.clientConn()
  3529. tc := testpb.NewTestServiceClient(cc)
  3530. doStreamingCall := func() {
  3531. req := &testpb.StreamingOutputCallRequest{}
  3532. stream, err := tc.StreamingOutputCall(context.Background(), req)
  3533. if err != nil {
  3534. t.Errorf("%v.StreamingOutputCall(_) = _, %v, want <nil>", tc, err)
  3535. return
  3536. }
  3537. var ngot int
  3538. var buf bytes.Buffer
  3539. for {
  3540. reply, err := stream.Recv()
  3541. if err == io.EOF {
  3542. break
  3543. }
  3544. if err != nil {
  3545. t.Fatal(err)
  3546. }
  3547. ngot++
  3548. if buf.Len() > 0 {
  3549. buf.WriteByte(',')
  3550. }
  3551. buf.Write(reply.GetPayload().GetBody())
  3552. }
  3553. if want := 10; ngot != want {
  3554. t.Errorf("Got %d replies, want %d", ngot, want)
  3555. }
  3556. if got, want := buf.String(), "0,1,2,3,4,5,6,7,8,9"; got != want {
  3557. t.Errorf("Got replies %q; want %q", got, want)
  3558. }
  3559. }
  3560. var wg sync.WaitGroup
  3561. for i := 0; i < 20; i++ {
  3562. wg.Add(1)
  3563. go func() {
  3564. defer wg.Done()
  3565. doStreamingCall()
  3566. }()
  3567. }
  3568. wg.Wait()
  3569. }
  3570. func generatePayloadSizes() [][]int {
  3571. reqSizes := [][]int{
  3572. {27182, 8, 1828, 45904},
  3573. }
  3574. num8KPayloads := 1024
  3575. eightKPayloads := []int{}
  3576. for i := 0; i < num8KPayloads; i++ {
  3577. eightKPayloads = append(eightKPayloads, (1 << 13))
  3578. }
  3579. reqSizes = append(reqSizes, eightKPayloads)
  3580. num2MPayloads := 8
  3581. twoMPayloads := []int{}
  3582. for i := 0; i < num2MPayloads; i++ {
  3583. twoMPayloads = append(twoMPayloads, (1 << 21))
  3584. }
  3585. reqSizes = append(reqSizes, twoMPayloads)
  3586. return reqSizes
  3587. }
  3588. func (s) TestClientStreaming(t *testing.T) {
  3589. for _, s := range generatePayloadSizes() {
  3590. for _, e := range listTestEnv() {
  3591. testClientStreaming(t, e, s)
  3592. }
  3593. }
  3594. }
  3595. func testClientStreaming(t *testing.T, e env, sizes []int) {
  3596. te := newTest(t, e)
  3597. te.startServer(&testServer{security: e.security})
  3598. defer te.tearDown()
  3599. tc := testpb.NewTestServiceClient(te.clientConn())
  3600. ctx, cancel := context.WithTimeout(te.ctx, time.Second*30)
  3601. defer cancel()
  3602. stream, err := tc.StreamingInputCall(ctx)
  3603. if err != nil {
  3604. t.Fatalf("%v.StreamingInputCall(_) = _, %v, want <nil>", tc, err)
  3605. }
  3606. var sum int
  3607. for _, s := range sizes {
  3608. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(s))
  3609. if err != nil {
  3610. t.Fatal(err)
  3611. }
  3612. req := &testpb.StreamingInputCallRequest{
  3613. Payload: payload,
  3614. }
  3615. if err := stream.Send(req); err != nil {
  3616. t.Fatalf("%v.Send(_) = %v, want <nil>", stream, err)
  3617. }
  3618. sum += s
  3619. }
  3620. reply, err := stream.CloseAndRecv()
  3621. if err != nil {
  3622. t.Fatalf("%v.CloseAndRecv() got error %v, want %v", stream, err, nil)
  3623. }
  3624. if reply.GetAggregatedPayloadSize() != int32(sum) {
  3625. t.Fatalf("%v.CloseAndRecv().GetAggregatePayloadSize() = %v; want %v", stream, reply.GetAggregatedPayloadSize(), sum)
  3626. }
  3627. }
  3628. func (s) TestClientStreamingError(t *testing.T) {
  3629. for _, e := range listTestEnv() {
  3630. if e.name == "handler-tls" {
  3631. continue
  3632. }
  3633. testClientStreamingError(t, e)
  3634. }
  3635. }
  3636. func testClientStreamingError(t *testing.T, e env) {
  3637. te := newTest(t, e)
  3638. te.startServer(&testServer{security: e.security, earlyFail: true})
  3639. defer te.tearDown()
  3640. tc := testpb.NewTestServiceClient(te.clientConn())
  3641. stream, err := tc.StreamingInputCall(te.ctx)
  3642. if err != nil {
  3643. t.Fatalf("%v.StreamingInputCall(_) = _, %v, want <nil>", tc, err)
  3644. }
  3645. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, 1)
  3646. if err != nil {
  3647. t.Fatal(err)
  3648. }
  3649. req := &testpb.StreamingInputCallRequest{
  3650. Payload: payload,
  3651. }
  3652. // The 1st request should go through.
  3653. if err := stream.Send(req); err != nil {
  3654. t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, req, err)
  3655. }
  3656. for {
  3657. if err := stream.Send(req); err != io.EOF {
  3658. continue
  3659. }
  3660. if _, err := stream.CloseAndRecv(); status.Code(err) != codes.NotFound {
  3661. t.Fatalf("%v.CloseAndRecv() = %v, want error %s", stream, err, codes.NotFound)
  3662. }
  3663. break
  3664. }
  3665. }
  3666. func (s) TestExceedMaxStreamsLimit(t *testing.T) {
  3667. for _, e := range listTestEnv() {
  3668. testExceedMaxStreamsLimit(t, e)
  3669. }
  3670. }
  3671. func testExceedMaxStreamsLimit(t *testing.T, e env) {
  3672. te := newTest(t, e)
  3673. te.declareLogNoise(
  3674. "http2Client.notifyError got notified that the client transport was broken",
  3675. "Conn.resetTransport failed to create client transport",
  3676. "grpc: the connection is closing",
  3677. )
  3678. te.maxStream = 1 // Only allows 1 live stream per server transport.
  3679. te.startServer(&testServer{security: e.security})
  3680. defer te.tearDown()
  3681. cc := te.clientConn()
  3682. tc := testpb.NewTestServiceClient(cc)
  3683. _, err := tc.StreamingInputCall(te.ctx)
  3684. if err != nil {
  3685. t.Fatalf("%v.StreamingInputCall(_) = _, %v, want _, <nil>", tc, err)
  3686. }
  3687. // Loop until receiving the new max stream setting from the server.
  3688. for {
  3689. ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
  3690. defer cancel()
  3691. _, err := tc.StreamingInputCall(ctx)
  3692. if err == nil {
  3693. time.Sleep(50 * time.Millisecond)
  3694. continue
  3695. }
  3696. if status.Code(err) == codes.DeadlineExceeded {
  3697. break
  3698. }
  3699. t.Fatalf("%v.StreamingInputCall(_) = _, %v, want _, %s", tc, err, codes.DeadlineExceeded)
  3700. }
  3701. }
  3702. func (s) TestStreamsQuotaRecovery(t *testing.T) {
  3703. for _, e := range listTestEnv() {
  3704. testStreamsQuotaRecovery(t, e)
  3705. }
  3706. }
  3707. func testStreamsQuotaRecovery(t *testing.T, e env) {
  3708. te := newTest(t, e)
  3709. te.declareLogNoise(
  3710. "http2Client.notifyError got notified that the client transport was broken",
  3711. "Conn.resetTransport failed to create client transport",
  3712. "grpc: the connection is closing",
  3713. )
  3714. te.maxStream = 1 // Allows 1 live stream.
  3715. te.startServer(&testServer{security: e.security})
  3716. defer te.tearDown()
  3717. cc := te.clientConn()
  3718. tc := testpb.NewTestServiceClient(cc)
  3719. ctx, cancel := context.WithCancel(context.Background())
  3720. defer cancel()
  3721. if _, err := tc.StreamingInputCall(ctx); err != nil {
  3722. t.Fatalf("tc.StreamingInputCall(_) = _, %v, want _, <nil>", err)
  3723. }
  3724. // Loop until the new max stream setting is effective.
  3725. for {
  3726. ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
  3727. _, err := tc.StreamingInputCall(ctx)
  3728. cancel()
  3729. if err == nil {
  3730. time.Sleep(5 * time.Millisecond)
  3731. continue
  3732. }
  3733. if status.Code(err) == codes.DeadlineExceeded {
  3734. break
  3735. }
  3736. t.Fatalf("tc.StreamingInputCall(_) = _, %v, want _, %s", err, codes.DeadlineExceeded)
  3737. }
  3738. var wg sync.WaitGroup
  3739. for i := 0; i < 10; i++ {
  3740. wg.Add(1)
  3741. go func() {
  3742. defer wg.Done()
  3743. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, 314)
  3744. if err != nil {
  3745. t.Error(err)
  3746. return
  3747. }
  3748. req := &testpb.SimpleRequest{
  3749. ResponseType: testpb.PayloadType_COMPRESSABLE,
  3750. ResponseSize: 1592,
  3751. Payload: payload,
  3752. }
  3753. // No rpc should go through due to the max streams limit.
  3754. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
  3755. defer cancel()
  3756. if _, err := tc.UnaryCall(ctx, req, grpc.WaitForReady(true)); status.Code(err) != codes.DeadlineExceeded {
  3757. t.Errorf("tc.UnaryCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded)
  3758. }
  3759. }()
  3760. }
  3761. wg.Wait()
  3762. cancel()
  3763. // A new stream should be allowed after canceling the first one.
  3764. ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
  3765. defer cancel()
  3766. if _, err := tc.StreamingInputCall(ctx); err != nil {
  3767. t.Fatalf("tc.StreamingInputCall(_) = _, %v, want _, %v", err, nil)
  3768. }
  3769. }
  3770. func (s) TestCompressServerHasNoSupport(t *testing.T) {
  3771. for _, e := range listTestEnv() {
  3772. testCompressServerHasNoSupport(t, e)
  3773. }
  3774. }
  3775. func testCompressServerHasNoSupport(t *testing.T, e env) {
  3776. te := newTest(t, e)
  3777. te.serverCompression = false
  3778. te.clientCompression = false
  3779. te.clientNopCompression = true
  3780. te.startServer(&testServer{security: e.security})
  3781. defer te.tearDown()
  3782. tc := testpb.NewTestServiceClient(te.clientConn())
  3783. const argSize = 271828
  3784. const respSize = 314159
  3785. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize)
  3786. if err != nil {
  3787. t.Fatal(err)
  3788. }
  3789. req := &testpb.SimpleRequest{
  3790. ResponseType: testpb.PayloadType_COMPRESSABLE,
  3791. ResponseSize: respSize,
  3792. Payload: payload,
  3793. }
  3794. if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.Unimplemented {
  3795. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code %s", err, codes.Unimplemented)
  3796. }
  3797. // Streaming RPC
  3798. stream, err := tc.FullDuplexCall(context.Background())
  3799. if err != nil {
  3800. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  3801. }
  3802. if _, err := stream.Recv(); err == nil || status.Code(err) != codes.Unimplemented {
  3803. t.Fatalf("%v.Recv() = %v, want error code %s", stream, err, codes.Unimplemented)
  3804. }
  3805. }
  3806. func (s) TestCompressOK(t *testing.T) {
  3807. for _, e := range listTestEnv() {
  3808. testCompressOK(t, e)
  3809. }
  3810. }
  3811. func testCompressOK(t *testing.T, e env) {
  3812. te := newTest(t, e)
  3813. te.serverCompression = true
  3814. te.clientCompression = true
  3815. te.startServer(&testServer{security: e.security})
  3816. defer te.tearDown()
  3817. tc := testpb.NewTestServiceClient(te.clientConn())
  3818. // Unary call
  3819. const argSize = 271828
  3820. const respSize = 314159
  3821. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize)
  3822. if err != nil {
  3823. t.Fatal(err)
  3824. }
  3825. req := &testpb.SimpleRequest{
  3826. ResponseType: testpb.PayloadType_COMPRESSABLE,
  3827. ResponseSize: respSize,
  3828. Payload: payload,
  3829. }
  3830. ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs("something", "something"))
  3831. if _, err := tc.UnaryCall(ctx, req); err != nil {
  3832. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, <nil>", err)
  3833. }
  3834. // Streaming RPC
  3835. ctx, cancel := context.WithCancel(context.Background())
  3836. defer cancel()
  3837. stream, err := tc.FullDuplexCall(ctx)
  3838. if err != nil {
  3839. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  3840. }
  3841. respParam := []*testpb.ResponseParameters{
  3842. {
  3843. Size: 31415,
  3844. },
  3845. }
  3846. payload, err = newPayload(testpb.PayloadType_COMPRESSABLE, int32(31415))
  3847. if err != nil {
  3848. t.Fatal(err)
  3849. }
  3850. sreq := &testpb.StreamingOutputCallRequest{
  3851. ResponseType: testpb.PayloadType_COMPRESSABLE,
  3852. ResponseParameters: respParam,
  3853. Payload: payload,
  3854. }
  3855. if err := stream.Send(sreq); err != nil {
  3856. t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err)
  3857. }
  3858. stream.CloseSend()
  3859. if _, err := stream.Recv(); err != nil {
  3860. t.Fatalf("%v.Recv() = %v, want <nil>", stream, err)
  3861. }
  3862. if _, err := stream.Recv(); err != io.EOF {
  3863. t.Fatalf("%v.Recv() = %v, want io.EOF", stream, err)
  3864. }
  3865. }
  3866. func (s) TestIdentityEncoding(t *testing.T) {
  3867. for _, e := range listTestEnv() {
  3868. testIdentityEncoding(t, e)
  3869. }
  3870. }
  3871. func testIdentityEncoding(t *testing.T, e env) {
  3872. te := newTest(t, e)
  3873. te.startServer(&testServer{security: e.security})
  3874. defer te.tearDown()
  3875. tc := testpb.NewTestServiceClient(te.clientConn())
  3876. // Unary call
  3877. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, 5)
  3878. if err != nil {
  3879. t.Fatal(err)
  3880. }
  3881. req := &testpb.SimpleRequest{
  3882. ResponseType: testpb.PayloadType_COMPRESSABLE,
  3883. ResponseSize: 10,
  3884. Payload: payload,
  3885. }
  3886. ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs("something", "something"))
  3887. if _, err := tc.UnaryCall(ctx, req); err != nil {
  3888. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, <nil>", err)
  3889. }
  3890. // Streaming RPC
  3891. ctx, cancel := context.WithCancel(context.Background())
  3892. defer cancel()
  3893. stream, err := tc.FullDuplexCall(ctx, grpc.UseCompressor("identity"))
  3894. if err != nil {
  3895. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  3896. }
  3897. payload, err = newPayload(testpb.PayloadType_COMPRESSABLE, int32(31415))
  3898. if err != nil {
  3899. t.Fatal(err)
  3900. }
  3901. sreq := &testpb.StreamingOutputCallRequest{
  3902. ResponseType: testpb.PayloadType_COMPRESSABLE,
  3903. ResponseParameters: []*testpb.ResponseParameters{{Size: 10}},
  3904. Payload: payload,
  3905. }
  3906. if err := stream.Send(sreq); err != nil {
  3907. t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err)
  3908. }
  3909. stream.CloseSend()
  3910. if _, err := stream.Recv(); err != nil {
  3911. t.Fatalf("%v.Recv() = %v, want <nil>", stream, err)
  3912. }
  3913. if _, err := stream.Recv(); err != io.EOF {
  3914. t.Fatalf("%v.Recv() = %v, want io.EOF", stream, err)
  3915. }
  3916. }
  3917. func (s) TestUnaryClientInterceptor(t *testing.T) {
  3918. for _, e := range listTestEnv() {
  3919. testUnaryClientInterceptor(t, e)
  3920. }
  3921. }
  3922. func failOkayRPC(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
  3923. err := invoker(ctx, method, req, reply, cc, opts...)
  3924. if err == nil {
  3925. return status.Error(codes.NotFound, "")
  3926. }
  3927. return err
  3928. }
  3929. func testUnaryClientInterceptor(t *testing.T, e env) {
  3930. te := newTest(t, e)
  3931. te.userAgent = testAppUA
  3932. te.unaryClientInt = failOkayRPC
  3933. te.startServer(&testServer{security: e.security})
  3934. defer te.tearDown()
  3935. tc := testpb.NewTestServiceClient(te.clientConn())
  3936. if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); status.Code(err) != codes.NotFound {
  3937. t.Fatalf("%v.EmptyCall(_, _) = _, %v, want _, error code %s", tc, err, codes.NotFound)
  3938. }
  3939. }
  3940. func (s) TestStreamClientInterceptor(t *testing.T) {
  3941. for _, e := range listTestEnv() {
  3942. testStreamClientInterceptor(t, e)
  3943. }
  3944. }
  3945. func failOkayStream(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
  3946. s, err := streamer(ctx, desc, cc, method, opts...)
  3947. if err == nil {
  3948. return nil, status.Error(codes.NotFound, "")
  3949. }
  3950. return s, nil
  3951. }
  3952. func testStreamClientInterceptor(t *testing.T, e env) {
  3953. te := newTest(t, e)
  3954. te.streamClientInt = failOkayStream
  3955. te.startServer(&testServer{security: e.security})
  3956. defer te.tearDown()
  3957. tc := testpb.NewTestServiceClient(te.clientConn())
  3958. respParam := []*testpb.ResponseParameters{
  3959. {
  3960. Size: int32(1),
  3961. },
  3962. }
  3963. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(1))
  3964. if err != nil {
  3965. t.Fatal(err)
  3966. }
  3967. req := &testpb.StreamingOutputCallRequest{
  3968. ResponseType: testpb.PayloadType_COMPRESSABLE,
  3969. ResponseParameters: respParam,
  3970. Payload: payload,
  3971. }
  3972. if _, err := tc.StreamingOutputCall(context.Background(), req); status.Code(err) != codes.NotFound {
  3973. t.Fatalf("%v.StreamingOutputCall(_) = _, %v, want _, error code %s", tc, err, codes.NotFound)
  3974. }
  3975. }
  3976. func (s) TestUnaryServerInterceptor(t *testing.T) {
  3977. for _, e := range listTestEnv() {
  3978. testUnaryServerInterceptor(t, e)
  3979. }
  3980. }
  3981. func errInjector(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
  3982. return nil, status.Error(codes.PermissionDenied, "")
  3983. }
  3984. func testUnaryServerInterceptor(t *testing.T, e env) {
  3985. te := newTest(t, e)
  3986. te.unaryServerInt = errInjector
  3987. te.startServer(&testServer{security: e.security})
  3988. defer te.tearDown()
  3989. tc := testpb.NewTestServiceClient(te.clientConn())
  3990. if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); status.Code(err) != codes.PermissionDenied {
  3991. t.Fatalf("%v.EmptyCall(_, _) = _, %v, want _, error code %s", tc, err, codes.PermissionDenied)
  3992. }
  3993. }
  3994. func (s) TestStreamServerInterceptor(t *testing.T) {
  3995. for _, e := range listTestEnv() {
  3996. // TODO(bradfitz): Temporarily skip this env due to #619.
  3997. if e.name == "handler-tls" {
  3998. continue
  3999. }
  4000. testStreamServerInterceptor(t, e)
  4001. }
  4002. }
  4003. func fullDuplexOnly(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
  4004. if info.FullMethod == "/grpc.testing.TestService/FullDuplexCall" {
  4005. return handler(srv, ss)
  4006. }
  4007. // Reject the other methods.
  4008. return status.Error(codes.PermissionDenied, "")
  4009. }
  4010. func testStreamServerInterceptor(t *testing.T, e env) {
  4011. te := newTest(t, e)
  4012. te.streamServerInt = fullDuplexOnly
  4013. te.startServer(&testServer{security: e.security})
  4014. defer te.tearDown()
  4015. tc := testpb.NewTestServiceClient(te.clientConn())
  4016. respParam := []*testpb.ResponseParameters{
  4017. {
  4018. Size: int32(1),
  4019. },
  4020. }
  4021. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(1))
  4022. if err != nil {
  4023. t.Fatal(err)
  4024. }
  4025. req := &testpb.StreamingOutputCallRequest{
  4026. ResponseType: testpb.PayloadType_COMPRESSABLE,
  4027. ResponseParameters: respParam,
  4028. Payload: payload,
  4029. }
  4030. s1, err := tc.StreamingOutputCall(context.Background(), req)
  4031. if err != nil {
  4032. t.Fatalf("%v.StreamingOutputCall(_) = _, %v, want _, <nil>", tc, err)
  4033. }
  4034. if _, err := s1.Recv(); status.Code(err) != codes.PermissionDenied {
  4035. t.Fatalf("%v.StreamingInputCall(_) = _, %v, want _, error code %s", tc, err, codes.PermissionDenied)
  4036. }
  4037. s2, err := tc.FullDuplexCall(context.Background())
  4038. if err != nil {
  4039. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  4040. }
  4041. if err := s2.Send(req); err != nil {
  4042. t.Fatalf("%v.Send(_) = %v, want <nil>", s2, err)
  4043. }
  4044. if _, err := s2.Recv(); err != nil {
  4045. t.Fatalf("%v.Recv() = _, %v, want _, <nil>", s2, err)
  4046. }
  4047. }
  4048. // funcServer implements methods of TestServiceServer using funcs,
  4049. // similar to an http.HandlerFunc.
  4050. // Any unimplemented method will crash. Tests implement the method(s)
  4051. // they need.
  4052. type funcServer struct {
  4053. testpb.TestServiceServer
  4054. unaryCall func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error)
  4055. streamingInputCall func(stream testpb.TestService_StreamingInputCallServer) error
  4056. fullDuplexCall func(stream testpb.TestService_FullDuplexCallServer) error
  4057. }
  4058. func (s *funcServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
  4059. return s.unaryCall(ctx, in)
  4060. }
  4061. func (s *funcServer) StreamingInputCall(stream testpb.TestService_StreamingInputCallServer) error {
  4062. return s.streamingInputCall(stream)
  4063. }
  4064. func (s *funcServer) FullDuplexCall(stream testpb.TestService_FullDuplexCallServer) error {
  4065. return s.fullDuplexCall(stream)
  4066. }
  4067. func (s) TestClientRequestBodyErrorUnexpectedEOF(t *testing.T) {
  4068. for _, e := range listTestEnv() {
  4069. testClientRequestBodyErrorUnexpectedEOF(t, e)
  4070. }
  4071. }
  4072. func testClientRequestBodyErrorUnexpectedEOF(t *testing.T, e env) {
  4073. te := newTest(t, e)
  4074. ts := &funcServer{unaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
  4075. errUnexpectedCall := errors.New("unexpected call func server method")
  4076. t.Error(errUnexpectedCall)
  4077. return nil, errUnexpectedCall
  4078. }}
  4079. te.startServer(ts)
  4080. defer te.tearDown()
  4081. te.withServerTester(func(st *serverTester) {
  4082. st.writeHeadersGRPC(1, "/grpc.testing.TestService/UnaryCall")
  4083. // Say we have 5 bytes coming, but set END_STREAM flag:
  4084. st.writeData(1, true, []byte{0, 0, 0, 0, 5})
  4085. st.wantAnyFrame() // wait for server to crash (it used to crash)
  4086. })
  4087. }
  4088. func (s) TestClientRequestBodyErrorCloseAfterLength(t *testing.T) {
  4089. for _, e := range listTestEnv() {
  4090. testClientRequestBodyErrorCloseAfterLength(t, e)
  4091. }
  4092. }
  4093. func testClientRequestBodyErrorCloseAfterLength(t *testing.T, e env) {
  4094. te := newTest(t, e)
  4095. te.declareLogNoise("Server.processUnaryRPC failed to write status")
  4096. ts := &funcServer{unaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
  4097. errUnexpectedCall := errors.New("unexpected call func server method")
  4098. t.Error(errUnexpectedCall)
  4099. return nil, errUnexpectedCall
  4100. }}
  4101. te.startServer(ts)
  4102. defer te.tearDown()
  4103. te.withServerTester(func(st *serverTester) {
  4104. st.writeHeadersGRPC(1, "/grpc.testing.TestService/UnaryCall")
  4105. // say we're sending 5 bytes, but then close the connection instead.
  4106. st.writeData(1, false, []byte{0, 0, 0, 0, 5})
  4107. st.cc.Close()
  4108. })
  4109. }
  4110. func (s) TestClientRequestBodyErrorCancel(t *testing.T) {
  4111. for _, e := range listTestEnv() {
  4112. testClientRequestBodyErrorCancel(t, e)
  4113. }
  4114. }
  4115. func testClientRequestBodyErrorCancel(t *testing.T, e env) {
  4116. te := newTest(t, e)
  4117. gotCall := make(chan bool, 1)
  4118. ts := &funcServer{unaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
  4119. gotCall <- true
  4120. return new(testpb.SimpleResponse), nil
  4121. }}
  4122. te.startServer(ts)
  4123. defer te.tearDown()
  4124. te.withServerTester(func(st *serverTester) {
  4125. st.writeHeadersGRPC(1, "/grpc.testing.TestService/UnaryCall")
  4126. // Say we have 5 bytes coming, but cancel it instead.
  4127. st.writeRSTStream(1, http2.ErrCodeCancel)
  4128. st.writeData(1, false, []byte{0, 0, 0, 0, 5})
  4129. // Verify we didn't a call yet.
  4130. select {
  4131. case <-gotCall:
  4132. t.Fatal("unexpected call")
  4133. default:
  4134. }
  4135. // And now send an uncanceled (but still invalid), just to get a response.
  4136. st.writeHeadersGRPC(3, "/grpc.testing.TestService/UnaryCall")
  4137. st.writeData(3, true, []byte{0, 0, 0, 0, 0})
  4138. <-gotCall
  4139. st.wantAnyFrame()
  4140. })
  4141. }
  4142. func (s) TestClientRequestBodyErrorCancelStreamingInput(t *testing.T) {
  4143. for _, e := range listTestEnv() {
  4144. testClientRequestBodyErrorCancelStreamingInput(t, e)
  4145. }
  4146. }
  4147. func testClientRequestBodyErrorCancelStreamingInput(t *testing.T, e env) {
  4148. te := newTest(t, e)
  4149. recvErr := make(chan error, 1)
  4150. ts := &funcServer{streamingInputCall: func(stream testpb.TestService_StreamingInputCallServer) error {
  4151. _, err := stream.Recv()
  4152. recvErr <- err
  4153. return nil
  4154. }}
  4155. te.startServer(ts)
  4156. defer te.tearDown()
  4157. te.withServerTester(func(st *serverTester) {
  4158. st.writeHeadersGRPC(1, "/grpc.testing.TestService/StreamingInputCall")
  4159. // Say we have 5 bytes coming, but cancel it instead.
  4160. st.writeData(1, false, []byte{0, 0, 0, 0, 5})
  4161. st.writeRSTStream(1, http2.ErrCodeCancel)
  4162. var got error
  4163. select {
  4164. case got = <-recvErr:
  4165. case <-time.After(3 * time.Second):
  4166. t.Fatal("timeout waiting for error")
  4167. }
  4168. if grpc.Code(got) != codes.Canceled {
  4169. t.Errorf("error = %#v; want error code %s", got, codes.Canceled)
  4170. }
  4171. })
  4172. }
  4173. func (s) TestClientResourceExhaustedCancelFullDuplex(t *testing.T) {
  4174. for _, e := range listTestEnv() {
  4175. if e.httpHandler {
  4176. // httpHandler write won't be blocked on flow control window.
  4177. continue
  4178. }
  4179. testClientResourceExhaustedCancelFullDuplex(t, e)
  4180. }
  4181. }
  4182. func testClientResourceExhaustedCancelFullDuplex(t *testing.T, e env) {
  4183. te := newTest(t, e)
  4184. recvErr := make(chan error, 1)
  4185. ts := &funcServer{fullDuplexCall: func(stream testpb.TestService_FullDuplexCallServer) error {
  4186. defer close(recvErr)
  4187. _, err := stream.Recv()
  4188. if err != nil {
  4189. return status.Errorf(codes.Internal, "stream.Recv() got error: %v, want <nil>", err)
  4190. }
  4191. // create a payload that's larger than the default flow control window.
  4192. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, 10)
  4193. if err != nil {
  4194. return err
  4195. }
  4196. resp := &testpb.StreamingOutputCallResponse{
  4197. Payload: payload,
  4198. }
  4199. ce := make(chan error)
  4200. go func() {
  4201. var err error
  4202. for {
  4203. if err = stream.Send(resp); err != nil {
  4204. break
  4205. }
  4206. }
  4207. ce <- err
  4208. }()
  4209. select {
  4210. case err = <-ce:
  4211. case <-time.After(10 * time.Second):
  4212. err = errors.New("10s timeout reached")
  4213. }
  4214. recvErr <- err
  4215. return err
  4216. }}
  4217. te.startServer(ts)
  4218. defer te.tearDown()
  4219. // set a low limit on receive message size to error with Resource Exhausted on
  4220. // client side when server send a large message.
  4221. te.maxClientReceiveMsgSize = newInt(10)
  4222. cc := te.clientConn()
  4223. tc := testpb.NewTestServiceClient(cc)
  4224. stream, err := tc.FullDuplexCall(context.Background())
  4225. if err != nil {
  4226. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  4227. }
  4228. req := &testpb.StreamingOutputCallRequest{}
  4229. if err := stream.Send(req); err != nil {
  4230. t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, req, err)
  4231. }
  4232. if _, err := stream.Recv(); status.Code(err) != codes.ResourceExhausted {
  4233. t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted)
  4234. }
  4235. err = <-recvErr
  4236. if status.Code(err) != codes.Canceled {
  4237. t.Fatalf("server got error %v, want error code: %s", err, codes.Canceled)
  4238. }
  4239. }
  4240. type clientTimeoutCreds struct {
  4241. timeoutReturned bool
  4242. }
  4243. func (c *clientTimeoutCreds) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
  4244. if !c.timeoutReturned {
  4245. c.timeoutReturned = true
  4246. return nil, nil, context.DeadlineExceeded
  4247. }
  4248. return rawConn, nil, nil
  4249. }
  4250. func (c *clientTimeoutCreds) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
  4251. return rawConn, nil, nil
  4252. }
  4253. func (c *clientTimeoutCreds) Info() credentials.ProtocolInfo {
  4254. return credentials.ProtocolInfo{}
  4255. }
  4256. func (c *clientTimeoutCreds) Clone() credentials.TransportCredentials {
  4257. return nil
  4258. }
  4259. func (c *clientTimeoutCreds) OverrideServerName(s string) error {
  4260. return nil
  4261. }
  4262. func (s) TestNonFailFastRPCSucceedOnTimeoutCreds(t *testing.T) {
  4263. te := newTest(t, env{name: "timeout-cred", network: "tcp", security: "clientTimeoutCreds", balancer: "v1"})
  4264. te.userAgent = testAppUA
  4265. te.startServer(&testServer{security: te.e.security})
  4266. defer te.tearDown()
  4267. cc := te.clientConn()
  4268. tc := testpb.NewTestServiceClient(cc)
  4269. // This unary call should succeed, because ClientHandshake will succeed for the second time.
  4270. if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.WaitForReady(true)); err != nil {
  4271. te.t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want <nil>", err)
  4272. }
  4273. }
  4274. type serverDispatchCred struct {
  4275. rawConnCh chan net.Conn
  4276. }
  4277. func newServerDispatchCred() *serverDispatchCred {
  4278. return &serverDispatchCred{
  4279. rawConnCh: make(chan net.Conn, 1),
  4280. }
  4281. }
  4282. func (c *serverDispatchCred) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
  4283. return rawConn, nil, nil
  4284. }
  4285. func (c *serverDispatchCred) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
  4286. select {
  4287. case c.rawConnCh <- rawConn:
  4288. default:
  4289. }
  4290. return nil, nil, credentials.ErrConnDispatched
  4291. }
  4292. func (c *serverDispatchCred) Info() credentials.ProtocolInfo {
  4293. return credentials.ProtocolInfo{}
  4294. }
  4295. func (c *serverDispatchCred) Clone() credentials.TransportCredentials {
  4296. return nil
  4297. }
  4298. func (c *serverDispatchCred) OverrideServerName(s string) error {
  4299. return nil
  4300. }
  4301. func (c *serverDispatchCred) getRawConn() net.Conn {
  4302. return <-c.rawConnCh
  4303. }
  4304. func (s) TestServerCredsDispatch(t *testing.T) {
  4305. lis, err := net.Listen("tcp", "localhost:0")
  4306. if err != nil {
  4307. t.Fatalf("Failed to listen: %v", err)
  4308. }
  4309. cred := newServerDispatchCred()
  4310. s := grpc.NewServer(grpc.Creds(cred))
  4311. go s.Serve(lis)
  4312. defer s.Stop()
  4313. cc, err := grpc.Dial(lis.Addr().String(), grpc.WithTransportCredentials(cred))
  4314. if err != nil {
  4315. t.Fatalf("grpc.Dial(%q) = %v", lis.Addr().String(), err)
  4316. }
  4317. defer cc.Close()
  4318. rawConn := cred.getRawConn()
  4319. // Give grpc a chance to see the error and potentially close the connection.
  4320. // And check that connection is not closed after that.
  4321. time.Sleep(100 * time.Millisecond)
  4322. // Check rawConn is not closed.
  4323. if n, err := rawConn.Write([]byte{0}); n <= 0 || err != nil {
  4324. t.Errorf("Read() = %v, %v; want n>0, <nil>", n, err)
  4325. }
  4326. }
  4327. type authorityCheckCreds struct {
  4328. got string
  4329. }
  4330. func (c *authorityCheckCreds) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
  4331. return rawConn, nil, nil
  4332. }
  4333. func (c *authorityCheckCreds) ClientHandshake(ctx context.Context, authority string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
  4334. c.got = authority
  4335. return rawConn, nil, nil
  4336. }
  4337. func (c *authorityCheckCreds) Info() credentials.ProtocolInfo {
  4338. return credentials.ProtocolInfo{}
  4339. }
  4340. func (c *authorityCheckCreds) Clone() credentials.TransportCredentials {
  4341. return c
  4342. }
  4343. func (c *authorityCheckCreds) OverrideServerName(s string) error {
  4344. return nil
  4345. }
  4346. // This test makes sure that the authority client handshake gets is the endpoint
  4347. // in dial target, not the resolved ip address.
  4348. func (s) TestCredsHandshakeAuthority(t *testing.T) {
  4349. const testAuthority = "test.auth.ori.ty"
  4350. lis, err := net.Listen("tcp", "localhost:0")
  4351. if err != nil {
  4352. t.Fatalf("Failed to listen: %v", err)
  4353. }
  4354. cred := &authorityCheckCreds{}
  4355. s := grpc.NewServer()
  4356. go s.Serve(lis)
  4357. defer s.Stop()
  4358. r, rcleanup := manual.GenerateAndRegisterManualResolver()
  4359. defer rcleanup()
  4360. cc, err := grpc.Dial(r.Scheme()+":///"+testAuthority, grpc.WithTransportCredentials(cred))
  4361. if err != nil {
  4362. t.Fatalf("grpc.Dial(%q) = %v", lis.Addr().String(), err)
  4363. }
  4364. defer cc.Close()
  4365. r.UpdateState(resolver.State{Addresses: []resolver.Address{{Addr: lis.Addr().String()}}})
  4366. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
  4367. defer cancel()
  4368. for {
  4369. s := cc.GetState()
  4370. if s == connectivity.Ready {
  4371. break
  4372. }
  4373. if !cc.WaitForStateChange(ctx, s) {
  4374. // ctx got timeout or canceled.
  4375. t.Fatalf("ClientConn is not ready after 100 ms")
  4376. }
  4377. }
  4378. if cred.got != testAuthority {
  4379. t.Fatalf("client creds got authority: %q, want: %q", cred.got, testAuthority)
  4380. }
  4381. }
  4382. type clientFailCreds struct{}
  4383. func (c *clientFailCreds) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
  4384. return rawConn, nil, nil
  4385. }
  4386. func (c *clientFailCreds) ClientHandshake(ctx context.Context, authority string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
  4387. return nil, nil, fmt.Errorf("client handshake fails with fatal error")
  4388. }
  4389. func (c *clientFailCreds) Info() credentials.ProtocolInfo {
  4390. return credentials.ProtocolInfo{}
  4391. }
  4392. func (c *clientFailCreds) Clone() credentials.TransportCredentials {
  4393. return c
  4394. }
  4395. func (c *clientFailCreds) OverrideServerName(s string) error {
  4396. return nil
  4397. }
  4398. // This test makes sure that failfast RPCs fail if client handshake fails with
  4399. // fatal errors.
  4400. func (s) TestFailfastRPCFailOnFatalHandshakeError(t *testing.T) {
  4401. lis, err := net.Listen("tcp", "localhost:0")
  4402. if err != nil {
  4403. t.Fatalf("Failed to listen: %v", err)
  4404. }
  4405. defer lis.Close()
  4406. cc, err := grpc.Dial("passthrough:///"+lis.Addr().String(), grpc.WithTransportCredentials(&clientFailCreds{}))
  4407. if err != nil {
  4408. t.Fatalf("grpc.Dial(_) = %v", err)
  4409. }
  4410. defer cc.Close()
  4411. tc := testpb.NewTestServiceClient(cc)
  4412. // This unary call should fail, but not timeout.
  4413. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  4414. defer cancel()
  4415. if _, err := tc.EmptyCall(ctx, &testpb.Empty{}, grpc.WaitForReady(false)); status.Code(err) != codes.Unavailable {
  4416. t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want <Unavailable>", err)
  4417. }
  4418. }
  4419. func (s) TestFlowControlLogicalRace(t *testing.T) {
  4420. // Test for a regression of https://github.com/grpc/grpc-go/issues/632,
  4421. // and other flow control bugs.
  4422. const (
  4423. itemCount = 100
  4424. itemSize = 1 << 10
  4425. recvCount = 2
  4426. maxFailures = 3
  4427. requestTimeout = time.Second * 5
  4428. )
  4429. requestCount := 10000
  4430. if raceMode {
  4431. requestCount = 1000
  4432. }
  4433. lis, err := net.Listen("tcp", "localhost:0")
  4434. if err != nil {
  4435. t.Fatalf("Failed to listen: %v", err)
  4436. }
  4437. defer lis.Close()
  4438. s := grpc.NewServer()
  4439. testpb.RegisterTestServiceServer(s, &flowControlLogicalRaceServer{
  4440. itemCount: itemCount,
  4441. itemSize: itemSize,
  4442. })
  4443. defer s.Stop()
  4444. go s.Serve(lis)
  4445. ctx := context.Background()
  4446. cc, err := grpc.Dial(lis.Addr().String(), grpc.WithInsecure(), grpc.WithBlock())
  4447. if err != nil {
  4448. t.Fatalf("grpc.Dial(%q) = %v", lis.Addr().String(), err)
  4449. }
  4450. defer cc.Close()
  4451. cl := testpb.NewTestServiceClient(cc)
  4452. failures := 0
  4453. for i := 0; i < requestCount; i++ {
  4454. ctx, cancel := context.WithTimeout(ctx, requestTimeout)
  4455. output, err := cl.StreamingOutputCall(ctx, &testpb.StreamingOutputCallRequest{})
  4456. if err != nil {
  4457. t.Fatalf("StreamingOutputCall; err = %q", err)
  4458. }
  4459. j := 0
  4460. loop:
  4461. for ; j < recvCount; j++ {
  4462. _, err := output.Recv()
  4463. if err != nil {
  4464. if err == io.EOF {
  4465. break loop
  4466. }
  4467. switch status.Code(err) {
  4468. case codes.DeadlineExceeded:
  4469. break loop
  4470. default:
  4471. t.Fatalf("Recv; err = %q", err)
  4472. }
  4473. }
  4474. }
  4475. cancel()
  4476. <-ctx.Done()
  4477. if j < recvCount {
  4478. t.Errorf("got %d responses to request %d", j, i)
  4479. failures++
  4480. if failures >= maxFailures {
  4481. // Continue past the first failure to see if the connection is
  4482. // entirely broken, or if only a single RPC was affected
  4483. break
  4484. }
  4485. }
  4486. }
  4487. }
  4488. type flowControlLogicalRaceServer struct {
  4489. testpb.TestServiceServer
  4490. itemSize int
  4491. itemCount int
  4492. }
  4493. func (s *flowControlLogicalRaceServer) StreamingOutputCall(req *testpb.StreamingOutputCallRequest, srv testpb.TestService_StreamingOutputCallServer) error {
  4494. for i := 0; i < s.itemCount; i++ {
  4495. err := srv.Send(&testpb.StreamingOutputCallResponse{
  4496. Payload: &testpb.Payload{
  4497. // Sending a large stream of data which the client reject
  4498. // helps to trigger some types of flow control bugs.
  4499. //
  4500. // Reallocating memory here is inefficient, but the stress it
  4501. // puts on the GC leads to more frequent flow control
  4502. // failures. The GC likely causes more variety in the
  4503. // goroutine scheduling orders.
  4504. Body: bytes.Repeat([]byte("a"), s.itemSize),
  4505. },
  4506. })
  4507. if err != nil {
  4508. return err
  4509. }
  4510. }
  4511. return nil
  4512. }
  4513. type lockingWriter struct {
  4514. mu sync.Mutex
  4515. w io.Writer
  4516. }
  4517. func (lw *lockingWriter) Write(p []byte) (n int, err error) {
  4518. lw.mu.Lock()
  4519. defer lw.mu.Unlock()
  4520. return lw.w.Write(p)
  4521. }
  4522. func (lw *lockingWriter) setWriter(w io.Writer) {
  4523. lw.mu.Lock()
  4524. defer lw.mu.Unlock()
  4525. lw.w = w
  4526. }
  4527. var testLogOutput = &lockingWriter{w: os.Stderr}
  4528. // awaitNewConnLogOutput waits for any of grpc.NewConn's goroutines to
  4529. // terminate, if they're still running. It spams logs with this
  4530. // message. We wait for it so our log filter is still
  4531. // active. Otherwise the "defer restore()" at the top of various test
  4532. // functions restores our log filter and then the goroutine spams.
  4533. func awaitNewConnLogOutput() {
  4534. awaitLogOutput(50*time.Millisecond, "grpc: the client connection is closing; please retry")
  4535. }
  4536. func awaitLogOutput(maxWait time.Duration, phrase string) {
  4537. pb := []byte(phrase)
  4538. timer := time.NewTimer(maxWait)
  4539. defer timer.Stop()
  4540. wakeup := make(chan bool, 1)
  4541. for {
  4542. if logOutputHasContents(pb, wakeup) {
  4543. return
  4544. }
  4545. select {
  4546. case <-timer.C:
  4547. // Too slow. Oh well.
  4548. return
  4549. case <-wakeup:
  4550. }
  4551. }
  4552. }
  4553. func logOutputHasContents(v []byte, wakeup chan<- bool) bool {
  4554. testLogOutput.mu.Lock()
  4555. defer testLogOutput.mu.Unlock()
  4556. fw, ok := testLogOutput.w.(*filterWriter)
  4557. if !ok {
  4558. return false
  4559. }
  4560. fw.mu.Lock()
  4561. defer fw.mu.Unlock()
  4562. if bytes.Contains(fw.buf.Bytes(), v) {
  4563. return true
  4564. }
  4565. fw.wakeup = wakeup
  4566. return false
  4567. }
  4568. var verboseLogs = flag.Bool("verbose_logs", false, "show all grpclog output, without filtering")
  4569. func noop() {}
  4570. // declareLogNoise declares that t is expected to emit the following noisy phrases,
  4571. // even on success. Those phrases will be filtered from grpclog output
  4572. // and only be shown if *verbose_logs or t ends up failing.
  4573. // The returned restore function should be called with defer to be run
  4574. // before the test ends.
  4575. func declareLogNoise(t *testing.T, phrases ...string) (restore func()) {
  4576. if *verboseLogs {
  4577. return noop
  4578. }
  4579. fw := &filterWriter{dst: os.Stderr, filter: phrases}
  4580. testLogOutput.setWriter(fw)
  4581. return func() {
  4582. if t.Failed() {
  4583. fw.mu.Lock()
  4584. defer fw.mu.Unlock()
  4585. if fw.buf.Len() > 0 {
  4586. t.Logf("Complete log output:\n%s", fw.buf.Bytes())
  4587. }
  4588. }
  4589. testLogOutput.setWriter(os.Stderr)
  4590. }
  4591. }
  4592. type filterWriter struct {
  4593. dst io.Writer
  4594. filter []string
  4595. mu sync.Mutex
  4596. buf bytes.Buffer
  4597. wakeup chan<- bool // if non-nil, gets true on write
  4598. }
  4599. func (fw *filterWriter) Write(p []byte) (n int, err error) {
  4600. fw.mu.Lock()
  4601. fw.buf.Write(p)
  4602. if fw.wakeup != nil {
  4603. select {
  4604. case fw.wakeup <- true:
  4605. default:
  4606. }
  4607. }
  4608. fw.mu.Unlock()
  4609. ps := string(p)
  4610. for _, f := range fw.filter {
  4611. if strings.Contains(ps, f) {
  4612. return len(p), nil
  4613. }
  4614. }
  4615. return fw.dst.Write(p)
  4616. }
  4617. // stubServer is a server that is easy to customize within individual test
  4618. // cases.
  4619. type stubServer struct {
  4620. // Guarantees we satisfy this interface; panics if unimplemented methods are called.
  4621. testpb.TestServiceServer
  4622. // Customizable implementations of server handlers.
  4623. emptyCall func(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error)
  4624. unaryCall func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error)
  4625. fullDuplexCall func(stream testpb.TestService_FullDuplexCallServer) error
  4626. // A client connected to this service the test may use. Created in Start().
  4627. client testpb.TestServiceClient
  4628. cc *grpc.ClientConn
  4629. addr string // address of listener
  4630. cleanups []func() // Lambdas executed in Stop(); populated by Start().
  4631. r *manual.Resolver
  4632. }
  4633. func (ss *stubServer) EmptyCall(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) {
  4634. return ss.emptyCall(ctx, in)
  4635. }
  4636. func (ss *stubServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
  4637. return ss.unaryCall(ctx, in)
  4638. }
  4639. func (ss *stubServer) FullDuplexCall(stream testpb.TestService_FullDuplexCallServer) error {
  4640. return ss.fullDuplexCall(stream)
  4641. }
  4642. // Start starts the server and creates a client connected to it.
  4643. func (ss *stubServer) Start(sopts []grpc.ServerOption, dopts ...grpc.DialOption) error {
  4644. r, cleanup := manual.GenerateAndRegisterManualResolver()
  4645. ss.r = r
  4646. ss.cleanups = append(ss.cleanups, cleanup)
  4647. lis, err := net.Listen("tcp", "localhost:0")
  4648. if err != nil {
  4649. return fmt.Errorf(`net.Listen("tcp", "localhost:0") = %v`, err)
  4650. }
  4651. ss.addr = lis.Addr().String()
  4652. ss.cleanups = append(ss.cleanups, func() { lis.Close() })
  4653. s := grpc.NewServer(sopts...)
  4654. testpb.RegisterTestServiceServer(s, ss)
  4655. go s.Serve(lis)
  4656. ss.cleanups = append(ss.cleanups, s.Stop)
  4657. target := ss.r.Scheme() + ":///" + ss.addr
  4658. opts := append([]grpc.DialOption{grpc.WithInsecure()}, dopts...)
  4659. cc, err := grpc.Dial(target, opts...)
  4660. if err != nil {
  4661. return fmt.Errorf("grpc.Dial(%q) = %v", target, err)
  4662. }
  4663. ss.cc = cc
  4664. ss.r.UpdateState(resolver.State{Addresses: []resolver.Address{{Addr: ss.addr}}})
  4665. if err := ss.waitForReady(cc); err != nil {
  4666. return err
  4667. }
  4668. ss.cleanups = append(ss.cleanups, func() { cc.Close() })
  4669. ss.client = testpb.NewTestServiceClient(cc)
  4670. return nil
  4671. }
  4672. func (ss *stubServer) newServiceConfig(sc string) {
  4673. ss.r.UpdateState(resolver.State{Addresses: []resolver.Address{{Addr: ss.addr}}, ServiceConfig: sc})
  4674. }
  4675. func (ss *stubServer) waitForReady(cc *grpc.ClientConn) error {
  4676. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  4677. defer cancel()
  4678. for {
  4679. s := cc.GetState()
  4680. if s == connectivity.Ready {
  4681. return nil
  4682. }
  4683. if !cc.WaitForStateChange(ctx, s) {
  4684. // ctx got timeout or canceled.
  4685. return ctx.Err()
  4686. }
  4687. }
  4688. }
  4689. func (ss *stubServer) Stop() {
  4690. for i := len(ss.cleanups) - 1; i >= 0; i-- {
  4691. ss.cleanups[i]()
  4692. }
  4693. }
  4694. func (s) TestGRPCMethod(t *testing.T) {
  4695. var method string
  4696. var ok bool
  4697. ss := &stubServer{
  4698. emptyCall: func(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) {
  4699. method, ok = grpc.Method(ctx)
  4700. return &testpb.Empty{}, nil
  4701. },
  4702. }
  4703. if err := ss.Start(nil); err != nil {
  4704. t.Fatalf("Error starting endpoint server: %v", err)
  4705. }
  4706. defer ss.Stop()
  4707. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  4708. defer cancel()
  4709. if _, err := ss.client.EmptyCall(ctx, &testpb.Empty{}); err != nil {
  4710. t.Fatalf("ss.client.EmptyCall(_, _) = _, %v; want _, nil", err)
  4711. }
  4712. if want := "/grpc.testing.TestService/EmptyCall"; !ok || method != want {
  4713. t.Fatalf("grpc.Method(_) = %q, %v; want %q, true", method, ok, want)
  4714. }
  4715. }
  4716. func (s) TestUnaryProxyDoesNotForwardMetadata(t *testing.T) {
  4717. const mdkey = "somedata"
  4718. // endpoint ensures mdkey is NOT in metadata and returns an error if it is.
  4719. endpoint := &stubServer{
  4720. emptyCall: func(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) {
  4721. if md, ok := metadata.FromIncomingContext(ctx); !ok || md[mdkey] != nil {
  4722. return nil, status.Errorf(codes.Internal, "endpoint: md=%v; want !contains(%q)", md, mdkey)
  4723. }
  4724. return &testpb.Empty{}, nil
  4725. },
  4726. }
  4727. if err := endpoint.Start(nil); err != nil {
  4728. t.Fatalf("Error starting endpoint server: %v", err)
  4729. }
  4730. defer endpoint.Stop()
  4731. // proxy ensures mdkey IS in metadata, then forwards the RPC to endpoint
  4732. // without explicitly copying the metadata.
  4733. proxy := &stubServer{
  4734. emptyCall: func(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) {
  4735. if md, ok := metadata.FromIncomingContext(ctx); !ok || md[mdkey] == nil {
  4736. return nil, status.Errorf(codes.Internal, "proxy: md=%v; want contains(%q)", md, mdkey)
  4737. }
  4738. return endpoint.client.EmptyCall(ctx, in)
  4739. },
  4740. }
  4741. if err := proxy.Start(nil); err != nil {
  4742. t.Fatalf("Error starting proxy server: %v", err)
  4743. }
  4744. defer proxy.Stop()
  4745. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  4746. defer cancel()
  4747. md := metadata.Pairs(mdkey, "val")
  4748. ctx = metadata.NewOutgoingContext(ctx, md)
  4749. // Sanity check that endpoint properly errors when it sees mdkey.
  4750. _, err := endpoint.client.EmptyCall(ctx, &testpb.Empty{})
  4751. if s, ok := status.FromError(err); !ok || s.Code() != codes.Internal {
  4752. t.Fatalf("endpoint.client.EmptyCall(_, _) = _, %v; want _, <status with Code()=Internal>", err)
  4753. }
  4754. if _, err := proxy.client.EmptyCall(ctx, &testpb.Empty{}); err != nil {
  4755. t.Fatal(err.Error())
  4756. }
  4757. }
  4758. func (s) TestStreamingProxyDoesNotForwardMetadata(t *testing.T) {
  4759. const mdkey = "somedata"
  4760. // doFDC performs a FullDuplexCall with client and returns the error from the
  4761. // first stream.Recv call, or nil if that error is io.EOF. Calls t.Fatal if
  4762. // the stream cannot be established.
  4763. doFDC := func(ctx context.Context, client testpb.TestServiceClient) error {
  4764. stream, err := client.FullDuplexCall(ctx)
  4765. if err != nil {
  4766. t.Fatalf("Unwanted error: %v", err)
  4767. }
  4768. if _, err := stream.Recv(); err != io.EOF {
  4769. return err
  4770. }
  4771. return nil
  4772. }
  4773. // endpoint ensures mdkey is NOT in metadata and returns an error if it is.
  4774. endpoint := &stubServer{
  4775. fullDuplexCall: func(stream testpb.TestService_FullDuplexCallServer) error {
  4776. ctx := stream.Context()
  4777. if md, ok := metadata.FromIncomingContext(ctx); !ok || md[mdkey] != nil {
  4778. return status.Errorf(codes.Internal, "endpoint: md=%v; want !contains(%q)", md, mdkey)
  4779. }
  4780. return nil
  4781. },
  4782. }
  4783. if err := endpoint.Start(nil); err != nil {
  4784. t.Fatalf("Error starting endpoint server: %v", err)
  4785. }
  4786. defer endpoint.Stop()
  4787. // proxy ensures mdkey IS in metadata, then forwards the RPC to endpoint
  4788. // without explicitly copying the metadata.
  4789. proxy := &stubServer{
  4790. fullDuplexCall: func(stream testpb.TestService_FullDuplexCallServer) error {
  4791. ctx := stream.Context()
  4792. if md, ok := metadata.FromIncomingContext(ctx); !ok || md[mdkey] == nil {
  4793. return status.Errorf(codes.Internal, "endpoint: md=%v; want !contains(%q)", md, mdkey)
  4794. }
  4795. return doFDC(ctx, endpoint.client)
  4796. },
  4797. }
  4798. if err := proxy.Start(nil); err != nil {
  4799. t.Fatalf("Error starting proxy server: %v", err)
  4800. }
  4801. defer proxy.Stop()
  4802. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  4803. defer cancel()
  4804. md := metadata.Pairs(mdkey, "val")
  4805. ctx = metadata.NewOutgoingContext(ctx, md)
  4806. // Sanity check that endpoint properly errors when it sees mdkey in ctx.
  4807. err := doFDC(ctx, endpoint.client)
  4808. if s, ok := status.FromError(err); !ok || s.Code() != codes.Internal {
  4809. t.Fatalf("stream.Recv() = _, %v; want _, <status with Code()=Internal>", err)
  4810. }
  4811. if err := doFDC(ctx, proxy.client); err != nil {
  4812. t.Fatalf("doFDC(_, proxy.client) = %v; want nil", err)
  4813. }
  4814. }
  4815. func (s) TestStatsTagsAndTrace(t *testing.T) {
  4816. // Data added to context by client (typically in a stats handler).
  4817. tags := []byte{1, 5, 2, 4, 3}
  4818. trace := []byte{5, 2, 1, 3, 4}
  4819. // endpoint ensures Tags() and Trace() in context match those that were added
  4820. // by the client and returns an error if not.
  4821. endpoint := &stubServer{
  4822. emptyCall: func(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) {
  4823. md, _ := metadata.FromIncomingContext(ctx)
  4824. if tg := stats.Tags(ctx); !reflect.DeepEqual(tg, tags) {
  4825. return nil, status.Errorf(codes.Internal, "stats.Tags(%v)=%v; want %v", ctx, tg, tags)
  4826. }
  4827. if !reflect.DeepEqual(md["grpc-tags-bin"], []string{string(tags)}) {
  4828. return nil, status.Errorf(codes.Internal, "md['grpc-tags-bin']=%v; want %v", md["grpc-tags-bin"], tags)
  4829. }
  4830. if tr := stats.Trace(ctx); !reflect.DeepEqual(tr, trace) {
  4831. return nil, status.Errorf(codes.Internal, "stats.Trace(%v)=%v; want %v", ctx, tr, trace)
  4832. }
  4833. if !reflect.DeepEqual(md["grpc-trace-bin"], []string{string(trace)}) {
  4834. return nil, status.Errorf(codes.Internal, "md['grpc-trace-bin']=%v; want %v", md["grpc-trace-bin"], trace)
  4835. }
  4836. return &testpb.Empty{}, nil
  4837. },
  4838. }
  4839. if err := endpoint.Start(nil); err != nil {
  4840. t.Fatalf("Error starting endpoint server: %v", err)
  4841. }
  4842. defer endpoint.Stop()
  4843. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  4844. defer cancel()
  4845. testCases := []struct {
  4846. ctx context.Context
  4847. want codes.Code
  4848. }{
  4849. {ctx: ctx, want: codes.Internal},
  4850. {ctx: stats.SetTags(ctx, tags), want: codes.Internal},
  4851. {ctx: stats.SetTrace(ctx, trace), want: codes.Internal},
  4852. {ctx: stats.SetTags(stats.SetTrace(ctx, tags), tags), want: codes.Internal},
  4853. {ctx: stats.SetTags(stats.SetTrace(ctx, trace), tags), want: codes.OK},
  4854. }
  4855. for _, tc := range testCases {
  4856. _, err := endpoint.client.EmptyCall(tc.ctx, &testpb.Empty{})
  4857. if tc.want == codes.OK && err != nil {
  4858. t.Fatalf("endpoint.client.EmptyCall(%v, _) = _, %v; want _, nil", tc.ctx, err)
  4859. }
  4860. if s, ok := status.FromError(err); !ok || s.Code() != tc.want {
  4861. t.Fatalf("endpoint.client.EmptyCall(%v, _) = _, %v; want _, <status with Code()=%v>", tc.ctx, err, tc.want)
  4862. }
  4863. }
  4864. }
  4865. func (s) TestTapTimeout(t *testing.T) {
  4866. sopts := []grpc.ServerOption{
  4867. grpc.InTapHandle(func(ctx context.Context, _ *tap.Info) (context.Context, error) {
  4868. c, cancel := context.WithCancel(ctx)
  4869. // Call cancel instead of setting a deadline so we can detect which error
  4870. // occurred -- this cancellation (desired) or the client's deadline
  4871. // expired (indicating this cancellation did not affect the RPC).
  4872. time.AfterFunc(10*time.Millisecond, cancel)
  4873. return c, nil
  4874. }),
  4875. }
  4876. ss := &stubServer{
  4877. emptyCall: func(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) {
  4878. <-ctx.Done()
  4879. return nil, status.Errorf(codes.Canceled, ctx.Err().Error())
  4880. },
  4881. }
  4882. if err := ss.Start(sopts); err != nil {
  4883. t.Fatalf("Error starting endpoint server: %v", err)
  4884. }
  4885. defer ss.Stop()
  4886. // This was known to be flaky; test several times.
  4887. for i := 0; i < 10; i++ {
  4888. // Set our own deadline in case the server hangs.
  4889. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  4890. res, err := ss.client.EmptyCall(ctx, &testpb.Empty{})
  4891. cancel()
  4892. if s, ok := status.FromError(err); !ok || s.Code() != codes.Canceled {
  4893. t.Fatalf("ss.client.EmptyCall(context.Background(), _) = %v, %v; want nil, <status with Code()=Canceled>", res, err)
  4894. }
  4895. }
  4896. }
  4897. func (s) TestClientWriteFailsAfterServerClosesStream(t *testing.T) {
  4898. ss := &stubServer{
  4899. fullDuplexCall: func(stream testpb.TestService_FullDuplexCallServer) error {
  4900. return status.Errorf(codes.Internal, "")
  4901. },
  4902. }
  4903. sopts := []grpc.ServerOption{}
  4904. if err := ss.Start(sopts); err != nil {
  4905. t.Fatalf("Error starting endpoint server: %v", err)
  4906. }
  4907. defer ss.Stop()
  4908. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  4909. defer cancel()
  4910. stream, err := ss.client.FullDuplexCall(ctx)
  4911. if err != nil {
  4912. t.Fatalf("Error while creating stream: %v", err)
  4913. }
  4914. for {
  4915. if err := stream.Send(&testpb.StreamingOutputCallRequest{}); err == nil {
  4916. time.Sleep(5 * time.Millisecond)
  4917. } else if err == io.EOF {
  4918. break // Success.
  4919. } else {
  4920. t.Fatalf("stream.Send(_) = %v, want io.EOF", err)
  4921. }
  4922. }
  4923. }
  4924. type windowSizeConfig struct {
  4925. serverStream int32
  4926. serverConn int32
  4927. clientStream int32
  4928. clientConn int32
  4929. }
  4930. func max(a, b int32) int32 {
  4931. if a > b {
  4932. return a
  4933. }
  4934. return b
  4935. }
  4936. func (s) TestConfigurableWindowSizeWithLargeWindow(t *testing.T) {
  4937. wc := windowSizeConfig{
  4938. serverStream: 8 * 1024 * 1024,
  4939. serverConn: 12 * 1024 * 1024,
  4940. clientStream: 6 * 1024 * 1024,
  4941. clientConn: 8 * 1024 * 1024,
  4942. }
  4943. for _, e := range listTestEnv() {
  4944. testConfigurableWindowSize(t, e, wc)
  4945. }
  4946. }
  4947. func (s) TestConfigurableWindowSizeWithSmallWindow(t *testing.T) {
  4948. wc := windowSizeConfig{
  4949. serverStream: 1,
  4950. serverConn: 1,
  4951. clientStream: 1,
  4952. clientConn: 1,
  4953. }
  4954. for _, e := range listTestEnv() {
  4955. testConfigurableWindowSize(t, e, wc)
  4956. }
  4957. }
  4958. func testConfigurableWindowSize(t *testing.T, e env, wc windowSizeConfig) {
  4959. te := newTest(t, e)
  4960. te.serverInitialWindowSize = wc.serverStream
  4961. te.serverInitialConnWindowSize = wc.serverConn
  4962. te.clientInitialWindowSize = wc.clientStream
  4963. te.clientInitialConnWindowSize = wc.clientConn
  4964. te.startServer(&testServer{security: e.security})
  4965. defer te.tearDown()
  4966. cc := te.clientConn()
  4967. tc := testpb.NewTestServiceClient(cc)
  4968. stream, err := tc.FullDuplexCall(context.Background())
  4969. if err != nil {
  4970. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  4971. }
  4972. numOfIter := 11
  4973. // Set message size to exhaust largest of window sizes.
  4974. messageSize := max(max(wc.serverStream, wc.serverConn), max(wc.clientStream, wc.clientConn)) / int32(numOfIter-1)
  4975. messageSize = max(messageSize, 64*1024)
  4976. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, messageSize)
  4977. if err != nil {
  4978. t.Fatal(err)
  4979. }
  4980. respParams := []*testpb.ResponseParameters{
  4981. {
  4982. Size: messageSize,
  4983. },
  4984. }
  4985. req := &testpb.StreamingOutputCallRequest{
  4986. ResponseType: testpb.PayloadType_COMPRESSABLE,
  4987. ResponseParameters: respParams,
  4988. Payload: payload,
  4989. }
  4990. for i := 0; i < numOfIter; i++ {
  4991. if err := stream.Send(req); err != nil {
  4992. t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, req, err)
  4993. }
  4994. if _, err := stream.Recv(); err != nil {
  4995. t.Fatalf("%v.Recv() = _, %v, want _, <nil>", stream, err)
  4996. }
  4997. }
  4998. if err := stream.CloseSend(); err != nil {
  4999. t.Fatalf("%v.CloseSend() = %v, want <nil>", stream, err)
  5000. }
  5001. }
  5002. var (
  5003. // test authdata
  5004. authdata = map[string]string{
  5005. "test-key": "test-value",
  5006. "test-key2-bin": string([]byte{1, 2, 3}),
  5007. }
  5008. )
  5009. type testPerRPCCredentials struct{}
  5010. func (cr testPerRPCCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
  5011. return authdata, nil
  5012. }
  5013. func (cr testPerRPCCredentials) RequireTransportSecurity() bool {
  5014. return false
  5015. }
  5016. func authHandle(ctx context.Context, info *tap.Info) (context.Context, error) {
  5017. md, ok := metadata.FromIncomingContext(ctx)
  5018. if !ok {
  5019. return ctx, fmt.Errorf("didn't find metadata in context")
  5020. }
  5021. for k, vwant := range authdata {
  5022. vgot, ok := md[k]
  5023. if !ok {
  5024. return ctx, fmt.Errorf("didn't find authdata key %v in context", k)
  5025. }
  5026. if vgot[0] != vwant {
  5027. return ctx, fmt.Errorf("for key %v, got value %v, want %v", k, vgot, vwant)
  5028. }
  5029. }
  5030. return ctx, nil
  5031. }
  5032. func (s) TestPerRPCCredentialsViaDialOptions(t *testing.T) {
  5033. for _, e := range listTestEnv() {
  5034. testPerRPCCredentialsViaDialOptions(t, e)
  5035. }
  5036. }
  5037. func testPerRPCCredentialsViaDialOptions(t *testing.T, e env) {
  5038. te := newTest(t, e)
  5039. te.tapHandle = authHandle
  5040. te.perRPCCreds = testPerRPCCredentials{}
  5041. te.startServer(&testServer{security: e.security})
  5042. defer te.tearDown()
  5043. cc := te.clientConn()
  5044. tc := testpb.NewTestServiceClient(cc)
  5045. if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); err != nil {
  5046. t.Fatalf("Test failed. Reason: %v", err)
  5047. }
  5048. }
  5049. func (s) TestPerRPCCredentialsViaCallOptions(t *testing.T) {
  5050. for _, e := range listTestEnv() {
  5051. testPerRPCCredentialsViaCallOptions(t, e)
  5052. }
  5053. }
  5054. func testPerRPCCredentialsViaCallOptions(t *testing.T, e env) {
  5055. te := newTest(t, e)
  5056. te.tapHandle = authHandle
  5057. te.startServer(&testServer{security: e.security})
  5058. defer te.tearDown()
  5059. cc := te.clientConn()
  5060. tc := testpb.NewTestServiceClient(cc)
  5061. if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.PerRPCCredentials(testPerRPCCredentials{})); err != nil {
  5062. t.Fatalf("Test failed. Reason: %v", err)
  5063. }
  5064. }
  5065. func (s) TestPerRPCCredentialsViaDialOptionsAndCallOptions(t *testing.T) {
  5066. for _, e := range listTestEnv() {
  5067. testPerRPCCredentialsViaDialOptionsAndCallOptions(t, e)
  5068. }
  5069. }
  5070. func testPerRPCCredentialsViaDialOptionsAndCallOptions(t *testing.T, e env) {
  5071. te := newTest(t, e)
  5072. te.perRPCCreds = testPerRPCCredentials{}
  5073. // When credentials are provided via both dial options and call options,
  5074. // we apply both sets.
  5075. te.tapHandle = func(ctx context.Context, _ *tap.Info) (context.Context, error) {
  5076. md, ok := metadata.FromIncomingContext(ctx)
  5077. if !ok {
  5078. return ctx, fmt.Errorf("couldn't find metadata in context")
  5079. }
  5080. for k, vwant := range authdata {
  5081. vgot, ok := md[k]
  5082. if !ok {
  5083. return ctx, fmt.Errorf("couldn't find metadata for key %v", k)
  5084. }
  5085. if len(vgot) != 2 {
  5086. return ctx, fmt.Errorf("len of value for key %v was %v, want 2", k, len(vgot))
  5087. }
  5088. if vgot[0] != vwant || vgot[1] != vwant {
  5089. return ctx, fmt.Errorf("value for %v was %v, want [%v, %v]", k, vgot, vwant, vwant)
  5090. }
  5091. }
  5092. return ctx, nil
  5093. }
  5094. te.startServer(&testServer{security: e.security})
  5095. defer te.tearDown()
  5096. cc := te.clientConn()
  5097. tc := testpb.NewTestServiceClient(cc)
  5098. if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.PerRPCCredentials(testPerRPCCredentials{})); err != nil {
  5099. t.Fatalf("Test failed. Reason: %v", err)
  5100. }
  5101. }
  5102. func (s) TestWaitForReadyConnection(t *testing.T) {
  5103. for _, e := range listTestEnv() {
  5104. testWaitForReadyConnection(t, e)
  5105. }
  5106. }
  5107. func testWaitForReadyConnection(t *testing.T, e env) {
  5108. te := newTest(t, e)
  5109. te.userAgent = testAppUA
  5110. te.startServer(&testServer{security: e.security})
  5111. defer te.tearDown()
  5112. cc := te.clientConn() // Non-blocking dial.
  5113. tc := testpb.NewTestServiceClient(cc)
  5114. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  5115. defer cancel()
  5116. state := cc.GetState()
  5117. // Wait for connection to be Ready.
  5118. for ; state != connectivity.Ready && cc.WaitForStateChange(ctx, state); state = cc.GetState() {
  5119. }
  5120. if state != connectivity.Ready {
  5121. t.Fatalf("Want connection state to be Ready, got %v", state)
  5122. }
  5123. ctx, cancel = context.WithTimeout(context.Background(), time.Second)
  5124. defer cancel()
  5125. // Make a fail-fast RPC.
  5126. if _, err := tc.EmptyCall(ctx, &testpb.Empty{}); err != nil {
  5127. t.Fatalf("TestService/EmptyCall(_,_) = _, %v, want _, nil", err)
  5128. }
  5129. }
  5130. type errCodec struct {
  5131. noError bool
  5132. }
  5133. func (c *errCodec) Marshal(v interface{}) ([]byte, error) {
  5134. if c.noError {
  5135. return []byte{}, nil
  5136. }
  5137. return nil, fmt.Errorf("3987^12 + 4365^12 = 4472^12")
  5138. }
  5139. func (c *errCodec) Unmarshal(data []byte, v interface{}) error {
  5140. return nil
  5141. }
  5142. func (c *errCodec) Name() string {
  5143. return "Fermat's near-miss."
  5144. }
  5145. func (s) TestEncodeDoesntPanic(t *testing.T) {
  5146. for _, e := range listTestEnv() {
  5147. testEncodeDoesntPanic(t, e)
  5148. }
  5149. }
  5150. func testEncodeDoesntPanic(t *testing.T, e env) {
  5151. te := newTest(t, e)
  5152. erc := &errCodec{}
  5153. te.customCodec = erc
  5154. te.startServer(&testServer{security: e.security})
  5155. defer te.tearDown()
  5156. te.customCodec = nil
  5157. tc := testpb.NewTestServiceClient(te.clientConn())
  5158. // Failure case, should not panic.
  5159. tc.EmptyCall(context.Background(), &testpb.Empty{})
  5160. erc.noError = true
  5161. // Passing case.
  5162. if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); err != nil {
  5163. t.Fatalf("EmptyCall(_, _) = _, %v, want _, <nil>", err)
  5164. }
  5165. }
  5166. func (s) TestSvrWriteStatusEarlyWrite(t *testing.T) {
  5167. for _, e := range listTestEnv() {
  5168. testSvrWriteStatusEarlyWrite(t, e)
  5169. }
  5170. }
  5171. func testSvrWriteStatusEarlyWrite(t *testing.T, e env) {
  5172. te := newTest(t, e)
  5173. const smallSize = 1024
  5174. const largeSize = 2048
  5175. const extraLargeSize = 4096
  5176. te.maxServerReceiveMsgSize = newInt(largeSize)
  5177. te.maxServerSendMsgSize = newInt(largeSize)
  5178. smallPayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, smallSize)
  5179. if err != nil {
  5180. t.Fatal(err)
  5181. }
  5182. extraLargePayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, extraLargeSize)
  5183. if err != nil {
  5184. t.Fatal(err)
  5185. }
  5186. te.startServer(&testServer{security: e.security})
  5187. defer te.tearDown()
  5188. tc := testpb.NewTestServiceClient(te.clientConn())
  5189. respParam := []*testpb.ResponseParameters{
  5190. {
  5191. Size: int32(smallSize),
  5192. },
  5193. }
  5194. sreq := &testpb.StreamingOutputCallRequest{
  5195. ResponseType: testpb.PayloadType_COMPRESSABLE,
  5196. ResponseParameters: respParam,
  5197. Payload: extraLargePayload,
  5198. }
  5199. // Test recv case: server receives a message larger than maxServerReceiveMsgSize.
  5200. stream, err := tc.FullDuplexCall(te.ctx)
  5201. if err != nil {
  5202. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  5203. }
  5204. if err = stream.Send(sreq); err != nil {
  5205. t.Fatalf("%v.Send() = _, %v, want <nil>", stream, err)
  5206. }
  5207. if _, err = stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted {
  5208. t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted)
  5209. }
  5210. // Test send case: server sends a message larger than maxServerSendMsgSize.
  5211. sreq.Payload = smallPayload
  5212. respParam[0].Size = int32(extraLargeSize)
  5213. stream, err = tc.FullDuplexCall(te.ctx)
  5214. if err != nil {
  5215. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  5216. }
  5217. if err = stream.Send(sreq); err != nil {
  5218. t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err)
  5219. }
  5220. if _, err = stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted {
  5221. t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted)
  5222. }
  5223. }
  5224. // The following functions with function name ending with TD indicates that they
  5225. // should be deleted after old service config API is deprecated and deleted.
  5226. func testServiceConfigSetupTD(t *testing.T, e env) (*test, chan grpc.ServiceConfig) {
  5227. te := newTest(t, e)
  5228. // We write before read.
  5229. ch := make(chan grpc.ServiceConfig, 1)
  5230. te.sc = ch
  5231. te.userAgent = testAppUA
  5232. te.declareLogNoise(
  5233. "transport: http2Client.notifyError got notified that the client transport was broken EOF",
  5234. "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing",
  5235. "grpc: addrConn.resetTransport failed to create client transport: connection error",
  5236. "Failed to dial : context canceled; please retry.",
  5237. )
  5238. return te, ch
  5239. }
  5240. func (s) TestServiceConfigGetMethodConfigTD(t *testing.T) {
  5241. for _, e := range listTestEnv() {
  5242. testGetMethodConfigTD(t, e)
  5243. }
  5244. }
  5245. func testGetMethodConfigTD(t *testing.T, e env) {
  5246. te, ch := testServiceConfigSetupTD(t, e)
  5247. defer te.tearDown()
  5248. mc1 := grpc.MethodConfig{
  5249. WaitForReady: newBool(true),
  5250. Timeout: newDuration(time.Millisecond),
  5251. }
  5252. mc2 := grpc.MethodConfig{WaitForReady: newBool(false)}
  5253. m := make(map[string]grpc.MethodConfig)
  5254. m["/grpc.testing.TestService/EmptyCall"] = mc1
  5255. m["/grpc.testing.TestService/"] = mc2
  5256. sc := grpc.ServiceConfig{
  5257. Methods: m,
  5258. }
  5259. ch <- sc
  5260. cc := te.clientConn()
  5261. tc := testpb.NewTestServiceClient(cc)
  5262. // The following RPCs are expected to become non-fail-fast ones with 1ms deadline.
  5263. if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); status.Code(err) != codes.DeadlineExceeded {
  5264. t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded)
  5265. }
  5266. m = make(map[string]grpc.MethodConfig)
  5267. m["/grpc.testing.TestService/UnaryCall"] = mc1
  5268. m["/grpc.testing.TestService/"] = mc2
  5269. sc = grpc.ServiceConfig{
  5270. Methods: m,
  5271. }
  5272. ch <- sc
  5273. // Wait for the new service config to propagate.
  5274. for {
  5275. if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); status.Code(err) == codes.DeadlineExceeded {
  5276. continue
  5277. }
  5278. break
  5279. }
  5280. // The following RPCs are expected to become fail-fast.
  5281. if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); status.Code(err) != codes.Unavailable {
  5282. t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.Unavailable)
  5283. }
  5284. }
  5285. func (s) TestServiceConfigWaitForReadyTD(t *testing.T) {
  5286. for _, e := range listTestEnv() {
  5287. testServiceConfigWaitForReadyTD(t, e)
  5288. }
  5289. }
  5290. func testServiceConfigWaitForReadyTD(t *testing.T, e env) {
  5291. te, ch := testServiceConfigSetupTD(t, e)
  5292. defer te.tearDown()
  5293. // Case1: Client API set failfast to be false, and service config set wait_for_ready to be false, Client API should win, and the rpc will wait until deadline exceeds.
  5294. mc := grpc.MethodConfig{
  5295. WaitForReady: newBool(false),
  5296. Timeout: newDuration(time.Millisecond),
  5297. }
  5298. m := make(map[string]grpc.MethodConfig)
  5299. m["/grpc.testing.TestService/EmptyCall"] = mc
  5300. m["/grpc.testing.TestService/FullDuplexCall"] = mc
  5301. sc := grpc.ServiceConfig{
  5302. Methods: m,
  5303. }
  5304. ch <- sc
  5305. cc := te.clientConn()
  5306. tc := testpb.NewTestServiceClient(cc)
  5307. // The following RPCs are expected to become non-fail-fast ones with 1ms deadline.
  5308. if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.WaitForReady(true)); status.Code(err) != codes.DeadlineExceeded {
  5309. t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded)
  5310. }
  5311. if _, err := tc.FullDuplexCall(context.Background(), grpc.WaitForReady(true)); status.Code(err) != codes.DeadlineExceeded {
  5312. t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want %s", err, codes.DeadlineExceeded)
  5313. }
  5314. // Generate a service config update.
  5315. // Case2: Client API does not set failfast, and service config set wait_for_ready to be true, and the rpc will wait until deadline exceeds.
  5316. mc.WaitForReady = newBool(true)
  5317. m = make(map[string]grpc.MethodConfig)
  5318. m["/grpc.testing.TestService/EmptyCall"] = mc
  5319. m["/grpc.testing.TestService/FullDuplexCall"] = mc
  5320. sc = grpc.ServiceConfig{
  5321. Methods: m,
  5322. }
  5323. ch <- sc
  5324. // Wait for the new service config to take effect.
  5325. mc = cc.GetMethodConfig("/grpc.testing.TestService/EmptyCall")
  5326. for {
  5327. if !*mc.WaitForReady {
  5328. time.Sleep(100 * time.Millisecond)
  5329. mc = cc.GetMethodConfig("/grpc.testing.TestService/EmptyCall")
  5330. continue
  5331. }
  5332. break
  5333. }
  5334. // The following RPCs are expected to become non-fail-fast ones with 1ms deadline.
  5335. if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); status.Code(err) != codes.DeadlineExceeded {
  5336. t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded)
  5337. }
  5338. if _, err := tc.FullDuplexCall(context.Background()); status.Code(err) != codes.DeadlineExceeded {
  5339. t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want %s", err, codes.DeadlineExceeded)
  5340. }
  5341. }
  5342. func (s) TestServiceConfigTimeoutTD(t *testing.T) {
  5343. for _, e := range listTestEnv() {
  5344. testServiceConfigTimeoutTD(t, e)
  5345. }
  5346. }
  5347. func testServiceConfigTimeoutTD(t *testing.T, e env) {
  5348. te, ch := testServiceConfigSetupTD(t, e)
  5349. defer te.tearDown()
  5350. // Case1: Client API sets timeout to be 1ns and ServiceConfig sets timeout to be 1hr. Timeout should be 1ns (min of 1ns and 1hr) and the rpc will wait until deadline exceeds.
  5351. mc := grpc.MethodConfig{
  5352. Timeout: newDuration(time.Hour),
  5353. }
  5354. m := make(map[string]grpc.MethodConfig)
  5355. m["/grpc.testing.TestService/EmptyCall"] = mc
  5356. m["/grpc.testing.TestService/FullDuplexCall"] = mc
  5357. sc := grpc.ServiceConfig{
  5358. Methods: m,
  5359. }
  5360. ch <- sc
  5361. cc := te.clientConn()
  5362. tc := testpb.NewTestServiceClient(cc)
  5363. // The following RPCs are expected to become non-fail-fast ones with 1ns deadline.
  5364. ctx, cancel := context.WithTimeout(context.Background(), time.Nanosecond)
  5365. if _, err := tc.EmptyCall(ctx, &testpb.Empty{}, grpc.WaitForReady(true)); status.Code(err) != codes.DeadlineExceeded {
  5366. t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded)
  5367. }
  5368. cancel()
  5369. ctx, cancel = context.WithTimeout(context.Background(), time.Nanosecond)
  5370. if _, err := tc.FullDuplexCall(ctx, grpc.WaitForReady(true)); status.Code(err) != codes.DeadlineExceeded {
  5371. t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want %s", err, codes.DeadlineExceeded)
  5372. }
  5373. cancel()
  5374. // Generate a service config update.
  5375. // Case2: Client API sets timeout to be 1hr and ServiceConfig sets timeout to be 1ns. Timeout should be 1ns (min of 1ns and 1hr) and the rpc will wait until deadline exceeds.
  5376. mc.Timeout = newDuration(time.Nanosecond)
  5377. m = make(map[string]grpc.MethodConfig)
  5378. m["/grpc.testing.TestService/EmptyCall"] = mc
  5379. m["/grpc.testing.TestService/FullDuplexCall"] = mc
  5380. sc = grpc.ServiceConfig{
  5381. Methods: m,
  5382. }
  5383. ch <- sc
  5384. // Wait for the new service config to take effect.
  5385. mc = cc.GetMethodConfig("/grpc.testing.TestService/FullDuplexCall")
  5386. for {
  5387. if *mc.Timeout != time.Nanosecond {
  5388. time.Sleep(100 * time.Millisecond)
  5389. mc = cc.GetMethodConfig("/grpc.testing.TestService/FullDuplexCall")
  5390. continue
  5391. }
  5392. break
  5393. }
  5394. ctx, cancel = context.WithTimeout(context.Background(), time.Hour)
  5395. if _, err := tc.EmptyCall(ctx, &testpb.Empty{}, grpc.WaitForReady(true)); status.Code(err) != codes.DeadlineExceeded {
  5396. t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded)
  5397. }
  5398. cancel()
  5399. ctx, cancel = context.WithTimeout(context.Background(), time.Hour)
  5400. if _, err := tc.FullDuplexCall(ctx, grpc.WaitForReady(true)); status.Code(err) != codes.DeadlineExceeded {
  5401. t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want %s", err, codes.DeadlineExceeded)
  5402. }
  5403. cancel()
  5404. }
  5405. func (s) TestServiceConfigMaxMsgSizeTD(t *testing.T) {
  5406. for _, e := range listTestEnv() {
  5407. testServiceConfigMaxMsgSizeTD(t, e)
  5408. }
  5409. }
  5410. func testServiceConfigMaxMsgSizeTD(t *testing.T, e env) {
  5411. // Setting up values and objects shared across all test cases.
  5412. const smallSize = 1
  5413. const largeSize = 1024
  5414. const extraLargeSize = 2048
  5415. smallPayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, smallSize)
  5416. if err != nil {
  5417. t.Fatal(err)
  5418. }
  5419. largePayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, largeSize)
  5420. if err != nil {
  5421. t.Fatal(err)
  5422. }
  5423. extraLargePayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, extraLargeSize)
  5424. if err != nil {
  5425. t.Fatal(err)
  5426. }
  5427. mc := grpc.MethodConfig{
  5428. MaxReqSize: newInt(extraLargeSize),
  5429. MaxRespSize: newInt(extraLargeSize),
  5430. }
  5431. m := make(map[string]grpc.MethodConfig)
  5432. m["/grpc.testing.TestService/UnaryCall"] = mc
  5433. m["/grpc.testing.TestService/FullDuplexCall"] = mc
  5434. sc := grpc.ServiceConfig{
  5435. Methods: m,
  5436. }
  5437. // Case1: sc set maxReqSize to 2048 (send), maxRespSize to 2048 (recv).
  5438. te1, ch1 := testServiceConfigSetupTD(t, e)
  5439. te1.startServer(&testServer{security: e.security})
  5440. defer te1.tearDown()
  5441. ch1 <- sc
  5442. tc := testpb.NewTestServiceClient(te1.clientConn())
  5443. req := &testpb.SimpleRequest{
  5444. ResponseType: testpb.PayloadType_COMPRESSABLE,
  5445. ResponseSize: int32(extraLargeSize),
  5446. Payload: smallPayload,
  5447. }
  5448. // Test for unary RPC recv.
  5449. if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted {
  5450. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted)
  5451. }
  5452. // Test for unary RPC send.
  5453. req.Payload = extraLargePayload
  5454. req.ResponseSize = int32(smallSize)
  5455. if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted {
  5456. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted)
  5457. }
  5458. // Test for streaming RPC recv.
  5459. respParam := []*testpb.ResponseParameters{
  5460. {
  5461. Size: int32(extraLargeSize),
  5462. },
  5463. }
  5464. sreq := &testpb.StreamingOutputCallRequest{
  5465. ResponseType: testpb.PayloadType_COMPRESSABLE,
  5466. ResponseParameters: respParam,
  5467. Payload: smallPayload,
  5468. }
  5469. stream, err := tc.FullDuplexCall(te1.ctx)
  5470. if err != nil {
  5471. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  5472. }
  5473. if err := stream.Send(sreq); err != nil {
  5474. t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err)
  5475. }
  5476. if _, err := stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted {
  5477. t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted)
  5478. }
  5479. // Test for streaming RPC send.
  5480. respParam[0].Size = int32(smallSize)
  5481. sreq.Payload = extraLargePayload
  5482. stream, err = tc.FullDuplexCall(te1.ctx)
  5483. if err != nil {
  5484. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  5485. }
  5486. if err := stream.Send(sreq); err == nil || status.Code(err) != codes.ResourceExhausted {
  5487. t.Fatalf("%v.Send(%v) = %v, want _, error code: %s", stream, sreq, err, codes.ResourceExhausted)
  5488. }
  5489. // Case2: Client API set maxReqSize to 1024 (send), maxRespSize to 1024 (recv). Sc sets maxReqSize to 2048 (send), maxRespSize to 2048 (recv).
  5490. te2, ch2 := testServiceConfigSetupTD(t, e)
  5491. te2.maxClientReceiveMsgSize = newInt(1024)
  5492. te2.maxClientSendMsgSize = newInt(1024)
  5493. te2.startServer(&testServer{security: e.security})
  5494. defer te2.tearDown()
  5495. ch2 <- sc
  5496. tc = testpb.NewTestServiceClient(te2.clientConn())
  5497. // Test for unary RPC recv.
  5498. req.Payload = smallPayload
  5499. req.ResponseSize = int32(largeSize)
  5500. if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted {
  5501. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted)
  5502. }
  5503. // Test for unary RPC send.
  5504. req.Payload = largePayload
  5505. req.ResponseSize = int32(smallSize)
  5506. if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted {
  5507. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted)
  5508. }
  5509. // Test for streaming RPC recv.
  5510. stream, err = tc.FullDuplexCall(te2.ctx)
  5511. respParam[0].Size = int32(largeSize)
  5512. sreq.Payload = smallPayload
  5513. if err != nil {
  5514. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  5515. }
  5516. if err := stream.Send(sreq); err != nil {
  5517. t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err)
  5518. }
  5519. if _, err := stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted {
  5520. t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted)
  5521. }
  5522. // Test for streaming RPC send.
  5523. respParam[0].Size = int32(smallSize)
  5524. sreq.Payload = largePayload
  5525. stream, err = tc.FullDuplexCall(te2.ctx)
  5526. if err != nil {
  5527. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  5528. }
  5529. if err := stream.Send(sreq); err == nil || status.Code(err) != codes.ResourceExhausted {
  5530. t.Fatalf("%v.Send(%v) = %v, want _, error code: %s", stream, sreq, err, codes.ResourceExhausted)
  5531. }
  5532. // Case3: Client API set maxReqSize to 4096 (send), maxRespSize to 4096 (recv). Sc sets maxReqSize to 2048 (send), maxRespSize to 2048 (recv).
  5533. te3, ch3 := testServiceConfigSetupTD(t, e)
  5534. te3.maxClientReceiveMsgSize = newInt(4096)
  5535. te3.maxClientSendMsgSize = newInt(4096)
  5536. te3.startServer(&testServer{security: e.security})
  5537. defer te3.tearDown()
  5538. ch3 <- sc
  5539. tc = testpb.NewTestServiceClient(te3.clientConn())
  5540. // Test for unary RPC recv.
  5541. req.Payload = smallPayload
  5542. req.ResponseSize = int32(largeSize)
  5543. if _, err := tc.UnaryCall(context.Background(), req); err != nil {
  5544. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want <nil>", err)
  5545. }
  5546. req.ResponseSize = int32(extraLargeSize)
  5547. if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted {
  5548. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted)
  5549. }
  5550. // Test for unary RPC send.
  5551. req.Payload = largePayload
  5552. req.ResponseSize = int32(smallSize)
  5553. if _, err := tc.UnaryCall(context.Background(), req); err != nil {
  5554. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want <nil>", err)
  5555. }
  5556. req.Payload = extraLargePayload
  5557. if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted {
  5558. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted)
  5559. }
  5560. // Test for streaming RPC recv.
  5561. stream, err = tc.FullDuplexCall(te3.ctx)
  5562. if err != nil {
  5563. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  5564. }
  5565. respParam[0].Size = int32(largeSize)
  5566. sreq.Payload = smallPayload
  5567. if err := stream.Send(sreq); err != nil {
  5568. t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err)
  5569. }
  5570. if _, err := stream.Recv(); err != nil {
  5571. t.Fatalf("%v.Recv() = _, %v, want <nil>", stream, err)
  5572. }
  5573. respParam[0].Size = int32(extraLargeSize)
  5574. if err := stream.Send(sreq); err != nil {
  5575. t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err)
  5576. }
  5577. if _, err := stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted {
  5578. t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted)
  5579. }
  5580. // Test for streaming RPC send.
  5581. respParam[0].Size = int32(smallSize)
  5582. sreq.Payload = largePayload
  5583. stream, err = tc.FullDuplexCall(te3.ctx)
  5584. if err != nil {
  5585. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  5586. }
  5587. if err := stream.Send(sreq); err != nil {
  5588. t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err)
  5589. }
  5590. sreq.Payload = extraLargePayload
  5591. if err := stream.Send(sreq); err == nil || status.Code(err) != codes.ResourceExhausted {
  5592. t.Fatalf("%v.Send(%v) = %v, want _, error code: %s", stream, sreq, err, codes.ResourceExhausted)
  5593. }
  5594. }
  5595. func (s) TestMethodFromServerStream(t *testing.T) {
  5596. const testMethod = "/package.service/method"
  5597. e := tcpClearRREnv
  5598. te := newTest(t, e)
  5599. var method string
  5600. var ok bool
  5601. te.unknownHandler = func(srv interface{}, stream grpc.ServerStream) error {
  5602. method, ok = grpc.MethodFromServerStream(stream)
  5603. return nil
  5604. }
  5605. te.startServer(nil)
  5606. defer te.tearDown()
  5607. _ = te.clientConn().Invoke(context.Background(), testMethod, nil, nil)
  5608. if !ok || method != testMethod {
  5609. t.Fatalf("Invoke with method %q, got %q, %v, want %q, true", testMethod, method, ok, testMethod)
  5610. }
  5611. }
  5612. func (s) TestInterceptorCanAccessCallOptions(t *testing.T) {
  5613. e := tcpClearRREnv
  5614. te := newTest(t, e)
  5615. te.startServer(&testServer{security: e.security})
  5616. defer te.tearDown()
  5617. type observedOptions struct {
  5618. headers []*metadata.MD
  5619. trailers []*metadata.MD
  5620. peer []*peer.Peer
  5621. creds []credentials.PerRPCCredentials
  5622. failFast []bool
  5623. maxRecvSize []int
  5624. maxSendSize []int
  5625. compressor []string
  5626. subtype []string
  5627. }
  5628. var observedOpts observedOptions
  5629. populateOpts := func(opts []grpc.CallOption) {
  5630. for _, o := range opts {
  5631. switch o := o.(type) {
  5632. case grpc.HeaderCallOption:
  5633. observedOpts.headers = append(observedOpts.headers, o.HeaderAddr)
  5634. case grpc.TrailerCallOption:
  5635. observedOpts.trailers = append(observedOpts.trailers, o.TrailerAddr)
  5636. case grpc.PeerCallOption:
  5637. observedOpts.peer = append(observedOpts.peer, o.PeerAddr)
  5638. case grpc.PerRPCCredsCallOption:
  5639. observedOpts.creds = append(observedOpts.creds, o.Creds)
  5640. case grpc.FailFastCallOption:
  5641. observedOpts.failFast = append(observedOpts.failFast, o.FailFast)
  5642. case grpc.MaxRecvMsgSizeCallOption:
  5643. observedOpts.maxRecvSize = append(observedOpts.maxRecvSize, o.MaxRecvMsgSize)
  5644. case grpc.MaxSendMsgSizeCallOption:
  5645. observedOpts.maxSendSize = append(observedOpts.maxSendSize, o.MaxSendMsgSize)
  5646. case grpc.CompressorCallOption:
  5647. observedOpts.compressor = append(observedOpts.compressor, o.CompressorType)
  5648. case grpc.ContentSubtypeCallOption:
  5649. observedOpts.subtype = append(observedOpts.subtype, o.ContentSubtype)
  5650. }
  5651. }
  5652. }
  5653. te.unaryClientInt = func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
  5654. populateOpts(opts)
  5655. return nil
  5656. }
  5657. te.streamClientInt = func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
  5658. populateOpts(opts)
  5659. return nil, nil
  5660. }
  5661. defaults := []grpc.CallOption{
  5662. grpc.WaitForReady(true),
  5663. grpc.MaxCallRecvMsgSize(1010),
  5664. }
  5665. tc := testpb.NewTestServiceClient(te.clientConn(grpc.WithDefaultCallOptions(defaults...)))
  5666. var headers metadata.MD
  5667. var trailers metadata.MD
  5668. var pr peer.Peer
  5669. tc.UnaryCall(context.Background(), &testpb.SimpleRequest{},
  5670. grpc.MaxCallRecvMsgSize(100),
  5671. grpc.MaxCallSendMsgSize(200),
  5672. grpc.PerRPCCredentials(testPerRPCCredentials{}),
  5673. grpc.Header(&headers),
  5674. grpc.Trailer(&trailers),
  5675. grpc.Peer(&pr))
  5676. expected := observedOptions{
  5677. failFast: []bool{false},
  5678. maxRecvSize: []int{1010, 100},
  5679. maxSendSize: []int{200},
  5680. creds: []credentials.PerRPCCredentials{testPerRPCCredentials{}},
  5681. headers: []*metadata.MD{&headers},
  5682. trailers: []*metadata.MD{&trailers},
  5683. peer: []*peer.Peer{&pr},
  5684. }
  5685. if !reflect.DeepEqual(expected, observedOpts) {
  5686. t.Errorf("unary call did not observe expected options: expected %#v, got %#v", expected, observedOpts)
  5687. }
  5688. observedOpts = observedOptions{} // reset
  5689. tc.StreamingInputCall(context.Background(),
  5690. grpc.WaitForReady(false),
  5691. grpc.MaxCallSendMsgSize(2020),
  5692. grpc.UseCompressor("comp-type"),
  5693. grpc.CallContentSubtype("json"))
  5694. expected = observedOptions{
  5695. failFast: []bool{false, true},
  5696. maxRecvSize: []int{1010},
  5697. maxSendSize: []int{2020},
  5698. compressor: []string{"comp-type"},
  5699. subtype: []string{"json"},
  5700. }
  5701. if !reflect.DeepEqual(expected, observedOpts) {
  5702. t.Errorf("streaming call did not observe expected options: expected %#v, got %#v", expected, observedOpts)
  5703. }
  5704. }
  5705. func (s) TestCompressorRegister(t *testing.T) {
  5706. for _, e := range listTestEnv() {
  5707. testCompressorRegister(t, e)
  5708. }
  5709. }
  5710. func testCompressorRegister(t *testing.T, e env) {
  5711. te := newTest(t, e)
  5712. te.clientCompression = false
  5713. te.serverCompression = false
  5714. te.clientUseCompression = true
  5715. te.startServer(&testServer{security: e.security})
  5716. defer te.tearDown()
  5717. tc := testpb.NewTestServiceClient(te.clientConn())
  5718. // Unary call
  5719. const argSize = 271828
  5720. const respSize = 314159
  5721. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize)
  5722. if err != nil {
  5723. t.Fatal(err)
  5724. }
  5725. req := &testpb.SimpleRequest{
  5726. ResponseType: testpb.PayloadType_COMPRESSABLE,
  5727. ResponseSize: respSize,
  5728. Payload: payload,
  5729. }
  5730. ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs("something", "something"))
  5731. if _, err := tc.UnaryCall(ctx, req); err != nil {
  5732. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, <nil>", err)
  5733. }
  5734. // Streaming RPC
  5735. ctx, cancel := context.WithCancel(context.Background())
  5736. defer cancel()
  5737. stream, err := tc.FullDuplexCall(ctx)
  5738. if err != nil {
  5739. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err)
  5740. }
  5741. respParam := []*testpb.ResponseParameters{
  5742. {
  5743. Size: 31415,
  5744. },
  5745. }
  5746. payload, err = newPayload(testpb.PayloadType_COMPRESSABLE, int32(31415))
  5747. if err != nil {
  5748. t.Fatal(err)
  5749. }
  5750. sreq := &testpb.StreamingOutputCallRequest{
  5751. ResponseType: testpb.PayloadType_COMPRESSABLE,
  5752. ResponseParameters: respParam,
  5753. Payload: payload,
  5754. }
  5755. if err := stream.Send(sreq); err != nil {
  5756. t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err)
  5757. }
  5758. if _, err := stream.Recv(); err != nil {
  5759. t.Fatalf("%v.Recv() = %v, want <nil>", stream, err)
  5760. }
  5761. }
  5762. func (s) TestServeExitsWhenListenerClosed(t *testing.T) {
  5763. ss := &stubServer{
  5764. emptyCall: func(context.Context, *testpb.Empty) (*testpb.Empty, error) {
  5765. return &testpb.Empty{}, nil
  5766. },
  5767. }
  5768. s := grpc.NewServer()
  5769. testpb.RegisterTestServiceServer(s, ss)
  5770. lis, err := net.Listen("tcp", "localhost:0")
  5771. if err != nil {
  5772. t.Fatalf("Failed to create listener: %v", err)
  5773. }
  5774. done := make(chan struct{})
  5775. go func() {
  5776. s.Serve(lis)
  5777. close(done)
  5778. }()
  5779. cc, err := grpc.Dial(lis.Addr().String(), grpc.WithInsecure(), grpc.WithBlock())
  5780. if err != nil {
  5781. t.Fatalf("Failed to dial server: %v", err)
  5782. }
  5783. defer cc.Close()
  5784. c := testpb.NewTestServiceClient(cc)
  5785. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  5786. defer cancel()
  5787. if _, err := c.EmptyCall(ctx, &testpb.Empty{}); err != nil {
  5788. t.Fatalf("Failed to send test RPC to server: %v", err)
  5789. }
  5790. if err := lis.Close(); err != nil {
  5791. t.Fatalf("Failed to close listener: %v", err)
  5792. }
  5793. const timeout = 5 * time.Second
  5794. timer := time.NewTimer(timeout)
  5795. select {
  5796. case <-done:
  5797. return
  5798. case <-timer.C:
  5799. t.Fatalf("Serve did not return after %v", timeout)
  5800. }
  5801. }
  5802. // Service handler returns status with invalid utf8 message.
  5803. func (s) TestStatusInvalidUTF8Message(t *testing.T) {
  5804. var (
  5805. origMsg = string([]byte{0xff, 0xfe, 0xfd})
  5806. wantMsg = "���"
  5807. )
  5808. ss := &stubServer{
  5809. emptyCall: func(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) {
  5810. return nil, status.Errorf(codes.Internal, origMsg)
  5811. },
  5812. }
  5813. if err := ss.Start(nil); err != nil {
  5814. t.Fatalf("Error starting endpoint server: %v", err)
  5815. }
  5816. defer ss.Stop()
  5817. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  5818. defer cancel()
  5819. if _, err := ss.client.EmptyCall(ctx, &testpb.Empty{}); status.Convert(err).Message() != wantMsg {
  5820. t.Fatalf("ss.client.EmptyCall(_, _) = _, %v (msg %q); want _, err with msg %q", err, status.Convert(err).Message(), wantMsg)
  5821. }
  5822. }
  5823. // Service handler returns status with details and invalid utf8 message. Proto
  5824. // will fail to marshal the status because of the invalid utf8 message. Details
  5825. // will be dropped when sending.
  5826. func (s) TestStatusInvalidUTF8Details(t *testing.T) {
  5827. var (
  5828. origMsg = string([]byte{0xff, 0xfe, 0xfd})
  5829. wantMsg = "���"
  5830. )
  5831. ss := &stubServer{
  5832. emptyCall: func(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) {
  5833. st := status.New(codes.Internal, origMsg)
  5834. st, err := st.WithDetails(&testpb.Empty{})
  5835. if err != nil {
  5836. return nil, err
  5837. }
  5838. return nil, st.Err()
  5839. },
  5840. }
  5841. if err := ss.Start(nil); err != nil {
  5842. t.Fatalf("Error starting endpoint server: %v", err)
  5843. }
  5844. defer ss.Stop()
  5845. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  5846. defer cancel()
  5847. _, err := ss.client.EmptyCall(ctx, &testpb.Empty{})
  5848. st := status.Convert(err)
  5849. if st.Message() != wantMsg {
  5850. t.Fatalf("ss.client.EmptyCall(_, _) = _, %v (msg %q); want _, err with msg %q", err, st.Message(), wantMsg)
  5851. }
  5852. if len(st.Details()) != 0 {
  5853. // Details should be dropped on the server side.
  5854. t.Fatalf("RPC status contain details: %v, want no details", st.Details())
  5855. }
  5856. }
  5857. func (s) TestClientDoesntDeadlockWhileWritingErrornousLargeMessages(t *testing.T) {
  5858. for _, e := range listTestEnv() {
  5859. if e.httpHandler {
  5860. continue
  5861. }
  5862. testClientDoesntDeadlockWhileWritingErrornousLargeMessages(t, e)
  5863. }
  5864. }
  5865. func testClientDoesntDeadlockWhileWritingErrornousLargeMessages(t *testing.T, e env) {
  5866. te := newTest(t, e)
  5867. te.userAgent = testAppUA
  5868. smallSize := 1024
  5869. te.maxServerReceiveMsgSize = &smallSize
  5870. te.startServer(&testServer{security: e.security})
  5871. defer te.tearDown()
  5872. tc := testpb.NewTestServiceClient(te.clientConn())
  5873. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, 1048576)
  5874. if err != nil {
  5875. t.Fatal(err)
  5876. }
  5877. req := &testpb.SimpleRequest{
  5878. ResponseType: testpb.PayloadType_COMPRESSABLE,
  5879. Payload: payload,
  5880. }
  5881. var wg sync.WaitGroup
  5882. for i := 0; i < 10; i++ {
  5883. wg.Add(1)
  5884. go func() {
  5885. defer wg.Done()
  5886. for j := 0; j < 100; j++ {
  5887. ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*10))
  5888. defer cancel()
  5889. if _, err := tc.UnaryCall(ctx, req); status.Code(err) != codes.ResourceExhausted {
  5890. t.Errorf("TestService/UnaryCall(_,_) = _. %v, want code: %s", err, codes.ResourceExhausted)
  5891. return
  5892. }
  5893. }
  5894. }()
  5895. }
  5896. wg.Wait()
  5897. }
  5898. const clientAlwaysFailCredErrorMsg = "clientAlwaysFailCred always fails"
  5899. var errClientAlwaysFailCred = errors.New(clientAlwaysFailCredErrorMsg)
  5900. type clientAlwaysFailCred struct{}
  5901. func (c clientAlwaysFailCred) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
  5902. return nil, nil, errClientAlwaysFailCred
  5903. }
  5904. func (c clientAlwaysFailCred) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
  5905. return rawConn, nil, nil
  5906. }
  5907. func (c clientAlwaysFailCred) Info() credentials.ProtocolInfo {
  5908. return credentials.ProtocolInfo{}
  5909. }
  5910. func (c clientAlwaysFailCred) Clone() credentials.TransportCredentials {
  5911. return nil
  5912. }
  5913. func (c clientAlwaysFailCred) OverrideServerName(s string) error {
  5914. return nil
  5915. }
  5916. func (s) TestFailFastRPCErrorOnBadCertificates(t *testing.T) {
  5917. te := newTest(t, env{name: "bad-cred", network: "tcp", security: "clientAlwaysFailCred", balancer: "round_robin"})
  5918. te.startServer(&testServer{security: te.e.security})
  5919. defer te.tearDown()
  5920. opts := []grpc.DialOption{grpc.WithTransportCredentials(clientAlwaysFailCred{})}
  5921. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  5922. defer cancel()
  5923. cc, err := grpc.DialContext(ctx, te.srvAddr, opts...)
  5924. if err != nil {
  5925. t.Fatalf("Dial(_) = %v, want %v", err, nil)
  5926. }
  5927. defer cc.Close()
  5928. tc := testpb.NewTestServiceClient(cc)
  5929. for i := 0; i < 1000; i++ {
  5930. // This loop runs for at most 1 second. The first several RPCs will fail
  5931. // with Unavailable because the connection hasn't started. When the
  5932. // first connection failed with creds error, the next RPC should also
  5933. // fail with the expected error.
  5934. if _, err = tc.EmptyCall(context.Background(), &testpb.Empty{}); strings.Contains(err.Error(), clientAlwaysFailCredErrorMsg) {
  5935. return
  5936. }
  5937. time.Sleep(time.Millisecond)
  5938. }
  5939. te.t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want err.Error() contains %q", err, clientAlwaysFailCredErrorMsg)
  5940. }
  5941. func (s) TestRPCTimeout(t *testing.T) {
  5942. for _, e := range listTestEnv() {
  5943. testRPCTimeout(t, e)
  5944. }
  5945. }
  5946. func testRPCTimeout(t *testing.T, e env) {
  5947. te := newTest(t, e)
  5948. te.startServer(&testServer{security: e.security, unaryCallSleepTime: 500 * time.Millisecond})
  5949. defer te.tearDown()
  5950. cc := te.clientConn()
  5951. tc := testpb.NewTestServiceClient(cc)
  5952. const argSize = 2718
  5953. const respSize = 314
  5954. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize)
  5955. if err != nil {
  5956. t.Fatal(err)
  5957. }
  5958. req := &testpb.SimpleRequest{
  5959. ResponseType: testpb.PayloadType_COMPRESSABLE,
  5960. ResponseSize: respSize,
  5961. Payload: payload,
  5962. }
  5963. for i := -1; i <= 10; i++ {
  5964. ctx, cancel := context.WithTimeout(context.Background(), time.Duration(i)*time.Millisecond)
  5965. if _, err := tc.UnaryCall(ctx, req); status.Code(err) != codes.DeadlineExceeded {
  5966. t.Fatalf("TestService/UnaryCallv(_, _) = _, %v; want <nil>, error code: %s", err, codes.DeadlineExceeded)
  5967. }
  5968. cancel()
  5969. }
  5970. }
  5971. func (s) TestDisabledIOBuffers(t *testing.T) {
  5972. payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(60000))
  5973. if err != nil {
  5974. t.Fatalf("Failed to create payload: %v", err)
  5975. }
  5976. req := &testpb.StreamingOutputCallRequest{
  5977. Payload: payload,
  5978. }
  5979. resp := &testpb.StreamingOutputCallResponse{
  5980. Payload: payload,
  5981. }
  5982. ss := &stubServer{
  5983. fullDuplexCall: func(stream testpb.TestService_FullDuplexCallServer) error {
  5984. for {
  5985. in, err := stream.Recv()
  5986. if err == io.EOF {
  5987. return nil
  5988. }
  5989. if err != nil {
  5990. t.Errorf("stream.Recv() = _, %v, want _, <nil>", err)
  5991. return err
  5992. }
  5993. if !reflect.DeepEqual(in.Payload.Body, payload.Body) {
  5994. t.Errorf("Received message(len: %v) on server not what was expected(len: %v).", len(in.Payload.Body), len(payload.Body))
  5995. return err
  5996. }
  5997. if err := stream.Send(resp); err != nil {
  5998. t.Errorf("stream.Send(_)= %v, want <nil>", err)
  5999. return err
  6000. }
  6001. }
  6002. },
  6003. }
  6004. s := grpc.NewServer(grpc.WriteBufferSize(0), grpc.ReadBufferSize(0))
  6005. testpb.RegisterTestServiceServer(s, ss)
  6006. lis, err := net.Listen("tcp", "localhost:0")
  6007. if err != nil {
  6008. t.Fatalf("Failed to create listener: %v", err)
  6009. }
  6010. done := make(chan struct{})
  6011. go func() {
  6012. s.Serve(lis)
  6013. close(done)
  6014. }()
  6015. defer s.Stop()
  6016. dctx, dcancel := context.WithTimeout(context.Background(), 5*time.Second)
  6017. defer dcancel()
  6018. cc, err := grpc.DialContext(dctx, lis.Addr().String(), grpc.WithInsecure(), grpc.WithBlock(), grpc.WithWriteBufferSize(0), grpc.WithReadBufferSize(0))
  6019. if err != nil {
  6020. t.Fatalf("Failed to dial server")
  6021. }
  6022. defer cc.Close()
  6023. c := testpb.NewTestServiceClient(cc)
  6024. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  6025. defer cancel()
  6026. stream, err := c.FullDuplexCall(ctx, grpc.WaitForReady(true))
  6027. if err != nil {
  6028. t.Fatalf("Failed to send test RPC to server")
  6029. }
  6030. for i := 0; i < 10; i++ {
  6031. if err := stream.Send(req); err != nil {
  6032. t.Fatalf("stream.Send(_) = %v, want <nil>", err)
  6033. }
  6034. in, err := stream.Recv()
  6035. if err != nil {
  6036. t.Fatalf("stream.Recv() = _, %v, want _, <nil>", err)
  6037. }
  6038. if !reflect.DeepEqual(in.Payload.Body, payload.Body) {
  6039. t.Fatalf("Received message(len: %v) on client not what was expected(len: %v).", len(in.Payload.Body), len(payload.Body))
  6040. }
  6041. }
  6042. stream.CloseSend()
  6043. if _, err := stream.Recv(); err != io.EOF {
  6044. t.Fatalf("stream.Recv() = _, %v, want _, io.EOF", err)
  6045. }
  6046. }
  6047. func (s) TestServerMaxHeaderListSizeClientUserViolation(t *testing.T) {
  6048. for _, e := range listTestEnv() {
  6049. if e.httpHandler {
  6050. continue
  6051. }
  6052. testServerMaxHeaderListSizeClientUserViolation(t, e)
  6053. }
  6054. }
  6055. func testServerMaxHeaderListSizeClientUserViolation(t *testing.T, e env) {
  6056. te := newTest(t, e)
  6057. te.maxServerHeaderListSize = new(uint32)
  6058. *te.maxServerHeaderListSize = 216
  6059. te.startServer(&testServer{security: e.security})
  6060. defer te.tearDown()
  6061. cc := te.clientConn()
  6062. tc := testpb.NewTestServiceClient(cc)
  6063. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  6064. defer cancel()
  6065. metadata.AppendToOutgoingContext(ctx, "oversize", string(make([]byte, 216)))
  6066. var err error
  6067. if err = verifyResultWithDelay(func() (bool, error) {
  6068. if _, err = tc.EmptyCall(ctx, &testpb.Empty{}); err != nil && status.Code(err) == codes.Internal {
  6069. return true, nil
  6070. }
  6071. return false, fmt.Errorf("tc.EmptyCall() = _, err: %v, want _, error code: %v", err, codes.Internal)
  6072. }); err != nil {
  6073. t.Fatal(err)
  6074. }
  6075. }
  6076. func (s) TestClientMaxHeaderListSizeServerUserViolation(t *testing.T) {
  6077. for _, e := range listTestEnv() {
  6078. if e.httpHandler {
  6079. continue
  6080. }
  6081. testClientMaxHeaderListSizeServerUserViolation(t, e)
  6082. }
  6083. }
  6084. func testClientMaxHeaderListSizeServerUserViolation(t *testing.T, e env) {
  6085. te := newTest(t, e)
  6086. te.maxClientHeaderListSize = new(uint32)
  6087. *te.maxClientHeaderListSize = 1 // any header server sends will violate
  6088. te.startServer(&testServer{security: e.security})
  6089. defer te.tearDown()
  6090. cc := te.clientConn()
  6091. tc := testpb.NewTestServiceClient(cc)
  6092. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  6093. defer cancel()
  6094. var err error
  6095. if err = verifyResultWithDelay(func() (bool, error) {
  6096. if _, err = tc.EmptyCall(ctx, &testpb.Empty{}); err != nil && status.Code(err) == codes.Internal {
  6097. return true, nil
  6098. }
  6099. return false, fmt.Errorf("tc.EmptyCall() = _, err: %v, want _, error code: %v", err, codes.Internal)
  6100. }); err != nil {
  6101. t.Fatal(err)
  6102. }
  6103. }
  6104. func (s) TestServerMaxHeaderListSizeClientIntentionalViolation(t *testing.T) {
  6105. for _, e := range listTestEnv() {
  6106. if e.httpHandler || e.security == "tls" {
  6107. continue
  6108. }
  6109. testServerMaxHeaderListSizeClientIntentionalViolation(t, e)
  6110. }
  6111. }
  6112. func testServerMaxHeaderListSizeClientIntentionalViolation(t *testing.T, e env) {
  6113. te := newTest(t, e)
  6114. te.maxServerHeaderListSize = new(uint32)
  6115. *te.maxServerHeaderListSize = 512
  6116. te.startServer(&testServer{security: e.security})
  6117. defer te.tearDown()
  6118. cc, dw := te.clientConnWithConnControl()
  6119. tc := &testServiceClientWrapper{TestServiceClient: testpb.NewTestServiceClient(cc)}
  6120. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  6121. defer cancel()
  6122. stream, err := tc.FullDuplexCall(ctx)
  6123. if err != nil {
  6124. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want _, <nil>", tc, err)
  6125. }
  6126. rcw := dw.getRawConnWrapper()
  6127. val := make([]string, 512)
  6128. for i := range val {
  6129. val[i] = "a"
  6130. }
  6131. // allow for client to send the initial header
  6132. time.Sleep(100 * time.Millisecond)
  6133. rcw.writeHeaders(http2.HeadersFrameParam{
  6134. StreamID: tc.getCurrentStreamID(),
  6135. BlockFragment: rcw.encodeHeader("oversize", strings.Join(val, "")),
  6136. EndStream: false,
  6137. EndHeaders: true,
  6138. })
  6139. if _, err := stream.Recv(); err == nil || status.Code(err) != codes.Internal {
  6140. t.Fatalf("stream.Recv() = _, %v, want _, error code: %v", err, codes.Internal)
  6141. }
  6142. }
  6143. func (s) TestClientMaxHeaderListSizeServerIntentionalViolation(t *testing.T) {
  6144. for _, e := range listTestEnv() {
  6145. if e.httpHandler || e.security == "tls" {
  6146. continue
  6147. }
  6148. testClientMaxHeaderListSizeServerIntentionalViolation(t, e)
  6149. }
  6150. }
  6151. func testClientMaxHeaderListSizeServerIntentionalViolation(t *testing.T, e env) {
  6152. te := newTest(t, e)
  6153. te.maxClientHeaderListSize = new(uint32)
  6154. *te.maxClientHeaderListSize = 200
  6155. lw := te.startServerWithConnControl(&testServer{security: e.security, setHeaderOnly: true})
  6156. defer te.tearDown()
  6157. cc, _ := te.clientConnWithConnControl()
  6158. tc := &testServiceClientWrapper{TestServiceClient: testpb.NewTestServiceClient(cc)}
  6159. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  6160. defer cancel()
  6161. stream, err := tc.FullDuplexCall(ctx)
  6162. if err != nil {
  6163. t.Fatalf("%v.FullDuplexCall(_) = _, %v, want _, <nil>", tc, err)
  6164. }
  6165. var i int
  6166. var rcw *rawConnWrapper
  6167. for i = 0; i < 100; i++ {
  6168. rcw = lw.getLastConn()
  6169. if rcw != nil {
  6170. break
  6171. }
  6172. time.Sleep(10 * time.Millisecond)
  6173. continue
  6174. }
  6175. if i == 100 {
  6176. t.Fatalf("failed to create server transport after 1s")
  6177. }
  6178. val := make([]string, 200)
  6179. for i := range val {
  6180. val[i] = "a"
  6181. }
  6182. // allow for client to send the initial header.
  6183. time.Sleep(100 * time.Millisecond)
  6184. rcw.writeHeaders(http2.HeadersFrameParam{
  6185. StreamID: tc.getCurrentStreamID(),
  6186. BlockFragment: rcw.encodeRawHeader("oversize", strings.Join(val, "")),
  6187. EndStream: false,
  6188. EndHeaders: true,
  6189. })
  6190. if _, err := stream.Recv(); err == nil || status.Code(err) != codes.Internal {
  6191. t.Fatalf("stream.Recv() = _, %v, want _, error code: %v", err, codes.Internal)
  6192. }
  6193. }
  6194. func (s) TestNetPipeConn(t *testing.T) {
  6195. // This test will block indefinitely if grpc writes both client and server
  6196. // prefaces without either reading from the Conn.
  6197. pl := testutils.NewPipeListener()
  6198. s := grpc.NewServer()
  6199. defer s.Stop()
  6200. ts := &funcServer{unaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
  6201. return &testpb.SimpleResponse{}, nil
  6202. }}
  6203. testpb.RegisterTestServiceServer(s, ts)
  6204. go s.Serve(pl)
  6205. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  6206. defer cancel()
  6207. cc, err := grpc.DialContext(ctx, "", grpc.WithInsecure(), grpc.WithDialer(pl.Dialer()))
  6208. if err != nil {
  6209. t.Fatalf("Error creating client: %v", err)
  6210. }
  6211. defer cc.Close()
  6212. client := testpb.NewTestServiceClient(cc)
  6213. if _, err := client.UnaryCall(ctx, &testpb.SimpleRequest{}); err != nil {
  6214. t.Fatalf("UnaryCall(_) = _, %v; want _, nil", err)
  6215. }
  6216. }
  6217. func (s) TestLargeTimeout(t *testing.T) {
  6218. for _, e := range listTestEnv() {
  6219. testLargeTimeout(t, e)
  6220. }
  6221. }
  6222. func testLargeTimeout(t *testing.T, e env) {
  6223. te := newTest(t, e)
  6224. te.declareLogNoise("Server.processUnaryRPC failed to write status")
  6225. ts := &funcServer{}
  6226. te.startServer(ts)
  6227. defer te.tearDown()
  6228. tc := testpb.NewTestServiceClient(te.clientConn())
  6229. timeouts := []time.Duration{
  6230. time.Duration(math.MaxInt64), // will be (correctly) converted to
  6231. // 2562048 hours, which overflows upon converting back to an int64
  6232. 2562047 * time.Hour, // the largest timeout that does not overflow
  6233. }
  6234. for i, maxTimeout := range timeouts {
  6235. ts.unaryCall = func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
  6236. deadline, ok := ctx.Deadline()
  6237. timeout := time.Until(deadline)
  6238. minTimeout := maxTimeout - 5*time.Second
  6239. if !ok || timeout < minTimeout || timeout > maxTimeout {
  6240. t.Errorf("ctx.Deadline() = (now+%v), %v; want [%v, %v], true", timeout, ok, minTimeout, maxTimeout)
  6241. return nil, status.Error(codes.OutOfRange, "deadline error")
  6242. }
  6243. return &testpb.SimpleResponse{}, nil
  6244. }
  6245. ctx, cancel := context.WithTimeout(context.Background(), maxTimeout)
  6246. defer cancel()
  6247. if _, err := tc.UnaryCall(ctx, &testpb.SimpleRequest{}); err != nil {
  6248. t.Errorf("case %v: UnaryCall(_) = _, %v; want _, nil", i, err)
  6249. }
  6250. }
  6251. }
  6252. // Proxies typically send GO_AWAY followed by connection closure a minute or so later. This
  6253. // test ensures that the connection is re-created after GO_AWAY and not affected by the
  6254. // subsequent (old) connection closure.
  6255. func (s) TestGoAwayThenClose(t *testing.T) {
  6256. ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
  6257. defer cancel()
  6258. lis1, err := net.Listen("tcp", "localhost:0")
  6259. if err != nil {
  6260. t.Fatalf("Error while listening. Err: %v", err)
  6261. }
  6262. s1 := grpc.NewServer()
  6263. defer s1.Stop()
  6264. ts1 := &funcServer{
  6265. unaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
  6266. return &testpb.SimpleResponse{}, nil
  6267. },
  6268. fullDuplexCall: func(stream testpb.TestService_FullDuplexCallServer) error {
  6269. // Wait forever.
  6270. _, err := stream.Recv()
  6271. if err == nil {
  6272. t.Error("expected to never receive any message")
  6273. }
  6274. return err
  6275. },
  6276. }
  6277. testpb.RegisterTestServiceServer(s1, ts1)
  6278. go s1.Serve(lis1)
  6279. conn2Established := grpcsync.NewEvent()
  6280. lis2, err := listenWithNotifyingListener("tcp", "localhost:0", conn2Established)
  6281. if err != nil {
  6282. t.Fatalf("Error while listening. Err: %v", err)
  6283. }
  6284. s2 := grpc.NewServer()
  6285. defer s2.Stop()
  6286. conn2Ready := grpcsync.NewEvent()
  6287. ts2 := &funcServer{unaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
  6288. conn2Ready.Fire()
  6289. return &testpb.SimpleResponse{}, nil
  6290. }}
  6291. testpb.RegisterTestServiceServer(s2, ts2)
  6292. go s2.Serve(lis2)
  6293. r, rcleanup := manual.GenerateAndRegisterManualResolver()
  6294. defer rcleanup()
  6295. r.InitialState(resolver.State{Addresses: []resolver.Address{
  6296. {Addr: lis1.Addr().String()},
  6297. {Addr: lis2.Addr().String()},
  6298. }})
  6299. cc, err := grpc.DialContext(ctx, r.Scheme()+":///", grpc.WithInsecure())
  6300. if err != nil {
  6301. t.Fatalf("Error creating client: %v", err)
  6302. }
  6303. defer cc.Close()
  6304. client := testpb.NewTestServiceClient(cc)
  6305. // Should go on connection 1. We use a long-lived RPC because it will cause GracefulStop to send GO_AWAY, but the
  6306. // connection doesn't get closed until the server stops and the client receives.
  6307. stream, err := client.FullDuplexCall(ctx)
  6308. if err != nil {
  6309. t.Fatalf("FullDuplexCall(_) = _, %v; want _, nil", err)
  6310. }
  6311. // Send GO_AWAY to connection 1.
  6312. go s1.GracefulStop()
  6313. // Wait for connection 2 to be established.
  6314. <-conn2Established.Done()
  6315. // Close connection 1.
  6316. s1.Stop()
  6317. // Wait for client to close.
  6318. _, err = stream.Recv()
  6319. if err == nil {
  6320. t.Fatal("expected the stream to die, but got a successful Recv")
  6321. }
  6322. // Do a bunch of RPCs, make sure it stays stable. These should go to connection 2.
  6323. for i := 0; i < 10; i++ {
  6324. if _, err := client.UnaryCall(ctx, &testpb.SimpleRequest{}); err != nil {
  6325. t.Fatalf("UnaryCall(_) = _, %v; want _, nil", err)
  6326. }
  6327. }
  6328. }
  6329. func listenWithNotifyingListener(network, address string, event *grpcsync.Event) (net.Listener, error) {
  6330. lis, err := net.Listen(network, address)
  6331. if err != nil {
  6332. return nil, err
  6333. }
  6334. return notifyingListener{connEstablished: event, Listener: lis}, nil
  6335. }
  6336. type notifyingListener struct {
  6337. connEstablished *grpcsync.Event
  6338. net.Listener
  6339. }
  6340. func (lis notifyingListener) Accept() (net.Conn, error) {
  6341. defer lis.connEstablished.Fire()
  6342. return lis.Listener.Accept()
  6343. }
  6344. func (s) TestRPCWaitsForResolver(t *testing.T) {
  6345. te := testServiceConfigSetup(t, tcpClearRREnv)
  6346. te.startServer(&testServer{security: tcpClearRREnv.security})
  6347. defer te.tearDown()
  6348. r, rcleanup := manual.GenerateAndRegisterManualResolver()
  6349. defer rcleanup()
  6350. te.resolverScheme = r.Scheme()
  6351. te.nonBlockingDial = true
  6352. cc := te.clientConn()
  6353. tc := testpb.NewTestServiceClient(cc)
  6354. ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
  6355. defer cancel()
  6356. // With no resolved addresses yet, this will timeout.
  6357. if _, err := tc.EmptyCall(ctx, &testpb.Empty{}); status.Code(err) != codes.DeadlineExceeded {
  6358. t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded)
  6359. }
  6360. ctx, cancel = context.WithTimeout(context.Background(), 10*time.Second)
  6361. defer cancel()
  6362. go func() {
  6363. time.Sleep(time.Second)
  6364. r.UpdateState(resolver.State{
  6365. Addresses: []resolver.Address{{Addr: te.srvAddr}},
  6366. ServiceConfig: `{
  6367. "methodConfig": [
  6368. {
  6369. "name": [
  6370. {
  6371. "service": "grpc.testing.TestService",
  6372. "method": "UnaryCall"
  6373. }
  6374. ],
  6375. "maxRequestMessageBytes": 0
  6376. }
  6377. ]
  6378. }`})
  6379. }()
  6380. // We wait a second before providing a service config and resolving
  6381. // addresses. So this will wait for that and then honor the
  6382. // maxRequestMessageBytes it contains.
  6383. if _, err := tc.UnaryCall(ctx, &testpb.SimpleRequest{ResponseType: testpb.PayloadType_UNCOMPRESSABLE}); status.Code(err) != codes.ResourceExhausted {
  6384. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, nil", err)
  6385. }
  6386. if got := ctx.Err(); got != nil {
  6387. t.Fatalf("ctx.Err() = %v; want nil (deadline should be set short by service config)", got)
  6388. }
  6389. if _, err := tc.UnaryCall(ctx, &testpb.SimpleRequest{}); err != nil {
  6390. t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, nil", err)
  6391. }
  6392. }
  6393. func (s) TestHTTPHeaderFrameErrorHandlingHTTPMode(t *testing.T) {
  6394. // Non-gRPC content-type fallback path.
  6395. for httpCode := range transport.HTTPStatusConvTab {
  6396. doHTTPHeaderTest(t, transport.HTTPStatusConvTab[int(httpCode)], []string{
  6397. ":status", fmt.Sprintf("%d", httpCode),
  6398. "content-type", "text/html", // non-gRPC content type to switch to HTTP mode.
  6399. "grpc-status", "1", // Make up a gRPC status error
  6400. "grpc-status-details-bin", "???", // Make up a gRPC field parsing error
  6401. })
  6402. }
  6403. // Missing content-type fallback path.
  6404. for httpCode := range transport.HTTPStatusConvTab {
  6405. doHTTPHeaderTest(t, transport.HTTPStatusConvTab[int(httpCode)], []string{
  6406. ":status", fmt.Sprintf("%d", httpCode),
  6407. // Omitting content type to switch to HTTP mode.
  6408. "grpc-status", "1", // Make up a gRPC status error
  6409. "grpc-status-details-bin", "???", // Make up a gRPC field parsing error
  6410. })
  6411. }
  6412. // Malformed HTTP status when fallback.
  6413. doHTTPHeaderTest(t, codes.Internal, []string{
  6414. ":status", "abc",
  6415. // Omitting content type to switch to HTTP mode.
  6416. "grpc-status", "1", // Make up a gRPC status error
  6417. "grpc-status-details-bin", "???", // Make up a gRPC field parsing error
  6418. })
  6419. }
  6420. // Testing erroneous ResponseHeader or Trailers-only (delivered in the first HEADERS frame).
  6421. func (s) TestHTTPHeaderFrameErrorHandlingInitialHeader(t *testing.T) {
  6422. for _, test := range []struct {
  6423. header []string
  6424. errCode codes.Code
  6425. }{
  6426. {
  6427. // missing gRPC status.
  6428. header: []string{
  6429. ":status", "403",
  6430. "content-type", "application/grpc",
  6431. },
  6432. errCode: codes.Unknown,
  6433. },
  6434. {
  6435. // malformed grpc-status.
  6436. header: []string{
  6437. ":status", "502",
  6438. "content-type", "application/grpc",
  6439. "grpc-status", "abc",
  6440. },
  6441. errCode: codes.Internal,
  6442. },
  6443. {
  6444. // Malformed grpc-tags-bin field.
  6445. header: []string{
  6446. ":status", "502",
  6447. "content-type", "application/grpc",
  6448. "grpc-status", "0",
  6449. "grpc-tags-bin", "???",
  6450. },
  6451. errCode: codes.Internal,
  6452. },
  6453. {
  6454. // gRPC status error.
  6455. header: []string{
  6456. ":status", "502",
  6457. "content-type", "application/grpc",
  6458. "grpc-status", "3",
  6459. },
  6460. errCode: codes.InvalidArgument,
  6461. },
  6462. } {
  6463. doHTTPHeaderTest(t, test.errCode, test.header)
  6464. }
  6465. }
  6466. // Testing non-Trailers-only Trailers (delievered in second HEADERS frame)
  6467. func (s) TestHTTPHeaderFrameErrorHandlingNormalTrailer(t *testing.T) {
  6468. for _, test := range []struct {
  6469. responseHeader []string
  6470. trailer []string
  6471. errCode codes.Code
  6472. }{
  6473. {
  6474. responseHeader: []string{
  6475. ":status", "200",
  6476. "content-type", "application/grpc",
  6477. },
  6478. trailer: []string{
  6479. // trailer missing grpc-status
  6480. ":status", "502",
  6481. },
  6482. errCode: codes.Unknown,
  6483. },
  6484. {
  6485. responseHeader: []string{
  6486. ":status", "404",
  6487. "content-type", "application/grpc",
  6488. },
  6489. trailer: []string{
  6490. // malformed grpc-status-details-bin field
  6491. "grpc-status", "0",
  6492. "grpc-status-details-bin", "????",
  6493. },
  6494. errCode: codes.Internal,
  6495. },
  6496. } {
  6497. doHTTPHeaderTest(t, test.errCode, test.responseHeader, test.trailer)
  6498. }
  6499. }
  6500. func (s) TestHTTPHeaderFrameErrorHandlingMoreThanTwoHeaders(t *testing.T) {
  6501. header := []string{
  6502. ":status", "200",
  6503. "content-type", "application/grpc",
  6504. }
  6505. doHTTPHeaderTest(t, codes.Internal, header, header, header)
  6506. }
  6507. type httpServer struct {
  6508. headerFields [][]string
  6509. }
  6510. func (s *httpServer) writeHeader(framer *http2.Framer, sid uint32, headerFields []string, endStream bool) error {
  6511. if len(headerFields)%2 == 1 {
  6512. panic("odd number of kv args")
  6513. }
  6514. var buf bytes.Buffer
  6515. henc := hpack.NewEncoder(&buf)
  6516. for len(headerFields) > 0 {
  6517. k, v := headerFields[0], headerFields[1]
  6518. headerFields = headerFields[2:]
  6519. henc.WriteField(hpack.HeaderField{Name: k, Value: v})
  6520. }
  6521. return framer.WriteHeaders(http2.HeadersFrameParam{
  6522. StreamID: sid,
  6523. BlockFragment: buf.Bytes(),
  6524. EndStream: endStream,
  6525. EndHeaders: true,
  6526. })
  6527. }
  6528. func (s *httpServer) start(t *testing.T, lis net.Listener) {
  6529. // Launch an HTTP server to send back header.
  6530. go func() {
  6531. conn, err := lis.Accept()
  6532. if err != nil {
  6533. t.Errorf("Error accepting connection: %v", err)
  6534. return
  6535. }
  6536. defer conn.Close()
  6537. // Read preface sent by client.
  6538. if _, err = io.ReadFull(conn, make([]byte, len(http2.ClientPreface))); err != nil {
  6539. t.Errorf("Error at server-side while reading preface from client. Err: %v", err)
  6540. return
  6541. }
  6542. reader := bufio.NewReader(conn)
  6543. writer := bufio.NewWriter(conn)
  6544. framer := http2.NewFramer(writer, reader)
  6545. if err = framer.WriteSettingsAck(); err != nil {
  6546. t.Errorf("Error at server-side while sending Settings ack. Err: %v", err)
  6547. return
  6548. }
  6549. writer.Flush() // necessary since client is expecting preface before declaring connection fully setup.
  6550. var sid uint32
  6551. // Read frames until a header is received.
  6552. for {
  6553. frame, err := framer.ReadFrame()
  6554. if err != nil {
  6555. t.Errorf("Error at server-side while reading frame. Err: %v", err)
  6556. return
  6557. }
  6558. if hframe, ok := frame.(*http2.HeadersFrame); ok {
  6559. sid = hframe.Header().StreamID
  6560. break
  6561. }
  6562. }
  6563. for i, headers := range s.headerFields {
  6564. if err = s.writeHeader(framer, sid, headers, i == len(s.headerFields)-1); err != nil {
  6565. t.Errorf("Error at server-side while writing headers. Err: %v", err)
  6566. return
  6567. }
  6568. writer.Flush()
  6569. }
  6570. }()
  6571. }
  6572. func doHTTPHeaderTest(t *testing.T, errCode codes.Code, headerFields ...[]string) {
  6573. lis, err := net.Listen("tcp", "localhost:0")
  6574. if err != nil {
  6575. t.Fatalf("Failed to listen. Err: %v", err)
  6576. }
  6577. defer lis.Close()
  6578. server := &httpServer{
  6579. headerFields: headerFields,
  6580. }
  6581. server.start(t, lis)
  6582. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  6583. defer cancel()
  6584. cc, err := grpc.DialContext(ctx, lis.Addr().String(), grpc.WithInsecure())
  6585. if err != nil {
  6586. t.Fatalf("failed to dial due to err: %v", err)
  6587. }
  6588. defer cc.Close()
  6589. client := testpb.NewTestServiceClient(cc)
  6590. stream, err := client.FullDuplexCall(ctx)
  6591. if err != nil {
  6592. t.Fatalf("error creating stream due to err: %v", err)
  6593. }
  6594. if _, err := stream.Recv(); err == nil || status.Code(err) != errCode {
  6595. t.Fatalf("stream.Recv() = _, %v, want error code: %v", err, errCode)
  6596. }
  6597. }