server.go 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122
  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, s.traceInfo(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. }, func(ctx context.Context, method string) context.Context {
  904. if !EnableTracing {
  905. return ctx
  906. }
  907. tr := trace.New("grpc.Recv."+methodFamily(method), method)
  908. return trace.NewContext(ctx, tr)
  909. })
  910. wg.Wait()
  911. }
  912. var _ http.Handler = (*Server)(nil)
  913. // ServeHTTP implements the Go standard library's http.Handler
  914. // interface by responding to the gRPC request r, by looking up
  915. // the requested gRPC method in the gRPC server s.
  916. //
  917. // The provided HTTP request must have arrived on an HTTP/2
  918. // connection. When using the Go standard library's server,
  919. // practically this means that the Request must also have arrived
  920. // over TLS.
  921. //
  922. // To share one port (such as 443 for https) between gRPC and an
  923. // existing http.Handler, use a root http.Handler such as:
  924. //
  925. // if r.ProtoMajor == 2 && strings.HasPrefix(
  926. // r.Header.Get("Content-Type"), "application/grpc") {
  927. // grpcServer.ServeHTTP(w, r)
  928. // } else {
  929. // yourMux.ServeHTTP(w, r)
  930. // }
  931. //
  932. // Note that ServeHTTP uses Go's HTTP/2 server implementation which is totally
  933. // separate from grpc-go's HTTP/2 server. Performance and features may vary
  934. // between the two paths. ServeHTTP does not support some gRPC features
  935. // available through grpc-go's HTTP/2 server.
  936. //
  937. // # Experimental
  938. //
  939. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  940. // later release.
  941. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  942. st, err := transport.NewServerHandlerTransport(w, r, s.opts.statsHandlers)
  943. if err != nil {
  944. // Errors returned from transport.NewServerHandlerTransport have
  945. // already been written to w.
  946. return
  947. }
  948. if !s.addConn(listenerAddressForServeHTTP, st) {
  949. return
  950. }
  951. defer s.removeConn(listenerAddressForServeHTTP, st)
  952. s.serveStreams(st)
  953. }
  954. // traceInfo returns a traceInfo and associates it with stream, if tracing is enabled.
  955. // If tracing is not enabled, it returns nil.
  956. func (s *Server) traceInfo(st transport.ServerTransport, stream *transport.Stream) (trInfo *traceInfo) {
  957. if !EnableTracing {
  958. return nil
  959. }
  960. tr, ok := trace.FromContext(stream.Context())
  961. if !ok {
  962. return nil
  963. }
  964. trInfo = &traceInfo{
  965. tr: tr,
  966. firstLine: firstLine{
  967. client: false,
  968. remoteAddr: st.RemoteAddr(),
  969. },
  970. }
  971. if dl, ok := stream.Context().Deadline(); ok {
  972. trInfo.firstLine.deadline = time.Until(dl)
  973. }
  974. return trInfo
  975. }
  976. func (s *Server) addConn(addr string, st transport.ServerTransport) bool {
  977. s.mu.Lock()
  978. defer s.mu.Unlock()
  979. if s.conns == nil {
  980. st.Close(errors.New("Server.addConn called when server has already been stopped"))
  981. return false
  982. }
  983. if s.drain {
  984. // Transport added after we drained our existing conns: drain it
  985. // immediately.
  986. st.Drain("")
  987. }
  988. if s.conns[addr] == nil {
  989. // Create a map entry if this is the first connection on this listener.
  990. s.conns[addr] = make(map[transport.ServerTransport]bool)
  991. }
  992. s.conns[addr][st] = true
  993. return true
  994. }
  995. func (s *Server) removeConn(addr string, st transport.ServerTransport) {
  996. s.mu.Lock()
  997. defer s.mu.Unlock()
  998. conns := s.conns[addr]
  999. if conns != nil {
  1000. delete(conns, st)
  1001. if len(conns) == 0 {
  1002. // If the last connection for this address is being removed, also
  1003. // remove the map entry corresponding to the address. This is used
  1004. // in GracefulStop() when waiting for all connections to be closed.
  1005. delete(s.conns, addr)
  1006. }
  1007. s.cv.Broadcast()
  1008. }
  1009. }
  1010. func (s *Server) channelzMetric() *channelz.ServerInternalMetric {
  1011. return &channelz.ServerInternalMetric{
  1012. CallsStarted: atomic.LoadInt64(&s.czData.callsStarted),
  1013. CallsSucceeded: atomic.LoadInt64(&s.czData.callsSucceeded),
  1014. CallsFailed: atomic.LoadInt64(&s.czData.callsFailed),
  1015. LastCallStartedTimestamp: time.Unix(0, atomic.LoadInt64(&s.czData.lastCallStartedTime)),
  1016. }
  1017. }
  1018. func (s *Server) incrCallsStarted() {
  1019. atomic.AddInt64(&s.czData.callsStarted, 1)
  1020. atomic.StoreInt64(&s.czData.lastCallStartedTime, time.Now().UnixNano())
  1021. }
  1022. func (s *Server) incrCallsSucceeded() {
  1023. atomic.AddInt64(&s.czData.callsSucceeded, 1)
  1024. }
  1025. func (s *Server) incrCallsFailed() {
  1026. atomic.AddInt64(&s.czData.callsFailed, 1)
  1027. }
  1028. func (s *Server) sendResponse(t transport.ServerTransport, stream *transport.Stream, msg any, cp Compressor, opts *transport.Options, comp encoding.Compressor) error {
  1029. data, err := encode(s.getCodec(stream.ContentSubtype()), msg)
  1030. if err != nil {
  1031. channelz.Error(logger, s.channelzID, "grpc: server failed to encode response: ", err)
  1032. return err
  1033. }
  1034. compData, err := compress(data, cp, comp)
  1035. if err != nil {
  1036. channelz.Error(logger, s.channelzID, "grpc: server failed to compress response: ", err)
  1037. return err
  1038. }
  1039. hdr, payload := msgHeader(data, compData)
  1040. // TODO(dfawley): should we be checking len(data) instead?
  1041. if len(payload) > s.opts.maxSendMessageSize {
  1042. return status.Errorf(codes.ResourceExhausted, "grpc: trying to send message larger than max (%d vs. %d)", len(payload), s.opts.maxSendMessageSize)
  1043. }
  1044. err = t.Write(stream, hdr, payload, opts)
  1045. if err == nil {
  1046. for _, sh := range s.opts.statsHandlers {
  1047. sh.HandleRPC(stream.Context(), outPayload(false, msg, data, payload, time.Now()))
  1048. }
  1049. }
  1050. return err
  1051. }
  1052. // chainUnaryServerInterceptors chains all unary server interceptors into one.
  1053. func chainUnaryServerInterceptors(s *Server) {
  1054. // Prepend opts.unaryInt to the chaining interceptors if it exists, since unaryInt will
  1055. // be executed before any other chained interceptors.
  1056. interceptors := s.opts.chainUnaryInts
  1057. if s.opts.unaryInt != nil {
  1058. interceptors = append([]UnaryServerInterceptor{s.opts.unaryInt}, s.opts.chainUnaryInts...)
  1059. }
  1060. var chainedInt UnaryServerInterceptor
  1061. if len(interceptors) == 0 {
  1062. chainedInt = nil
  1063. } else if len(interceptors) == 1 {
  1064. chainedInt = interceptors[0]
  1065. } else {
  1066. chainedInt = chainUnaryInterceptors(interceptors)
  1067. }
  1068. s.opts.unaryInt = chainedInt
  1069. }
  1070. func chainUnaryInterceptors(interceptors []UnaryServerInterceptor) UnaryServerInterceptor {
  1071. return func(ctx context.Context, req any, info *UnaryServerInfo, handler UnaryHandler) (any, error) {
  1072. return interceptors[0](ctx, req, info, getChainUnaryHandler(interceptors, 0, info, handler))
  1073. }
  1074. }
  1075. func getChainUnaryHandler(interceptors []UnaryServerInterceptor, curr int, info *UnaryServerInfo, finalHandler UnaryHandler) UnaryHandler {
  1076. if curr == len(interceptors)-1 {
  1077. return finalHandler
  1078. }
  1079. return func(ctx context.Context, req any) (any, error) {
  1080. return interceptors[curr+1](ctx, req, info, getChainUnaryHandler(interceptors, curr+1, info, finalHandler))
  1081. }
  1082. }
  1083. func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport.Stream, info *serviceInfo, md *MethodDesc, trInfo *traceInfo) (err error) {
  1084. shs := s.opts.statsHandlers
  1085. if len(shs) != 0 || trInfo != nil || channelz.IsOn() {
  1086. if channelz.IsOn() {
  1087. s.incrCallsStarted()
  1088. }
  1089. var statsBegin *stats.Begin
  1090. for _, sh := range shs {
  1091. beginTime := time.Now()
  1092. statsBegin = &stats.Begin{
  1093. BeginTime: beginTime,
  1094. IsClientStream: false,
  1095. IsServerStream: false,
  1096. }
  1097. sh.HandleRPC(stream.Context(), statsBegin)
  1098. }
  1099. if trInfo != nil {
  1100. trInfo.tr.LazyLog(&trInfo.firstLine, false)
  1101. }
  1102. // The deferred error handling for tracing, stats handler and channelz are
  1103. // combined into one function to reduce stack usage -- a defer takes ~56-64
  1104. // bytes on the stack, so overflowing the stack will require a stack
  1105. // re-allocation, which is expensive.
  1106. //
  1107. // To maintain behavior similar to separate deferred statements, statements
  1108. // should be executed in the reverse order. That is, tracing first, stats
  1109. // handler second, and channelz last. Note that panics *within* defers will
  1110. // lead to different behavior, but that's an acceptable compromise; that
  1111. // would be undefined behavior territory anyway.
  1112. defer func() {
  1113. if trInfo != nil {
  1114. if err != nil && err != io.EOF {
  1115. trInfo.tr.LazyLog(&fmtStringer{"%v", []any{err}}, true)
  1116. trInfo.tr.SetError()
  1117. }
  1118. trInfo.tr.Finish()
  1119. }
  1120. for _, sh := range shs {
  1121. end := &stats.End{
  1122. BeginTime: statsBegin.BeginTime,
  1123. EndTime: time.Now(),
  1124. }
  1125. if err != nil && err != io.EOF {
  1126. end.Error = toRPCErr(err)
  1127. }
  1128. sh.HandleRPC(stream.Context(), end)
  1129. }
  1130. if channelz.IsOn() {
  1131. if err != nil && err != io.EOF {
  1132. s.incrCallsFailed()
  1133. } else {
  1134. s.incrCallsSucceeded()
  1135. }
  1136. }
  1137. }()
  1138. }
  1139. var binlogs []binarylog.MethodLogger
  1140. if ml := binarylog.GetMethodLogger(stream.Method()); ml != nil {
  1141. binlogs = append(binlogs, ml)
  1142. }
  1143. if s.opts.binaryLogger != nil {
  1144. if ml := s.opts.binaryLogger.GetMethodLogger(stream.Method()); ml != nil {
  1145. binlogs = append(binlogs, ml)
  1146. }
  1147. }
  1148. if len(binlogs) != 0 {
  1149. ctx := stream.Context()
  1150. md, _ := metadata.FromIncomingContext(ctx)
  1151. logEntry := &binarylog.ClientHeader{
  1152. Header: md,
  1153. MethodName: stream.Method(),
  1154. PeerAddr: nil,
  1155. }
  1156. if deadline, ok := ctx.Deadline(); ok {
  1157. logEntry.Timeout = time.Until(deadline)
  1158. if logEntry.Timeout < 0 {
  1159. logEntry.Timeout = 0
  1160. }
  1161. }
  1162. if a := md[":authority"]; len(a) > 0 {
  1163. logEntry.Authority = a[0]
  1164. }
  1165. if peer, ok := peer.FromContext(ctx); ok {
  1166. logEntry.PeerAddr = peer.Addr
  1167. }
  1168. for _, binlog := range binlogs {
  1169. binlog.Log(ctx, logEntry)
  1170. }
  1171. }
  1172. // comp and cp are used for compression. decomp and dc are used for
  1173. // decompression. If comp and decomp are both set, they are the same;
  1174. // however they are kept separate to ensure that at most one of the
  1175. // compressor/decompressor variable pairs are set for use later.
  1176. var comp, decomp encoding.Compressor
  1177. var cp Compressor
  1178. var dc Decompressor
  1179. var sendCompressorName string
  1180. // If dc is set and matches the stream's compression, use it. Otherwise, try
  1181. // to find a matching registered compressor for decomp.
  1182. if rc := stream.RecvCompress(); s.opts.dc != nil && s.opts.dc.Type() == rc {
  1183. dc = s.opts.dc
  1184. } else if rc != "" && rc != encoding.Identity {
  1185. decomp = encoding.GetCompressor(rc)
  1186. if decomp == nil {
  1187. st := status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", rc)
  1188. t.WriteStatus(stream, st)
  1189. return st.Err()
  1190. }
  1191. }
  1192. // If cp is set, use it. Otherwise, attempt to compress the response using
  1193. // the incoming message compression method.
  1194. //
  1195. // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686.
  1196. if s.opts.cp != nil {
  1197. cp = s.opts.cp
  1198. sendCompressorName = cp.Type()
  1199. } else if rc := stream.RecvCompress(); rc != "" && rc != encoding.Identity {
  1200. // Legacy compressor not specified; attempt to respond with same encoding.
  1201. comp = encoding.GetCompressor(rc)
  1202. if comp != nil {
  1203. sendCompressorName = comp.Name()
  1204. }
  1205. }
  1206. if sendCompressorName != "" {
  1207. if err := stream.SetSendCompress(sendCompressorName); err != nil {
  1208. return status.Errorf(codes.Internal, "grpc: failed to set send compressor: %v", err)
  1209. }
  1210. }
  1211. var payInfo *payloadInfo
  1212. if len(shs) != 0 || len(binlogs) != 0 {
  1213. payInfo = &payloadInfo{}
  1214. }
  1215. d, err := recvAndDecompress(&parser{r: stream, recvBufferPool: s.opts.recvBufferPool}, stream, dc, s.opts.maxReceiveMessageSize, payInfo, decomp)
  1216. if err != nil {
  1217. if e := t.WriteStatus(stream, status.Convert(err)); e != nil {
  1218. channelz.Warningf(logger, s.channelzID, "grpc: Server.processUnaryRPC failed to write status: %v", e)
  1219. }
  1220. return err
  1221. }
  1222. if channelz.IsOn() {
  1223. t.IncrMsgRecv()
  1224. }
  1225. df := func(v any) error {
  1226. if err := s.getCodec(stream.ContentSubtype()).Unmarshal(d, v); err != nil {
  1227. return status.Errorf(codes.Internal, "grpc: error unmarshalling request: %v", err)
  1228. }
  1229. for _, sh := range shs {
  1230. sh.HandleRPC(stream.Context(), &stats.InPayload{
  1231. RecvTime: time.Now(),
  1232. Payload: v,
  1233. Length: len(d),
  1234. WireLength: payInfo.compressedLength + headerLen,
  1235. CompressedLength: payInfo.compressedLength,
  1236. Data: d,
  1237. })
  1238. }
  1239. if len(binlogs) != 0 {
  1240. cm := &binarylog.ClientMessage{
  1241. Message: d,
  1242. }
  1243. for _, binlog := range binlogs {
  1244. binlog.Log(stream.Context(), cm)
  1245. }
  1246. }
  1247. if trInfo != nil {
  1248. trInfo.tr.LazyLog(&payload{sent: false, msg: v}, true)
  1249. }
  1250. return nil
  1251. }
  1252. ctx := NewContextWithServerTransportStream(stream.Context(), stream)
  1253. reply, appErr := md.Handler(info.serviceImpl, ctx, df, s.opts.unaryInt)
  1254. if appErr != nil {
  1255. appStatus, ok := status.FromError(appErr)
  1256. if !ok {
  1257. // Convert non-status application error to a status error with code
  1258. // Unknown, but handle context errors specifically.
  1259. appStatus = status.FromContextError(appErr)
  1260. appErr = appStatus.Err()
  1261. }
  1262. if trInfo != nil {
  1263. trInfo.tr.LazyLog(stringer(appStatus.Message()), true)
  1264. trInfo.tr.SetError()
  1265. }
  1266. if e := t.WriteStatus(stream, appStatus); e != nil {
  1267. channelz.Warningf(logger, s.channelzID, "grpc: Server.processUnaryRPC failed to write status: %v", e)
  1268. }
  1269. if len(binlogs) != 0 {
  1270. if h, _ := stream.Header(); h.Len() > 0 {
  1271. // Only log serverHeader if there was header. Otherwise it can
  1272. // be trailer only.
  1273. sh := &binarylog.ServerHeader{
  1274. Header: h,
  1275. }
  1276. for _, binlog := range binlogs {
  1277. binlog.Log(stream.Context(), sh)
  1278. }
  1279. }
  1280. st := &binarylog.ServerTrailer{
  1281. Trailer: stream.Trailer(),
  1282. Err: appErr,
  1283. }
  1284. for _, binlog := range binlogs {
  1285. binlog.Log(stream.Context(), st)
  1286. }
  1287. }
  1288. return appErr
  1289. }
  1290. if trInfo != nil {
  1291. trInfo.tr.LazyLog(stringer("OK"), false)
  1292. }
  1293. opts := &transport.Options{Last: true}
  1294. // Server handler could have set new compressor by calling SetSendCompressor.
  1295. // In case it is set, we need to use it for compressing outbound message.
  1296. if stream.SendCompress() != sendCompressorName {
  1297. comp = encoding.GetCompressor(stream.SendCompress())
  1298. }
  1299. if err := s.sendResponse(t, stream, reply, cp, opts, comp); err != nil {
  1300. if err == io.EOF {
  1301. // The entire stream is done (for unary RPC only).
  1302. return err
  1303. }
  1304. if sts, ok := status.FromError(err); ok {
  1305. if e := t.WriteStatus(stream, sts); e != nil {
  1306. channelz.Warningf(logger, s.channelzID, "grpc: Server.processUnaryRPC failed to write status: %v", e)
  1307. }
  1308. } else {
  1309. switch st := err.(type) {
  1310. case transport.ConnectionError:
  1311. // Nothing to do here.
  1312. default:
  1313. panic(fmt.Sprintf("grpc: Unexpected error (%T) from sendResponse: %v", st, st))
  1314. }
  1315. }
  1316. if len(binlogs) != 0 {
  1317. h, _ := stream.Header()
  1318. sh := &binarylog.ServerHeader{
  1319. Header: h,
  1320. }
  1321. st := &binarylog.ServerTrailer{
  1322. Trailer: stream.Trailer(),
  1323. Err: appErr,
  1324. }
  1325. for _, binlog := range binlogs {
  1326. binlog.Log(stream.Context(), sh)
  1327. binlog.Log(stream.Context(), st)
  1328. }
  1329. }
  1330. return err
  1331. }
  1332. if len(binlogs) != 0 {
  1333. h, _ := stream.Header()
  1334. sh := &binarylog.ServerHeader{
  1335. Header: h,
  1336. }
  1337. sm := &binarylog.ServerMessage{
  1338. Message: reply,
  1339. }
  1340. for _, binlog := range binlogs {
  1341. binlog.Log(stream.Context(), sh)
  1342. binlog.Log(stream.Context(), sm)
  1343. }
  1344. }
  1345. if channelz.IsOn() {
  1346. t.IncrMsgSent()
  1347. }
  1348. if trInfo != nil {
  1349. trInfo.tr.LazyLog(&payload{sent: true, msg: reply}, true)
  1350. }
  1351. // TODO: Should we be logging if writing status failed here, like above?
  1352. // Should the logging be in WriteStatus? Should we ignore the WriteStatus
  1353. // error or allow the stats handler to see it?
  1354. if len(binlogs) != 0 {
  1355. st := &binarylog.ServerTrailer{
  1356. Trailer: stream.Trailer(),
  1357. Err: appErr,
  1358. }
  1359. for _, binlog := range binlogs {
  1360. binlog.Log(stream.Context(), st)
  1361. }
  1362. }
  1363. return t.WriteStatus(stream, statusOK)
  1364. }
  1365. // chainStreamServerInterceptors chains all stream server interceptors into one.
  1366. func chainStreamServerInterceptors(s *Server) {
  1367. // Prepend opts.streamInt to the chaining interceptors if it exists, since streamInt will
  1368. // be executed before any other chained interceptors.
  1369. interceptors := s.opts.chainStreamInts
  1370. if s.opts.streamInt != nil {
  1371. interceptors = append([]StreamServerInterceptor{s.opts.streamInt}, s.opts.chainStreamInts...)
  1372. }
  1373. var chainedInt StreamServerInterceptor
  1374. if len(interceptors) == 0 {
  1375. chainedInt = nil
  1376. } else if len(interceptors) == 1 {
  1377. chainedInt = interceptors[0]
  1378. } else {
  1379. chainedInt = chainStreamInterceptors(interceptors)
  1380. }
  1381. s.opts.streamInt = chainedInt
  1382. }
  1383. func chainStreamInterceptors(interceptors []StreamServerInterceptor) StreamServerInterceptor {
  1384. return func(srv any, ss ServerStream, info *StreamServerInfo, handler StreamHandler) error {
  1385. return interceptors[0](srv, ss, info, getChainStreamHandler(interceptors, 0, info, handler))
  1386. }
  1387. }
  1388. func getChainStreamHandler(interceptors []StreamServerInterceptor, curr int, info *StreamServerInfo, finalHandler StreamHandler) StreamHandler {
  1389. if curr == len(interceptors)-1 {
  1390. return finalHandler
  1391. }
  1392. return func(srv any, stream ServerStream) error {
  1393. return interceptors[curr+1](srv, stream, info, getChainStreamHandler(interceptors, curr+1, info, finalHandler))
  1394. }
  1395. }
  1396. func (s *Server) processStreamingRPC(t transport.ServerTransport, stream *transport.Stream, info *serviceInfo, sd *StreamDesc, trInfo *traceInfo) (err error) {
  1397. if channelz.IsOn() {
  1398. s.incrCallsStarted()
  1399. }
  1400. shs := s.opts.statsHandlers
  1401. var statsBegin *stats.Begin
  1402. if len(shs) != 0 {
  1403. beginTime := time.Now()
  1404. statsBegin = &stats.Begin{
  1405. BeginTime: beginTime,
  1406. IsClientStream: sd.ClientStreams,
  1407. IsServerStream: sd.ServerStreams,
  1408. }
  1409. for _, sh := range shs {
  1410. sh.HandleRPC(stream.Context(), statsBegin)
  1411. }
  1412. }
  1413. ctx := NewContextWithServerTransportStream(stream.Context(), stream)
  1414. ss := &serverStream{
  1415. ctx: ctx,
  1416. t: t,
  1417. s: stream,
  1418. p: &parser{r: stream, recvBufferPool: s.opts.recvBufferPool},
  1419. codec: s.getCodec(stream.ContentSubtype()),
  1420. maxReceiveMessageSize: s.opts.maxReceiveMessageSize,
  1421. maxSendMessageSize: s.opts.maxSendMessageSize,
  1422. trInfo: trInfo,
  1423. statsHandler: shs,
  1424. }
  1425. if len(shs) != 0 || trInfo != nil || channelz.IsOn() {
  1426. // See comment in processUnaryRPC on defers.
  1427. defer func() {
  1428. if trInfo != nil {
  1429. ss.mu.Lock()
  1430. if err != nil && err != io.EOF {
  1431. ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []any{err}}, true)
  1432. ss.trInfo.tr.SetError()
  1433. }
  1434. ss.trInfo.tr.Finish()
  1435. ss.trInfo.tr = nil
  1436. ss.mu.Unlock()
  1437. }
  1438. if len(shs) != 0 {
  1439. end := &stats.End{
  1440. BeginTime: statsBegin.BeginTime,
  1441. EndTime: time.Now(),
  1442. }
  1443. if err != nil && err != io.EOF {
  1444. end.Error = toRPCErr(err)
  1445. }
  1446. for _, sh := range shs {
  1447. sh.HandleRPC(stream.Context(), end)
  1448. }
  1449. }
  1450. if channelz.IsOn() {
  1451. if err != nil && err != io.EOF {
  1452. s.incrCallsFailed()
  1453. } else {
  1454. s.incrCallsSucceeded()
  1455. }
  1456. }
  1457. }()
  1458. }
  1459. if ml := binarylog.GetMethodLogger(stream.Method()); ml != nil {
  1460. ss.binlogs = append(ss.binlogs, ml)
  1461. }
  1462. if s.opts.binaryLogger != nil {
  1463. if ml := s.opts.binaryLogger.GetMethodLogger(stream.Method()); ml != nil {
  1464. ss.binlogs = append(ss.binlogs, ml)
  1465. }
  1466. }
  1467. if len(ss.binlogs) != 0 {
  1468. md, _ := metadata.FromIncomingContext(ctx)
  1469. logEntry := &binarylog.ClientHeader{
  1470. Header: md,
  1471. MethodName: stream.Method(),
  1472. PeerAddr: nil,
  1473. }
  1474. if deadline, ok := ctx.Deadline(); ok {
  1475. logEntry.Timeout = time.Until(deadline)
  1476. if logEntry.Timeout < 0 {
  1477. logEntry.Timeout = 0
  1478. }
  1479. }
  1480. if a := md[":authority"]; len(a) > 0 {
  1481. logEntry.Authority = a[0]
  1482. }
  1483. if peer, ok := peer.FromContext(ss.Context()); ok {
  1484. logEntry.PeerAddr = peer.Addr
  1485. }
  1486. for _, binlog := range ss.binlogs {
  1487. binlog.Log(stream.Context(), logEntry)
  1488. }
  1489. }
  1490. // If dc is set and matches the stream's compression, use it. Otherwise, try
  1491. // to find a matching registered compressor for decomp.
  1492. if rc := stream.RecvCompress(); s.opts.dc != nil && s.opts.dc.Type() == rc {
  1493. ss.dc = s.opts.dc
  1494. } else if rc != "" && rc != encoding.Identity {
  1495. ss.decomp = encoding.GetCompressor(rc)
  1496. if ss.decomp == nil {
  1497. st := status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", rc)
  1498. t.WriteStatus(ss.s, st)
  1499. return st.Err()
  1500. }
  1501. }
  1502. // If cp is set, use it. Otherwise, attempt to compress the response using
  1503. // the incoming message compression method.
  1504. //
  1505. // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686.
  1506. if s.opts.cp != nil {
  1507. ss.cp = s.opts.cp
  1508. ss.sendCompressorName = s.opts.cp.Type()
  1509. } else if rc := stream.RecvCompress(); rc != "" && rc != encoding.Identity {
  1510. // Legacy compressor not specified; attempt to respond with same encoding.
  1511. ss.comp = encoding.GetCompressor(rc)
  1512. if ss.comp != nil {
  1513. ss.sendCompressorName = rc
  1514. }
  1515. }
  1516. if ss.sendCompressorName != "" {
  1517. if err := stream.SetSendCompress(ss.sendCompressorName); err != nil {
  1518. return status.Errorf(codes.Internal, "grpc: failed to set send compressor: %v", err)
  1519. }
  1520. }
  1521. ss.ctx = newContextWithRPCInfo(ss.ctx, false, ss.codec, ss.cp, ss.comp)
  1522. if trInfo != nil {
  1523. trInfo.tr.LazyLog(&trInfo.firstLine, false)
  1524. }
  1525. var appErr error
  1526. var server any
  1527. if info != nil {
  1528. server = info.serviceImpl
  1529. }
  1530. if s.opts.streamInt == nil {
  1531. appErr = sd.Handler(server, ss)
  1532. } else {
  1533. info := &StreamServerInfo{
  1534. FullMethod: stream.Method(),
  1535. IsClientStream: sd.ClientStreams,
  1536. IsServerStream: sd.ServerStreams,
  1537. }
  1538. appErr = s.opts.streamInt(server, ss, info, sd.Handler)
  1539. }
  1540. if appErr != nil {
  1541. appStatus, ok := status.FromError(appErr)
  1542. if !ok {
  1543. // Convert non-status application error to a status error with code
  1544. // Unknown, but handle context errors specifically.
  1545. appStatus = status.FromContextError(appErr)
  1546. appErr = appStatus.Err()
  1547. }
  1548. if trInfo != nil {
  1549. ss.mu.Lock()
  1550. ss.trInfo.tr.LazyLog(stringer(appStatus.Message()), true)
  1551. ss.trInfo.tr.SetError()
  1552. ss.mu.Unlock()
  1553. }
  1554. if len(ss.binlogs) != 0 {
  1555. st := &binarylog.ServerTrailer{
  1556. Trailer: ss.s.Trailer(),
  1557. Err: appErr,
  1558. }
  1559. for _, binlog := range ss.binlogs {
  1560. binlog.Log(stream.Context(), st)
  1561. }
  1562. }
  1563. t.WriteStatus(ss.s, appStatus)
  1564. // TODO: Should we log an error from WriteStatus here and below?
  1565. return appErr
  1566. }
  1567. if trInfo != nil {
  1568. ss.mu.Lock()
  1569. ss.trInfo.tr.LazyLog(stringer("OK"), false)
  1570. ss.mu.Unlock()
  1571. }
  1572. if len(ss.binlogs) != 0 {
  1573. st := &binarylog.ServerTrailer{
  1574. Trailer: ss.s.Trailer(),
  1575. Err: appErr,
  1576. }
  1577. for _, binlog := range ss.binlogs {
  1578. binlog.Log(stream.Context(), st)
  1579. }
  1580. }
  1581. return t.WriteStatus(ss.s, statusOK)
  1582. }
  1583. func (s *Server) handleStream(t transport.ServerTransport, stream *transport.Stream, trInfo *traceInfo) {
  1584. sm := stream.Method()
  1585. if sm != "" && sm[0] == '/' {
  1586. sm = sm[1:]
  1587. }
  1588. pos := strings.LastIndex(sm, "/")
  1589. if pos == -1 {
  1590. if trInfo != nil {
  1591. trInfo.tr.LazyLog(&fmtStringer{"Malformed method name %q", []any{sm}}, true)
  1592. trInfo.tr.SetError()
  1593. }
  1594. errDesc := fmt.Sprintf("malformed method name: %q", stream.Method())
  1595. if err := t.WriteStatus(stream, status.New(codes.Unimplemented, errDesc)); err != nil {
  1596. if trInfo != nil {
  1597. trInfo.tr.LazyLog(&fmtStringer{"%v", []any{err}}, true)
  1598. trInfo.tr.SetError()
  1599. }
  1600. channelz.Warningf(logger, s.channelzID, "grpc: Server.handleStream failed to write status: %v", err)
  1601. }
  1602. if trInfo != nil {
  1603. trInfo.tr.Finish()
  1604. }
  1605. return
  1606. }
  1607. service := sm[:pos]
  1608. method := sm[pos+1:]
  1609. srv, knownService := s.services[service]
  1610. if knownService {
  1611. if md, ok := srv.methods[method]; ok {
  1612. s.processUnaryRPC(t, stream, srv, md, trInfo)
  1613. return
  1614. }
  1615. if sd, ok := srv.streams[method]; ok {
  1616. s.processStreamingRPC(t, stream, srv, sd, trInfo)
  1617. return
  1618. }
  1619. }
  1620. // Unknown service, or known server unknown method.
  1621. if unknownDesc := s.opts.unknownStreamDesc; unknownDesc != nil {
  1622. s.processStreamingRPC(t, stream, nil, unknownDesc, trInfo)
  1623. return
  1624. }
  1625. var errDesc string
  1626. if !knownService {
  1627. errDesc = fmt.Sprintf("unknown service %v", service)
  1628. } else {
  1629. errDesc = fmt.Sprintf("unknown method %v for service %v", method, service)
  1630. }
  1631. if trInfo != nil {
  1632. trInfo.tr.LazyPrintf("%s", errDesc)
  1633. trInfo.tr.SetError()
  1634. }
  1635. if err := t.WriteStatus(stream, status.New(codes.Unimplemented, errDesc)); err != nil {
  1636. if trInfo != nil {
  1637. trInfo.tr.LazyLog(&fmtStringer{"%v", []any{err}}, true)
  1638. trInfo.tr.SetError()
  1639. }
  1640. channelz.Warningf(logger, s.channelzID, "grpc: Server.handleStream failed to write status: %v", err)
  1641. }
  1642. if trInfo != nil {
  1643. trInfo.tr.Finish()
  1644. }
  1645. }
  1646. // The key to save ServerTransportStream in the context.
  1647. type streamKey struct{}
  1648. // NewContextWithServerTransportStream creates a new context from ctx and
  1649. // attaches stream to it.
  1650. //
  1651. // # Experimental
  1652. //
  1653. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  1654. // later release.
  1655. func NewContextWithServerTransportStream(ctx context.Context, stream ServerTransportStream) context.Context {
  1656. return context.WithValue(ctx, streamKey{}, stream)
  1657. }
  1658. // ServerTransportStream is a minimal interface that a transport stream must
  1659. // implement. This can be used to mock an actual transport stream for tests of
  1660. // handler code that use, for example, grpc.SetHeader (which requires some
  1661. // stream to be in context).
  1662. //
  1663. // See also NewContextWithServerTransportStream.
  1664. //
  1665. // # Experimental
  1666. //
  1667. // Notice: This type is EXPERIMENTAL and may be changed or removed in a
  1668. // later release.
  1669. type ServerTransportStream interface {
  1670. Method() string
  1671. SetHeader(md metadata.MD) error
  1672. SendHeader(md metadata.MD) error
  1673. SetTrailer(md metadata.MD) error
  1674. }
  1675. // ServerTransportStreamFromContext returns the ServerTransportStream saved in
  1676. // ctx. Returns nil if the given context has no stream associated with it
  1677. // (which implies it is not an RPC invocation context).
  1678. //
  1679. // # Experimental
  1680. //
  1681. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  1682. // later release.
  1683. func ServerTransportStreamFromContext(ctx context.Context) ServerTransportStream {
  1684. s, _ := ctx.Value(streamKey{}).(ServerTransportStream)
  1685. return s
  1686. }
  1687. // Stop stops the gRPC server. It immediately closes all open
  1688. // connections and listeners.
  1689. // It cancels all active RPCs on the server side and the corresponding
  1690. // pending RPCs on the client side will get notified by connection
  1691. // errors.
  1692. func (s *Server) Stop() {
  1693. s.quit.Fire()
  1694. defer func() {
  1695. s.serveWG.Wait()
  1696. s.done.Fire()
  1697. }()
  1698. s.channelzRemoveOnce.Do(func() { channelz.RemoveEntry(s.channelzID) })
  1699. s.mu.Lock()
  1700. listeners := s.lis
  1701. s.lis = nil
  1702. conns := s.conns
  1703. s.conns = nil
  1704. // interrupt GracefulStop if Stop and GracefulStop are called concurrently.
  1705. s.cv.Broadcast()
  1706. s.mu.Unlock()
  1707. for lis := range listeners {
  1708. lis.Close()
  1709. }
  1710. for _, cs := range conns {
  1711. for st := range cs {
  1712. st.Close(errors.New("Server.Stop called"))
  1713. }
  1714. }
  1715. if s.opts.numServerWorkers > 0 {
  1716. s.stopServerWorkers()
  1717. }
  1718. s.mu.Lock()
  1719. if s.events != nil {
  1720. s.events.Finish()
  1721. s.events = nil
  1722. }
  1723. s.mu.Unlock()
  1724. }
  1725. // GracefulStop stops the gRPC server gracefully. It stops the server from
  1726. // accepting new connections and RPCs and blocks until all the pending RPCs are
  1727. // finished.
  1728. func (s *Server) GracefulStop() {
  1729. s.quit.Fire()
  1730. defer s.done.Fire()
  1731. s.channelzRemoveOnce.Do(func() { channelz.RemoveEntry(s.channelzID) })
  1732. s.mu.Lock()
  1733. if s.conns == nil {
  1734. s.mu.Unlock()
  1735. return
  1736. }
  1737. for lis := range s.lis {
  1738. lis.Close()
  1739. }
  1740. s.lis = nil
  1741. if !s.drain {
  1742. for _, conns := range s.conns {
  1743. for st := range conns {
  1744. st.Drain("graceful_stop")
  1745. }
  1746. }
  1747. s.drain = true
  1748. }
  1749. // Wait for serving threads to be ready to exit. Only then can we be sure no
  1750. // new conns will be created.
  1751. s.mu.Unlock()
  1752. s.serveWG.Wait()
  1753. s.mu.Lock()
  1754. for len(s.conns) != 0 {
  1755. s.cv.Wait()
  1756. }
  1757. s.conns = nil
  1758. if s.events != nil {
  1759. s.events.Finish()
  1760. s.events = nil
  1761. }
  1762. s.mu.Unlock()
  1763. }
  1764. // contentSubtype must be lowercase
  1765. // cannot return nil
  1766. func (s *Server) getCodec(contentSubtype string) baseCodec {
  1767. if s.opts.codec != nil {
  1768. return s.opts.codec
  1769. }
  1770. if contentSubtype == "" {
  1771. return encoding.GetCodec(proto.Name)
  1772. }
  1773. codec := encoding.GetCodec(contentSubtype)
  1774. if codec == nil {
  1775. return encoding.GetCodec(proto.Name)
  1776. }
  1777. return codec
  1778. }
  1779. // SetHeader sets the header metadata to be sent from the server to the client.
  1780. // The context provided must be the context passed to the server's handler.
  1781. //
  1782. // Streaming RPCs should prefer the SetHeader method of the ServerStream.
  1783. //
  1784. // When called multiple times, all the provided metadata will be merged. All
  1785. // the metadata will be sent out when one of the following happens:
  1786. //
  1787. // - grpc.SendHeader is called, or for streaming handlers, stream.SendHeader.
  1788. // - The first response message is sent. For unary handlers, this occurs when
  1789. // the handler returns; for streaming handlers, this can happen when stream's
  1790. // SendMsg method is called.
  1791. // - An RPC status is sent out (error or success). This occurs when the handler
  1792. // returns.
  1793. //
  1794. // SetHeader will fail if called after any of the events above.
  1795. //
  1796. // The error returned is compatible with the status package. However, the
  1797. // status code will often not match the RPC status as seen by the client
  1798. // application, and therefore, should not be relied upon for this purpose.
  1799. func SetHeader(ctx context.Context, md metadata.MD) error {
  1800. if md.Len() == 0 {
  1801. return nil
  1802. }
  1803. stream := ServerTransportStreamFromContext(ctx)
  1804. if stream == nil {
  1805. return status.Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx)
  1806. }
  1807. return stream.SetHeader(md)
  1808. }
  1809. // SendHeader sends header metadata. It may be called at most once, and may not
  1810. // be called after any event that causes headers to be sent (see SetHeader for
  1811. // a complete list). The provided md and headers set by SetHeader() will be
  1812. // sent.
  1813. //
  1814. // The error returned is compatible with the status package. However, the
  1815. // status code will often not match the RPC status as seen by the client
  1816. // application, and therefore, should not be relied upon for this purpose.
  1817. func SendHeader(ctx context.Context, md metadata.MD) error {
  1818. stream := ServerTransportStreamFromContext(ctx)
  1819. if stream == nil {
  1820. return status.Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx)
  1821. }
  1822. if err := stream.SendHeader(md); err != nil {
  1823. return toRPCErr(err)
  1824. }
  1825. return nil
  1826. }
  1827. // SetSendCompressor sets a compressor for outbound messages from the server.
  1828. // It must not be called after any event that causes headers to be sent
  1829. // (see ServerStream.SetHeader for the complete list). Provided compressor is
  1830. // used when below conditions are met:
  1831. //
  1832. // - compressor is registered via encoding.RegisterCompressor
  1833. // - compressor name must exist in the client advertised compressor names
  1834. // sent in grpc-accept-encoding header. Use ClientSupportedCompressors to
  1835. // get client supported compressor names.
  1836. //
  1837. // The context provided must be the context passed to the server's handler.
  1838. // It must be noted that compressor name encoding.Identity disables the
  1839. // outbound compression.
  1840. // By default, server messages will be sent using the same compressor with
  1841. // which request messages were sent.
  1842. //
  1843. // It is not safe to call SetSendCompressor concurrently with SendHeader and
  1844. // SendMsg.
  1845. //
  1846. // # Experimental
  1847. //
  1848. // Notice: This function is EXPERIMENTAL and may be changed or removed in a
  1849. // later release.
  1850. func SetSendCompressor(ctx context.Context, name string) error {
  1851. stream, ok := ServerTransportStreamFromContext(ctx).(*transport.Stream)
  1852. if !ok || stream == nil {
  1853. return fmt.Errorf("failed to fetch the stream from the given context")
  1854. }
  1855. if err := validateSendCompressor(name, stream.ClientAdvertisedCompressors()); err != nil {
  1856. return fmt.Errorf("unable to set send compressor: %w", err)
  1857. }
  1858. return stream.SetSendCompress(name)
  1859. }
  1860. // ClientSupportedCompressors returns compressor names advertised by the client
  1861. // via grpc-accept-encoding header.
  1862. //
  1863. // The context provided must be the context passed to the server's handler.
  1864. //
  1865. // # Experimental
  1866. //
  1867. // Notice: This function is EXPERIMENTAL and may be changed or removed in a
  1868. // later release.
  1869. func ClientSupportedCompressors(ctx context.Context) ([]string, error) {
  1870. stream, ok := ServerTransportStreamFromContext(ctx).(*transport.Stream)
  1871. if !ok || stream == nil {
  1872. return nil, fmt.Errorf("failed to fetch the stream from the given context %v", ctx)
  1873. }
  1874. return strings.Split(stream.ClientAdvertisedCompressors(), ","), nil
  1875. }
  1876. // SetTrailer sets the trailer metadata that will be sent when an RPC returns.
  1877. // When called more than once, all the provided metadata will be merged.
  1878. //
  1879. // The error returned is compatible with the status package. However, the
  1880. // status code will often not match the RPC status as seen by the client
  1881. // application, and therefore, should not be relied upon for this purpose.
  1882. func SetTrailer(ctx context.Context, md metadata.MD) error {
  1883. if md.Len() == 0 {
  1884. return nil
  1885. }
  1886. stream := ServerTransportStreamFromContext(ctx)
  1887. if stream == nil {
  1888. return status.Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx)
  1889. }
  1890. return stream.SetTrailer(md)
  1891. }
  1892. // Method returns the method string for the server context. The returned
  1893. // string is in the format of "/service/method".
  1894. func Method(ctx context.Context) (string, bool) {
  1895. s := ServerTransportStreamFromContext(ctx)
  1896. if s == nil {
  1897. return "", false
  1898. }
  1899. return s.Method(), true
  1900. }
  1901. type channelzServer struct {
  1902. s *Server
  1903. }
  1904. func (c *channelzServer) ChannelzMetric() *channelz.ServerInternalMetric {
  1905. return c.s.channelzMetric()
  1906. }
  1907. // validateSendCompressor returns an error when given compressor name cannot be
  1908. // handled by the server or the client based on the advertised compressors.
  1909. func validateSendCompressor(name, clientCompressors string) error {
  1910. if name == encoding.Identity {
  1911. return nil
  1912. }
  1913. if !grpcutil.IsCompressorNameRegistered(name) {
  1914. return fmt.Errorf("compressor not registered %q", name)
  1915. }
  1916. for _, c := range strings.Split(clientCompressors, ",") {
  1917. if c == name {
  1918. return nil // found match
  1919. }
  1920. }
  1921. return fmt.Errorf("client does not support compressor %q", name)
  1922. }
  1923. // atomicSemaphore implements a blocking, counting semaphore. acquire should be
  1924. // called synchronously; release may be called asynchronously.
  1925. type atomicSemaphore struct {
  1926. n atomic.Int64
  1927. wait chan struct{}
  1928. }
  1929. func (q *atomicSemaphore) acquire() {
  1930. if q.n.Add(-1) < 0 {
  1931. // We ran out of quota. Block until a release happens.
  1932. <-q.wait
  1933. }
  1934. }
  1935. func (q *atomicSemaphore) release() {
  1936. // N.B. the "<= 0" check below should allow for this to work with multiple
  1937. // concurrent calls to acquire, but also note that with synchronous calls to
  1938. // acquire, as our system does, n will never be less than -1. There are
  1939. // fairness issues (queuing) to consider if this was to be generalized.
  1940. if q.n.Add(1) <= 0 {
  1941. // An acquire was waiting on us. Unblock it.
  1942. q.wait <- struct{}{}
  1943. }
  1944. }
  1945. func newHandlerQuota(n uint32) *atomicSemaphore {
  1946. a := &atomicSemaphore{wait: make(chan struct{}, 1)}
  1947. a.n.Store(int64(n))
  1948. return a
  1949. }