end2end_test.go 219 KB

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