end2end_test.go 215 KB

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