server.go 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108
  1. /*
  2. *
  3. * Copyright 2014 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package grpc
  19. import (
  20. "context"
  21. "errors"
  22. "fmt"
  23. "io"
  24. "math"
  25. "net"
  26. "net/http"
  27. "reflect"
  28. "runtime"
  29. "strings"
  30. "sync"
  31. "sync/atomic"
  32. "time"
  33. "golang.org/x/net/trace"
  34. "google.golang.org/grpc/codes"
  35. "google.golang.org/grpc/credentials"
  36. "google.golang.org/grpc/encoding"
  37. "google.golang.org/grpc/encoding/proto"
  38. "google.golang.org/grpc/grpclog"
  39. "google.golang.org/grpc/internal"
  40. "google.golang.org/grpc/internal/binarylog"
  41. "google.golang.org/grpc/internal/channelz"
  42. "google.golang.org/grpc/internal/grpcsync"
  43. "google.golang.org/grpc/internal/grpcutil"
  44. "google.golang.org/grpc/internal/transport"
  45. "google.golang.org/grpc/keepalive"
  46. "google.golang.org/grpc/metadata"
  47. "google.golang.org/grpc/peer"
  48. "google.golang.org/grpc/stats"
  49. "google.golang.org/grpc/status"
  50. "google.golang.org/grpc/tap"
  51. )
  52. const (
  53. defaultServerMaxReceiveMessageSize = 1024 * 1024 * 4
  54. defaultServerMaxSendMessageSize = math.MaxInt32
  55. // Server transports are tracked in a map which is keyed on listener
  56. // address. For regular gRPC traffic, connections are accepted in Serve()
  57. // through a call to Accept(), and we use the actual listener address as key
  58. // when we add it to the map. But for connections received through
  59. // ServeHTTP(), we do not have a listener and hence use this dummy value.
  60. listenerAddressForServeHTTP = "listenerAddressForServeHTTP"
  61. )
  62. func init() {
  63. internal.GetServerCredentials = func(srv *Server) credentials.TransportCredentials {
  64. return srv.opts.creds
  65. }
  66. internal.DrainServerTransports = func(srv *Server, addr string) {
  67. srv.drainServerTransports(addr)
  68. }
  69. internal.AddGlobalServerOptions = func(opt ...ServerOption) {
  70. globalServerOptions = append(globalServerOptions, opt...)
  71. }
  72. internal.ClearGlobalServerOptions = func() {
  73. globalServerOptions = nil
  74. }
  75. internal.BinaryLogger = binaryLogger
  76. internal.JoinServerOptions = newJoinServerOption
  77. }
  78. var statusOK = status.New(codes.OK, "")
  79. var logger = grpclog.Component("core")
  80. type methodHandler func(srv any, ctx context.Context, dec func(any) error, interceptor UnaryServerInterceptor) (any, error)
  81. // MethodDesc represents an RPC service's method specification.
  82. type MethodDesc struct {
  83. MethodName string
  84. Handler methodHandler
  85. }
  86. // ServiceDesc represents an RPC service's specification.
  87. type ServiceDesc struct {
  88. ServiceName string
  89. // The pointer to the service interface. Used to check whether the user
  90. // provided implementation satisfies the interface requirements.
  91. HandlerType any
  92. Methods []MethodDesc
  93. Streams []StreamDesc
  94. Metadata any
  95. }
  96. // serviceInfo wraps information about a service. It is very similar to
  97. // ServiceDesc and is constructed from it for internal purposes.
  98. type serviceInfo struct {
  99. // Contains the implementation for the methods in this service.
  100. serviceImpl any
  101. methods map[string]*MethodDesc
  102. streams map[string]*StreamDesc
  103. mdata any
  104. }
  105. // Server is a gRPC server to serve RPC requests.
  106. type Server struct {
  107. opts serverOptions
  108. mu sync.Mutex // guards following
  109. lis map[net.Listener]bool
  110. // conns contains all active server transports. It is a map keyed on a
  111. // listener address with the value being the set of active transports
  112. // belonging to that listener.
  113. conns map[string]map[transport.ServerTransport]bool
  114. serve bool
  115. drain bool
  116. cv *sync.Cond // signaled when connections close for GracefulStop
  117. services map[string]*serviceInfo // service name -> service info
  118. events trace.EventLog
  119. quit *grpcsync.Event
  120. done *grpcsync.Event
  121. channelzRemoveOnce sync.Once
  122. serveWG sync.WaitGroup // counts active Serve goroutines for GracefulStop
  123. channelzID *channelz.Identifier
  124. czData *channelzData
  125. serverWorkerChannel chan func()
  126. }
  127. type serverOptions struct {
  128. creds credentials.TransportCredentials
  129. codec baseCodec
  130. cp Compressor
  131. dc Decompressor
  132. unaryInt UnaryServerInterceptor
  133. streamInt StreamServerInterceptor
  134. chainUnaryInts []UnaryServerInterceptor
  135. chainStreamInts []StreamServerInterceptor
  136. binaryLogger binarylog.Logger
  137. inTapHandle tap.ServerInHandle
  138. statsHandlers []stats.Handler
  139. maxConcurrentStreams uint32
  140. maxReceiveMessageSize int
  141. maxSendMessageSize int
  142. unknownStreamDesc *StreamDesc
  143. keepaliveParams keepalive.ServerParameters
  144. keepalivePolicy keepalive.EnforcementPolicy
  145. initialWindowSize int32
  146. initialConnWindowSize int32
  147. writeBufferSize int
  148. readBufferSize int
  149. sharedWriteBuffer bool
  150. connectionTimeout time.Duration
  151. maxHeaderListSize *uint32
  152. headerTableSize *uint32
  153. numServerWorkers uint32
  154. recvBufferPool SharedBufferPool
  155. }
  156. var defaultServerOptions = serverOptions{
  157. maxConcurrentStreams: math.MaxUint32,
  158. maxReceiveMessageSize: defaultServerMaxReceiveMessageSize,
  159. maxSendMessageSize: defaultServerMaxSendMessageSize,
  160. connectionTimeout: 120 * time.Second,
  161. writeBufferSize: defaultWriteBufSize,
  162. readBufferSize: defaultReadBufSize,
  163. recvBufferPool: nopBufferPool{},
  164. }
  165. var globalServerOptions []ServerOption
  166. // A ServerOption sets options such as credentials, codec and keepalive parameters, etc.
  167. type ServerOption interface {
  168. apply(*serverOptions)
  169. }
  170. // EmptyServerOption does not alter the server configuration. It can be embedded
  171. // in another structure to build custom server options.
  172. //
  173. // # Experimental
  174. //
  175. // Notice: This type is EXPERIMENTAL and may be changed or removed in a
  176. // later release.
  177. type EmptyServerOption struct{}
  178. func (EmptyServerOption) apply(*serverOptions) {}
  179. // funcServerOption wraps a function that modifies serverOptions into an
  180. // implementation of the ServerOption interface.
  181. type funcServerOption struct {
  182. f func(*serverOptions)
  183. }
  184. func (fdo *funcServerOption) apply(do *serverOptions) {
  185. fdo.f(do)
  186. }
  187. func newFuncServerOption(f func(*serverOptions)) *funcServerOption {
  188. return &funcServerOption{
  189. f: f,
  190. }
  191. }
  192. // joinServerOption provides a way to combine arbitrary number of server
  193. // options into one.
  194. type joinServerOption struct {
  195. opts []ServerOption
  196. }
  197. func (mdo *joinServerOption) apply(do *serverOptions) {
  198. for _, opt := range mdo.opts {
  199. opt.apply(do)
  200. }
  201. }
  202. func newJoinServerOption(opts ...ServerOption) ServerOption {
  203. return &joinServerOption{opts: opts}
  204. }
  205. // SharedWriteBuffer allows reusing per-connection transport write buffer.
  206. // If this option is set to true every connection will release the buffer after
  207. // flushing the data on the wire.
  208. //
  209. // # Experimental
  210. //
  211. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  212. // later release.
  213. func SharedWriteBuffer(val bool) ServerOption {
  214. return newFuncServerOption(func(o *serverOptions) {
  215. o.sharedWriteBuffer = val
  216. })
  217. }
  218. // WriteBufferSize determines how much data can be batched before doing a write
  219. // on the wire. The corresponding memory allocation for this buffer will be
  220. // twice the size to keep syscalls low. The default value for this buffer is
  221. // 32KB. Zero or negative values will disable the write buffer such that each
  222. // write will be on underlying connection.
  223. // Note: A Send call may not directly translate to a write.
  224. func WriteBufferSize(s int) ServerOption {
  225. return newFuncServerOption(func(o *serverOptions) {
  226. o.writeBufferSize = s
  227. })
  228. }
  229. // ReadBufferSize lets you set the size of read buffer, this determines how much
  230. // data can be read at most for one read syscall. The default value for this
  231. // buffer is 32KB. Zero or negative values will disable read buffer for a
  232. // connection so data framer can access the underlying conn directly.
  233. func ReadBufferSize(s int) ServerOption {
  234. return newFuncServerOption(func(o *serverOptions) {
  235. o.readBufferSize = s
  236. })
  237. }
  238. // InitialWindowSize returns a ServerOption that sets window size for stream.
  239. // The lower bound for window size is 64K and any value smaller than that will be ignored.
  240. func InitialWindowSize(s int32) ServerOption {
  241. return newFuncServerOption(func(o *serverOptions) {
  242. o.initialWindowSize = s
  243. })
  244. }
  245. // InitialConnWindowSize returns a ServerOption that sets window size for a connection.
  246. // The lower bound for window size is 64K and any value smaller than that will be ignored.
  247. func InitialConnWindowSize(s int32) ServerOption {
  248. return newFuncServerOption(func(o *serverOptions) {
  249. o.initialConnWindowSize = s
  250. })
  251. }
  252. // KeepaliveParams returns a ServerOption that sets keepalive and max-age parameters for the server.
  253. func KeepaliveParams(kp keepalive.ServerParameters) ServerOption {
  254. if kp.Time > 0 && kp.Time < internal.KeepaliveMinServerPingTime {
  255. logger.Warning("Adjusting keepalive ping interval to minimum period of 1s")
  256. kp.Time = internal.KeepaliveMinServerPingTime
  257. }
  258. return newFuncServerOption(func(o *serverOptions) {
  259. o.keepaliveParams = kp
  260. })
  261. }
  262. // KeepaliveEnforcementPolicy returns a ServerOption that sets keepalive enforcement policy for the server.
  263. func KeepaliveEnforcementPolicy(kep keepalive.EnforcementPolicy) ServerOption {
  264. return newFuncServerOption(func(o *serverOptions) {
  265. o.keepalivePolicy = kep
  266. })
  267. }
  268. // CustomCodec returns a ServerOption that sets a codec for message marshaling and unmarshaling.
  269. //
  270. // This will override any lookups by content-subtype for Codecs registered with RegisterCodec.
  271. //
  272. // Deprecated: register codecs using encoding.RegisterCodec. The server will
  273. // automatically use registered codecs based on the incoming requests' headers.
  274. // See also
  275. // https://github.com/grpc/grpc-go/blob/master/Documentation/encoding.md#using-a-codec.
  276. // Will be supported throughout 1.x.
  277. func CustomCodec(codec Codec) ServerOption {
  278. return newFuncServerOption(func(o *serverOptions) {
  279. o.codec = codec
  280. })
  281. }
  282. // ForceServerCodec returns a ServerOption that sets a codec for message
  283. // marshaling and unmarshaling.
  284. //
  285. // This will override any lookups by content-subtype for Codecs registered
  286. // with RegisterCodec.
  287. //
  288. // See Content-Type on
  289. // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
  290. // more details. Also see the documentation on RegisterCodec and
  291. // CallContentSubtype for more details on the interaction between encoding.Codec
  292. // and content-subtype.
  293. //
  294. // This function is provided for advanced users; prefer to register codecs
  295. // using encoding.RegisterCodec.
  296. // The server will automatically use registered codecs based on the incoming
  297. // requests' headers. See also
  298. // https://github.com/grpc/grpc-go/blob/master/Documentation/encoding.md#using-a-codec.
  299. // Will be supported throughout 1.x.
  300. //
  301. // # Experimental
  302. //
  303. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  304. // later release.
  305. func ForceServerCodec(codec encoding.Codec) ServerOption {
  306. return newFuncServerOption(func(o *serverOptions) {
  307. o.codec = codec
  308. })
  309. }
  310. // RPCCompressor returns a ServerOption that sets a compressor for outbound
  311. // messages. For backward compatibility, all outbound messages will be sent
  312. // using this compressor, regardless of incoming message compression. By
  313. // default, server messages will be sent using the same compressor with which
  314. // request messages were sent.
  315. //
  316. // Deprecated: use encoding.RegisterCompressor instead. Will be supported
  317. // throughout 1.x.
  318. func RPCCompressor(cp Compressor) ServerOption {
  319. return newFuncServerOption(func(o *serverOptions) {
  320. o.cp = cp
  321. })
  322. }
  323. // RPCDecompressor returns a ServerOption that sets a decompressor for inbound
  324. // messages. It has higher priority than decompressors registered via
  325. // encoding.RegisterCompressor.
  326. //
  327. // Deprecated: use encoding.RegisterCompressor instead. Will be supported
  328. // throughout 1.x.
  329. func RPCDecompressor(dc Decompressor) ServerOption {
  330. return newFuncServerOption(func(o *serverOptions) {
  331. o.dc = dc
  332. })
  333. }
  334. // MaxMsgSize returns a ServerOption to set the max message size in bytes the server can receive.
  335. // If this is not set, gRPC uses the default limit.
  336. //
  337. // Deprecated: use MaxRecvMsgSize instead. Will be supported throughout 1.x.
  338. func MaxMsgSize(m int) ServerOption {
  339. return MaxRecvMsgSize(m)
  340. }
  341. // MaxRecvMsgSize returns a ServerOption to set the max message size in bytes the server can receive.
  342. // If this is not set, gRPC uses the default 4MB.
  343. func MaxRecvMsgSize(m int) ServerOption {
  344. return newFuncServerOption(func(o *serverOptions) {
  345. o.maxReceiveMessageSize = m
  346. })
  347. }
  348. // MaxSendMsgSize returns a ServerOption to set the max message size in bytes the server can send.
  349. // If this is not set, gRPC uses the default `math.MaxInt32`.
  350. func MaxSendMsgSize(m int) ServerOption {
  351. return newFuncServerOption(func(o *serverOptions) {
  352. o.maxSendMessageSize = m
  353. })
  354. }
  355. // MaxConcurrentStreams returns a ServerOption that will apply a limit on the number
  356. // of concurrent streams to each ServerTransport.
  357. func MaxConcurrentStreams(n uint32) ServerOption {
  358. if n == 0 {
  359. n = math.MaxUint32
  360. }
  361. return newFuncServerOption(func(o *serverOptions) {
  362. o.maxConcurrentStreams = n
  363. })
  364. }
  365. // Creds returns a ServerOption that sets credentials for server connections.
  366. func Creds(c credentials.TransportCredentials) ServerOption {
  367. return newFuncServerOption(func(o *serverOptions) {
  368. o.creds = c
  369. })
  370. }
  371. // UnaryInterceptor returns a ServerOption that sets the UnaryServerInterceptor for the
  372. // server. Only one unary interceptor can be installed. The construction of multiple
  373. // interceptors (e.g., chaining) can be implemented at the caller.
  374. func UnaryInterceptor(i UnaryServerInterceptor) ServerOption {
  375. return newFuncServerOption(func(o *serverOptions) {
  376. if o.unaryInt != nil {
  377. panic("The unary server interceptor was already set and may not be reset.")
  378. }
  379. o.unaryInt = i
  380. })
  381. }
  382. // ChainUnaryInterceptor returns a ServerOption that specifies the chained interceptor
  383. // for unary RPCs. The first interceptor will be the outer most,
  384. // while the last interceptor will be the inner most wrapper around the real call.
  385. // All unary interceptors added by this method will be chained.
  386. func ChainUnaryInterceptor(interceptors ...UnaryServerInterceptor) ServerOption {
  387. return newFuncServerOption(func(o *serverOptions) {
  388. o.chainUnaryInts = append(o.chainUnaryInts, interceptors...)
  389. })
  390. }
  391. // StreamInterceptor returns a ServerOption that sets the StreamServerInterceptor for the
  392. // server. Only one stream interceptor can be installed.
  393. func StreamInterceptor(i StreamServerInterceptor) ServerOption {
  394. return newFuncServerOption(func(o *serverOptions) {
  395. if o.streamInt != nil {
  396. panic("The stream server interceptor was already set and may not be reset.")
  397. }
  398. o.streamInt = i
  399. })
  400. }
  401. // ChainStreamInterceptor returns a ServerOption that specifies the chained interceptor
  402. // for streaming RPCs. The first interceptor will be the outer most,
  403. // while the last interceptor will be the inner most wrapper around the real call.
  404. // All stream interceptors added by this method will be chained.
  405. func ChainStreamInterceptor(interceptors ...StreamServerInterceptor) ServerOption {
  406. return newFuncServerOption(func(o *serverOptions) {
  407. o.chainStreamInts = append(o.chainStreamInts, interceptors...)
  408. })
  409. }
  410. // InTapHandle returns a ServerOption that sets the tap handle for all the server
  411. // transport to be created. Only one can be installed.
  412. //
  413. // # Experimental
  414. //
  415. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  416. // later release.
  417. func InTapHandle(h tap.ServerInHandle) ServerOption {
  418. return newFuncServerOption(func(o *serverOptions) {
  419. if o.inTapHandle != nil {
  420. panic("The tap handle was already set and may not be reset.")
  421. }
  422. o.inTapHandle = h
  423. })
  424. }
  425. // StatsHandler returns a ServerOption that sets the stats handler for the server.
  426. func StatsHandler(h stats.Handler) ServerOption {
  427. return newFuncServerOption(func(o *serverOptions) {
  428. if h == nil {
  429. logger.Error("ignoring nil parameter in grpc.StatsHandler ServerOption")
  430. // Do not allow a nil stats handler, which would otherwise cause
  431. // panics.
  432. return
  433. }
  434. o.statsHandlers = append(o.statsHandlers, h)
  435. })
  436. }
  437. // binaryLogger returns a ServerOption that can set the binary logger for the
  438. // server.
  439. func binaryLogger(bl binarylog.Logger) ServerOption {
  440. return newFuncServerOption(func(o *serverOptions) {
  441. o.binaryLogger = bl
  442. })
  443. }
  444. // UnknownServiceHandler returns a ServerOption that allows for adding a custom
  445. // unknown service handler. The provided method is a bidi-streaming RPC service
  446. // handler that will be invoked instead of returning the "unimplemented" gRPC
  447. // error whenever a request is received for an unregistered service or method.
  448. // The handling function and stream interceptor (if set) have full access to
  449. // the ServerStream, including its Context.
  450. func UnknownServiceHandler(streamHandler StreamHandler) ServerOption {
  451. return newFuncServerOption(func(o *serverOptions) {
  452. o.unknownStreamDesc = &StreamDesc{
  453. StreamName: "unknown_service_handler",
  454. Handler: streamHandler,
  455. // We need to assume that the users of the streamHandler will want to use both.
  456. ClientStreams: true,
  457. ServerStreams: true,
  458. }
  459. })
  460. }
  461. // ConnectionTimeout returns a ServerOption that sets the timeout for
  462. // connection establishment (up to and including HTTP/2 handshaking) for all
  463. // new connections. If this is not set, the default is 120 seconds. A zero or
  464. // negative value will result in an immediate timeout.
  465. //
  466. // # Experimental
  467. //
  468. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  469. // later release.
  470. func ConnectionTimeout(d time.Duration) ServerOption {
  471. return newFuncServerOption(func(o *serverOptions) {
  472. o.connectionTimeout = d
  473. })
  474. }
  475. // MaxHeaderListSize returns a ServerOption that sets the max (uncompressed) size
  476. // of header list that the server is prepared to accept.
  477. func MaxHeaderListSize(s uint32) ServerOption {
  478. return newFuncServerOption(func(o *serverOptions) {
  479. o.maxHeaderListSize = &s
  480. })
  481. }
  482. // HeaderTableSize returns a ServerOption that sets the size of dynamic
  483. // header table for stream.
  484. //
  485. // # Experimental
  486. //
  487. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  488. // later release.
  489. func HeaderTableSize(s uint32) ServerOption {
  490. return newFuncServerOption(func(o *serverOptions) {
  491. o.headerTableSize = &s
  492. })
  493. }
  494. // NumStreamWorkers returns a ServerOption that sets the number of worker
  495. // goroutines that should be used to process incoming streams. Setting this to
  496. // zero (default) will disable workers and spawn a new goroutine for each
  497. // stream.
  498. //
  499. // # Experimental
  500. //
  501. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  502. // later release.
  503. func NumStreamWorkers(numServerWorkers uint32) ServerOption {
  504. // TODO: If/when this API gets stabilized (i.e. stream workers become the
  505. // only way streams are processed), change the behavior of the zero value to
  506. // a sane default. Preliminary experiments suggest that a value equal to the
  507. // number of CPUs available is most performant; requires thorough testing.
  508. return newFuncServerOption(func(o *serverOptions) {
  509. o.numServerWorkers = numServerWorkers
  510. })
  511. }
  512. // RecvBufferPool returns a ServerOption that configures the server
  513. // to use the provided shared buffer pool for parsing incoming messages. Depending
  514. // on the application's workload, this could result in reduced memory allocation.
  515. //
  516. // If you are unsure about how to implement a memory pool but want to utilize one,
  517. // begin with grpc.NewSharedBufferPool.
  518. //
  519. // Note: The shared buffer pool feature will not be active if any of the following
  520. // options are used: StatsHandler, EnableTracing, or binary logging. In such
  521. // cases, the shared buffer pool will be ignored.
  522. //
  523. // # Experimental
  524. //
  525. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  526. // later release.
  527. func RecvBufferPool(bufferPool SharedBufferPool) ServerOption {
  528. return newFuncServerOption(func(o *serverOptions) {
  529. o.recvBufferPool = bufferPool
  530. })
  531. }
  532. // serverWorkerResetThreshold defines how often the stack must be reset. Every
  533. // N requests, by spawning a new goroutine in its place, a worker can reset its
  534. // stack so that large stacks don't live in memory forever. 2^16 should allow
  535. // each goroutine stack to live for at least a few seconds in a typical
  536. // workload (assuming a QPS of a few thousand requests/sec).
  537. const serverWorkerResetThreshold = 1 << 16
  538. // serverWorkers blocks on a *transport.Stream channel forever and waits for
  539. // data to be fed by serveStreams. This allows multiple requests to be
  540. // processed by the same goroutine, removing the need for expensive stack
  541. // re-allocations (see the runtime.morestack problem [1]).
  542. //
  543. // [1] https://github.com/golang/go/issues/18138
  544. func (s *Server) serverWorker() {
  545. for completed := 0; completed < serverWorkerResetThreshold; completed++ {
  546. f, ok := <-s.serverWorkerChannel
  547. if !ok {
  548. return
  549. }
  550. f()
  551. }
  552. go s.serverWorker()
  553. }
  554. // initServerWorkers creates worker goroutines and a channel to process incoming
  555. // connections to reduce the time spent overall on runtime.morestack.
  556. func (s *Server) initServerWorkers() {
  557. s.serverWorkerChannel = make(chan func())
  558. for i := uint32(0); i < s.opts.numServerWorkers; i++ {
  559. go s.serverWorker()
  560. }
  561. }
  562. func (s *Server) stopServerWorkers() {
  563. close(s.serverWorkerChannel)
  564. }
  565. // NewServer creates a gRPC server which has no service registered and has not
  566. // started to accept requests yet.
  567. func NewServer(opt ...ServerOption) *Server {
  568. opts := defaultServerOptions
  569. for _, o := range globalServerOptions {
  570. o.apply(&opts)
  571. }
  572. for _, o := range opt {
  573. o.apply(&opts)
  574. }
  575. s := &Server{
  576. lis: make(map[net.Listener]bool),
  577. opts: opts,
  578. conns: make(map[string]map[transport.ServerTransport]bool),
  579. services: make(map[string]*serviceInfo),
  580. quit: grpcsync.NewEvent(),
  581. done: grpcsync.NewEvent(),
  582. czData: new(channelzData),
  583. }
  584. chainUnaryServerInterceptors(s)
  585. chainStreamServerInterceptors(s)
  586. s.cv = sync.NewCond(&s.mu)
  587. if EnableTracing {
  588. _, file, line, _ := runtime.Caller(1)
  589. s.events = trace.NewEventLog("grpc.Server", fmt.Sprintf("%s:%d", file, line))
  590. }
  591. if s.opts.numServerWorkers > 0 {
  592. s.initServerWorkers()
  593. }
  594. s.channelzID = channelz.RegisterServer(&channelzServer{s}, "")
  595. channelz.Info(logger, s.channelzID, "Server created")
  596. return s
  597. }
  598. // printf records an event in s's event log, unless s has been stopped.
  599. // REQUIRES s.mu is held.
  600. func (s *Server) printf(format string, a ...any) {
  601. if s.events != nil {
  602. s.events.Printf(format, a...)
  603. }
  604. }
  605. // errorf records an error in s's event log, unless s has been stopped.
  606. // REQUIRES s.mu is held.
  607. func (s *Server) errorf(format string, a ...any) {
  608. if s.events != nil {
  609. s.events.Errorf(format, a...)
  610. }
  611. }
  612. // ServiceRegistrar wraps a single method that supports service registration. It
  613. // enables users to pass concrete types other than grpc.Server to the service
  614. // registration methods exported by the IDL generated code.
  615. type ServiceRegistrar interface {
  616. // RegisterService registers a service and its implementation to the
  617. // concrete type implementing this interface. It may not be called
  618. // once the server has started serving.
  619. // desc describes the service and its methods and handlers. impl is the
  620. // service implementation which is passed to the method handlers.
  621. RegisterService(desc *ServiceDesc, impl any)
  622. }
  623. // RegisterService registers a service and its implementation to the gRPC
  624. // server. It is called from the IDL generated code. This must be called before
  625. // invoking Serve. If ss is non-nil (for legacy code), its type is checked to
  626. // ensure it implements sd.HandlerType.
  627. func (s *Server) RegisterService(sd *ServiceDesc, ss any) {
  628. if ss != nil {
  629. ht := reflect.TypeOf(sd.HandlerType).Elem()
  630. st := reflect.TypeOf(ss)
  631. if !st.Implements(ht) {
  632. logger.Fatalf("grpc: Server.RegisterService found the handler of type %v that does not satisfy %v", st, ht)
  633. }
  634. }
  635. s.register(sd, ss)
  636. }
  637. func (s *Server) register(sd *ServiceDesc, ss any) {
  638. s.mu.Lock()
  639. defer s.mu.Unlock()
  640. s.printf("RegisterService(%q)", sd.ServiceName)
  641. if s.serve {
  642. logger.Fatalf("grpc: Server.RegisterService after Server.Serve for %q", sd.ServiceName)
  643. }
  644. if _, ok := s.services[sd.ServiceName]; ok {
  645. logger.Fatalf("grpc: Server.RegisterService found duplicate service registration for %q", sd.ServiceName)
  646. }
  647. info := &serviceInfo{
  648. serviceImpl: ss,
  649. methods: make(map[string]*MethodDesc),
  650. streams: make(map[string]*StreamDesc),
  651. mdata: sd.Metadata,
  652. }
  653. for i := range sd.Methods {
  654. d := &sd.Methods[i]
  655. info.methods[d.MethodName] = d
  656. }
  657. for i := range sd.Streams {
  658. d := &sd.Streams[i]
  659. info.streams[d.StreamName] = d
  660. }
  661. s.services[sd.ServiceName] = info
  662. }
  663. // MethodInfo contains the information of an RPC including its method name and type.
  664. type MethodInfo struct {
  665. // Name is the method name only, without the service name or package name.
  666. Name string
  667. // IsClientStream indicates whether the RPC is a client streaming RPC.
  668. IsClientStream bool
  669. // IsServerStream indicates whether the RPC is a server streaming RPC.
  670. IsServerStream bool
  671. }
  672. // ServiceInfo contains unary RPC method info, streaming RPC method info and metadata for a service.
  673. type ServiceInfo struct {
  674. Methods []MethodInfo
  675. // Metadata is the metadata specified in ServiceDesc when registering service.
  676. Metadata any
  677. }
  678. // GetServiceInfo returns a map from service names to ServiceInfo.
  679. // Service names include the package names, in the form of <package>.<service>.
  680. func (s *Server) GetServiceInfo() map[string]ServiceInfo {
  681. ret := make(map[string]ServiceInfo)
  682. for n, srv := range s.services {
  683. methods := make([]MethodInfo, 0, len(srv.methods)+len(srv.streams))
  684. for m := range srv.methods {
  685. methods = append(methods, MethodInfo{
  686. Name: m,
  687. IsClientStream: false,
  688. IsServerStream: false,
  689. })
  690. }
  691. for m, d := range srv.streams {
  692. methods = append(methods, MethodInfo{
  693. Name: m,
  694. IsClientStream: d.ClientStreams,
  695. IsServerStream: d.ServerStreams,
  696. })
  697. }
  698. ret[n] = ServiceInfo{
  699. Methods: methods,
  700. Metadata: srv.mdata,
  701. }
  702. }
  703. return ret
  704. }
  705. // ErrServerStopped indicates that the operation is now illegal because of
  706. // the server being stopped.
  707. var ErrServerStopped = errors.New("grpc: the server has been stopped")
  708. type listenSocket struct {
  709. net.Listener
  710. channelzID *channelz.Identifier
  711. }
  712. func (l *listenSocket) ChannelzMetric() *channelz.SocketInternalMetric {
  713. return &channelz.SocketInternalMetric{
  714. SocketOptions: channelz.GetSocketOption(l.Listener),
  715. LocalAddr: l.Listener.Addr(),
  716. }
  717. }
  718. func (l *listenSocket) Close() error {
  719. err := l.Listener.Close()
  720. channelz.RemoveEntry(l.channelzID)
  721. channelz.Info(logger, l.channelzID, "ListenSocket deleted")
  722. return err
  723. }
  724. // Serve accepts incoming connections on the listener lis, creating a new
  725. // ServerTransport and service goroutine for each. The service goroutines
  726. // read gRPC requests and then call the registered handlers to reply to them.
  727. // Serve returns when lis.Accept fails with fatal errors. lis will be closed when
  728. // this method returns.
  729. // Serve will return a non-nil error unless Stop or GracefulStop is called.
  730. func (s *Server) Serve(lis net.Listener) error {
  731. s.mu.Lock()
  732. s.printf("serving")
  733. s.serve = true
  734. if s.lis == nil {
  735. // Serve called after Stop or GracefulStop.
  736. s.mu.Unlock()
  737. lis.Close()
  738. return ErrServerStopped
  739. }
  740. s.serveWG.Add(1)
  741. defer func() {
  742. s.serveWG.Done()
  743. if s.quit.HasFired() {
  744. // Stop or GracefulStop called; block until done and return nil.
  745. <-s.done.Done()
  746. }
  747. }()
  748. ls := &listenSocket{Listener: lis}
  749. s.lis[ls] = true
  750. defer func() {
  751. s.mu.Lock()
  752. if s.lis != nil && s.lis[ls] {
  753. ls.Close()
  754. delete(s.lis, ls)
  755. }
  756. s.mu.Unlock()
  757. }()
  758. var err error
  759. ls.channelzID, err = channelz.RegisterListenSocket(ls, s.channelzID, lis.Addr().String())
  760. if err != nil {
  761. s.mu.Unlock()
  762. return err
  763. }
  764. s.mu.Unlock()
  765. channelz.Info(logger, ls.channelzID, "ListenSocket created")
  766. var tempDelay time.Duration // how long to sleep on accept failure
  767. for {
  768. rawConn, err := lis.Accept()
  769. if err != nil {
  770. if ne, ok := err.(interface {
  771. Temporary() bool
  772. }); ok && ne.Temporary() {
  773. if tempDelay == 0 {
  774. tempDelay = 5 * time.Millisecond
  775. } else {
  776. tempDelay *= 2
  777. }
  778. if max := 1 * time.Second; tempDelay > max {
  779. tempDelay = max
  780. }
  781. s.mu.Lock()
  782. s.printf("Accept error: %v; retrying in %v", err, tempDelay)
  783. s.mu.Unlock()
  784. timer := time.NewTimer(tempDelay)
  785. select {
  786. case <-timer.C:
  787. case <-s.quit.Done():
  788. timer.Stop()
  789. return nil
  790. }
  791. continue
  792. }
  793. s.mu.Lock()
  794. s.printf("done serving; Accept = %v", err)
  795. s.mu.Unlock()
  796. if s.quit.HasFired() {
  797. return nil
  798. }
  799. return err
  800. }
  801. tempDelay = 0
  802. // Start a new goroutine to deal with rawConn so we don't stall this Accept
  803. // loop goroutine.
  804. //
  805. // Make sure we account for the goroutine so GracefulStop doesn't nil out
  806. // s.conns before this conn can be added.
  807. s.serveWG.Add(1)
  808. go func() {
  809. s.handleRawConn(lis.Addr().String(), rawConn)
  810. s.serveWG.Done()
  811. }()
  812. }
  813. }
  814. // handleRawConn forks a goroutine to handle a just-accepted connection that
  815. // has not had any I/O performed on it yet.
  816. func (s *Server) handleRawConn(lisAddr string, rawConn net.Conn) {
  817. if s.quit.HasFired() {
  818. rawConn.Close()
  819. return
  820. }
  821. rawConn.SetDeadline(time.Now().Add(s.opts.connectionTimeout))
  822. // Finish handshaking (HTTP2)
  823. st := s.newHTTP2Transport(rawConn)
  824. rawConn.SetDeadline(time.Time{})
  825. if st == nil {
  826. return
  827. }
  828. if !s.addConn(lisAddr, st) {
  829. return
  830. }
  831. go func() {
  832. s.serveStreams(st)
  833. s.removeConn(lisAddr, st)
  834. }()
  835. }
  836. func (s *Server) drainServerTransports(addr string) {
  837. s.mu.Lock()
  838. conns := s.conns[addr]
  839. for st := range conns {
  840. st.Drain("")
  841. }
  842. s.mu.Unlock()
  843. }
  844. // newHTTP2Transport sets up a http/2 transport (using the
  845. // gRPC http2 server transport in transport/http2_server.go).
  846. func (s *Server) newHTTP2Transport(c net.Conn) transport.ServerTransport {
  847. config := &transport.ServerConfig{
  848. MaxStreams: s.opts.maxConcurrentStreams,
  849. ConnectionTimeout: s.opts.connectionTimeout,
  850. Credentials: s.opts.creds,
  851. InTapHandle: s.opts.inTapHandle,
  852. StatsHandlers: s.opts.statsHandlers,
  853. KeepaliveParams: s.opts.keepaliveParams,
  854. KeepalivePolicy: s.opts.keepalivePolicy,
  855. InitialWindowSize: s.opts.initialWindowSize,
  856. InitialConnWindowSize: s.opts.initialConnWindowSize,
  857. WriteBufferSize: s.opts.writeBufferSize,
  858. ReadBufferSize: s.opts.readBufferSize,
  859. SharedWriteBuffer: s.opts.sharedWriteBuffer,
  860. ChannelzParentID: s.channelzID,
  861. MaxHeaderListSize: s.opts.maxHeaderListSize,
  862. HeaderTableSize: s.opts.headerTableSize,
  863. }
  864. st, err := transport.NewServerTransport(c, config)
  865. if err != nil {
  866. s.mu.Lock()
  867. s.errorf("NewServerTransport(%q) failed: %v", c.RemoteAddr(), err)
  868. s.mu.Unlock()
  869. // ErrConnDispatched means that the connection was dispatched away from
  870. // gRPC; those connections should be left open.
  871. if err != credentials.ErrConnDispatched {
  872. // Don't log on ErrConnDispatched and io.EOF to prevent log spam.
  873. if err != io.EOF {
  874. channelz.Info(logger, s.channelzID, "grpc: Server.Serve failed to create ServerTransport: ", err)
  875. }
  876. c.Close()
  877. }
  878. return nil
  879. }
  880. return st
  881. }
  882. func (s *Server) serveStreams(st transport.ServerTransport) {
  883. defer st.Close(errors.New("finished serving streams for the server transport"))
  884. var wg sync.WaitGroup
  885. streamQuota := newHandlerQuota(s.opts.maxConcurrentStreams)
  886. st.HandleStreams(func(stream *transport.Stream) {
  887. wg.Add(1)
  888. streamQuota.acquire()
  889. f := func() {
  890. defer streamQuota.release()
  891. defer wg.Done()
  892. s.handleStream(st, stream)
  893. }
  894. if s.opts.numServerWorkers > 0 {
  895. select {
  896. case s.serverWorkerChannel <- f:
  897. return
  898. default:
  899. // If all stream workers are busy, fallback to the default code path.
  900. }
  901. }
  902. go f()
  903. })
  904. wg.Wait()
  905. }
  906. var _ http.Handler = (*Server)(nil)
  907. // ServeHTTP implements the Go standard library's http.Handler
  908. // interface by responding to the gRPC request r, by looking up
  909. // the requested gRPC method in the gRPC server s.
  910. //
  911. // The provided HTTP request must have arrived on an HTTP/2
  912. // connection. When using the Go standard library's server,
  913. // practically this means that the Request must also have arrived
  914. // over TLS.
  915. //
  916. // To share one port (such as 443 for https) between gRPC and an
  917. // existing http.Handler, use a root http.Handler such as:
  918. //
  919. // if r.ProtoMajor == 2 && strings.HasPrefix(
  920. // r.Header.Get("Content-Type"), "application/grpc") {
  921. // grpcServer.ServeHTTP(w, r)
  922. // } else {
  923. // yourMux.ServeHTTP(w, r)
  924. // }
  925. //
  926. // Note that ServeHTTP uses Go's HTTP/2 server implementation which is totally
  927. // separate from grpc-go's HTTP/2 server. Performance and features may vary
  928. // between the two paths. ServeHTTP does not support some gRPC features
  929. // available through grpc-go's HTTP/2 server.
  930. //
  931. // # Experimental
  932. //
  933. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  934. // later release.
  935. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  936. st, err := transport.NewServerHandlerTransport(w, r, s.opts.statsHandlers)
  937. if err != nil {
  938. // Errors returned from transport.NewServerHandlerTransport have
  939. // already been written to w.
  940. return
  941. }
  942. if !s.addConn(listenerAddressForServeHTTP, st) {
  943. return
  944. }
  945. defer s.removeConn(listenerAddressForServeHTTP, st)
  946. s.serveStreams(st)
  947. }
  948. func (s *Server) addConn(addr string, st transport.ServerTransport) bool {
  949. s.mu.Lock()
  950. defer s.mu.Unlock()
  951. if s.conns == nil {
  952. st.Close(errors.New("Server.addConn called when server has already been stopped"))
  953. return false
  954. }
  955. if s.drain {
  956. // Transport added after we drained our existing conns: drain it
  957. // immediately.
  958. st.Drain("")
  959. }
  960. if s.conns[addr] == nil {
  961. // Create a map entry if this is the first connection on this listener.
  962. s.conns[addr] = make(map[transport.ServerTransport]bool)
  963. }
  964. s.conns[addr][st] = true
  965. return true
  966. }
  967. func (s *Server) removeConn(addr string, st transport.ServerTransport) {
  968. s.mu.Lock()
  969. defer s.mu.Unlock()
  970. conns := s.conns[addr]
  971. if conns != nil {
  972. delete(conns, st)
  973. if len(conns) == 0 {
  974. // If the last connection for this address is being removed, also
  975. // remove the map entry corresponding to the address. This is used
  976. // in GracefulStop() when waiting for all connections to be closed.
  977. delete(s.conns, addr)
  978. }
  979. s.cv.Broadcast()
  980. }
  981. }
  982. func (s *Server) channelzMetric() *channelz.ServerInternalMetric {
  983. return &channelz.ServerInternalMetric{
  984. CallsStarted: atomic.LoadInt64(&s.czData.callsStarted),
  985. CallsSucceeded: atomic.LoadInt64(&s.czData.callsSucceeded),
  986. CallsFailed: atomic.LoadInt64(&s.czData.callsFailed),
  987. LastCallStartedTimestamp: time.Unix(0, atomic.LoadInt64(&s.czData.lastCallStartedTime)),
  988. }
  989. }
  990. func (s *Server) incrCallsStarted() {
  991. atomic.AddInt64(&s.czData.callsStarted, 1)
  992. atomic.StoreInt64(&s.czData.lastCallStartedTime, time.Now().UnixNano())
  993. }
  994. func (s *Server) incrCallsSucceeded() {
  995. atomic.AddInt64(&s.czData.callsSucceeded, 1)
  996. }
  997. func (s *Server) incrCallsFailed() {
  998. atomic.AddInt64(&s.czData.callsFailed, 1)
  999. }
  1000. func (s *Server) sendResponse(ctx context.Context, t transport.ServerTransport, stream *transport.Stream, msg any, cp Compressor, opts *transport.Options, comp encoding.Compressor) error {
  1001. data, err := encode(s.getCodec(stream.ContentSubtype()), msg)
  1002. if err != nil {
  1003. channelz.Error(logger, s.channelzID, "grpc: server failed to encode response: ", err)
  1004. return err
  1005. }
  1006. compData, err := compress(data, cp, comp)
  1007. if err != nil {
  1008. channelz.Error(logger, s.channelzID, "grpc: server failed to compress response: ", err)
  1009. return err
  1010. }
  1011. hdr, payload := msgHeader(data, compData)
  1012. // TODO(dfawley): should we be checking len(data) instead?
  1013. if len(payload) > s.opts.maxSendMessageSize {
  1014. return status.Errorf(codes.ResourceExhausted, "grpc: trying to send message larger than max (%d vs. %d)", len(payload), s.opts.maxSendMessageSize)
  1015. }
  1016. err = t.Write(stream, hdr, payload, opts)
  1017. if err == nil {
  1018. for _, sh := range s.opts.statsHandlers {
  1019. sh.HandleRPC(ctx, outPayload(false, msg, data, payload, time.Now()))
  1020. }
  1021. }
  1022. return err
  1023. }
  1024. // chainUnaryServerInterceptors chains all unary server interceptors into one.
  1025. func chainUnaryServerInterceptors(s *Server) {
  1026. // Prepend opts.unaryInt to the chaining interceptors if it exists, since unaryInt will
  1027. // be executed before any other chained interceptors.
  1028. interceptors := s.opts.chainUnaryInts
  1029. if s.opts.unaryInt != nil {
  1030. interceptors = append([]UnaryServerInterceptor{s.opts.unaryInt}, s.opts.chainUnaryInts...)
  1031. }
  1032. var chainedInt UnaryServerInterceptor
  1033. if len(interceptors) == 0 {
  1034. chainedInt = nil
  1035. } else if len(interceptors) == 1 {
  1036. chainedInt = interceptors[0]
  1037. } else {
  1038. chainedInt = chainUnaryInterceptors(interceptors)
  1039. }
  1040. s.opts.unaryInt = chainedInt
  1041. }
  1042. func chainUnaryInterceptors(interceptors []UnaryServerInterceptor) UnaryServerInterceptor {
  1043. return func(ctx context.Context, req any, info *UnaryServerInfo, handler UnaryHandler) (any, error) {
  1044. return interceptors[0](ctx, req, info, getChainUnaryHandler(interceptors, 0, info, handler))
  1045. }
  1046. }
  1047. func getChainUnaryHandler(interceptors []UnaryServerInterceptor, curr int, info *UnaryServerInfo, finalHandler UnaryHandler) UnaryHandler {
  1048. if curr == len(interceptors)-1 {
  1049. return finalHandler
  1050. }
  1051. return func(ctx context.Context, req any) (any, error) {
  1052. return interceptors[curr+1](ctx, req, info, getChainUnaryHandler(interceptors, curr+1, info, finalHandler))
  1053. }
  1054. }
  1055. func (s *Server) processUnaryRPC(ctx context.Context, t transport.ServerTransport, stream *transport.Stream, info *serviceInfo, md *MethodDesc, trInfo *traceInfo) (err error) {
  1056. shs := s.opts.statsHandlers
  1057. if len(shs) != 0 || trInfo != nil || channelz.IsOn() {
  1058. if channelz.IsOn() {
  1059. s.incrCallsStarted()
  1060. }
  1061. var statsBegin *stats.Begin
  1062. for _, sh := range shs {
  1063. beginTime := time.Now()
  1064. statsBegin = &stats.Begin{
  1065. BeginTime: beginTime,
  1066. IsClientStream: false,
  1067. IsServerStream: false,
  1068. }
  1069. sh.HandleRPC(ctx, statsBegin)
  1070. }
  1071. if trInfo != nil {
  1072. trInfo.tr.LazyLog(&trInfo.firstLine, false)
  1073. }
  1074. // The deferred error handling for tracing, stats handler and channelz are
  1075. // combined into one function to reduce stack usage -- a defer takes ~56-64
  1076. // bytes on the stack, so overflowing the stack will require a stack
  1077. // re-allocation, which is expensive.
  1078. //
  1079. // To maintain behavior similar to separate deferred statements, statements
  1080. // should be executed in the reverse order. That is, tracing first, stats
  1081. // handler second, and channelz last. Note that panics *within* defers will
  1082. // lead to different behavior, but that's an acceptable compromise; that
  1083. // would be undefined behavior territory anyway.
  1084. defer func() {
  1085. if trInfo != nil {
  1086. if err != nil && err != io.EOF {
  1087. trInfo.tr.LazyLog(&fmtStringer{"%v", []any{err}}, true)
  1088. trInfo.tr.SetError()
  1089. }
  1090. trInfo.tr.Finish()
  1091. }
  1092. for _, sh := range shs {
  1093. end := &stats.End{
  1094. BeginTime: statsBegin.BeginTime,
  1095. EndTime: time.Now(),
  1096. }
  1097. if err != nil && err != io.EOF {
  1098. end.Error = toRPCErr(err)
  1099. }
  1100. sh.HandleRPC(ctx, end)
  1101. }
  1102. if channelz.IsOn() {
  1103. if err != nil && err != io.EOF {
  1104. s.incrCallsFailed()
  1105. } else {
  1106. s.incrCallsSucceeded()
  1107. }
  1108. }
  1109. }()
  1110. }
  1111. var binlogs []binarylog.MethodLogger
  1112. if ml := binarylog.GetMethodLogger(stream.Method()); ml != nil {
  1113. binlogs = append(binlogs, ml)
  1114. }
  1115. if s.opts.binaryLogger != nil {
  1116. if ml := s.opts.binaryLogger.GetMethodLogger(stream.Method()); ml != nil {
  1117. binlogs = append(binlogs, ml)
  1118. }
  1119. }
  1120. if len(binlogs) != 0 {
  1121. md, _ := metadata.FromIncomingContext(ctx)
  1122. logEntry := &binarylog.ClientHeader{
  1123. Header: md,
  1124. MethodName: stream.Method(),
  1125. PeerAddr: nil,
  1126. }
  1127. if deadline, ok := ctx.Deadline(); ok {
  1128. logEntry.Timeout = time.Until(deadline)
  1129. if logEntry.Timeout < 0 {
  1130. logEntry.Timeout = 0
  1131. }
  1132. }
  1133. if a := md[":authority"]; len(a) > 0 {
  1134. logEntry.Authority = a[0]
  1135. }
  1136. if peer, ok := peer.FromContext(ctx); ok {
  1137. logEntry.PeerAddr = peer.Addr
  1138. }
  1139. for _, binlog := range binlogs {
  1140. binlog.Log(ctx, logEntry)
  1141. }
  1142. }
  1143. // comp and cp are used for compression. decomp and dc are used for
  1144. // decompression. If comp and decomp are both set, they are the same;
  1145. // however they are kept separate to ensure that at most one of the
  1146. // compressor/decompressor variable pairs are set for use later.
  1147. var comp, decomp encoding.Compressor
  1148. var cp Compressor
  1149. var dc Decompressor
  1150. var sendCompressorName string
  1151. // If dc is set and matches the stream's compression, use it. Otherwise, try
  1152. // to find a matching registered compressor for decomp.
  1153. if rc := stream.RecvCompress(); s.opts.dc != nil && s.opts.dc.Type() == rc {
  1154. dc = s.opts.dc
  1155. } else if rc != "" && rc != encoding.Identity {
  1156. decomp = encoding.GetCompressor(rc)
  1157. if decomp == nil {
  1158. st := status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", rc)
  1159. t.WriteStatus(stream, st)
  1160. return st.Err()
  1161. }
  1162. }
  1163. // If cp is set, use it. Otherwise, attempt to compress the response using
  1164. // the incoming message compression method.
  1165. //
  1166. // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686.
  1167. if s.opts.cp != nil {
  1168. cp = s.opts.cp
  1169. sendCompressorName = cp.Type()
  1170. } else if rc := stream.RecvCompress(); rc != "" && rc != encoding.Identity {
  1171. // Legacy compressor not specified; attempt to respond with same encoding.
  1172. comp = encoding.GetCompressor(rc)
  1173. if comp != nil {
  1174. sendCompressorName = comp.Name()
  1175. }
  1176. }
  1177. if sendCompressorName != "" {
  1178. if err := stream.SetSendCompress(sendCompressorName); err != nil {
  1179. return status.Errorf(codes.Internal, "grpc: failed to set send compressor: %v", err)
  1180. }
  1181. }
  1182. var payInfo *payloadInfo
  1183. if len(shs) != 0 || len(binlogs) != 0 {
  1184. payInfo = &payloadInfo{}
  1185. }
  1186. d, err := recvAndDecompress(&parser{r: stream, recvBufferPool: s.opts.recvBufferPool}, stream, dc, s.opts.maxReceiveMessageSize, payInfo, decomp)
  1187. if err != nil {
  1188. if e := t.WriteStatus(stream, status.Convert(err)); e != nil {
  1189. channelz.Warningf(logger, s.channelzID, "grpc: Server.processUnaryRPC failed to write status: %v", e)
  1190. }
  1191. return err
  1192. }
  1193. if channelz.IsOn() {
  1194. t.IncrMsgRecv()
  1195. }
  1196. df := func(v any) error {
  1197. if err := s.getCodec(stream.ContentSubtype()).Unmarshal(d, v); err != nil {
  1198. return status.Errorf(codes.Internal, "grpc: error unmarshalling request: %v", err)
  1199. }
  1200. for _, sh := range shs {
  1201. sh.HandleRPC(ctx, &stats.InPayload{
  1202. RecvTime: time.Now(),
  1203. Payload: v,
  1204. Length: len(d),
  1205. WireLength: payInfo.compressedLength + headerLen,
  1206. CompressedLength: payInfo.compressedLength,
  1207. Data: d,
  1208. })
  1209. }
  1210. if len(binlogs) != 0 {
  1211. cm := &binarylog.ClientMessage{
  1212. Message: d,
  1213. }
  1214. for _, binlog := range binlogs {
  1215. binlog.Log(ctx, cm)
  1216. }
  1217. }
  1218. if trInfo != nil {
  1219. trInfo.tr.LazyLog(&payload{sent: false, msg: v}, true)
  1220. }
  1221. return nil
  1222. }
  1223. ctx = NewContextWithServerTransportStream(ctx, stream)
  1224. reply, appErr := md.Handler(info.serviceImpl, ctx, df, s.opts.unaryInt)
  1225. if appErr != nil {
  1226. appStatus, ok := status.FromError(appErr)
  1227. if !ok {
  1228. // Convert non-status application error to a status error with code
  1229. // Unknown, but handle context errors specifically.
  1230. appStatus = status.FromContextError(appErr)
  1231. appErr = appStatus.Err()
  1232. }
  1233. if trInfo != nil {
  1234. trInfo.tr.LazyLog(stringer(appStatus.Message()), true)
  1235. trInfo.tr.SetError()
  1236. }
  1237. if e := t.WriteStatus(stream, appStatus); e != nil {
  1238. channelz.Warningf(logger, s.channelzID, "grpc: Server.processUnaryRPC failed to write status: %v", e)
  1239. }
  1240. if len(binlogs) != 0 {
  1241. if h, _ := stream.Header(); h.Len() > 0 {
  1242. // Only log serverHeader if there was header. Otherwise it can
  1243. // be trailer only.
  1244. sh := &binarylog.ServerHeader{
  1245. Header: h,
  1246. }
  1247. for _, binlog := range binlogs {
  1248. binlog.Log(ctx, sh)
  1249. }
  1250. }
  1251. st := &binarylog.ServerTrailer{
  1252. Trailer: stream.Trailer(),
  1253. Err: appErr,
  1254. }
  1255. for _, binlog := range binlogs {
  1256. binlog.Log(ctx, st)
  1257. }
  1258. }
  1259. return appErr
  1260. }
  1261. if trInfo != nil {
  1262. trInfo.tr.LazyLog(stringer("OK"), false)
  1263. }
  1264. opts := &transport.Options{Last: true}
  1265. // Server handler could have set new compressor by calling SetSendCompressor.
  1266. // In case it is set, we need to use it for compressing outbound message.
  1267. if stream.SendCompress() != sendCompressorName {
  1268. comp = encoding.GetCompressor(stream.SendCompress())
  1269. }
  1270. if err := s.sendResponse(ctx, t, stream, reply, cp, opts, comp); err != nil {
  1271. if err == io.EOF {
  1272. // The entire stream is done (for unary RPC only).
  1273. return err
  1274. }
  1275. if sts, ok := status.FromError(err); ok {
  1276. if e := t.WriteStatus(stream, sts); e != nil {
  1277. channelz.Warningf(logger, s.channelzID, "grpc: Server.processUnaryRPC failed to write status: %v", e)
  1278. }
  1279. } else {
  1280. switch st := err.(type) {
  1281. case transport.ConnectionError:
  1282. // Nothing to do here.
  1283. default:
  1284. panic(fmt.Sprintf("grpc: Unexpected error (%T) from sendResponse: %v", st, st))
  1285. }
  1286. }
  1287. if len(binlogs) != 0 {
  1288. h, _ := stream.Header()
  1289. sh := &binarylog.ServerHeader{
  1290. Header: h,
  1291. }
  1292. st := &binarylog.ServerTrailer{
  1293. Trailer: stream.Trailer(),
  1294. Err: appErr,
  1295. }
  1296. for _, binlog := range binlogs {
  1297. binlog.Log(ctx, sh)
  1298. binlog.Log(ctx, st)
  1299. }
  1300. }
  1301. return err
  1302. }
  1303. if len(binlogs) != 0 {
  1304. h, _ := stream.Header()
  1305. sh := &binarylog.ServerHeader{
  1306. Header: h,
  1307. }
  1308. sm := &binarylog.ServerMessage{
  1309. Message: reply,
  1310. }
  1311. for _, binlog := range binlogs {
  1312. binlog.Log(ctx, sh)
  1313. binlog.Log(ctx, sm)
  1314. }
  1315. }
  1316. if channelz.IsOn() {
  1317. t.IncrMsgSent()
  1318. }
  1319. if trInfo != nil {
  1320. trInfo.tr.LazyLog(&payload{sent: true, msg: reply}, true)
  1321. }
  1322. // TODO: Should we be logging if writing status failed here, like above?
  1323. // Should the logging be in WriteStatus? Should we ignore the WriteStatus
  1324. // error or allow the stats handler to see it?
  1325. if len(binlogs) != 0 {
  1326. st := &binarylog.ServerTrailer{
  1327. Trailer: stream.Trailer(),
  1328. Err: appErr,
  1329. }
  1330. for _, binlog := range binlogs {
  1331. binlog.Log(ctx, st)
  1332. }
  1333. }
  1334. return t.WriteStatus(stream, statusOK)
  1335. }
  1336. // chainStreamServerInterceptors chains all stream server interceptors into one.
  1337. func chainStreamServerInterceptors(s *Server) {
  1338. // Prepend opts.streamInt to the chaining interceptors if it exists, since streamInt will
  1339. // be executed before any other chained interceptors.
  1340. interceptors := s.opts.chainStreamInts
  1341. if s.opts.streamInt != nil {
  1342. interceptors = append([]StreamServerInterceptor{s.opts.streamInt}, s.opts.chainStreamInts...)
  1343. }
  1344. var chainedInt StreamServerInterceptor
  1345. if len(interceptors) == 0 {
  1346. chainedInt = nil
  1347. } else if len(interceptors) == 1 {
  1348. chainedInt = interceptors[0]
  1349. } else {
  1350. chainedInt = chainStreamInterceptors(interceptors)
  1351. }
  1352. s.opts.streamInt = chainedInt
  1353. }
  1354. func chainStreamInterceptors(interceptors []StreamServerInterceptor) StreamServerInterceptor {
  1355. return func(srv any, ss ServerStream, info *StreamServerInfo, handler StreamHandler) error {
  1356. return interceptors[0](srv, ss, info, getChainStreamHandler(interceptors, 0, info, handler))
  1357. }
  1358. }
  1359. func getChainStreamHandler(interceptors []StreamServerInterceptor, curr int, info *StreamServerInfo, finalHandler StreamHandler) StreamHandler {
  1360. if curr == len(interceptors)-1 {
  1361. return finalHandler
  1362. }
  1363. return func(srv any, stream ServerStream) error {
  1364. return interceptors[curr+1](srv, stream, info, getChainStreamHandler(interceptors, curr+1, info, finalHandler))
  1365. }
  1366. }
  1367. func (s *Server) processStreamingRPC(ctx context.Context, t transport.ServerTransport, stream *transport.Stream, info *serviceInfo, sd *StreamDesc, trInfo *traceInfo) (err error) {
  1368. if channelz.IsOn() {
  1369. s.incrCallsStarted()
  1370. }
  1371. shs := s.opts.statsHandlers
  1372. var statsBegin *stats.Begin
  1373. if len(shs) != 0 {
  1374. beginTime := time.Now()
  1375. statsBegin = &stats.Begin{
  1376. BeginTime: beginTime,
  1377. IsClientStream: sd.ClientStreams,
  1378. IsServerStream: sd.ServerStreams,
  1379. }
  1380. for _, sh := range shs {
  1381. sh.HandleRPC(ctx, statsBegin)
  1382. }
  1383. }
  1384. ctx = NewContextWithServerTransportStream(ctx, stream)
  1385. ss := &serverStream{
  1386. ctx: ctx,
  1387. t: t,
  1388. s: stream,
  1389. p: &parser{r: stream, recvBufferPool: s.opts.recvBufferPool},
  1390. codec: s.getCodec(stream.ContentSubtype()),
  1391. maxReceiveMessageSize: s.opts.maxReceiveMessageSize,
  1392. maxSendMessageSize: s.opts.maxSendMessageSize,
  1393. trInfo: trInfo,
  1394. statsHandler: shs,
  1395. }
  1396. if len(shs) != 0 || trInfo != nil || channelz.IsOn() {
  1397. // See comment in processUnaryRPC on defers.
  1398. defer func() {
  1399. if trInfo != nil {
  1400. ss.mu.Lock()
  1401. if err != nil && err != io.EOF {
  1402. ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []any{err}}, true)
  1403. ss.trInfo.tr.SetError()
  1404. }
  1405. ss.trInfo.tr.Finish()
  1406. ss.trInfo.tr = nil
  1407. ss.mu.Unlock()
  1408. }
  1409. if len(shs) != 0 {
  1410. end := &stats.End{
  1411. BeginTime: statsBegin.BeginTime,
  1412. EndTime: time.Now(),
  1413. }
  1414. if err != nil && err != io.EOF {
  1415. end.Error = toRPCErr(err)
  1416. }
  1417. for _, sh := range shs {
  1418. sh.HandleRPC(ctx, end)
  1419. }
  1420. }
  1421. if channelz.IsOn() {
  1422. if err != nil && err != io.EOF {
  1423. s.incrCallsFailed()
  1424. } else {
  1425. s.incrCallsSucceeded()
  1426. }
  1427. }
  1428. }()
  1429. }
  1430. if ml := binarylog.GetMethodLogger(stream.Method()); ml != nil {
  1431. ss.binlogs = append(ss.binlogs, ml)
  1432. }
  1433. if s.opts.binaryLogger != nil {
  1434. if ml := s.opts.binaryLogger.GetMethodLogger(stream.Method()); ml != nil {
  1435. ss.binlogs = append(ss.binlogs, ml)
  1436. }
  1437. }
  1438. if len(ss.binlogs) != 0 {
  1439. md, _ := metadata.FromIncomingContext(ctx)
  1440. logEntry := &binarylog.ClientHeader{
  1441. Header: md,
  1442. MethodName: stream.Method(),
  1443. PeerAddr: nil,
  1444. }
  1445. if deadline, ok := ctx.Deadline(); ok {
  1446. logEntry.Timeout = time.Until(deadline)
  1447. if logEntry.Timeout < 0 {
  1448. logEntry.Timeout = 0
  1449. }
  1450. }
  1451. if a := md[":authority"]; len(a) > 0 {
  1452. logEntry.Authority = a[0]
  1453. }
  1454. if peer, ok := peer.FromContext(ss.Context()); ok {
  1455. logEntry.PeerAddr = peer.Addr
  1456. }
  1457. for _, binlog := range ss.binlogs {
  1458. binlog.Log(ctx, logEntry)
  1459. }
  1460. }
  1461. // If dc is set and matches the stream's compression, use it. Otherwise, try
  1462. // to find a matching registered compressor for decomp.
  1463. if rc := stream.RecvCompress(); s.opts.dc != nil && s.opts.dc.Type() == rc {
  1464. ss.dc = s.opts.dc
  1465. } else if rc != "" && rc != encoding.Identity {
  1466. ss.decomp = encoding.GetCompressor(rc)
  1467. if ss.decomp == nil {
  1468. st := status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", rc)
  1469. t.WriteStatus(ss.s, st)
  1470. return st.Err()
  1471. }
  1472. }
  1473. // If cp is set, use it. Otherwise, attempt to compress the response using
  1474. // the incoming message compression method.
  1475. //
  1476. // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686.
  1477. if s.opts.cp != nil {
  1478. ss.cp = s.opts.cp
  1479. ss.sendCompressorName = s.opts.cp.Type()
  1480. } else if rc := stream.RecvCompress(); rc != "" && rc != encoding.Identity {
  1481. // Legacy compressor not specified; attempt to respond with same encoding.
  1482. ss.comp = encoding.GetCompressor(rc)
  1483. if ss.comp != nil {
  1484. ss.sendCompressorName = rc
  1485. }
  1486. }
  1487. if ss.sendCompressorName != "" {
  1488. if err := stream.SetSendCompress(ss.sendCompressorName); err != nil {
  1489. return status.Errorf(codes.Internal, "grpc: failed to set send compressor: %v", err)
  1490. }
  1491. }
  1492. ss.ctx = newContextWithRPCInfo(ss.ctx, false, ss.codec, ss.cp, ss.comp)
  1493. if trInfo != nil {
  1494. trInfo.tr.LazyLog(&trInfo.firstLine, false)
  1495. }
  1496. var appErr error
  1497. var server any
  1498. if info != nil {
  1499. server = info.serviceImpl
  1500. }
  1501. if s.opts.streamInt == nil {
  1502. appErr = sd.Handler(server, ss)
  1503. } else {
  1504. info := &StreamServerInfo{
  1505. FullMethod: stream.Method(),
  1506. IsClientStream: sd.ClientStreams,
  1507. IsServerStream: sd.ServerStreams,
  1508. }
  1509. appErr = s.opts.streamInt(server, ss, info, sd.Handler)
  1510. }
  1511. if appErr != nil {
  1512. appStatus, ok := status.FromError(appErr)
  1513. if !ok {
  1514. // Convert non-status application error to a status error with code
  1515. // Unknown, but handle context errors specifically.
  1516. appStatus = status.FromContextError(appErr)
  1517. appErr = appStatus.Err()
  1518. }
  1519. if trInfo != nil {
  1520. ss.mu.Lock()
  1521. ss.trInfo.tr.LazyLog(stringer(appStatus.Message()), true)
  1522. ss.trInfo.tr.SetError()
  1523. ss.mu.Unlock()
  1524. }
  1525. if len(ss.binlogs) != 0 {
  1526. st := &binarylog.ServerTrailer{
  1527. Trailer: ss.s.Trailer(),
  1528. Err: appErr,
  1529. }
  1530. for _, binlog := range ss.binlogs {
  1531. binlog.Log(ctx, st)
  1532. }
  1533. }
  1534. t.WriteStatus(ss.s, appStatus)
  1535. // TODO: Should we log an error from WriteStatus here and below?
  1536. return appErr
  1537. }
  1538. if trInfo != nil {
  1539. ss.mu.Lock()
  1540. ss.trInfo.tr.LazyLog(stringer("OK"), false)
  1541. ss.mu.Unlock()
  1542. }
  1543. if len(ss.binlogs) != 0 {
  1544. st := &binarylog.ServerTrailer{
  1545. Trailer: ss.s.Trailer(),
  1546. Err: appErr,
  1547. }
  1548. for _, binlog := range ss.binlogs {
  1549. binlog.Log(ctx, st)
  1550. }
  1551. }
  1552. return t.WriteStatus(ss.s, statusOK)
  1553. }
  1554. func (s *Server) handleStream(t transport.ServerTransport, stream *transport.Stream) {
  1555. ctx := stream.Context()
  1556. var ti *traceInfo
  1557. if EnableTracing {
  1558. tr := trace.New("grpc.Recv."+methodFamily(stream.Method()), stream.Method())
  1559. ctx = trace.NewContext(ctx, tr)
  1560. ti = &traceInfo{
  1561. tr: tr,
  1562. firstLine: firstLine{
  1563. client: false,
  1564. remoteAddr: t.RemoteAddr(),
  1565. },
  1566. }
  1567. if dl, ok := ctx.Deadline(); ok {
  1568. ti.firstLine.deadline = time.Until(dl)
  1569. }
  1570. }
  1571. sm := stream.Method()
  1572. if sm != "" && sm[0] == '/' {
  1573. sm = sm[1:]
  1574. }
  1575. pos := strings.LastIndex(sm, "/")
  1576. if pos == -1 {
  1577. if ti != nil {
  1578. ti.tr.LazyLog(&fmtStringer{"Malformed method name %q", []any{sm}}, true)
  1579. ti.tr.SetError()
  1580. }
  1581. errDesc := fmt.Sprintf("malformed method name: %q", stream.Method())
  1582. if err := t.WriteStatus(stream, status.New(codes.Unimplemented, errDesc)); err != nil {
  1583. if ti != nil {
  1584. ti.tr.LazyLog(&fmtStringer{"%v", []any{err}}, true)
  1585. ti.tr.SetError()
  1586. }
  1587. channelz.Warningf(logger, s.channelzID, "grpc: Server.handleStream failed to write status: %v", err)
  1588. }
  1589. if ti != nil {
  1590. ti.tr.Finish()
  1591. }
  1592. return
  1593. }
  1594. service := sm[:pos]
  1595. method := sm[pos+1:]
  1596. srv, knownService := s.services[service]
  1597. if knownService {
  1598. if md, ok := srv.methods[method]; ok {
  1599. s.processUnaryRPC(ctx, t, stream, srv, md, ti)
  1600. return
  1601. }
  1602. if sd, ok := srv.streams[method]; ok {
  1603. s.processStreamingRPC(ctx, t, stream, srv, sd, ti)
  1604. return
  1605. }
  1606. }
  1607. // Unknown service, or known server unknown method.
  1608. if unknownDesc := s.opts.unknownStreamDesc; unknownDesc != nil {
  1609. s.processStreamingRPC(ctx, t, stream, nil, unknownDesc, ti)
  1610. return
  1611. }
  1612. var errDesc string
  1613. if !knownService {
  1614. errDesc = fmt.Sprintf("unknown service %v", service)
  1615. } else {
  1616. errDesc = fmt.Sprintf("unknown method %v for service %v", method, service)
  1617. }
  1618. if ti != nil {
  1619. ti.tr.LazyPrintf("%s", errDesc)
  1620. ti.tr.SetError()
  1621. }
  1622. if err := t.WriteStatus(stream, status.New(codes.Unimplemented, errDesc)); err != nil {
  1623. if ti != nil {
  1624. ti.tr.LazyLog(&fmtStringer{"%v", []any{err}}, true)
  1625. ti.tr.SetError()
  1626. }
  1627. channelz.Warningf(logger, s.channelzID, "grpc: Server.handleStream failed to write status: %v", err)
  1628. }
  1629. if ti != nil {
  1630. ti.tr.Finish()
  1631. }
  1632. }
  1633. // The key to save ServerTransportStream in the context.
  1634. type streamKey struct{}
  1635. // NewContextWithServerTransportStream creates a new context from ctx and
  1636. // attaches stream to it.
  1637. //
  1638. // # Experimental
  1639. //
  1640. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  1641. // later release.
  1642. func NewContextWithServerTransportStream(ctx context.Context, stream ServerTransportStream) context.Context {
  1643. return context.WithValue(ctx, streamKey{}, stream)
  1644. }
  1645. // ServerTransportStream is a minimal interface that a transport stream must
  1646. // implement. This can be used to mock an actual transport stream for tests of
  1647. // handler code that use, for example, grpc.SetHeader (which requires some
  1648. // stream to be in context).
  1649. //
  1650. // See also NewContextWithServerTransportStream.
  1651. //
  1652. // # Experimental
  1653. //
  1654. // Notice: This type is EXPERIMENTAL and may be changed or removed in a
  1655. // later release.
  1656. type ServerTransportStream interface {
  1657. Method() string
  1658. SetHeader(md metadata.MD) error
  1659. SendHeader(md metadata.MD) error
  1660. SetTrailer(md metadata.MD) error
  1661. }
  1662. // ServerTransportStreamFromContext returns the ServerTransportStream saved in
  1663. // ctx. Returns nil if the given context has no stream associated with it
  1664. // (which implies it is not an RPC invocation context).
  1665. //
  1666. // # Experimental
  1667. //
  1668. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  1669. // later release.
  1670. func ServerTransportStreamFromContext(ctx context.Context) ServerTransportStream {
  1671. s, _ := ctx.Value(streamKey{}).(ServerTransportStream)
  1672. return s
  1673. }
  1674. // Stop stops the gRPC server. It immediately closes all open
  1675. // connections and listeners.
  1676. // It cancels all active RPCs on the server side and the corresponding
  1677. // pending RPCs on the client side will get notified by connection
  1678. // errors.
  1679. func (s *Server) Stop() {
  1680. s.quit.Fire()
  1681. defer func() {
  1682. s.serveWG.Wait()
  1683. s.done.Fire()
  1684. }()
  1685. s.channelzRemoveOnce.Do(func() { channelz.RemoveEntry(s.channelzID) })
  1686. s.mu.Lock()
  1687. listeners := s.lis
  1688. s.lis = nil
  1689. conns := s.conns
  1690. s.conns = nil
  1691. // interrupt GracefulStop if Stop and GracefulStop are called concurrently.
  1692. s.cv.Broadcast()
  1693. s.mu.Unlock()
  1694. for lis := range listeners {
  1695. lis.Close()
  1696. }
  1697. for _, cs := range conns {
  1698. for st := range cs {
  1699. st.Close(errors.New("Server.Stop called"))
  1700. }
  1701. }
  1702. if s.opts.numServerWorkers > 0 {
  1703. s.stopServerWorkers()
  1704. }
  1705. s.mu.Lock()
  1706. if s.events != nil {
  1707. s.events.Finish()
  1708. s.events = nil
  1709. }
  1710. s.mu.Unlock()
  1711. }
  1712. // GracefulStop stops the gRPC server gracefully. It stops the server from
  1713. // accepting new connections and RPCs and blocks until all the pending RPCs are
  1714. // finished.
  1715. func (s *Server) GracefulStop() {
  1716. s.quit.Fire()
  1717. defer s.done.Fire()
  1718. s.channelzRemoveOnce.Do(func() { channelz.RemoveEntry(s.channelzID) })
  1719. s.mu.Lock()
  1720. if s.conns == nil {
  1721. s.mu.Unlock()
  1722. return
  1723. }
  1724. for lis := range s.lis {
  1725. lis.Close()
  1726. }
  1727. s.lis = nil
  1728. if !s.drain {
  1729. for _, conns := range s.conns {
  1730. for st := range conns {
  1731. st.Drain("graceful_stop")
  1732. }
  1733. }
  1734. s.drain = true
  1735. }
  1736. // Wait for serving threads to be ready to exit. Only then can we be sure no
  1737. // new conns will be created.
  1738. s.mu.Unlock()
  1739. s.serveWG.Wait()
  1740. s.mu.Lock()
  1741. for len(s.conns) != 0 {
  1742. s.cv.Wait()
  1743. }
  1744. s.conns = nil
  1745. if s.events != nil {
  1746. s.events.Finish()
  1747. s.events = nil
  1748. }
  1749. s.mu.Unlock()
  1750. }
  1751. // contentSubtype must be lowercase
  1752. // cannot return nil
  1753. func (s *Server) getCodec(contentSubtype string) baseCodec {
  1754. if s.opts.codec != nil {
  1755. return s.opts.codec
  1756. }
  1757. if contentSubtype == "" {
  1758. return encoding.GetCodec(proto.Name)
  1759. }
  1760. codec := encoding.GetCodec(contentSubtype)
  1761. if codec == nil {
  1762. return encoding.GetCodec(proto.Name)
  1763. }
  1764. return codec
  1765. }
  1766. // SetHeader sets the header metadata to be sent from the server to the client.
  1767. // The context provided must be the context passed to the server's handler.
  1768. //
  1769. // Streaming RPCs should prefer the SetHeader method of the ServerStream.
  1770. //
  1771. // When called multiple times, all the provided metadata will be merged. All
  1772. // the metadata will be sent out when one of the following happens:
  1773. //
  1774. // - grpc.SendHeader is called, or for streaming handlers, stream.SendHeader.
  1775. // - The first response message is sent. For unary handlers, this occurs when
  1776. // the handler returns; for streaming handlers, this can happen when stream's
  1777. // SendMsg method is called.
  1778. // - An RPC status is sent out (error or success). This occurs when the handler
  1779. // returns.
  1780. //
  1781. // SetHeader will fail if called after any of the events above.
  1782. //
  1783. // The error returned is compatible with the status package. However, the
  1784. // status code will often not match the RPC status as seen by the client
  1785. // application, and therefore, should not be relied upon for this purpose.
  1786. func SetHeader(ctx context.Context, md metadata.MD) error {
  1787. if md.Len() == 0 {
  1788. return nil
  1789. }
  1790. stream := ServerTransportStreamFromContext(ctx)
  1791. if stream == nil {
  1792. return status.Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx)
  1793. }
  1794. return stream.SetHeader(md)
  1795. }
  1796. // SendHeader sends header metadata. It may be called at most once, and may not
  1797. // be called after any event that causes headers to be sent (see SetHeader for
  1798. // a complete list). The provided md and headers set by SetHeader() will be
  1799. // sent.
  1800. //
  1801. // The error returned is compatible with the status package. However, the
  1802. // status code will often not match the RPC status as seen by the client
  1803. // application, and therefore, should not be relied upon for this purpose.
  1804. func SendHeader(ctx context.Context, md metadata.MD) error {
  1805. stream := ServerTransportStreamFromContext(ctx)
  1806. if stream == nil {
  1807. return status.Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx)
  1808. }
  1809. if err := stream.SendHeader(md); err != nil {
  1810. return toRPCErr(err)
  1811. }
  1812. return nil
  1813. }
  1814. // SetSendCompressor sets a compressor for outbound messages from the server.
  1815. // It must not be called after any event that causes headers to be sent
  1816. // (see ServerStream.SetHeader for the complete list). Provided compressor is
  1817. // used when below conditions are met:
  1818. //
  1819. // - compressor is registered via encoding.RegisterCompressor
  1820. // - compressor name must exist in the client advertised compressor names
  1821. // sent in grpc-accept-encoding header. Use ClientSupportedCompressors to
  1822. // get client supported compressor names.
  1823. //
  1824. // The context provided must be the context passed to the server's handler.
  1825. // It must be noted that compressor name encoding.Identity disables the
  1826. // outbound compression.
  1827. // By default, server messages will be sent using the same compressor with
  1828. // which request messages were sent.
  1829. //
  1830. // It is not safe to call SetSendCompressor concurrently with SendHeader and
  1831. // SendMsg.
  1832. //
  1833. // # Experimental
  1834. //
  1835. // Notice: This function is EXPERIMENTAL and may be changed or removed in a
  1836. // later release.
  1837. func SetSendCompressor(ctx context.Context, name string) error {
  1838. stream, ok := ServerTransportStreamFromContext(ctx).(*transport.Stream)
  1839. if !ok || stream == nil {
  1840. return fmt.Errorf("failed to fetch the stream from the given context")
  1841. }
  1842. if err := validateSendCompressor(name, stream.ClientAdvertisedCompressors()); err != nil {
  1843. return fmt.Errorf("unable to set send compressor: %w", err)
  1844. }
  1845. return stream.SetSendCompress(name)
  1846. }
  1847. // ClientSupportedCompressors returns compressor names advertised by the client
  1848. // via grpc-accept-encoding header.
  1849. //
  1850. // The context provided must be the context passed to the server's handler.
  1851. //
  1852. // # Experimental
  1853. //
  1854. // Notice: This function is EXPERIMENTAL and may be changed or removed in a
  1855. // later release.
  1856. func ClientSupportedCompressors(ctx context.Context) ([]string, error) {
  1857. stream, ok := ServerTransportStreamFromContext(ctx).(*transport.Stream)
  1858. if !ok || stream == nil {
  1859. return nil, fmt.Errorf("failed to fetch the stream from the given context %v", ctx)
  1860. }
  1861. return strings.Split(stream.ClientAdvertisedCompressors(), ","), nil
  1862. }
  1863. // SetTrailer sets the trailer metadata that will be sent when an RPC returns.
  1864. // When called more than once, all the provided metadata will be merged.
  1865. //
  1866. // The error returned is compatible with the status package. However, the
  1867. // status code will often not match the RPC status as seen by the client
  1868. // application, and therefore, should not be relied upon for this purpose.
  1869. func SetTrailer(ctx context.Context, md metadata.MD) error {
  1870. if md.Len() == 0 {
  1871. return nil
  1872. }
  1873. stream := ServerTransportStreamFromContext(ctx)
  1874. if stream == nil {
  1875. return status.Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx)
  1876. }
  1877. return stream.SetTrailer(md)
  1878. }
  1879. // Method returns the method string for the server context. The returned
  1880. // string is in the format of "/service/method".
  1881. func Method(ctx context.Context) (string, bool) {
  1882. s := ServerTransportStreamFromContext(ctx)
  1883. if s == nil {
  1884. return "", false
  1885. }
  1886. return s.Method(), true
  1887. }
  1888. type channelzServer struct {
  1889. s *Server
  1890. }
  1891. func (c *channelzServer) ChannelzMetric() *channelz.ServerInternalMetric {
  1892. return c.s.channelzMetric()
  1893. }
  1894. // validateSendCompressor returns an error when given compressor name cannot be
  1895. // handled by the server or the client based on the advertised compressors.
  1896. func validateSendCompressor(name, clientCompressors string) error {
  1897. if name == encoding.Identity {
  1898. return nil
  1899. }
  1900. if !grpcutil.IsCompressorNameRegistered(name) {
  1901. return fmt.Errorf("compressor not registered %q", name)
  1902. }
  1903. for _, c := range strings.Split(clientCompressors, ",") {
  1904. if c == name {
  1905. return nil // found match
  1906. }
  1907. }
  1908. return fmt.Errorf("client does not support compressor %q", name)
  1909. }
  1910. // atomicSemaphore implements a blocking, counting semaphore. acquire should be
  1911. // called synchronously; release may be called asynchronously.
  1912. type atomicSemaphore struct {
  1913. n atomic.Int64
  1914. wait chan struct{}
  1915. }
  1916. func (q *atomicSemaphore) acquire() {
  1917. if q.n.Add(-1) < 0 {
  1918. // We ran out of quota. Block until a release happens.
  1919. <-q.wait
  1920. }
  1921. }
  1922. func (q *atomicSemaphore) release() {
  1923. // N.B. the "<= 0" check below should allow for this to work with multiple
  1924. // concurrent calls to acquire, but also note that with synchronous calls to
  1925. // acquire, as our system does, n will never be less than -1. There are
  1926. // fairness issues (queuing) to consider if this was to be generalized.
  1927. if q.n.Add(1) <= 0 {
  1928. // An acquire was waiting on us. Unblock it.
  1929. q.wait <- struct{}{}
  1930. }
  1931. }
  1932. func newHandlerQuota(n uint32) *atomicSemaphore {
  1933. a := &atomicSemaphore{wait: make(chan struct{}, 1)}
  1934. a.n.Store(int64(n))
  1935. return a
  1936. }